diff --git "a/test.jsonl" "b/test.jsonl" --- "a/test.jsonl" +++ "b/test.jsonl" @@ -1,573 +1,545 @@ -{"code": " public function testAuthCheckToken()\n {\n $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';\n $GLOBALS['cfg']['Server']['SignonSession'] = 'session123';\n $GLOBALS['cfg']['Server']['host'] = 'localhost';\n $GLOBALS['cfg']['Server']['port'] = '80';\n $GLOBALS['cfg']['Server']['user'] = 'user';\n $GLOBALS['cfg']['Server']['SignonScript'] = '';\n $_COOKIE['session123'] = true;\n $_REQUEST['old_usr'] = 'oldUser';\n $_SESSION['PMA_single_signon_user'] = 'user123';\n $_SESSION['PMA_single_signon_password'] = 'pass123';\n $_SESSION['PMA_single_signon_host'] = 'local';\n $_SESSION['PMA_single_signon_port'] = '12';\n $_SESSION['PMA_single_signon_cfgupdate'] = array('foo' => 'bar');\n $_SESSION['PMA_single_signon_token'] = 'pmaToken';\n $sessionName = session_name();\n $sessionID = session_id();\n\n $this->assertFalse(\n $this->object->authCheck()\n );\n\n $this->assertEquals(\n array(\n 'SignonURL' => 'http://phpmyadmin.net/SignonURL',\n 'SignonScript' => '',\n 'SignonSession' => 'session123',\n 'host' => 'local',\n 'port' => '12',\n 'user' => 'user',\n 'foo' => 'bar'\n ),\n $GLOBALS['cfg']['Server']\n );\n\n $this->assertEquals(\n 'pmaToken',\n $_SESSION[' PMA_token ']\n );\n\n $this->assertEquals(\n $sessionName,\n session_name()\n );\n\n $this->assertEquals(\n $sessionID,\n session_id()\n );\n\n $this->assertFalse(\n isset($_SESSION['LAST_SIGNON_URL'])\n );\n }", "label_name": "CWE-200", "label": "200"} -{"code": "function barcode_encode($code,$encoding)\n{\n global $genbarcode_loc;\n\n if (\n ((preg_match(\"/^ean$/i\", $encoding)\n && ( strlen($code)==12 || strlen($code)==13)))\n\n || (($encoding) && (preg_match(\"/^isbn$/i\", $encoding))\n && (( strlen($code)==9 || strlen($code)==10) ||\n (((preg_match(\"/^978/\", $code) && strlen($code)==12) ||\n (strlen($code)==13)))))\n\n || (( !isset($encoding) || !$encoding || (preg_match(\"/^ANY$/i\", $encoding) ))\n && (preg_match(\"/^[0-9]{12,13}$/\", $code)))\n )\n {\n /* use built-in EAN-Encoder */\n dol_syslog(\"barcode.lib.php::barcode_encode Use barcode_encode_ean\");\n $bars=barcode_encode_ean($code, $encoding);\n }\n else if (file_exists($genbarcode_loc))\n {\n /* use genbarcode */\n dol_syslog(\"barcode.lib.php::barcode_encode Use genbarcode \".$genbarcode_loc.\" code=\".$code.\" encoding=\".$encoding);\n $bars=barcode_encode_genbarcode($code, $encoding);\n }\n else\n {\n print \"barcode_encode needs an external programm for encodings other then EAN/ISBN
\\n\";\n print \"\\n\";\n print \"
\\n\";\n return false;\n }\n return $bars;\n}", "label_name": "CWE-20", "label": "20"} -{"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": "20"} -{"code": "function XMLRPCremoveResourceGroupPriv($name, $type, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"resourceGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to remove group privileges on this node');\n }\n if($typeid = getResourceTypeID($type)){\n if(!checkForGroupName($name, 'resource', '', $typeid)){\n return array('status' => 'error',\n 'errorcode' => 28,\n 'errormsg' => 'resource group does not exist');\n }\n $perms = explode(':', $permissions);\n updateResourcePrivs(\"$type/$name\", $nodeid, array(), $perms);\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'Invalid resource type');\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "function execute_backup($command) {\n\t$backup_options = get_option('dbmanager_options');\n\tcheck_backup_files();\n\n\tif( realpath( $backup_options['path'] ) === false ) {\n\t\treturn sprintf( __( '%s is not a valid backup path', 'wp-dbmanager' ), stripslashes( $backup_options['path'] ) );\n\t} else if( dbmanager_is_valid_path( $backup_options['mysqldumppath'] ) === 0 ) {\n\t\treturn sprintf( __( '%s is not a valid mysqldump path', 'wp-dbmanager' ), stripslashes( $backup_options['mysqldumppath'] ) );\n\t} else if( dbmanager_is_valid_path( $backup_options['mysqlpath'] ) === 0 ) {\n\t\treturn sprintf( __( '%s is not a valid mysql path', 'wp-dbmanager' ), stripslashes( $backup_options['mysqlpath'] ) );\n\t}\n\n\tif(substr(PHP_OS, 0, 3) == 'WIN') {\n\t\t$writable_dir = $backup_options['path'];\n\t\t$tmpnam = $writable_dir.'/wp-dbmanager.bat';\n\t\t$fp = fopen($tmpnam, 'w');\n\t\tfwrite($fp, $command);\n\t\tfclose($fp);\n\t\tsystem($tmpnam.' > NUL', $error);\n\t\tunlink($tmpnam);\n\t} else {\n\t\tpassthru($command, $error);\n\t}\n\treturn $error;\n}", "label_name": "CWE-20", "label": "20"} -{"code": " protected function loginRequired()\n {\n Yii::$app->user->logout();\n Yii::$app->user->loginRequired();\n\n return false;\n }", "label_name": "CWE-863", "label": "863"} -{"code": " public function uploadCustomLogoAction(Request $request)\n {\n $fileExt = File::getFileExtension($_FILES['Filedata']['name']);\n if (!in_array($fileExt, ['svg', 'png', 'jpg'])) {\n throw new \\Exception('Unsupported file format');\n }\n\n if ($fileExt === 'svg' && stripos(file_get_contents($_FILES['Filedata']['tmp_name']), 'writeStream(self::CUSTOM_LOGO_PATH, fopen($_FILES['Filedata']['tmp_name'], 'rb'));\n\n // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in\n // Ext.form.Action.Submit and mark the submission as failed\n\n $response = $this->adminJson(['success' => true]);\n $response->headers->set('Content-Type', 'text/html');\n\n return $response;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function Recipient($to) {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Recipient() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"RCPT TO:<\" . $to . \">\" . $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 && $code != 251) {\n $this->error =\n array(\"error\" => \"RCPT 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": "20"} -{"code": " $modelName = ucfirst ($module->name);\n if (class_exists ($modelName)) {\n // prefix widget class name with custom module model name and a delimiter\n $cache[$widgetType][$modelName.'::TemplatesGridViewProfileWidget'] =\n Yii::t(\n 'app', '{modelName} Summary', array ('{modelName}' => $modelName));\n }\n }\n }\n }\n return $cache[$widgetType];\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function actionPublishPost() {\n $post = new Events;\n // $user = $this->loadModel($id);\n if (isset($_POST['text']) && $_POST['text'] != \"\") {\n $post->text = $_POST['text'];\n $post->visibility = $_POST['visibility'];\n if (isset($_POST['associationId']))\n $post->associationId = $_POST['associationId'];\n //$soc->attributes = $_POST['Social'];\n //die(var_dump($_POST['Social']));\n $post->user = Yii::app()->user->getName();\n $post->type = 'feed';\n $post->subtype = $_POST['subtype'];\n $post->lastUpdated = time();\n $post->timestamp = time();\n if ($post->save()) {\n if (!empty($post->associationId) && $post->associationId != Yii::app()->user->getId()) {\n\n $notif = new Notification;\n\n $notif->type = 'social_post';\n $notif->createdBy = $post->user;\n $notif->modelType = 'Profile';\n $notif->modelId = $post->associationId;\n\n $notif->user = Yii::app()->db->createCommand()\n ->select('username')\n ->from('x2_users')\n ->where('id=:id', array(':id' => $post->associationId))\n ->queryScalar();\n\n // $prof = X2Model::model('Profile')->findByAttributes(array('username'=>$post->user));\n // $notif->text = \"$prof->fullName posted on your profile.\";\n // $notif->record = \"profile:$prof->id\";\n // $notif->viewed = 0;\n $notif->createDate = time();\n // $subject=X2Model::model('Profile')->findByPk($id);\n // $notif->user = $subject->username;\n $notif->save();\n }\n }\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function actionGetItems(){\n\t\t$sql = 'SELECT id, name as value FROM x2_docs WHERE name LIKE :qterm ORDER BY name ASC';\n\t\t$command = Yii::app()->db->createCommand($sql);\n\t\t$qterm = '%'.$_GET['term'].'%';\n\t\t$command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n\t\t$result = $command->queryAll();\n\t\techo CJSON::encode($result); exit;\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function restoreX2AuthManager () {\n if (isset (self::$_oldAuthManagerComponent)) {\n Yii::app()->setComponent ('authManager', self::$_oldAuthManagerComponent);\n } else {\n throw new CException ('X2AuthManager component could not be restored'); \n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function testPages () {\n $this->visitPages ( $this->allPages );\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function referenceFixtures() {\n return array(\n 'campaign' => array ('Campaign', '.CampaignMailingBehaviorTest'),\n 'lists' => 'X2List',\n 'credentials' => 'Credentials',\n 'users' => 'User',\n 'profile' => array('Profile','.marketing')\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function getFilePath($fileName = null)\n {\n if ($fileName === null) {\n $fileName = $this->fileName;\n }\n\n return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;\n }", "label_name": "CWE-610", "label": "610"} -{"code": "\tpublic function Insert() {\n\n\t\t$ins_stmt = Database::prepare(\"\n\t\t\tINSERT INTO `\" . TABLE_PANEL_TICKETS . \"` SET\n `customerid` = :customerid,\n `adminid` = :adminid,\n `category` = :category,\n `priority` = :priority,\n `subject` = :subject,\n `message` = :message,\n `dt` = :dt,\n `lastchange` = :lastchange,\n `ip` = :ip,\n `status` = :status,\n `lastreplier` = :lastreplier,\n `by` = :by,\n `answerto` = :answerto\"\n\t\t);\n\t\t$ins_data = array(\n\t\t\t'customerid' => $this->Get('customer'),\n\t\t\t'adminid' => $this->Get('admin'),\n\t\t\t'category' => $this->Get('category'),\n\t\t\t'priority' => $this->Get('priority'),\n\t\t\t'subject' => $this->Get('subject'),\n\t\t\t'message' => $this->Get('message'),\n\t\t\t'dt' => time(),\n\t\t\t'lastchange' => time(),\n\t\t\t'ip' => $this->Get('ip'),\n\t\t\t'status' => $this->Get('status'),\n\t\t\t'lastreplier' => $this->Get('lastreplier'),\n\t\t\t'by' => $this->Get('by'),\n\t\t\t'answerto' => $this->Get('answerto')\n\t\t);\n\t\tDatabase::pexecute($ins_stmt, $ins_data);\n\t\t$this->tid = Database::lastInsertId();\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "\tstatic public function getCategoryName($_id = 0) {\n\n\t\tif ($_id != 0) {\n\t\t\t$stmt = Database::prepare(\"\n\t\t\t\tSELECT `name` FROM `\" . TABLE_PANEL_TICKET_CATS . \"` WHERE `id` = :id\"\n\t\t\t);\n\t\t\t$category = Database::pexecute_first($stmt, array('id' => $_id));\n\t\t\treturn $category['name'];\n\t\t}\n\t\treturn null;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " public function view() {\n $params = func_get_args();\n $content = '';\n\n $filename = urldecode(join('/', $params));\n\n // Sanitize filename for securtiy\n // We don't allow backlinks\n if (strpos($filename, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $filename = str_replace('..', '', $filename);\n\n // Clean up nicely\n $filename = str_replace('//', '', $filename);\n\n // We don't allow leading slashes\n $filename = preg_replace('/^\\//', '', $filename);\n \n // Check if file had URL_SUFFIX - if so, append it to filename\n $filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';\n \n $file = FILES_DIR . '/' . $filename;\n if (!$this->_isImage($file) && file_exists($file)) {\n $content = file_get_contents($file);\n }\n \n $this->display('file_manager/views/view', array(\n 'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),\n 'is_image' => $this->_isImage($file),\n 'filename' => $filename,\n 'content' => $content\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function create_directory() {\n if (!AuthUser::hasPermission('file_manager_mkdir')) {\n Flash::set('error', __('You do not have sufficient permissions to create a directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_directory')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['directory'];\n\n $path = str_replace('..', '', $data['path']);\n $dirname = str_replace('..', '', $data['name']);\n $dir = FILES_DIR . \"/{$path}/{$dirname}\";\n\n if (mkdir($dir)) {\n $mode = Plugin::getSetting('dirmode', 'file_manager');\n chmod($dir, octdec($mode));\n } else {\n Flash::set('error', __('Directory :name has not been created!', array(':name' => $dirname)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function create_directory() {\n if (!AuthUser::hasPermission('file_manager_mkdir')) {\n Flash::set('error', __('You do not have sufficient permissions to create a directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_directory')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['directory'];\n\n $path = str_replace('..', '', $data['path']);\n $dirname = str_replace('..', '', $data['name']);\n $dir = FILES_DIR . \"/{$path}/{$dirname}\";\n\n if (mkdir($dir)) {\n $mode = Plugin::getSetting('dirmode', 'file_manager');\n chmod($dir, octdec($mode));\n } else {\n Flash::set('error', __('Directory :name has not been created!', array(':name' => $dirname)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function chmod() {\n if (!AuthUser::hasPermission('file_manager_chmod')) {\n Flash::set('error', __('You do not have sufficient permissions to change the permissions on a 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/chmod')) {\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 $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . '/' . $data['name'];\n\n if (file_exists($file)) {\n if (@!chmod($file, octdec($data['mode'])))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!'));\n }\n\n $path = substr($data['name'], 0, strrpos($data['name'], '/'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function browse() {\n $params = func_get_args();\n\n $this->path = join('/', $params);\n // make sure there's a / at the end\n if (substr($this->path, -1, 1) != '/')\n $this->path .= '/';\n\n //security\n // we dont allow back link\n if (strpos($this->path, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $this->path = str_replace('..', '', $this->path);\n\n // clean up nicely\n $this->path = str_replace('//', '', $this->path);\n\n // we dont allow leading slashes\n $this->path = preg_replace('/^\\//', '', $this->path);\n\n $this->fullpath = FILES_DIR . '/' . $this->path;\n\n // clean up nicely\n $this->fullpath = preg_replace('/\\/\\//', '/', $this->fullpath);\n\n $this->display('file_manager/views/index', array(\n 'dir' => $this->path,\n //'files' => $this->_getListFiles()\n 'files' => $this->_listFiles()\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"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": "20"} -{"code": "\tfunction lockTable($table,$lockType=\"WRITE\") {\n $sql = \"LOCK TABLES `\" . $this->prefix . \"$table` $lockType\";\n \n $res = mysqli_query($this->connection, $sql); \n return $res;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function selectArraysBySql($sql) { \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return array();\n $arrays = array();\n for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)\n $arrays[] = mysqli_fetch_assoc($res);\n return $arrays;\n }", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\t\t\n\t\treturn true;\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tstatic function convertXMLFeedSafeChar($str) {\n\t\t$str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\""\",'\"',$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"’\",\"'\",$str);\n $str = str_replace(\"‘\",\"'\",$str); \n $str = str_replace(\"®\",\"\",$str);\n $str = str_replace(\"\ufffd\",\"-\", $str);\n $str = str_replace(\"\ufffd\",\"-\", $str); \n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"”\",'\"', $str);\n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"“\",'\"', $str);\n $str = str_replace(\"\\r\\n\",\" \",$str); \n $str = str_replace(\"\ufffd\",\" 1/4\",$str);\n $str = str_replace(\"¼\",\" 1/4\", $str);\n $str = str_replace(\"\ufffd\",\" 1/2\",$str);\n $str = str_replace(\"½\",\" 1/2\",$str);\n $str = str_replace(\"\ufffd\",\" 3/4\",$str);\n $str = str_replace(\"¾\",\" 3/4\",$str);\n $str = str_replace(\"\ufffd\", \"(TM)\", $str);\n $str = str_replace(\"™\",\"(TM)\", $str);\n $str = str_replace(\"®\",\"(R)\", $str);\n $str = str_replace(\"\ufffd\",\"(R)\",$str); \n $str = str_replace(\"&\",\"&\",$str); \n\t\t$str = str_replace(\">\",\">\",$str); \t\t\n return trim($str);\n\t}", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"code": "\tpublic function delete() {\n\t global $user;\n\n $count = $this->address->find('count', 'user_id=' . $user->id);\n if($count > 1)\n { \n $address = new address($this->params['id']);\n\t if ($user->isAdmin() || ($user->id == $address->user_id)) {\n if ($address->is_billing)\n {\n $billAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $billAddress->is_billing = true;\n $billAddress->save();\n }\n if ($address->is_shipping) \n {\n $shipAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $shipAddress->is_shipping = true;\n $shipAddress->save();\n }\n\t parent::delete();\n\t }\n }\n else\n {\n flash(\"error\", gt(\"You must have at least one address.\"));\n }\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function delete() {\n\t global $user;\n\n $count = $this->address->find('count', 'user_id=' . $user->id);\n if($count > 1)\n { \n $address = new address($this->params['id']);\n\t if ($user->isAdmin() || ($user->id == $address->user_id)) {\n if ($address->is_billing)\n {\n $billAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $billAddress->is_billing = true;\n $billAddress->save();\n }\n if ($address->is_shipping) \n {\n $shipAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $shipAddress->is_shipping = true;\n $shipAddress->save();\n }\n\t parent::delete();\n\t }\n }\n else\n {\n flash(\"error\", gt(\"You must have at least one address.\"));\n }\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction edit() {\n\t if (empty($this->params['content_id'])) {\n\t flash('message',gt('An error occurred: No content id set.'));\n expHistory::back(); \n\t } \n /* The global constants can be overridden 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 \n \n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $comment = new expComment($id);\n //FIXME here is where we might sanitize the comment before displaying/editing it\n\t\tassign_to_template(array(\n\t\t 'content_id'=>$this->params['content_id'],\n 'content_type'=>$this->params['content_type'],\n\t\t 'comment'=>$comment\n\t\t));\n\t}\t", "label_name": "CWE-74", "label": "74"} -{"code": " public function approve_toggle() {\n global $history;\n \n if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n \n $simplenote = new expSimpleNote($this->params['id']);\n $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $db->insertObject($obj, 'expeAlerts_subscribers');\n }\n \n $count = count($this->params['ealerts']);\n \n if ($count > 0) {\n flash('message', gt(\"Your subscriptions have been updated. You are now subscriber to\").\" \".$count.' '.gt('E-Alerts.'));\n } else {\n flash('error', gt(\"You have been unsubscribed from all E-Alerts.\"));\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"code": " public function update_discount() {\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $discount = new discounts($id);\n // find required shipping method if needed\n if ($this->params['required_shipping_calculator_id'] > 0) {\n $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];\n } else {\n $this->params['required_shipping_calculator_id'] = 0;\n }\n \n $discount->update($this->params);\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function configure() {\n expHistory::set('editable', $this->params);\n // little bit of trickery so that that categories can have their own configs\n \n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n $this->config = $config->config;\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $views = expTemplate::get_config_templates($this, $this->loc);\n \n $gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all');\n \n assign_to_template(array(\n 'config'=>$this->config,\n 'pullable_modules'=>$pullable_modules,\n 'views'=>$views,\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'title'=>static::displayname()\n ));\n } ", "label_name": "CWE-74", "label": "74"} -{"code": "\t function manage_upcharge() {\n\t\t$this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\n\t\t$gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''\n ));\n\t }", "label_name": "CWE-74", "label": "74"} -{"code": "\t function update_upcharge() {\n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\t\t\n\t\t//This will make sure that only the country or region that given a rate value will be saved in the db\n\t\t$upcharge = array();\n\t\tforeach($this->params['upcharge'] as $key => $item) {\n\t\t\tif(!empty($item)) {\n\t\t\t\t$upcharge[$key] = $item;\n\t\t\t}\n\t\t}\n\t\t$this->config['upcharge'] = $upcharge;\n\t\t\n $config->update(array('config'=>$this->config));\n flash('message', gt('Configuration updated'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function search() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function search() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function search_external() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.source as source, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"external_addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function search_external() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.source as source, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"external_addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction delete_vendor() {\n\t\tglobal $db;\n\t\t\n if (!empty($this->params['id'])){\n\t\t\t$db->delete('vendor', 'id =' .$this->params['id']);\n\t\t}\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction manage_vendors () {\n\t expHistory::set('viewable', $this->params);\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendors = $vendor->find('all');\n\t\tassign_to_template(array(\n 'vendors'=>$vendors\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction edit_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\tassign_to_template(array(\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " function delete() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);\n $product = new $product_type($this->params['id'], true, false);\n //eDebug($product_type); \n //eDebug($product, true);\n //if (!empty($product->product_type_id)) {\n //$db->delete($product_type, 'id='.$product->product_id);\n //}\n\n $db->delete('option', 'product_id=' . $product->id . \" AND optiongroup_id IN (SELECT id from \" . $db->prefix . \"optiongroup WHERE product_id=\" . $product->id . \")\");\n $db->delete('optiongroup', 'product_id=' . $product->id);\n //die();\n $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type=\"' . $product_type . '\"');\n\n if ($product->product_type == \"product\") {\n if ($product->hasChildren()) {\n $this->deleteChildren();\n }\n }\n\n $product->delete();\n\n flash('message', gt('Product deleted successfully.'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function searchNew() {\n global $db, $user;\n //$this->params['query'] = str_ireplace('-','\\-',$this->params['query']);\n $sql = \"select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, \";\n $sql .= \"match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) as relevance, \";\n $sql .= \"CASE when p.model like '\" . $this->params['query'] . \"%' then 1 else 0 END as modelmatch, \";\n $sql .= \"CASE when p.title like '%\" . $this->params['query'] . \"%' then 1 else 0 END as titlematch \";\n $sql .= \"from \" . $db->prefix . \"product as p INNER JOIN \" .\n $db->prefix . \"content_expFiles as cef ON p.id=cef.content_id AND cef.content_type IN ('product','eventregistration','donation','giftcard') AND cef.subtype='mainimage' INNER JOIN \" . $db->prefix .\n \"expFiles as f ON cef.expFiles_id = f.id WHERE \";\n if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';\n $sql .= \" match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) AND p.parent_id=0 \";\n $sql .= \" HAVING relevance > 0 \";\n //$sql .= \"GROUP BY p.id \"; \n $sql .= \"order by modelmatch,titlematch,relevance desc LIMIT 10\";\n\n eDebug($sql);\n $res = $db->selectObjectsBySql($sql);\n eDebug($res, true);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function categoryBreadcrumb() {\n// global $db, $router;\n\n //eDebug($this->category);\n\n /*if(isset($router->params['action']))\n {\n $ancestors = $this->category->pathToNode(); \n }else if(isset($router->params['section']))\n {\n $current = $db->selectObject('section',' id= '.$router->params['section']);\n $ancestors[] = $current;\n if( $current->parent != -1 || $current->parent != 0 )\n { \n while ($db->selectObject('section',' id= '.$router->params['section']);)\n if ($section->id == $id) {\n $current = $section;\n break;\n }\n }\n }\n eDebug($sections);\n $ancestors = $this->category->pathToNode(); \n }*/\n\n $ancestors = $this->category->pathToNode();\n // eDebug($ancestors);\n assign_to_template(array(\n 'ancestors' => $ancestors\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " static function displayname() {\r\n return \"Events\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($day as $extevent) {\r\n $event_cache = new stdClass();\r\n $event_cache->feed = $extgcalurl;\r\n $event_cache->event_id = $extevent->event_id;\r\n $event_cache->title = $extevent->title;\r\n $event_cache->body = $extevent->body;\r\n $event_cache->eventdate = $extevent->eventdate->date;\r\n if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)\r\n $event_cache->dateFinished = $extevent->dateFinished;\r\n if (isset($extevent->eventstart))\r\n $event_cache->eventstart = $extevent->eventstart;\r\n if (isset($extevent->eventend))\r\n $event_cache->eventend = $extevent->eventend;\r\n if (isset($extevent->is_allday))\r\n $event_cache->is_allday = $extevent->is_allday;\r\n $found = false;\r\n if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries\r\n $found = $db->selectObject('event_cache','feed=\"'.$extgcalurl.'\" AND event_id=\"'.$event_cache->event_id.'\" AND eventdate='.$event_cache->eventdate);\r\n if (!$found)\r\n $db->insertObject($event_cache,'event_cache');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $evs = $this->event->find('all', \"id=\" . $edate->event_id . $featuresql);\r\n foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r\n if (count($events) < 500) { // magic number to not crash loop?\r\n $events = array_merge($events, $evs);\r\n } else {\r\n// $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');\r\n// $events = array_merge($events, $evs);\r\n flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));\r\n break; // keep from breaking system by too much data\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function send_feedback() {\r\n $success = false;\r\n if (isset($this->params['id'])) {\r\n $ed = new eventdate($this->params['id']);\r\n// $email_addrs = array();\r\n if ($ed->event->feedback_email != '') {\r\n $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);\r\n $msgtemplate->assign('params', $this->params);\r\n $msgtemplate->assign('event', $ed);\r\n $email_addrs = explode(',', $ed->event->feedback_email);\r\n //This is an easy way to remove duplicates\r\n $email_addrs = array_flip(array_flip($email_addrs));\r\n $email_addrs = array_map('trim', $email_addrs);\r\n $mail = new expMail();\r\n $success += $mail->quickSend(array(\r\n \"text_message\" => $msgtemplate->render(),\r\n 'to' => $email_addrs,\r\n 'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),\r\n 'subject' => $this->params['subject'],\r\n ));\r\n }\r\n }\r\n\r\n if ($success) {\r\n flashAndFlow('message', gt('Your feedback was successfully sent.'));\r\n } else {\r\n flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function send_feedback() {\r\n $success = false;\r\n if (isset($this->params['id'])) {\r\n $ed = new eventdate($this->params['id']);\r\n// $email_addrs = array();\r\n if ($ed->event->feedback_email != '') {\r\n $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);\r\n $msgtemplate->assign('params', $this->params);\r\n $msgtemplate->assign('event', $ed);\r\n $email_addrs = explode(',', $ed->event->feedback_email);\r\n //This is an easy way to remove duplicates\r\n $email_addrs = array_flip(array_flip($email_addrs));\r\n $email_addrs = array_map('trim', $email_addrs);\r\n $mail = new expMail();\r\n $success += $mail->quickSend(array(\r\n \"text_message\" => $msgtemplate->render(),\r\n 'to' => $email_addrs,\r\n 'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),\r\n 'subject' => $this->params['subject'],\r\n ));\r\n }\r\n }\r\n\r\n if ($success) {\r\n flashAndFlow('message', gt('Your feedback was successfully sent.'));\r\n } else {\r\n flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"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": "74"} -{"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": "74"} -{"code": " public static function fixName($name) {\n $name = preg_replace('/[^A-Za-z0-9\\.]/','_',$name);\n if ($name[0] == '.')\n $name[0] = '_';\n return $name;\n// return preg_replace('/[^A-Za-z0-9\\.]/', '-', $name);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function downloadfile() {\n if (empty($this->params['fileid'])) {\n flash('error', gt('There was an error while trying to download your file. No File Specified.'));\n expHistory::back();\n }\n \n $fd = new filedownload($this->params['fileid']); \n if (empty($this->params['filenum'])) $this->params['filenum'] = 0;\n\n if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {\n flash('error', gt('There was an error while trying to download your file. The file you were looking for could not be found.'));\n expHistory::back();\n } \n \n $fd->downloads++;\n $fd->save();\n \n // this will set the id to the id of the actual file..makes the download go right.\n $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;\n parent::downloadfile(); \n }", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($nodes as $node) {\r\n if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {\r\n if ($node->active == 1) {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;\r\n } else {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';\r\n }\r\n $ar[$node->id] = $text;\r\n foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {\r\n $ar[$id] = $text;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function edit_externalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\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 }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function reparent_standalone() {\r\n $standalone = $this->section->find($this->params['page']);\r\n if ($standalone) {\r\n $standalone->parent = $this->params['parent'];\r\n $standalone->update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function showall() {\r\n global $user, $sectionObj, $sections;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // all we need to do is determine the current section\r\n $navsections = $sections;\r\n if ($sectionObj->parent == -1) {\r\n $current = $sectionObj;\r\n } else {\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n 'canManage' => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function showall() {\r\n global $user, $sectionObj, $sections;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // all we need to do is determine the current section\r\n $navsections = $sections;\r\n if ($sectionObj->parent == -1) {\r\n $current = $sectionObj;\r\n } else {\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n 'canManage' => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public static function DragnDropReRank2() {\r\n global $router, $db;\r\n\r\n $id = $router->params['id'];\r\n $page = new section($id);\r\n $old_rank = $page->rank;\r\n $old_parent = $page->parent;\r\n $new_rank = $router->params['position'] + 1; // rank\r\n $new_parent = intval($router->params['parent']);\r\n\r\n $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent); // close in hole\r\n $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent); // make room\r\n\r\n $params = array();\r\n $params['parent'] = $new_parent;\r\n $params['rank'] = $new_rank;\r\n $page->update($params);\r\n\r\n self::checkForSectionalAdmins($id);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " static function displayname() { return gt(\"Navigation\"); }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function manage_sitemap() {\r\n global $db, $user, $sectionObj, $sections;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // all we need to do is determine the current section\r\n $navsections = $sections;\r\n if ($sectionObj->parent == -1) {\r\n $current = $sectionObj;\r\n } else {\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n 'canManage' => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"code": " public static function parseAndTrim($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n //$str = str_replace(\",\",\"\\,\",$str); \n\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t $controller = new $ctlname();\n\t\t if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {\n//\t\t\t $mods[$controller->name()] = $controller->addContentToSearch();\n $mods[$controller->searchName()] = $controller->addContentToSearch();\n\t\t }\n\t }\n\t\n\t uksort($mods,'strnatcasecmp');\n\t assign_to_template(array(\n 'mods'=>$mods\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": "20"} -{"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": "20"} -{"code": " function preview()\n {\n if ($this->params['id'] == 0) { // we want the default editor\n $demo = new stdClass();\n $demo->id = 0;\n $demo->name = \"Default\";\n if ($this->params['editor'] == 'ckeditor') {\n $demo->skin = 'kama';\n } elseif ($this->params['editor'] == 'tinymce') {\n $demo->skin = 'lightgray';\n }\n } else {\n $demo = self::getEditorSettings($this->params['id'], $this->params['editor']);\n }\n assign_to_template(\n array(\n 'demo' => $demo,\n 'editor' => $this->params['editor']\n )\n );\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));\n\n if (! empty($action) && $this->actionModel->remove($action['id'])) {\n $this->flash->success(t('Action removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this action.'));\n }\n\n $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $category = $this->getCategory();\n\n $this->response->html($this->helper->layout->project('category/remove', array(\n 'project' => $project,\n 'category' => $category,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"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": "200"} -{"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": "200"} -{"code": " public function disable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->disable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function disable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->disable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " protected function getSubtask()\n {\n $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));\n\n if (empty($subtask)) {\n throw new PageNotFoundException();\n }\n\n return $subtask;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " protected function getComment()\n {\n $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));\n\n if (empty($comment)) {\n throw new PageNotFoundException();\n }\n\n if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {\n throw new AccessForbiddenException();\n }\n\n return $comment;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $comment = $this->getComment();\n\n $this->response->html($this->template->render('comment/remove', array(\n 'comment' => $comment,\n 'task' => $task,\n 'title' => t('Remove a comment')\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $comment = $this->getComment();\n\n $this->response->html($this->template->render('comment/remove', array(\n 'comment' => $comment,\n 'task' => $task,\n 'title' => t('Remove a comment')\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function fromData($data, $filename)\n {\n if ($data === null) {\n return;\n }\n\n $tempPath = temp_path(basename($filename));\n FileHelper::put($tempPath, $data);\n\n $file = $this->fromFile($tempPath);\n FileHelper::delete($tempPath);\n\n return $file;\n }", "label_name": "CWE-362", "label": "362"} -{"code": " protected function renderImageByGD($code)\n {\n $image = imagecreatetruecolor($this->width, $this->height);\n\n $backColor = imagecolorallocate(\n $image,\n (int) ($this->backColor % 0x1000000 / 0x10000),\n (int) ($this->backColor % 0x10000 / 0x100),\n $this->backColor % 0x100\n );\n imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);\n imagecolordeallocate($image, $backColor);\n\n if ($this->transparent) {\n imagecolortransparent($image, $backColor);\n }\n\n $foreColor = imagecolorallocate(\n $image,\n (int) ($this->foreColor % 0x1000000 / 0x10000),\n (int) ($this->foreColor % 0x10000 / 0x100),\n $this->foreColor % 0x100\n );\n\n $length = strlen($code);\n $box = imagettfbbox(30, 0, $this->fontFile, $code);\n $w = $box[4] - $box[0] + $this->offset * ($length - 1);\n $h = $box[1] - $box[5];\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);\n $angle = mt_rand(-10, 10);\n $letter = $code[$i];\n $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);\n $x = $box[2] + $this->offset;\n }\n\n imagecolordeallocate($image, $foreColor);\n\n ob_start();\n imagepng($image);\n imagedestroy($image);\n\n return ob_get_clean();\n }", "label_name": "CWE-330", "label": "330"} -{"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": "330"} -{"code": " public function validateMulti(array $credentialCandidates)\n {\n $lastException = null;\n\n foreach ($credentialCandidates as $credential) {\n if (false == $credential instanceof CredentialInterface) {\n throw new \\InvalidArgumentException('Expected CredentialInterface');\n }\n if (null == $credential->getPublicKey()) {\n continue;\n }\n\n try {\n $result = $this->validate($credential->getPublicKey());\n\n if ($result === false) {\n return;\n }\n\n return $credential;\n } catch (LightSamlSecurityException $ex) {\n $lastException = $ex;\n }\n }\n\n if ($lastException) {\n throw $lastException;\n } else {\n throw new LightSamlSecurityException('No public key available for signature verification');\n }\n }", "label_name": "CWE-732", "label": "732"} -{"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": "20"} -{"code": " public function testPOSTForRestProjectManager()\n {\n $post_resource = json_encode([\n 'label' => 'Test Request 9748',\n 'shortname' => 'test9748',\n 'description' => 'Test of Request 9748 for REST API Project Creation',\n 'is_public' => true,\n 'template_id' => 100,\n ]);\n\n $response = $this->getResponseByName(\n REST_TestDataBuilder::TEST_USER_DELEGATED_REST_PROJECT_MANAGER_NAME,\n $this->request_factory->createRequest(\n 'POST',\n 'projects'\n )->withBody(\n $this->stream_factory->createStream(\n $post_resource\n )\n )\n );\n\n $project = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);\n self::assertEquals(201, $response->getStatusCode());\n self::assertArrayHasKey(\"id\", $project);\n }", "label_name": "CWE-863", "label": "863"} -{"code": " function prepareInputForUpdate($input) {\n\n if (isset($input[\"rootdn_passwd\"])) {\n if (empty($input[\"rootdn_passwd\"])) {\n unset($input[\"rootdn_passwd\"]);\n } else {\n $input[\"rootdn_passwd\"] = Toolbox::encrypt(stripslashes($input[\"rootdn_passwd\"]),\n GLPIKEY);\n }\n }\n\n if (isset($input[\"_blank_passwd\"]) && $input[\"_blank_passwd\"]) {\n $input['rootdn_passwd'] = '';\n }\n\n // Set attributes in lower case\n if (count($input)) {\n foreach ($input as $key => $val) {\n if (preg_match('/_field$/', $key)) {\n $input[$key] = Toolbox::strtolower($val);\n }\n }\n }\n\n //do not permit to override sync_field\n if ($this->isSyncFieldEnabled()\n && isset($input['sync_field'])\n && $this->isSyncFieldUsed()\n ) {\n if ($input['sync_field'] == $this->fields['sync_field']) {\n unset($input['sync_field']);\n } else {\n Session::addMessageAfterRedirect(\n __('Synchronization field cannot be changed once in use.'),\n false,\n ERROR\n );\n return false;\n };\n }\n return $input;\n }", "label_name": "CWE-327", "label": "327"} -{"code": " function prepareInputForAdd($input) {\n\n //If it's the first ldap directory then set it as the default directory\n if (!self::getNumberOfServers()) {\n $input['is_default'] = 1;\n }\n\n if (isset($input[\"rootdn_passwd\"]) && !empty($input[\"rootdn_passwd\"])) {\n $input[\"rootdn_passwd\"] = Toolbox::encrypt(stripslashes($input[\"rootdn_passwd\"]), GLPIKEY);\n }\n\n return $input;\n }", "label_name": "CWE-327", "label": "327"} -{"code": " function __construct(bool $connect = false) {\n global $CFG_GLPI;\n\n $options = [\n 'base_uri' => GLPI_MARKETPLACE_PLUGINS_API_URI,\n 'connect_timeout' => self::TIMEOUT,\n ];\n\n // add proxy string if configured in glpi\n if (!empty($CFG_GLPI[\"proxy_name\"])) {\n $proxy_creds = !empty($CFG_GLPI[\"proxy_user\"])\n ? $CFG_GLPI[\"proxy_user\"].\":\".Toolbox::decrypt($CFG_GLPI[\"proxy_passwd\"], GLPIKEY).\"@\"\n : \"\";\n $proxy_string = \"http://{$proxy_creds}\".$CFG_GLPI['proxy_name'].\":\".$CFG_GLPI['proxy_port'];\n $options['proxy'] = $proxy_string;\n }\n\n // init guzzle client with base options\n $this->httpClient = new Guzzle_Client($options);\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public function getAcl($node) {\n if (is_string($node)) {\n $node = $this->server->tree->getNodeForPath($node);\n }\n\n $acl = parent::getAcl($node);\n\n // Authenticated user have read access to all nodes, as node list only contains elements\n // that user can read.\n $acl[] = [\n 'principal' => '{DAV:}authenticated',\n 'privilege' => '{DAV:}read',\n 'protected' => true,\n ];\n\n if ($node instanceof Calendar && \\Session::haveRight(\\PlanningExternalEvent::$rightname, UPDATE)) {\n // If user can update external events, then he is able to write on calendar to create new events.\n $acl[] = [\n 'principal' => '{DAV:}authenticated',\n 'privilege' => '{DAV:}write',\n 'protected' => true,\n ];\n } else if ($node instanceof CalendarObject) {\n $item = $this->getCalendarItemForPath($node->getName());\n if ($item instanceof \\CommonDBTM && $item->can($item->fields['id'], UPDATE)) {\n $acl[] = [\n 'principal' => '{DAV:}authenticated',\n 'privilege' => '{DAV:}write',\n 'protected' => true,\n ];\n }\n }\n\n return $acl;\n }", "label_name": "CWE-862", "label": "862"} -{"code": "\tfunction test_allowed_anon_comments() {\n\t\tadd_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );\n\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'',\n\t\t\t'',\n\t\t\tself::$post->ID,\n\t\t\tarray(\n\t\t\t\t'author' => 'WordPress',\n\t\t\t\t'author_email' => 'noreply@wordpress.org',\n\t\t\t\t'content' => 'Test Anon Comments',\n\t\t\t),\n\t\t);\n\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$this->assertNotIXRError( $result );\n\t\t$this->assertInternalType( 'int', $result );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": "\tfunction test_new_comment_duplicated() {\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'administrator',\n\t\t\t'administrator',\n\t\t\tself::$post->ID,\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": "862"} -{"code": "\tfunction test_empty_comment() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => '',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": "862"} -{"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": "862"} -{"code": "\t\tforeach($row as $key => $value) {\n\t\t\t$type = gettype($value);\n\t\t\t$sqltype=NULL;\n\t\t\tswitch($type) {\n\t\t\t\tcase \"integer\":\n\t\t\t\t\t$sqltype = SQLITE3_INTEGER;\n\t\t\t\tbreak;\n\t\t\t\tcase \"string\":\n\t\t\t\t\t$sqltype = SQLITE3_TEXT;\n\t\t\t\tbreak;\n\t\t\t\tcase \"NULL\":\n\t\t\t\t\t$sqltype = SQLITE3_NULL;\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t$sqltype = \"UNK\";\n\t\t\t}\n\t\t\t$stmt->bindValue(\":\".$key, $value, $sqltype);\n\t\t}", "label_name": "CWE-862", "label": "862"} -{"code": " public static function showModal($params) {\n\n if (!isset($params['argument']) || empty($params['argument'])) {\n return array(\n 'processed' => true,\n 'process_status' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/chatcommand', 'Please provide modal URL!')\n );\n }\n\n $paramsURL = explode(' ',$params['argument']);\n $URL = array_shift($paramsURL);\n\n if (is_numeric($URL)) {\n $URL = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . erLhcoreClassDesign::baseurldirect('form/formwidget') . '/' . $URL;\n }", "label_name": "CWE-116", "label": "116"} -{"code": "\t\t$params = ['uitype' => 71, 'displaytype' => 1, 'typeofdata' => 'N~O', 'isEditableReadOnly' => false, 'maximumlength' => '99999999999999999'];", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function validate($value, $isUserFormat = false)\n\t{\n\t\tif (empty($value)) {\n\t\t\treturn;\n\t\t}\n\t\tif (\\is_string($value)) {\n\t\t\t$value = \\App\\Json::decode($value);\n\t\t}\n\t\tif (!\\is_array($value)) {\n\t\t\tthrow new \\App\\Exceptions\\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $value, 406);\n\t\t}\n\t\t$currencies = \\App\\Fields\\Currency::getAll(true);\n\t\tforeach ($value['currencies'] ?? [] as $id => $currency) {\n\t\t\tif (!isset($currencies[$id])) {\n\t\t\t\tthrow new \\App\\Exceptions\\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $id, 406);\n\t\t\t}\n\t\t\t$price = $currency['price'];\n\t\t\tif ($isUserFormat) {\n\t\t\t\t$price = App\\Fields\\Double::formatToDb($price);\n\t\t\t}\n\t\t\tif (!is_numeric($price)) {\n\t\t\t\tthrow new \\App\\Exceptions\\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $price, 406);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic static function dplParserFunction( &$parser ) {\n\t\tself::setLikeIntersection( false );\n\n\t\t$parser->addTrackingCategory( 'dpl-parserfunc-tracking-category' );\n\n\t\t// callback for the parser function {{#dpl:\t or {{DynamicPageList::\n\t\t$input = \"\";\n\n\t\t$numargs = func_num_args();\n\t\tif ( $numargs < 2 ) {\n\t\t\t$input = \"#dpl: no arguments specified\";\n\t\t\treturn str_replace( '\u00a7', '<', '\u00a7pre>\u00a7nowiki>' . $input . '\u00a7/nowiki>\u00a7/pre>' );\n\t\t}\n\n\t\t// fetch all user-provided arguments (skipping $parser)\n\t\t$arg_list = func_get_args();\n\t\tfor ( $i = 1; $i < $numargs; $i++ ) {\n\t\t\t$p1 = $arg_list[$i];\n\t\t\t$input .= str_replace( \"\\n\", \"\", $p1 ) . \"\\n\";\n\t\t}\n\n\t\t$parse = new \\DPL\\Parse();\n\t\t$dplresult = $parse->parse( $input, $parser, $reset, $eliminate, false );\n\t\treturn [ // parser needs to be coaxed to do further recursive processing\n\t\t\t$parser->getPreprocessor()->preprocessToObj( $dplresult, Parser::PTD_FOR_INCLUSION ),\n\t\t\t'isLocalObj' => true,\n\t\t\t'title' => $parser->getTitle()\n\t\t];\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tprivate static function executeTag( $input, array $args, Parser $parser, PPFrame $frame ) {\n\t\t// entry point for user tag or \n\t\t// create list and do a recursive parse of the output\n\n\t\t$parse = new \\DPL\\Parse();\n\t\tif ( \\DPL\\Config::getSetting( 'recursiveTagParse' ) ) {\n\t\t\t$input = $parser->recursiveTagParse( $input, $frame );\n\t\t}\n\n\t\t$text = $parse->parse( $input, $parser, $reset, $eliminate, true );\n\n\t\tif ( isset( $reset['templates'] ) && $reset['templates'] ) {\t// we can remove the templates by save/restore\n\t\t\t$saveTemplates = $parser->getOutput()->mTemplates;\n\t\t}\n\t\tif ( isset( $reset['categories'] ) && $reset['categories'] ) {\t// we can remove the categories by save/restore\n\t\t\t$saveCategories = $parser->getOutput()->mCategories;\n\t\t}\n\t\tif ( isset( $reset['images'] ) && $reset['images'] ) {\t// we can remove the images by save/restore\n\t\t\t$saveImages = $parser->getOutput()->mImages;\n\t\t}\n\t\t$parsedDPL = $parser->recursiveTagParse( $text );\n\t\tif ( isset( $reset['templates'] ) && $reset['templates'] ) {\n\t\t\t$parser->getOutput()->mTemplates = $saveTemplates;\n\t\t}\n\t\tif ( isset( $reset['categories'] ) && $reset['categories'] ) {\n\t\t\t$parser->getOutput()->mCategories = $saveCategories;\n\t\t}\n\t\tif ( isset( $reset['images'] ) && $reset['images'] ) {\n\t\t\t$parser->getOutput()->mImages = $saveImages;\n\t\t}\n\n\t\treturn $parsedDPL;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\t\t\t$dplArg = $this->wgRequest->getVal( $arg, '' );\n\t\t\tif ( $dplArg == '' ) {\n\t\t\t\t$input = preg_replace( '/\\{%' . $arg . ':(.*)%\\}/U', '\\1', $input );\n\t\t\t\t$input = str_replace( '{%' . $arg . '%}', '', $input );\n\t\t\t} else {\n\t\t\t\t$input = preg_replace( '/\\{%' . $arg . ':.*%\\}/U ', $dplArg, $input );\n\t\t\t\t$input = str_replace( '{%' . $arg . '%}', $dplArg, $input );\n\t\t\t}\n\t\t}\n\t\treturn $input;\n\t}", "label_name": "CWE-400", "label": "400"} -{"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": "400"} -{"code": "\tprivate function _categoriesminmax( $option ) {\n\t\tif ( is_numeric( $option[0] ) ) {\n\t\t\t$this->addWhere( intval( $option[0] ) . ' <= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );\n\t\t}\n\t\tif ( is_numeric( $option[1] ) ) {\n\t\t\t$this->addWhere( intval( $option[1] ) . ' >= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\t\t\t$temp_result_value = str_replace( $search, $v, $subject );\n\t\t\t$rendered_values[] = $temp_result_value;\n\t\t}\n\t\treturn [\n\t\t\timplode( $delimiter, $rendered_values ),\n\t\t\t'noparse'\t=> false,\n\t\t\t'isHTML'\t=> false\n\t\t];\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function __construct( \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\tparent::__construct( $parameters, $parser );\n\t\t$this->textSeparator = $parameters->getParameter( 'inlinetext' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function formatTemplateArg( $arg, $s, $argNr, $firstCall, $maxLength, Article $article ) {\n\t\t$tableFormat = $this->getParameters()->getParameter( 'tablerow' );\n\t\t// we could try to format fields differently within the first call of a template\n\t\t// currently we do not make such a difference\n\n\t\t// if the result starts with a '-' we add a leading space; thus we avoid a misinterpretation of |- as\n\t\t// a start of a new row (wiki table syntax)\n\t\tif ( array_key_exists( \"$s.$argNr\", $tableFormat ) ) {\n\t\t\t$n = -1;\n\t\t\tif ( $s >= 1 && $argNr == 0 && !$firstCall ) {\n\t\t\t\t$n = strpos( $tableFormat[\"$s.$argNr\"], '|' );\n\t\t\t\tif ( $n === false || !( strpos( substr( $tableFormat[\"$s.$argNr\"], 0, $n ), '{' ) === false ) || !( strpos( substr( $tableFormat[\"$s.$argNr\"], 0, $n ), '[' ) === false ) ) {\n\t\t\t\t\t$n = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$result = str_replace( '%%', $arg, substr( $tableFormat[\"$s.$argNr\"], $n + 1 ) );\n\t\t\t$result = str_replace( '%PAGE%', $article->mTitle->getPrefixedText(), $result );\n\t\t\t$result = str_replace( '%IMAGE%', $this->parseImageUrlWithPath( $arg ), $result ); //@TODO: This just blindly passes the argument through hoping it is an image. --Alexia\n\t\t\t$result = $this->cutAt( $maxLength, $result );\n\t\t\tif ( strlen( $result ) > 0 && $result[0] == '-' ) {\n\t\t\t\treturn ' ' . $result;\n\t\t\t} else {\n\t\t\t\treturn $result;\n\t\t\t}\n\t\t}\n\t\t$result = $this->cutAt( $maxLength, $arg );\n\t\tif ( strlen( $result ) > 0 && $result[0] == '-' ) {\n\t\t\treturn ' ' . $result;\n\t\t} else {\n\t\t\treturn $result;\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function setPageTextMatch( array $pageTextMatch = [] ) {\n\t\t$this->pageTextMatch = (array)$pageTextMatch;\n\t}", "label_name": "CWE-400", "label": "400"} -{"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": "287"} -{"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": "610"} -{"code": "\t\tpublic function renameRemote($oldName, $newName)\n\t\t{\n\t\t\t$this->run('remote', 'rename', $oldName, $newName);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\t\t\t\t$this->run('rm', $item, '-r');\n\t\t\t}\n\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\t\tpublic function renameTag($oldName, $newName)\n\t\t{\n\t\t\t// http://stackoverflow.com/a/1873932\n\t\t\t// create new as alias to old (`git tag NEW OLD`)\n\t\t\t$this->run('tag', $newName, $oldName);\n\t\t\t// delete old (`git tag -d OLD`)\n\t\t\t$this->removeTag($oldName);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": " public function getCookiePathsDataProvider()\n {\n return [\n ['', '/'],\n ['/', '/'],\n ['/foo', '/'],\n ['/foo/bar', '/foo'],\n ['/foo/bar/', '/foo/bar'],\n ['foo', '/'],\n ['foo/bar', '/'],\n ['foo/bar/', '/'],\n ];\n }", "label_name": "CWE-200", "label": "200"} -{"code": " self::assertSame($shouldBePresent, $request->hasHeader('Authorization'));\n self::assertSame($shouldBePresent, $request->hasHeader('Cookie'));\n\n return new Response(200);\n }\n ]);", "label_name": "CWE-200", "label": "200"} -{"code": "TagCreationContainer.prototype._resizeTag = function(textfield) {\n var that = this; \n\n x2.DEBUG && console.log ('_resizeTag');\n $(textfield).each(function() {\n that.textsize.html(encodeURIComponent($(this).val()));\n x2.DEBUG && console.log ('that.textsize.width = ' + that.textsize.width ());\n $(this).css('width', (that.textsize.width() + 10) + 'px');\n });\n\n return $(textfield);\n};", "label_name": "CWE-20", "label": "20"} -{"code": " self._getForwarded = function(message) {\n\n try {\n var forwarded_message = $(message.getNode()).find('forwarded[xmlns=\"' + NS_URN_FORWARD + '\"]:first message:first');\n\n if(forwarded_message[0]) {\n return JSJaCPacket.wrapNode(forwarded_message[0]);\n }\n\n return null;\n } catch(e) {\n Console.error('Carbons._getForwarded', e);\n }\n\n };", "label_name": "CWE-346", "label": "346"} -{"code": "DotObject.prototype.dot = function (obj, tgt, path) {\n tgt = tgt || {}\n path = path || []\n var isArray = Array.isArray(obj)\n\n Object.keys(obj).forEach(function (key) {\n var index = isArray && this.useBrackets ? '[' + key + ']' : key\n if (\n (\n isArrayOrObject(obj[key]) &&\n (\n (isObject(obj[key]) && !isEmptyObject(obj[key])) ||\n (Array.isArray(obj[key]) && (!this.keepArray && (obj[key].length !== 0)))\n )\n )\n ) {\n if (isArray && this.useBrackets) {\n var previousKey = path[path.length - 1] || ''\n return this.dot(obj[key], tgt, path.slice(0, -1).concat(previousKey + index))\n } else {\n return this.dot(obj[key], tgt, path.concat(index))\n }\n } else {\n if (isArray && this.useBrackets) {\n tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key]\n } else {\n tgt[path.concat(index).join(this.separator)] = obj[key]\n }\n }\n }.bind(this))\n return tgt\n}", "label_name": "CWE-74", "label": "74"} -{"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": "20"} -{"code": " preload: path.resolve(basePath, './build/preload.js')\n }\n };\n\n mainWindow = new BrowserWindow(options);\n windowState.manage(mainWindow);\n mainWindow.loadURL(indexURL);\n\n initPopupsConfigurationMain(mainWindow);\n setupAlwaysOnTopMain(mainWindow);\n setupPowerMonitorMain(mainWindow);\n setupScreenSharingMain(mainWindow, config.default.appName);\n\n mainWindow.webContents.on('new-window', (event, url, frameName) => {\n const target = getPopupTarget(url, frameName);\n\n if (!target || target === 'browser') {\n event.preventDefault();\n shell.openExternal(url);\n }\n });\n mainWindow.on('closed', () => {\n mainWindow = null;\n });\n mainWindow.once('ready-to-show', () => {\n mainWindow.show();\n });\n\n /**\n * This is for windows [win32]\n * so when someone tries to enter something like jitsi-meet://test\n * while app is closed\n * it will trigger this event below\n */\n if (process.platform === 'win32') {\n handleProtocolCall(process.argv.pop());\n }\n}", "label_name": "CWE-345", "label": "345"} -{"code": "c,b){var e=function(h,f,l){var p=function(n){n&&(this.res=n)};p.prototype=h;p.prototype.constructor=p;h=new p(l);for(var k in f||{})l=f[k],h[k]=l.slice?l.slice():l;return h},g={res:e(c.res,b.res)};g.formatter=e(c.formatter,b.formatter,g.res);g.parser=e(c.parser,b.parser,g.res);t[a]=g};d.compile=function(a){for(var c=/\\[([^\\[\\]]*|\\[[^\\[\\]]*\\])*\\]|([A-Za-z])\\2+|\\.{3}|./g,b,e=[a];b=c.exec(a);)e[e.length]=b[0];return e};d.format=function(a,c,b){c=\"string\"===typeof c?d.compile(c):c;a=d.addMinutes(a,b?", "label_name": "CWE-400", "label": "400"} -{"code": "b.Z||840a.Y?22801:1,b||a.Z?new Date(Date.UTC(a.Y,a.M,a.D,a.H,a.m+a.Z,a.s,a.S)):new Date(a.Y,a.M,a.D,a.H,a.m,a.s,a.S)):new Date(NaN)};d.transform=function(a,c,b,e){return d.format(d.parse(a,c),b,e)};d.addYears=function(a,c){return d.addMonths(a,12*c)};d.addMonths=function(a,c){var b=new Date(a.getTime());b.setMonth(b.getMonth()+c);return b};d.addDays=function(a,c){var b=new Date(a.getTime());b.setDate(b.getDate()+c);return b};", "label_name": "CWE-400", "label": "400"} -{"code": " getHasOwnProperty: function(element, property) {\n var key = element + '.' + property;\n var own = this.current().own;\n if (!own.hasOwnProperty(key)) {\n own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');\n }\n return own[key];\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function toJson(obj, pretty) {\n if (isUndefined(obj)) return undefined;\n if (!isNumber(pretty)) {\n pretty = pretty ? 2 : null;\n }\n return JSON.stringify(obj, toJsonReplacer, pretty);\n}", "label_name": "CWE-74", "label": "74"} -{"code": "function assertNotHasOwnProperty(name, context) {\n if (name === 'hasOwnProperty') {\n throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n }\n}", "label_name": "CWE-74", "label": "74"} -{"code": "function inherit(parent, extra) {\n return extend(Object.create(parent), extra);\n}", "label_name": "CWE-74", "label": "74"} -{"code": "function hasCustomToString(obj) {\n return isFunction(obj.toString) && obj.toString !== toString;\n}", "label_name": "CWE-74", "label": "74"} -{"code": "var manualLowercase = function(s) {\n /* eslint-disable no-bitwise */\n return isString(s)\n ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\n : s;\n /* eslint-enable */\n};", "label_name": "CWE-74", "label": "74"} -{"code": " return scope.$watch(function expressionInputsWatch(scope) {\n var changed = false;\n\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n var newInputValue = inputExpressions[i](scope);\n if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\n oldInputValues[i] = newInputValue;\n oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n }\n }\n\n if (changed) {\n lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);\n }\n\n return lastResult;\n }, listener, objectEquality, prettyPrintExpression);", "label_name": "CWE-74", "label": "74"} -{"code": " isIdentifierContinue: function(ch) {\n return this.options.isIdentifierContinue ?\n this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :\n this.isValidIdentifierContinue(ch);\n },", "label_name": "CWE-74", "label": "74"} -{"code": " identifier: function(name, context, create) {\n return function(scope, locals, assign, inputs) {\n var base = locals && (name in locals) ? locals : scope;\n if (create && create !== 1 && base && base[name] == null) {\n base[name] = {};\n }\n var value = base ? base[name] : undefined;\n if (context) {\n return {context: base, name: name, value: value};\n } else {\n return value;\n }\n };\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function nextUid() {\n return ++uid;\n}", "label_name": "CWE-74", "label": "74"} -{"code": "function extend(dst) {\n return baseExtend(dst, slice.call(arguments, 1), false);\n}", "label_name": "CWE-74", "label": "74"} -{"code": "function forEach(obj, iterator, context) {\n var key, length;\n if (obj) {\n if (isFunction(obj)) {\n for (key in obj) {\n if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n } else if (isArray(obj) || isArrayLike(obj)) {\n var isPrimitive = typeof obj !== 'object';\n for (key = 0, length = obj.length; key < length; key++) {\n if (isPrimitive || key in obj) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n } else if (obj.forEach && obj.forEach !== forEach) {\n obj.forEach(iterator, context, obj);\n } else if (isBlankObject(obj)) {\n // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n for (key in obj) {\n iterator.call(context, obj[key], key, obj);\n }\n } else if (typeof obj.hasOwnProperty === 'function') {\n // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n } else {\n // Slow path for objects which do not have a method `hasOwnProperty`\n for (key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n iterator.call(context, obj[key], key, obj);\n }\n }\n }\n }\n return obj;\n}", "label_name": "CWE-74", "label": "74"} -{"code": "var jq = function() {\n if (isDefined(jq.name_)) return jq.name_;\n var el;\n var i, ii = ngAttrPrefixes.length, prefix, name;\n for (i = 0; i < ii; ++i) {\n prefix = ngAttrPrefixes[i];\n el = window.document.querySelector('[' + prefix.replace(':', '\\\\:') + 'jq]');\n if (el) {\n name = el.getAttribute(prefix + 'jq');\n break;\n }\n }\n\n return (jq.name_ = name);\n};", "label_name": "CWE-74", "label": "74"} -{"code": " left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};\n }\n return left;\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function isDefined(value) {return typeof value !== 'undefined';}", "label_name": "CWE-74", "label": "74"} -{"code": " identifier: function() {\n var token = this.consume();\n if (!token.identifier) {\n this.throwError('is not a valid identifier', token);\n }\n return { type: AST.Identifier, name: token.text };\n },", "label_name": "CWE-74", "label": "74"} -{"code": " lazyAssign: function(id, value) {\n var self = this;\n return function() {\n self.assign(id, value);\n };\n },", "label_name": "CWE-74", "label": "74"} -{"code": " is: function(ch, chars) {\n return chars.indexOf(ch) !== -1;\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function toKeyValue(obj) {\n var parts = [];\n forEach(obj, function(value, key) {\n if (isArray(value)) {\n forEach(value, function(arrayValue) {\n parts.push(encodeUriQuery(key, true) +\n (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\n });\n } else {\n parts.push(encodeUriQuery(key, true) +\n (value === true ? '' : '=' + encodeUriQuery(value, true)));\n }\n });\n return parts.length ? parts.join('&') : '';\n}", "label_name": "CWE-74", "label": "74"} -{"code": " not: function(expression) {\n return '!(' + expression + ')';\n },", "label_name": "CWE-74", "label": "74"} -{"code": " throwError: function(error, start, end) {\n end = end || this.index;\n var colStr = (isDefined(start)\n ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n : ' ' + end);\n throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n error, colStr, this.text);\n },", "label_name": "CWE-74", "label": "74"} -{"code": " text: this.text.slice(start, this.index),\n identifier: true\n });\n },", "label_name": "CWE-74", "label": "74"} -{"code": "var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};", "label_name": "CWE-74", "label": "74"} -{"code": " 'binary<': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function fromJson(json) {\n return isString(json)\n ? JSON.parse(json)\n : json;\n}", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction jqMix(obj, props){\n\t\t// summary:\n\t\t//\t\tan attempt at a mixin that follows\n\t\t//\t\tjquery's .extend rules. Seems odd. Not sure how\n\t\t//\t\tto resolve this with dojo.mixin and what the use\n\t\t//\t\tcases are for the jquery version.\n\t\t//\t\tCopying some code from dojo._mixin.\n\t\tif(obj == props){\n\t\t\treturn obj;\n\t\t}\n\t\tvar tobj = {};\n\t\tfor(var x in props){\n\t\t\t// the \"tobj\" condition avoid copying properties in \"props\"\n\t\t\t// inherited from Object.prototype. For example, if obj has a custom\n\t\t\t// toString() method, don't overwrite it with the toString() method\n\t\t\t// that props inherited from Object.prototype\n\t\t\tif((tobj[x] === undefined || tobj[x] != props[x]) && props[x] !== undefined && obj != props[x]){\n\t\t\t\tif(dojo.isObject(obj[x]) && dojo.isObject(props[x])){\n\t\t\t\t\tif(dojo.isArray(props[x])){\n\t\t\t\t\t\tobj[x] = props[x];\n\t\t\t\t\t}else{\n\t\t\t\t\t\tobj[x] = jqMix(obj[x], props[x]);\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tobj[x] = props[x];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// IE doesn't recognize custom toStrings in for..in\n\t\tif(dojo.isIE && props){\n\t\t\tvar p = props.toString;\n\t\t\tif(typeof p == \"function\" && p != obj.toString && p != tobj.toString &&\n\t\t\t\tp != \"\\nfunction toString() {\\n [native code]\\n}\\n\"){\n\t\t\t\t\tobj.toString = props.toString;\n\t\t\t}\n\t\t}\n\t\treturn obj; // Object\n\t}", "label_name": "CWE-74", "label": "74"} -{"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": "77"} -{"code": "export function getInnerText (element, buffer) {\n const first = (buffer === undefined)\n if (first) {\n buffer = {\n _text: '',\n flush: function () {\n const text = this._text\n this._text = ''\n return text\n },\n set: function (text) {\n this._text = text\n }\n }\n }\n\n // text node\n if (element.nodeValue) {\n // remove return characters and the whitespace surrounding return characters\n const trimmedValue = element.nodeValue.replace(/\\s*\\n\\s*/g, '')\n if (trimmedValue !== '') {\n return buffer.flush() + trimmedValue\n } else {\n // ignore empty text\n return ''\n }\n }\n\n // divs or other HTML elements\n if (element.hasChildNodes()) {\n const childNodes = element.childNodes\n let innerText = ''\n\n for (let i = 0, iMax = childNodes.length; i < iMax; i++) {\n const child = childNodes[i]\n\n if (child.nodeName === 'DIV' || child.nodeName === 'P') {\n const prevChild = childNodes[i - 1]\n const prevName = prevChild ? prevChild.nodeName : undefined\n if (prevName && prevName !== 'DIV' && prevName !== 'P' && prevName !== 'BR') {\n if (innerText !== '') {\n innerText += '\\n'\n }\n buffer.flush()\n }\n innerText += getInnerText(child, buffer)\n buffer.set('\\n')\n } else if (child.nodeName === 'BR') {\n innerText += buffer.flush()\n buffer.set('\\n')\n } else {\n innerText += getInnerText(child, buffer)\n }\n }\n\n return innerText\n }\n\n // br or unknown\n return ''\n}", "label_name": "CWE-400", "label": "400"} -{"code": "exports.quote = function (xs) {\n return xs.map(function (s) {\n if (s && typeof s === 'object') {\n return s.op.replace(/(.)/g, '\\\\$1');\n }\n else if (/[\"\\s]/.test(s) && !/'/.test(s)) {\n return \"'\" + s.replace(/(['\\\\])/g, '\\\\$1') + \"'\";\n }\n else if (/[\"'\\s]/.test(s)) {\n return '\"' + s.replace(/([\"\\\\$`!])/g, '\\\\$1') + '\"';\n }\n else {\n return String(s).replace(/([A-z]:)?([#!\"$&'()*,:;<=>?@\\[\\\\\\]^`{|}])/g, '$1\\\\$2');\n }\n }).join(' ');\n};", "label_name": "CWE-77", "label": "77"} -{"code": "Format.prototype.refresh=function(){null!=this.editorUi.getCurrentFile()||\"1\"==urlParams.embed||this.editorUi.editor.chromeless?l.apply(this,arguments):this.clear()};DiagramFormatPanel.prototype.isShadowOptionVisible=function(){var u=this.editorUi.getCurrentFile();return\"1\"==urlParams.embed||null!=u&&u.isEditable()};DiagramFormatPanel.prototype.isMathOptionVisible=function(u){return!1};var p=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(u){u=p.apply(this,arguments);\nthis.editorUi.getCurrentFile();if(mxClient.IS_SVG&&this.isShadowOptionVisible()){var E=this.editorUi,J=E.editor.graph,T=this.createOption(mxResources.get(\"shadow\"),function(){return J.shadowVisible},function(N){var Q=new ChangePageSetup(E);Q.ignoreColor=!0;Q.ignoreImage=!0;Q.shadowVisible=N;J.model.execute(Q)},{install:function(N){this.listener=function(){N(J.shadowVisible)};E.addListener(\"shadowVisibleChanged\",this.listener)},destroy:function(){E.removeListener(this.listener)}});Editor.enableShadowOption||\n(T.getElementsByTagName(\"input\")[0].setAttribute(\"disabled\",\"disabled\"),mxUtils.setOpacity(T,60));u.appendChild(T)}return u};var q=DiagramFormatPanel.prototype.addOptions;DiagramFormatPanel.prototype.addOptions=function(u){u=q.apply(this,arguments);var E=this.editorUi,J=E.editor.graph;if(J.isEnabled()){var T=E.getCurrentFile();if(null!=T&&T.isAutosaveOptional()){var N=this.createOption(mxResources.get(\"autosave\"),function(){return E.editor.autosave},function(R){E.editor.setAutosave(R);E.editor.autosave&&", "label_name": "CWE-20", "label": "20"} -{"code": "Editor.enableExportUrl=!0;Editor.compressXml=!0;Editor.oneDriveInlinePicker=null!=window.urlParams&&\"0\"==window.urlParams.inlinePicker?!1:!0;Editor.globalVars=null;Editor.config=null;Editor.configVersion=null;Editor.defaultBorder=5;Editor.commonProperties=[{name:\"enumerate\",dispName:\"Enumerate\",type:\"bool\",defVal:!1,onChange:function(u){u.refresh()}},{name:\"enumerateValue\",dispName:\"Enumerate Value\",type:\"string\",defVal:\"\",isVisible:function(u,E){return\"1\"==mxUtils.getValue(u.style,\"enumerate\",\"0\")}},", "label_name": "CWE-20", "label": "20"} -{"code": "null,\"Error fetching folder items\")+(null!=Ca?\" (\"+Ca+\")\":\"\"));V=!1;P.stop()}})}}function L(N){J.className=J.className.replace(\"odCatSelected\",\"\");J=N;J.className+=\" odCatSelected\"}function C(N){V||(T=null,z(\"search\",null,null,null,N))}var D=\"\";null==e&&(e=I,D='
');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": "20"} -{"code": "index:J,defVal:ja.defVal,countProperty:ja.countProperty,size:ja.size},0==J%2,ja.flipBkg),E.parentNode.insertBefore(Ga,E.nextSibling),E=Ga;u.appendChild(va);ra();return u};StyleFormatPanel.prototype.addStyles=function(u){function E(ja){mxEvent.addListener(ja,\"mouseenter\",function(){ja.style.opacity=\"1\"});mxEvent.addListener(ja,\"mouseleave\",function(){ja.style.opacity=\"0.5\"})}var J=this.editorUi,T=J.editor.graph,N=document.createElement(\"div\");N.style.whiteSpace=\"nowrap\";N.style.paddingLeft=\"24px\";", "label_name": "CWE-20", "label": "20"} -{"code": "var O=mxText.prototype.redraw;mxText.prototype.redraw=function(){O.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(u,E,J){function T(){for(var ja=R.getSelectionCells(),Ba=[],Ha=0;Ha=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": "20"} -{"code": "\"url(\"+mxWindow.prototype.normalizeImage+\")\";aa.style.backgroundPosition=\"top center\";aa.style.backgroundRepeat=\"no-repeat\";aa.setAttribute(\"title\",\"Minimize\");var va=!1,ja=mxUtils.bind(this,function(){N.innerHTML=\"\";if(!va){var da=function(ia,ma,qa){ia=D(\"\",ia.funct,null,ma,ia,qa);ia.style.width=\"40px\";ia.style.opacity=\"0.7\";return ca(ia,null,\"pointer\")},ca=function(ia,ma,qa){null!=ma&&ia.setAttribute(\"title\",ma);ia.style.cursor=null!=qa?qa:\"default\";ia.style.margin=\"2px 0px\";N.appendChild(ia);mxUtils.br(N);", "label_name": "CWE-20", "label": "20"} -{"code": "this.graph.isMouseDown=!0;x.hoverIcons.reset();mxEvent.consume(H)})))};var P=mxVertexHandler.prototype.redrawHandles;mxVertexHandler.prototype.redrawHandles=function(){P.apply(this,arguments);null!=this.moveHandle&&(this.moveHandle.style.left=this.state.x+this.state.width+(40>this.state.width?10:0)+2+\"px\",this.moveHandle.style.top=this.state.y+this.state.height+(40>this.state.height?10:0)+2+\"px\")};var K=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(H){K.apply(this,\narguments);null!=this.moveHandle&&(this.moveHandle.style.display=H?\"\":\"none\")};var F=mxVertexHandler.prototype.destroy;mxVertexHandler.prototype.destroy=function(H,S){F.apply(this,arguments);null!=this.moveHandle&&(this.moveHandle.parentNode.removeChild(this.moveHandle),this.moveHandle=null)}};if(\"undefined\"!==typeof Sidebar){var f=Sidebar.prototype.createAdvancedShapes;Sidebar.prototype.createAdvancedShapes=function(){var c=f.apply(this,arguments),m=this.graph;return c.concat([this.addEntry(\"tree container\",", "label_name": "CWE-20", "label": "20"} -{"code": "mxDualRuler.prototype.setUnit=function(b){this.vRuler.setUnit(b);this.hRuler.setUnit(b)};mxDualRuler.prototype.setStyle=function(b){this.vRuler.setStyle(b);this.hRuler.setStyle(b)};mxDualRuler.prototype.destroy=function(){this.vRuler.destroy();this.hRuler.destroy();this.ui.refresh=this.editorUiRefresh;mxGuide.prototype.move=this.origGuideMove;mxGuide.prototype.destroy=this.origGuideDestroy;this.ui.getDiagramContainerOffset=this.editorUiGetDiagContOffset};function mxFreehand(b){var e=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=e){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var f=mxFreehand.prototype.NORMAL_SMOOTHING,c=null,m=[],n,v=[],d,g=!1,k=!0,l=!0,p=!0,q=!0,x=[],y=!1,A=!0,B=!1,I={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},O=!1;this.setClosedPath=function(K){g=K};this.setAutoClose=function(K){k=K};this.setAutoInsert=", "label_name": "CWE-20", "label": "20"} -{"code": "T[N],\"cells\"),this.updateCustomLinkAction(u,T[N],\"excludeCells\")}};Graph.prototype.updateCustomLinkAction=function(u,E,J){if(null!=E&&null!=E[J]){for(var T=[],N=0;Nu.excludeCells.indexOf(E[T].id)&&J.push(E[T]);", "label_name": "CWE-20", "label": "20"} -{"code": "[H];!m(H)&&!c(H)||v(H)||y.traverse(H,!0,function(V,M){var W=null!=M&&y.isTreeEdge(M);W&&0>mxUtils.indexOf(S,M)&&S.push(M);(null==M||W)&&0>mxUtils.indexOf(S,V)&&S.push(V);return null==M||W});return S};var G=mxVertexHandler.prototype.init;mxVertexHandler.prototype.init=function(){G.apply(this,arguments);(m(this.state.cell)||c(this.state.cell))&&!v(this.state.cell)&&0this.state.width?10:0)+2+\"px\",this.moveHandle.style.top=this.state.y+this.state.height+(40>this.state.height?10:0)+2+\"px\")};var K=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(H){K.apply(this,", "label_name": "CWE-20", "label": "20"} -{"code": "fa=Array(Z.length);for(var aa=0;aaN.offsetTop-N.offsetHeight/2?\"70px\":\"10px\");else{for(var da=S.firstChild;null!=da;){var ca=da.nextSibling;\"geMenuItem\"!=da.className&&\"geItem\"!=da.className||", "label_name": "CWE-20", "label": "20"} -{"code": "J.substring(0,17)&&(N[R].setAttribute(\"href\",this.updateCustomLink(u,J)),Q=!0);Q&&this.labelChanged(E,T.innerHTML)}};Graph.prototype.updateCustomLink=function(u,E){if(\"data:action/json,\"==E.substring(0,17))try{var J=JSON.parse(E.substring(17));null!=J.actions&&(this.updateCustomLinkActions(u,J.actions),E=\"data:action/json,\"+JSON.stringify(J))}catch(T){}return E};Graph.prototype.updateCustomLinkActions=function(u,E){for(var J=0;Ju.excludeCells.indexOf(E[T].id)&&J.push(E[T]);", "label_name": "CWE-20", "label": "20"} -{"code": "u.substring(0,29)||\"https://fonts.gstatic.com/\"===u.substring(0,26)};Editor.prototype.createImageUrlConverter=function(){var u=new mxUrlConverter;u.updateBaseUrl();var E=u.convert,J=this;u.convert=function(T){if(null!=T){var N=\"http://\"==T.substring(0,7)||\"https://\"==T.substring(0,8);N&&!navigator.onLine?T=Editor.svgBrokenImage.src:!N||T.substring(0,u.baseUrl.length)==u.baseUrl||J.crossOriginImages&&J.isCorsEnabledForUrl(T)?\"chrome-extension://\"==T.substring(0,19)||mxClient.IS_CHROMEAPP||(T=E.apply(this,\narguments)):T=PROXY_URL+\"?url=\"+encodeURIComponent(T)}return T};return u};Editor.createSvgDataUri=function(u){return\"data:image/svg+xml;base64,\"+btoa(unescape(encodeURIComponent(u)))};Editor.prototype.convertImageToDataUri=function(u,E){try{var J=!0,T=window.setTimeout(mxUtils.bind(this,function(){J=!1;E(Editor.svgBrokenImage.src)}),this.timeout);if(/(\\.svg)$/i.test(u))mxUtils.get(u,mxUtils.bind(this,function(Q){window.clearTimeout(T);J&&E(Editor.createSvgDataUri(Q.getText()))}),function(){window.clearTimeout(T);", "label_name": "CWE-20", "label": "20"} -{"code": "\"url(\"+Editor.plusImage+\")\",aa.setAttribute(\"title\",mxResources.get(\"insert\")),aa.style.width=\"24px\",va=!0)}));ja();F.addListener(\"darkModeChanged\",ja);F.addListener(\"sketchModeChanged\",ja)}else F.editor.addListener(\"statusChanged\",mxUtils.bind(this,function(){F.setStatusText(F.editor.getStatus())}));if(null!=E){var Ba=function(da){H.popupMenuHandler.hideMenu();mxEvent.isAltDown(da)||mxEvent.isShiftDown(da)?F.actions.get(\"customZoom\").funct():F.actions.get(\"smartFit\").funct()},Ha=F.actions.get(\"zoomIn\"),", "label_name": "CWE-20", "label": "20"} -{"code": "C)):P.isSelectionEmpty()&&P.isEnabled()?(C.addSeparator(),this.addMenuItems(C,[\"editData\"],null,G),C.addSeparator(),this.addSubmenu(\"layout\",C),this.addSubmenu(\"insert\",C),this.addMenuItems(C,[\"-\",\"exitGroup\"],null,G)):P.isEnabled()&&this.addMenuItems(C,[\"-\",\"lockUnlock\"],null,G)};var A=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(C,D,G){A.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&this.addMenuItems(C,[\"copyAsImage\"],null,G)};EditorUi.prototype.toggleFormatPanel=", "label_name": "CWE-20", "label": "20"} -{"code": "function(u,E,J){if(null!=E){var T=function(Q){if(null!=Q)if(J)for(var R=0;R=Ia.getStatus()&&(qa=Ia.getText());Ka(qa)}))):Ka(qa)}function ma(na,Ka,Ia){if(null!=na&&mxUtils.isAncestorNode(document.body,da)&&(na=mxUtils.parseXml(na),na=Editor.extractGraphModel(na.documentElement,!0),null!=na)){\"mxfile\"==\nna.nodeName&&(na=Editor.parseDiagramNode(na.getElementsByTagName(\"diagram\")[0]));var Ra=new mxCodec(na.ownerDocument),Sa=new mxGraphModel;Ra.decode(na,Sa);na=Sa.root.getChildAt(0).children||[];b.sidebar.createTooltip(da,na,Math.min((window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)-80,1E3),Math.min((window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-80,800),null!=ha.title?mxResources.get(ha.title,null,ha.title):null,!0,new mxPoint(Ka,\nIa),!0,null,!0);var Ja=document.createElement(\"div\");Ja.className=\"geTempDlgDialogMask\";M.appendChild(Ja);var Oa=b.sidebar.hideTooltip;b.sidebar.hideTooltip=function(){Ja&&(M.removeChild(Ja),Ja=null,Oa.apply(this,arguments),b.sidebar.hideTooltip=Oa)};mxEvent.addListener(Ja,\"click\",function(){b.sidebar.hideTooltip()})}}var qa=null;if(Da||b.sidebar.currentElt==da)b.sidebar.hideTooltip();else{var pa=function(na){Da&&b.sidebar.currentElt==da&&ma(na,mxEvent.getClientX(la),mxEvent.getClientY(la));Da=!1;\nca.src=\"/images/icon-search.svg\"};b.sidebar.hideTooltip();b.sidebar.currentElt=da;Da=!0;ca.src=\"/images/aui-wait.gif\";ha.isExt?g(ha,pa,function(){A(mxResources.get(\"cantLoadPrev\"));Da=!1;ca.src=\"/images/icon-search.svg\"}):ia(ha.url,pa)}}function t(ha,da,ca){if(null!=E){for(var la=E.className.split(\" \"),ia=0;ia>2);E+=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt((N&3)<<4);E+=\"==\";break}Q=u.charCodeAt(J++);if(J==T){E+=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(N>>2);E+=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt((N&", "label_name": "CWE-20", "label": "20"} -{"code": "m=P.name;v=\"\";O(null,!0)})));k.appendChild(F)})(D[G],G)}100==D.length&&(k.appendChild(A),B=function(){k.scrollTop>=k.scrollHeight-k.offsetHeight&&C()},mxEvent.addListener(k,\"scroll\",B))}),y)});t()};GitHubClient.prototype.logout=function(){this.clearPersistentToken();this.setUser(null);b=null}})();TrelloFile=function(b,e,f){DrawioFile.call(this,b,e);this.meta=f;this.saveNeededCounter=0};mxUtils.extend(TrelloFile,DrawioFile);TrelloFile.prototype.getHash=function(){return\"T\"+encodeURIComponent(this.meta.compoundId)};TrelloFile.prototype.getMode=function(){return App.MODE_TRELLO};TrelloFile.prototype.isAutosave=function(){return!0};TrelloFile.prototype.getTitle=function(){return this.meta.name};TrelloFile.prototype.isRenamable=function(){return!1};TrelloFile.prototype.getSize=function(){return this.meta.bytes};", "label_name": "CWE-20", "label": "20"} -{"code": "\"#ffffff\")),Da=mxUtils.setStyle(Da,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(Aa,mxConstants.STYLE_STROKECOLOR,\"#000000\")),Da=mxUtils.setStyle(Da,mxConstants.STYLE_GRADIENTCOLOR,mxUtils.getValue(Aa,mxConstants.STYLE_GRADIENTCOLOR,null)),T.getModel().isVertex(Fa[Ea])&&(Da=mxUtils.setStyle(Da,mxConstants.STYLE_FONTCOLOR,mxUtils.getValue(Aa,mxConstants.STYLE_FONTCOLOR,null))));T.getModel().setStyle(Fa[Ea],Da)}}finally{T.getModel().endUpdate()}}));Ca.className=\"geStyleButton\";Ca.style.width=\"36px\";", "label_name": "CWE-20", "label": "20"} -{"code": "!0,d=JSON.parse(this.getPersistentToken(!0));null!=d?(new mxXmlRequest(this.redirectUri+\"?state=\"+encodeURIComponent(\"cId=\"+this.clientId+\"&domain=\"+window.location.hostname+\"&token=\"+e),null,\"GET\")).send(mxUtils.bind(this,function(g){200<=g.getStatus()&&299>=g.getStatus()?this.updateAuthInfo(JSON.parse(g.getText()),d.remember,!1,f,c):(this.clearPersistentToken(),this.setUser(null),b=null,401!=g.getStatus()||m?c({message:mxResources.get(\"accessDenied\"),retry:n}):n())}),c):this.ui.showAuthDialog(this,", "label_name": "CWE-20", "label": "20"} -{"code": "0;N=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": "20"} -{"code": "0==T?ba():R()}else this.stoppingCustomActions=this.executingCustomActions=!1,R(),null!=E&&E()});ba()}};Graph.prototype.doUpdateCustomLinksForCell=function(u,E){var J=this.getLinkForCell(E);null!=J&&\"data:action/json,\"==J.substring(0,17)&&this.setLinkForCell(E,this.updateCustomLink(u,J));if(this.isHtmlLabel(E)){var T=document.createElement(\"div\");T.innerHTML=this.sanitizeHtml(this.getLabel(E));for(var N=T.getElementsByTagName(\"a\"),Q=!1,R=0;R').src;mxWindow.prototype.closeImage=Graph.createSvgImage(18,10,'').src;", "label_name": "CWE-20", "label": "20"} -{"code": "Number(I.value),[e[t]])}}finally{f.getModel().endUpdate()}});O.className=\"geBtn gePrimaryBtn\";mxEvent.addListener(m,\"keypress\",function(t){13==t.keyCode&&O.click()});n=document.createElement(\"div\");n.style.marginTop=\"20px\";n.style.textAlign=\"right\";b.editor.cancelFirst?(n.appendChild(c),n.appendChild(O)):(n.appendChild(O),n.appendChild(c));m.appendChild(n);this.container=m},LibraryDialog=function(b,e,f,c,m,n){function v(D){for(D=document.elementFromPoint(D.clientX,D.clientY);null!=D&&D.parentNode!=", "label_name": "CWE-20", "label": "20"} -{"code": "\"checked\"),O.style.visibility=\"visible\"):A.setAttribute(\"checked\",\"checked\")):f=null}else f=null}catch(J){}x.style=y+(f?f:m());x.vertex=!0;l.addCell(x,null,null,null,null);l.selectAll();l.addListener(mxEvent.CELLS_MOVED,C);l.addListener(mxEvent.CELLS_RESIZED,C);var X=l.graphHandler.mouseUp,u=l.graphHandler.mouseDown;l.graphHandler.mouseUp=function(){X.apply(this,arguments);k.style.backgroundColor=\"#fff9\"};l.graphHandler.mouseDown=function(){u.apply(this,arguments);k.style.backgroundColor=\"\"};l.dblClick=", "label_name": "CWE-20", "label": "20"} -{"code": "function g(D){D.dataTransfer.dropEffect=null!=B?\"move\":\"copy\";D.stopPropagation();D.preventDefault()}function k(D){D.stopPropagation();D.preventDefault();z=!1;I=v(D);if(null!=B)null!=I&&IB?I-1:I,0,l.splice(B,1)[0]),x.insertBefore(x.children[B],x.children[I])):(l.push(l.splice(B,1)[0]),x.appendChild(x.children[B]));else if(0e.lastIndexOf(\".\")&&0>J){u=null!=u?u:G.value;var T=\"\";u==App.MODE_GOOGLE?T=b.drive.extension:u==App.MODE_GITHUB?T=b.gitHub.extension:u==App.MODE_GITLAB?T=b.gitLab.extension:u==App.MODE_TRELLO?T=b.trello.extension:u==App.MODE_DROPBOX?T=b.dropbox.extension:u==App.MODE_ONEDRIVE?T=b.oneDrive.extension:u==App.MODE_DEVICE&&\n(T=\".drawio\");0<=J&&(E=E.substring(0,J));z.value=E+T}}O(F)})}var V=document.createElement(\"a\");V.style.overflow=\"hidden\";var M=document.createElement(\"img\");M.src=P;M.setAttribute(\"border\",\"0\");M.setAttribute(\"align\",\"absmiddle\");M.style.width=\"60px\";M.style.height=\"60px\";M.style.paddingBottom=\"6px\";V.style.display=\"inline-block\";V.className=\"geBaseButton\";V.style.position=\"relative\";V.style.margin=\"4px\";V.style.padding=\"8px 8px 10px 8px\";V.style.whiteSpace=\"nowrap\";V.appendChild(M);V.style.color=", "label_name": "CWE-20", "label": "20"} -{"code": "this.handleError(J)}return x};EditorUi.prototype.updatePageLinks=function(c,e){for(var g=0;g=na.getStatus()?ja(na.getText(),oa):ia()})):ja(b.emptyDiagramXml,oa)},ja=function(oa,na){x||b.hideDialog(!0);f(oa,na,qa,ca)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){I=qa;Ba.className=\"geTempDlgCreateBtn\";ca&&(Ka.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": "20"} -{"code": "document.createElement(\"tr\");la.className=\"gePropHeader\";var Aa=document.createElement(\"th\");Aa.className=\"gePropHeaderCell\";var Fa=document.createElement(\"img\");Fa.src=Sidebar.prototype.expandedImage;Fa.style.verticalAlign=\"middle\";Aa.appendChild(Fa);mxUtils.write(Aa,mxResources.get(\"property\"));la.style.cursor=\"pointer\";var xa=function(){var za=ua.querySelectorAll(\".gePropNonHeaderRow\");if(Z.editorUi.propertiesCollapsed){Fa.src=Sidebar.prototype.collapsedImage;var ta=\"none\";for(var ka=p.childNodes.length-\n1;0<=ka;ka--)try{var pa=p.childNodes[ka],sa=pa.nodeName.toUpperCase();\"INPUT\"!=sa&&\"SELECT\"!=sa||p.removeChild(pa)}catch(ya){}}else Fa.src=Sidebar.prototype.expandedImage,ta=\"\";for(ka=0;ka+\";var g=e.getElementsByTagName(\"span\")[0];g.style.fontSize=\"18px\";g.style.marginRight=\"5px\";mxUtils.write(e,mxResources.get(\"moreShapes\")+\"...\");mxEvent.addListener(e,mxClient.IS_POINTER?\"pointerdown\":\"mousedown\",mxUtils.bind(this,function(k){k.preventDefault()}));mxEvent.addListener(e,\"click\",mxUtils.bind(this,\nfunction(k){this.actions.get(\"shapes\").funct();mxEvent.consume(k)}));c.appendChild(e);return c};EditorUi.prototype.handleError=function(c,e,g,k,m,q,v){var x=null!=this.spinner&&null!=this.spinner.pause?this.spinner.pause():function(){},A=null!=c&&null!=c.error?c.error:c;if(null!=c&&(\"1\"==urlParams.test||null!=c.stack)&&null!=c.message)try{v?null!=window.console&&console.error(\"EditorUi.handleError:\",c):EditorUi.logError(\"Caught: \"+(\"\"==c.message&&null!=c.name)?c.name:c.message,c.filename,c.lineNumber,", "label_name": "CWE-20", "label": "20"} -{"code": "F=B.createElement(\"output\");B.appendChild(F);B=new mxXmlCanvas2D(F);B.translate(Math.floor((1-y.x)/K),Math.floor((1-y.y)/K));B.scale(1/K);var G=0,N=B.save;B.save=function(){G++;N.apply(this,arguments)};var J=B.restore;B.restore=function(){G--;J.apply(this,arguments)};var E=n.drawShape;n.drawShape=function(H){mxLog.debug(\"entering shape\",H,G);E.apply(this,arguments);mxLog.debug(\"leaving shape\",H,G)};n.drawState(u.getView().getState(u.model.root),B);mxLog.show();mxLog.debug(mxUtils.getXml(F));mxLog.debug(\"stateCounter\",", "label_name": "CWE-20", "label": "20"} -{"code": "else{var z=c.getFileData(!0,null,null,null,null,!0),L=A.getGraphBounds(),M=Math.floor(L.width*m/A.view.scale),n=Math.floor(L.height*m/A.view.scale);if(z.length<=MAX_REQUEST_SIZE&&M*nthis.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\");0=x?2:6f.lastIndexOf(\".\")&&0>I){p=null!=p?p:G.value;var T=\"\";p==App.MODE_GOOGLE?T=b.drive.extension:p==App.MODE_GITHUB?T=b.gitHub.extension:p==App.MODE_GITLAB?T=b.gitLab.extension:p==App.MODE_TRELLO?T=b.trello.extension:p==App.MODE_DROPBOX?T=b.dropbox.extension:p==App.MODE_ONEDRIVE?T=b.oneDrive.extension:p==App.MODE_DEVICE&&\n(T=\".drawio\");0<=I&&(C=C.substring(0,I));y.value=C+T}}M(E)})}var U=document.createElement(\"a\");U.style.overflow=\"hidden\";var Q=document.createElement(\"img\");Q.src=N;Q.setAttribute(\"border\",\"0\");Q.setAttribute(\"align\",\"absmiddle\");Q.style.width=\"60px\";Q.style.height=\"60px\";Q.style.paddingBottom=\"6px\";U.style.display=\"inline-block\";U.className=\"geBaseButton\";U.style.position=\"relative\";U.style.margin=\"4px\";U.style.padding=\"8px 8px 10px 8px\";U.style.whiteSpace=\"nowrap\";U.appendChild(Q);U.style.color=\n\"gray\";U.style.fontSize=\"11px\";var W=document.createElement(\"div\");U.appendChild(W);mxUtils.write(W,J);if(null!=H&&null==b[H]){Q.style.visibility=\"hidden\";mxUtils.setOpacity(W,10);var V=new Spinner({lines:12,length:12,width:5,radius:10,rotate:0,color:\"#000\",speed:1.5,trail:60,shadow:!1,hwaccel:!1,top:\"40%\",zIndex:2E9});V.spin(U);var X=window.setTimeout(function(){null==b[H]&&(V.stop(),U.style.display=\"none\")},3E4);b.addListener(\"clientLoaded\",mxUtils.bind(this,function(){null!=b[H]&&(window.clearTimeout(X),\nmxUtils.setOpacity(W,100),Q.style.visibility=\"\",V.stop(),S())}))}else S();B.appendChild(U);++F==m&&(mxUtils.br(B),F=0)}function M(N){var J=y.value;if(null==N||null!=J&&0=x.status?q(x.responseText):this.handleError({message:mxResources.get(413==x.status?\"drawingTooLarge\":\"invalidOrMissingFile\")},mxResources.get(\"errorLoadingFile\")))}));else if(this.isLucidChartData(c))/(\\.json)$/i.test(e)&&(e=e.substring(0,e.length-5)+\".drawio\"),this.convertLucidChart(c,mxUtils.bind(this,", "label_name": "CWE-20", "label": "20"} -{"code": "\"&from=\"+q;break}q=y.background;\"png\"!=e&&\"pdf\"!=e&&\"svg\"!=e||!m?m||null!=q&&q!=mxConstants.NONE||(q=\"#ffffff\"):q=mxConstants.NONE;m={globalVars:y.getExportVariables()};A&&(m.grid={size:y.gridSize,steps:y.view.gridSteps,color:y.view.gridColor});Graph.translateDiagram&&(m.diagramLanguage=Graph.diagramLanguage);return new mxXmlRequest(EXPORT_URL,\"format=\"+e+B+F+\"&bg=\"+(null!=q?q:mxConstants.NONE)+\"&base64=\"+k+\"&embedXml=\"+z+\"&xml=\"+encodeURIComponent(g)+(null!=c?\"&filename=\"+encodeURIComponent(c):\"\")+\n\"&extras=\"+encodeURIComponent(JSON.stringify(m))+(null!=v?\"&scale=\"+v:\"\")+(null!=x?\"&border=\"+x:\"\")+(M&&isFinite(M)?\"&w=\"+M:\"\")+(n&&isFinite(n)?\"&h=\"+n:\"\"))};EditorUi.prototype.setMode=function(c,e){this.mode=c};EditorUi.prototype.loadDescriptor=function(c,e,g){var k=window.location.hash,m=mxUtils.bind(this,function(q){var v=null!=c.data?c.data:\"\";null!=q&&0P.offsetTop-P.offsetHeight/2?\"70px\":\"10px\");else{for(var ca=S.firstChild;null!=ca;){var ba=ca.nextSibling;\"geMenuItem\"!=ca.className&&\"geItem\"!=ca.className||", "label_name": "CWE-20", "label": "20"} -{"code": "EditorUi.prototype.cellProperties={id:!0,value:!0,xmlValue:!0,vertex:!0,edge:!0,visible:!0,collapsed:!0,connectable:!0,parent:!0,children:!0,previous:!0,source:!0,target:!0,edges:!0,geometry:!0,style:!0,mxObjectId:!0,mxTransient:!0};EditorUi.prototype.codec=new mxCodec;EditorUi.prototype.applyPatches=function(b,f,l,d,u){if(null!=f)for(var t=0;t {\n const messageBuilder = new MessageBuilder();\n\n let full_message_body_event_received = false;\n let on_message__received = false;\n\n messageBuilder\n .on(\"message\", (message) => {\n on_message__received = true;\n })\n .on(\"full_message_body\", (full_message_body) => {\n full_message_body_event_received = true;\n })\n .on(\"invalid_message\", (err) => {\n expectError.should.eql(false);\n on_message__received.should.equal(false);\n full_message_body_event_received.should.equal(true);\n done();\n })\n .on(\"error\", (err) => {\n err.should.be.instanceOf(Error);\n expectError.should.eql(true);\n done();\n });\n\n messageBuilder.feed(bad_packet); // OpenSecureChannel message\n },\n function () {}\n );\n }", "label_name": "CWE-400", "label": "400"} -{"code": "function gitPullOrClone (url, outPath, opts, cb) {\n if (typeof opts === 'function') {\n cb = opts\n opts = {}\n }\n\n const depth = opts.depth == null ? 1 : opts.depth\n\n if (depth <= 0) {\n throw new RangeError('The \"depth\" option must be greater than 0')\n }\n\n fs.access(outPath, fs.R_OK | fs.W_OK, function (err) {\n if (err) {\n gitClone()\n } else {\n gitPull()\n }\n })\n\n function gitClone () {\n // --depth implies --single-branch\n const flag = depth < Infinity ? '--depth=' + depth : '--single-branch'\n const args = ['clone', flag, url, outPath]\n debug('git ' + args.join(' '))\n spawn('git', args, {}, function (err) {\n if (err) err.message += ' (git clone) (' + url + ')'\n cb(err)\n })\n }\n\n function gitPull () {\n const args = depth < Infinity ? ['pull', '--depth=' + depth] : ['pull']\n debug('git ' + args.join(' '))\n spawn('git', args, { cwd: outPath }, function (err) {\n if (err) err.message += ' (git pull) (' + url + ')'\n cb(err)\n })\n }\n}", "label_name": "CWE-77", "label": "77"} -{"code": " function iframeLoaded() {\n var iframes = Array.from(document.querySelectorAll('iframe'));\n return Promise.all(iframes.filter(function(iframe) {\n return iframe.src;\n }).map(function(iframe) {\n return new Promise(function(resolve, reject) {\n iframe.addEventListener('load', () => {\n resolve();\n }, true);\n iframe.addEventListener('error', reject, true);\n });\n })).then(delay(sysend.timeout));\n // delay is required, something with browser is not intitled properly\n // the number was pick by experimentation\n }", "label_name": "CWE-200", "label": "200"} -{"code": "export default function parseUrl(href, part, parseQuery) {\n href = String(href);\n var match = href.match(_parse_url_exp)\n , map = _parse_url_map\n , i, ret = false\n ;\n if (match) {\n if (part && part in map) {\n ret = match[map[part]] || NIL;\n if (part == 'pathname') {\n if (!ret) ret = '/';\n }\n if (parseQuery && part == 'query') {\n ret = toObject(ret || NIL);\n }\n }\n else {\n let _ = this;\n if(typeof _ != 'function') {\n _ = typeof URL == 'function' && URL.createObjectURL ? URL : Object;\n ret = new _(href);\n // ret.toString = function _uri_to_string_() {\n // return fromLocation(this);\n // };\n }\n else {\n ret = new _(); // URLJS() constructor?\n }\n\n for (i in map) if (map.hasOwnProperty(i)) {\n ret[i] = match[map[i]] || NIL;\n }\n if (part && part in ret) return ret[part];\n\n if (!ret.pathname) ret.pathname = '/';\n if (!ret.path) ret.path = ret.pathname + ret.search;\n if (!ret.origin) ret.origin = ret.protocol + '//' + ret.host;\n if (!ret.domain) ret.domain = getDomainName(ret.hostname);\n if (parseQuery) ret.query = toObject(ret.query || NIL);\n if (!ret.origin) ret.href = String(href); // ??? may need some parse\n\n if (part) ret = ret[part];\n }\n }\n return ret;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int rose_parse_facilities(unsigned char *p,\n\tstruct rose_facilities_struct *facilities)\n{\n\tint facilities_len, len;\n\n\tfacilities_len = *p++;\n\n\tif (facilities_len == 0)\n\t\treturn 0;\n\n\twhile (facilities_len > 0) {\n\t\tif (*p == 0x00) {\n\t\t\tfacilities_len--;\n\t\t\tp++;\n\n\t\t\tswitch (*p) {\n\t\t\tcase FAC_NATIONAL:\t\t/* National */\n\t\t\t\tlen = rose_parse_national(p + 1, facilities, facilities_len - 1);\n\t\t\t\tif (len < 0)\n\t\t\t\t\treturn 0;\n\t\t\t\tfacilities_len -= len + 1;\n\t\t\t\tp += len + 1;\n\t\t\t\tbreak;\n\n\t\t\tcase FAC_CCITT:\t\t/* CCITT */\n\t\t\t\tlen = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);\n\t\t\t\tif (len < 0)\n\t\t\t\t\treturn 0;\n\t\t\t\tfacilities_len -= len + 1;\n\t\t\t\tp += len + 1;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tprintk(KERN_DEBUG \"ROSE: rose_parse_facilities - unknown facilities family %02X\\n\", *p);\n\t\t\t\tfacilities_len--;\n\t\t\t\tp++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else\n\t\t\tbreak;\t/* Error in facilities format */\n\t}\n\n\treturn 1;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void inet_sock_destruct(struct sock *sk)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\n\t__skb_queue_purge(&sk->sk_receive_queue);\n\t__skb_queue_purge(&sk->sk_error_queue);\n\n\tsk_mem_reclaim(sk);\n\n\tif (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) {\n\t\tpr_err(\"Attempt to release TCP socket in state %d %p\\n\",\n\t\t sk->sk_state, sk);\n\t\treturn;\n\t}\n\tif (!sock_flag(sk, SOCK_DEAD)) {\n\t\tpr_err(\"Attempt to release alive inet socket %p\\n\", sk);\n\t\treturn;\n\t}\n\n\tWARN_ON(atomic_read(&sk->sk_rmem_alloc));\n\tWARN_ON(atomic_read(&sk->sk_wmem_alloc));\n\tWARN_ON(sk->sk_wmem_queued);\n\tWARN_ON(sk->sk_forward_alloc);\n\n\tkfree(inet->opt);\n\tdst_release(rcu_dereference_check(sk->sk_dst_cache, 1));\n\tsk_refcnt_debug_dec(sk);\n}", "label_name": "CWE-362", "label": "362"} -{"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": "362"} -{"code": "void ip_send_reply(struct sock *sk, struct sk_buff *skb, struct ip_reply_arg *arg,\n\t\t unsigned int len)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct {\n\t\tstruct ip_options\topt;\n\t\tchar\t\t\tdata[40];\n\t} replyopts;\n\tstruct ipcm_cookie ipc;\n\t__be32 daddr;\n\tstruct rtable *rt = skb_rtable(skb);\n\n\tif (ip_options_echo(&replyopts.opt, skb))\n\t\treturn;\n\n\tdaddr = ipc.addr = rt->rt_src;\n\tipc.opt = NULL;\n\tipc.tx_flags = 0;\n\n\tif (replyopts.opt.optlen) {\n\t\tipc.opt = &replyopts.opt;\n\n\t\tif (ipc.opt->srr)\n\t\t\tdaddr = replyopts.opt.faddr;\n\t}\n\n\t{\n\t\tstruct flowi4 fl4;\n\n\t\tflowi4_init_output(&fl4, arg->bound_dev_if, 0,\n\t\t\t\t RT_TOS(ip_hdr(skb)->tos),\n\t\t\t\t RT_SCOPE_UNIVERSE, sk->sk_protocol,\n\t\t\t\t ip_reply_arg_flowi_flags(arg),\n\t\t\t\t daddr, rt->rt_spec_dst,\n\t\t\t\t tcp_hdr(skb)->source, tcp_hdr(skb)->dest);\n\t\tsecurity_skb_classify_flow(skb, flowi4_to_flowi(&fl4));\n\t\trt = ip_route_output_key(sock_net(sk), &fl4);\n\t\tif (IS_ERR(rt))\n\t\t\treturn;\n\t}\n\n\t/* And let IP do all the hard work.\n\n\t This chunk is not reenterable, hence spinlock.\n\t Note that it uses the fact, that this function is called\n\t with locally disabled BH and that sk cannot be already spinlocked.\n\t */\n\tbh_lock_sock(sk);\n\tinet->tos = ip_hdr(skb)->tos;\n\tsk->sk_priority = skb->priority;\n\tsk->sk_protocol = ip_hdr(skb)->protocol;\n\tsk->sk_bound_dev_if = arg->bound_dev_if;\n\tip_append_data(sk, ip_reply_glue_bits, arg->iov->iov_base, len, 0,\n\t\t &ipc, &rt, MSG_DONTWAIT);\n\tif ((skb = skb_peek(&sk->sk_write_queue)) != NULL) {\n\t\tif (arg->csumoffset >= 0)\n\t\t\t*((__sum16 *)skb_transport_header(skb) +\n\t\t\t arg->csumoffset) = csum_fold(csum_add(skb->csum,\n\t\t\t\t\t\t\t\targ->csum));\n\t\tskb->ip_summed = CHECKSUM_NONE;\n\t\tip_push_pending_frames(sk);\n\t}\n\n\tbh_unlock_sock(sk);\n\n\tip_rt_put(rt);\n}", "label_name": "CWE-362", "label": "362"} -{"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": "400"} -{"code": "static int write_empty_blocks(struct page *page, unsigned from, unsigned to,\n\t\t\t int mode)\n{\n\tstruct inode *inode = page->mapping->host;\n\tunsigned start, end, next, blksize;\n\tsector_t block = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);\n\tint ret;\n\n\tblksize = 1 << inode->i_blkbits;\n\tnext = end = 0;\n\twhile (next < from) {\n\t\tnext += blksize;\n\t\tblock++;\n\t}\n\tstart = next;\n\tdo {\n\t\tnext += blksize;\n\t\tret = needs_empty_write(block, inode);\n\t\tif (unlikely(ret < 0))\n\t\t\treturn ret;\n\t\tif (ret == 0) {\n\t\t\tif (end) {\n\t\t\t\tret = __block_write_begin(page, start, end - start,\n\t\t\t\t\t\t\t gfs2_block_map);\n\t\t\t\tif (unlikely(ret))\n\t\t\t\t\treturn ret;\n\t\t\t\tret = empty_write_end(page, start, end, mode);\n\t\t\t\tif (unlikely(ret))\n\t\t\t\t\treturn ret;\n\t\t\t\tend = 0;\n\t\t\t}\n\t\t\tstart = next;\n\t\t}\n\t\telse\n\t\t\tend = next;\n\t\tblock++;\n\t} while (next < to);\n\n\tif (end) {\n\t\tret = __block_write_begin(page, start, end - start, gfs2_block_map);\n\t\tif (unlikely(ret))\n\t\t\treturn ret;\n\t\tret = empty_write_end(page, start, end, mode);\n\t\tif (unlikely(ret))\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static __u8 *nci_extract_rf_params_nfcf_passive_poll(struct nci_dev *ndev,\n\t\t\tstruct rf_tech_specific_params_nfcf_poll *nfcf_poll,\n\t\t\t\t\t\t __u8 *data)\n{\n\tnfcf_poll->bit_rate = *data++;\n\tnfcf_poll->sensf_res_len = *data++;\n\n\tpr_debug(\"bit_rate %d, sensf_res_len %d\\n\",\n\t\t nfcf_poll->bit_rate, nfcf_poll->sensf_res_len);\n\n\tmemcpy(nfcf_poll->sensf_res, data, nfcf_poll->sensf_res_len);\n\tdata += nfcf_poll->sensf_res_len;\n\n\treturn data;\n}", "label_name": "CWE-119", "label": "119"} -{"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": "200"} -{"code": "static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,\n\t\t\t\t\t\tpmd_t *pmd, unsigned int flags)\n{\n\tint result;\n\thandle_t *handle = NULL;\n\tstruct inode *inode = file_inode(vma->vm_file);\n\tstruct super_block *sb = inode->i_sb;\n\tbool write = flags & FAULT_FLAG_WRITE;\n\n\tif (write) {\n\t\tsb_start_pagefault(sb);\n\t\tfile_update_time(vma->vm_file);\n\t\thandle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,\n\t\t\t\text4_chunk_trans_blocks(inode,\n\t\t\t\t\t\t\tPMD_SIZE / PAGE_SIZE));\n\t}\n\n\tif (IS_ERR(handle))\n\t\tresult = VM_FAULT_SIGBUS;\n\telse\n\t\tresult = __dax_pmd_fault(vma, addr, pmd, flags,\n\t\t\t\text4_get_block_dax, ext4_end_io_unwritten);\n\n\tif (write) {\n\t\tif (!IS_ERR(handle))\n\t\t\text4_journal_stop(handle);\n\t\tsb_end_pagefault(sb);\n\t}\n\n\treturn result;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static int snd_timer_start_slave(struct snd_timer_instance *timeri)\n{\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&slave_active_lock, flags);\n\ttimeri->flags |= SNDRV_TIMER_IFLG_RUNNING;\n\tif (timeri->master)\n\t\tlist_add_tail(&timeri->active_list,\n\t\t\t &timeri->master->slave_active_head);\n\tspin_unlock_irqrestore(&slave_active_lock, flags);\n\treturn 1; /* delayed start */\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int ecryptfs_privileged_open(struct file **lower_file,\n\t\t\t struct dentry *lower_dentry,\n\t\t\t struct vfsmount *lower_mnt,\n\t\t\t const struct cred *cred)\n{\n\tstruct ecryptfs_open_req req;\n\tint flags = O_LARGEFILE;\n\tint rc = 0;\n\n\tinit_completion(&req.done);\n\treq.lower_file = lower_file;\n\treq.path.dentry = lower_dentry;\n\treq.path.mnt = lower_mnt;\n\n\t/* Corresponding dput() and mntput() are done when the\n\t * lower file is fput() when all eCryptfs files for the inode are\n\t * released. */\n\tflags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;\n\t(*lower_file) = dentry_open(&req.path, flags, cred);\n\tif (!IS_ERR(*lower_file))\n\t\tgoto out;\n\tif ((flags & O_ACCMODE) == O_RDONLY) {\n\t\trc = PTR_ERR((*lower_file));\n\t\tgoto out;\n\t}\n\tmutex_lock(&ecryptfs_kthread_ctl.mux);\n\tif (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {\n\t\trc = -EIO;\n\t\tmutex_unlock(&ecryptfs_kthread_ctl.mux);\n\t\tprintk(KERN_ERR \"%s: We are in the middle of shutting down; \"\n\t\t \"aborting privileged request to open lower file\\n\",\n\t\t\t__func__);\n\t\tgoto out;\n\t}\n\tlist_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);\n\tmutex_unlock(&ecryptfs_kthread_ctl.mux);\n\twake_up(&ecryptfs_kthread_ctl.wait);\n\twait_for_completion(&req.done);\n\tif (IS_ERR(*lower_file))\n\t\trc = PTR_ERR(*lower_file);\nout:\n\treturn rc;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint error;\n\tint len;\n\tchar *data;\n\tconst char *name = gfs2_acl_name(type);\n\n\tif (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode)))\n\t\treturn -E2BIG;\n\n\tif (type == ACL_TYPE_ACCESS) {\n\t\tumode_t mode = inode->i_mode;\n\n\t\terror = posix_acl_equiv_mode(acl, &mode);\n\t\tif (error < 0)\n\t\t\treturn error;\n\n\t\tif (error == 0)\n\t\t\tacl = NULL;\n\n\t\tif (mode != inode->i_mode) {\n\t\t\tinode->i_mode = mode;\n\t\t\tmark_inode_dirty(inode);\n\t\t}\n\t}\n\n\tif (acl) {\n\t\tlen = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0);\n\t\tif (len == 0)\n\t\t\treturn 0;\n\t\tdata = kmalloc(len, GFP_NOFS);\n\t\tif (data == NULL)\n\t\t\treturn -ENOMEM;\n\t\terror = posix_acl_to_xattr(&init_user_ns, acl, data, len);\n\t\tif (error < 0)\n\t\t\tgoto out;\n\t} else {\n\t\tdata = NULL;\n\t\tlen = 0;\n\t}\n\n\terror = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS);\n\tif (error)\n\t\tgoto out;\n\tset_cached_acl(inode, type, acl);\nout:\n\tkfree(data);\n\treturn error;\n}", "label_name": "CWE-285", "label": "285"} -{"code": "static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,\n\t\t struct posix_acl *acl)\n{\n\tchar *ea_name;\n\tint rc;\n\tint size = 0;\n\tchar *value = NULL;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\tea_name = XATTR_NAME_POSIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\trc = posix_acl_equiv_mode(acl, &inode->i_mode);\n\t\t\tif (rc < 0)\n\t\t\t\treturn rc;\n\t\t\tinode->i_ctime = CURRENT_TIME;\n\t\t\tmark_inode_dirty(inode);\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\tea_name = 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\treturn -ENOMEM;\n\t\trc = posix_acl_to_xattr(&init_user_ns, acl, value, size);\n\t\tif (rc < 0)\n\t\t\tgoto out;\n\t}\n\trc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);\nout:\n\tkfree(value);\n\n\tif (!rc)\n\t\tset_cached_acl(inode, type, acl);\n\n\treturn rc;\n}", "label_name": "CWE-285", "label": "285"} -{"code": "static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port)\n{\n\tstruct usb_serial\t*serial = port->serial;\n\tstruct usb_serial_port\t*wport;\n\n\twport = serial->port[1];\n\ttty_port_tty_set(&wport->port, tty);\n\n\treturn usb_serial_generic_open(tty, port);\n}", "label_name": "CWE-404", "label": "404"} -{"code": "static inline void fsnotify_oldname_free(const unsigned char *old_name)\n{\n\tkfree(old_name);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)\n{\n\tstruct encrypted_key_payload *epayload = key->payload.data[0];\n\tstruct encrypted_key_payload *new_epayload;\n\tchar *buf;\n\tchar *new_master_desc = NULL;\n\tconst char *format = NULL;\n\tsize_t datalen = prep->datalen;\n\tint ret = 0;\n\n\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n\t\treturn -ENOKEY;\n\tif (datalen <= 0 || datalen > 32767 || !prep->data)\n\t\treturn -EINVAL;\n\n\tbuf = kmalloc(datalen + 1, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;\n\n\tbuf[datalen] = 0;\n\tmemcpy(buf, prep->data, datalen);\n\tret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);\n\tif (ret < 0)\n\t\tgoto out;\n\n\tret = valid_master_desc(new_master_desc, epayload->master_desc);\n\tif (ret < 0)\n\t\tgoto out;\n\n\tnew_epayload = encrypted_key_alloc(key, epayload->format,\n\t\t\t\t\t new_master_desc, epayload->datalen);\n\tif (IS_ERR(new_epayload)) {\n\t\tret = PTR_ERR(new_epayload);\n\t\tgoto out;\n\t}\n\n\t__ekey_init(new_epayload, epayload->format, new_master_desc,\n\t\t epayload->datalen);\n\n\tmemcpy(new_epayload->iv, epayload->iv, ivsize);\n\tmemcpy(new_epayload->payload_data, epayload->payload_data,\n\t epayload->payload_datalen);\n\n\trcu_assign_keypointer(key, new_epayload);\n\tcall_rcu(&epayload->rcu, encrypted_rcu_free);\nout:\n\tkzfree(buf);\n\treturn ret;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int encrypt(struct blkcipher_desc *desc,\n\t\t struct scatterlist *dst, struct scatterlist *src,\n\t\t unsigned int nbytes)\n{\n\tstruct blkcipher_walk walk;\n\tstruct crypto_blkcipher *tfm = desc->tfm;\n\tstruct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);\n\tint err;\n\n\tblkcipher_walk_init(&walk, dst, src, nbytes);\n\terr = blkcipher_walk_virt_block(desc, &walk, 64);\n\n\tsalsa20_ivsetup(ctx, walk.iv);\n\n\tif (likely(walk.nbytes == nbytes))\n\t{\n\t\tsalsa20_encrypt_bytes(ctx, walk.dst.virt.addr,\n\t\t\t\t walk.src.virt.addr, nbytes);\n\t\treturn blkcipher_walk_done(desc, &walk, 0);\n\t}\n\n\twhile (walk.nbytes >= 64) {\n\t\tsalsa20_encrypt_bytes(ctx, walk.dst.virt.addr,\n\t\t\t\t walk.src.virt.addr,\n\t\t\t\t walk.nbytes - (walk.nbytes % 64));\n\t\terr = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);\n\t}\n\n\tif (walk.nbytes) {\n\t\tsalsa20_encrypt_bytes(ctx, walk.dst.virt.addr,\n\t\t\t\t walk.src.virt.addr, walk.nbytes);\n\t\terr = blkcipher_walk_done(desc, &walk, 0);\n\t}\n\n\treturn err;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static void construct_get_dest_keyring(struct key **_dest_keyring)\n{\n\tstruct request_key_auth *rka;\n\tconst struct cred *cred = current_cred();\n\tstruct key *dest_keyring = *_dest_keyring, *authkey;\n\n\tkenter(\"%p\", dest_keyring);\n\n\t/* find the appropriate keyring */\n\tif (dest_keyring) {\n\t\t/* the caller supplied one */\n\t\tkey_get(dest_keyring);\n\t} else {\n\t\t/* use a default keyring; falling through the cases until we\n\t\t * find one that we actually have */\n\t\tswitch (cred->jit_keyring) {\n\t\tcase KEY_REQKEY_DEFL_DEFAULT:\n\t\tcase KEY_REQKEY_DEFL_REQUESTOR_KEYRING:\n\t\t\tif (cred->request_key_auth) {\n\t\t\t\tauthkey = cred->request_key_auth;\n\t\t\t\tdown_read(&authkey->sem);\n\t\t\t\trka = authkey->payload.data[0];\n\t\t\t\tif (!test_bit(KEY_FLAG_REVOKED,\n\t\t\t\t\t &authkey->flags))\n\t\t\t\t\tdest_keyring =\n\t\t\t\t\t\tkey_get(rka->dest_keyring);\n\t\t\t\tup_read(&authkey->sem);\n\t\t\t\tif (dest_keyring)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\tcase KEY_REQKEY_DEFL_THREAD_KEYRING:\n\t\t\tdest_keyring = key_get(cred->thread_keyring);\n\t\t\tif (dest_keyring)\n\t\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_PROCESS_KEYRING:\n\t\t\tdest_keyring = key_get(cred->process_keyring);\n\t\t\tif (dest_keyring)\n\t\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_SESSION_KEYRING:\n\t\t\trcu_read_lock();\n\t\t\tdest_keyring = key_get(\n\t\t\t\trcu_dereference(cred->session_keyring));\n\t\t\trcu_read_unlock();\n\n\t\t\tif (dest_keyring)\n\t\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_USER_SESSION_KEYRING:\n\t\t\tdest_keyring =\n\t\t\t\tkey_get(cred->user->session_keyring);\n\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_USER_KEYRING:\n\t\t\tdest_keyring = key_get(cred->user->uid_keyring);\n\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_GROUP_KEYRING:\n\t\tdefault:\n\t\t\tBUG();\n\t\t}\n\t}\n\n\t*_dest_keyring = dest_keyring;\n\tkleave(\" [dk %d]\", key_serial(dest_keyring));\n\treturn;\n}", "label_name": "CWE-862", "label": "862"} -{"code": "static int n_tty_ioctl(struct tty_struct *tty, struct file *file,\n\t\t unsigned int cmd, unsigned long arg)\n{\n\tstruct n_tty_data *ldata = tty->disc_data;\n\tint retval;\n\n\tswitch (cmd) {\n\tcase TIOCOUTQ:\n\t\treturn put_user(tty_chars_in_buffer(tty), (int __user *) arg);\n\tcase TIOCINQ:\n\t\tdown_write(&tty->termios_rwsem);\n\t\tif (L_ICANON(tty))\n\t\t\tretval = inq_canon(ldata);\n\t\telse\n\t\t\tretval = read_cnt(ldata);\n\t\tup_write(&tty->termios_rwsem);\n\t\treturn put_user(retval, (unsigned int __user *) arg);\n\tdefault:\n\t\treturn n_tty_ioctl_helper(tty, file, cmd, arg);\n\t}\n}", "label_name": "CWE-704", "label": "704"} -{"code": "static int netlbl_cipsov4_add_common(struct genl_info *info,\n\t\t\t\t struct cipso_v4_doi *doi_def)\n{\n\tstruct nlattr *nla;\n\tint nla_rem;\n\tu32 iter = 0;\n\n\tdoi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);\n\n\tif (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST],\n\t\t\t\tNLBL_CIPSOV4_A_MAX,\n\t\t\t\tnetlbl_cipsov4_genl_policy) != 0)\n\t\treturn -EINVAL;\n\n\tnla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem)\n\t\tif (nla->nla_type == NLBL_CIPSOV4_A_TAG) {\n\t\t\tif (iter > CIPSO_V4_TAG_MAXCNT)\n\t\t\t\treturn -EINVAL;\n\t\t\tdoi_def->tags[iter++] = nla_get_u8(nla);\n\t\t}\n\tif (iter < CIPSO_V4_TAG_MAXCNT)\n\t\tdoi_def->tags[iter] = CIPSO_V4_TAG_INVALID;\n\n\treturn 0;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static void __exit xfrm6_tunnel_fini(void)\n{\n\tunregister_pernet_subsys(&xfrm6_tunnel_net_ops);\n\txfrm6_tunnel_spi_fini();\n\txfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);\n\txfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);\n\txfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "mISDN_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tstruct sk_buff\t\t*skb;\n\tstruct sock\t\t*sk = sock->sk;\n\tstruct sockaddr_mISDN\t*maddr;\n\n\tint\t\tcopied, err;\n\n\tif (*debug & DEBUG_SOCKET)\n\t\tprintk(KERN_DEBUG \"%s: len %d, flags %x ch.nr %d, proto %x\\n\",\n\t\t __func__, (int)len, flags, _pms(sk)->ch.nr,\n\t\t sk->sk_protocol);\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tif (sk->sk_state == MISDN_CLOSED)\n\t\treturn 0;\n\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\treturn err;\n\n\tif (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) {\n\t\tmsg->msg_namelen = sizeof(struct sockaddr_mISDN);\n\t\tmaddr = (struct sockaddr_mISDN *)msg->msg_name;\n\t\tmaddr->family = AF_ISDN;\n\t\tmaddr->dev = _pms(sk)->dev->id;\n\t\tif ((sk->sk_protocol == ISDN_P_LAPD_TE) ||\n\t\t (sk->sk_protocol == ISDN_P_LAPD_NT)) {\n\t\t\tmaddr->channel = (mISDN_HEAD_ID(skb) >> 16) & 0xff;\n\t\t\tmaddr->tei = (mISDN_HEAD_ID(skb) >> 8) & 0xff;\n\t\t\tmaddr->sapi = mISDN_HEAD_ID(skb) & 0xff;\n\t\t} else {\n\t\t\tmaddr->channel = _pms(sk)->ch.nr;\n\t\t\tmaddr->sapi = _pms(sk)->ch.addr & 0xFF;\n\t\t\tmaddr->tei = (_pms(sk)->ch.addr >> 8) & 0xFF;\n\t\t}\n\t} else {\n\t\tif (msg->msg_namelen)\n\t\t\tprintk(KERN_WARNING \"%s: too small namelen %d\\n\",\n\t\t\t __func__, msg->msg_namelen);\n\t\tmsg->msg_namelen = 0;\n\t}\n\n\tcopied = skb->len + MISDN_HEADER_LEN;\n\tif (len < copied) {\n\t\tif (flags & MSG_PEEK)\n\t\t\tatomic_dec(&skb->users);\n\t\telse\n\t\t\tskb_queue_head(&sk->sk_receive_queue, skb);\n\t\treturn -ENOSPC;\n\t}\n\tmemcpy(skb_push(skb, MISDN_HEADER_LEN), mISDN_HEAD_P(skb),\n\t MISDN_HEADER_LEN);\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tmISDN_sock_cmsg(sk, msg, skb);\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t struct msghdr *m, size_t total_len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint error = 0;\n\n\tif (sk->sk_state & PPPOX_BOUND) {\n\t\terror = -EIO;\n\t\tgoto end;\n\t}\n\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &error);\n\tif (error < 0)\n\t\tgoto end;\n\n\tm->msg_namelen = 0;\n\n\tif (skb) {\n\t\ttotal_len = min_t(size_t, total_len, skb->len);\n\t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);\n\t\tif (error == 0) {\n\t\t\tconsume_skb(skb);\n\t\t\treturn total_len;\n\t\t}\n\t}\n\n\tkfree_skb(skb);\nend:\n\treturn error;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int atalk_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,\n\t\t\t size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sockaddr_at *sat = (struct sockaddr_at *)msg->msg_name;\n\tstruct ddpehdr *ddp;\n\tint copied = 0;\n\tint offset = 0;\n\tint err = 0;\n\tstruct sk_buff *skb;\n\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tlock_sock(sk);\n\n\tif (!skb)\n\t\tgoto out;\n\n\t/* FIXME: use skb->cb to be able to use shared skbs */\n\tddp = ddp_hdr(skb);\n\tcopied = ntohs(ddp->deh_len_hops) & 1023;\n\n\tif (sk->sk_type != SOCK_RAW) {\n\t\toffset = sizeof(*ddp);\n\t\tcopied -= offset;\n\t}\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\terr = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, copied);\n\n\tif (!err) {\n\t\tif (sat) {\n\t\t\tsat->sat_family = AF_APPLETALK;\n\t\t\tsat->sat_port = ddp->deh_sport;\n\t\t\tsat->sat_addr.s_node = ddp->deh_snode;\n\t\t\tsat->sat_addr.s_net = ddp->deh_snet;\n\t\t}\n\t\tmsg->msg_namelen = sizeof(*sat);\n\t}\n\n\tskb_free_datagram(sk, skb);\t/* Free the datagram. */\n\nout:\n\trelease_sock(sk);\n\treturn err ? : copied;\n}", "label_name": "CWE-20", "label": "20"} -{"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": "20"} -{"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": "20"} -{"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": "20"} -{"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": "20"} -{"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": "20"} -{"code": "static int rawsock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied;\n\tint rc;\n\n\tpr_debug(\"sock=%p sk=%p len=%zu flags=%d\\n\", sock, sk, len, flags);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rc);\n\tif (!skb)\n\t\treturn rc;\n\n\tmsg->msg_namelen = 0;\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\trc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tskb_free_datagram(sk, skb);\n\n\treturn rc ? : copied;\n}", "label_name": "CWE-20", "label": "20"} -{"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": "20"} -{"code": "static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)\n{\n\tns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\tshm_rmid(ns, shp);\n\tshm_unlock(shp);\n\tif (!is_file_hugepages(shp->shm_file))\n\t\tshmem_lock(shp->shm_file, 0, shp->mlock_user);\n\telse if (shp->mlock_user)\n\t\tuser_shm_unlock(file_inode(shp->shm_file)->i_size,\n\t\t\t\t\t\tshp->mlock_user);\n\tfput (shp->shm_file);\n\tipc_rcu_putref(shp, shm_rcu_free);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static inline int ldsem_cmpxchg(long *old, long new, struct ld_semaphore *sem)\n{\n\tlong tmp = *old;\n\t*old = atomic_long_cmpxchg(&sem->count, *old, new);\n\treturn *old == tmp;\n}", "label_name": "CWE-362", "label": "362"} -{"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": "20"} -{"code": "static int raw_cmd_copyin(int cmd, void __user *param,\n\t\t\t\t struct floppy_raw_cmd **rcmd)\n{\n\tstruct floppy_raw_cmd *ptr;\n\tint ret;\n\tint i;\n\n\t*rcmd = NULL;\n\nloop:\n\tptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);\n\tif (!ptr)\n\t\treturn -ENOMEM;\n\t*rcmd = ptr;\n\tret = copy_from_user(ptr, param, sizeof(*ptr));\n\tif (ret)\n\t\treturn -EFAULT;\n\tptr->next = NULL;\n\tptr->buffer_length = 0;\n\tparam += sizeof(struct floppy_raw_cmd);\n\tif (ptr->cmd_count > 33)\n\t\t\t/* the command may now also take up the space\n\t\t\t * initially intended for the reply & the\n\t\t\t * reply count. Needed for long 82078 commands\n\t\t\t * such as RESTORE, which takes ... 17 command\n\t\t\t * bytes. Murphy's law #137: When you reserve\n\t\t\t * 16 bytes for a structure, you'll one day\n\t\t\t * discover that you really need 17...\n\t\t\t */\n\t\treturn -EINVAL;\n\n\tfor (i = 0; i < 16; i++)\n\t\tptr->reply[i] = 0;\n\tptr->resultcode = 0;\n\tptr->kernel_data = NULL;\n\n\tif (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {\n\t\tif (ptr->length <= 0)\n\t\t\treturn -EINVAL;\n\t\tptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);\n\t\tfallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);\n\t\tif (!ptr->kernel_data)\n\t\t\treturn -ENOMEM;\n\t\tptr->buffer_length = ptr->length;\n\t}\n\tif (ptr->flags & FD_RAW_WRITE) {\n\t\tret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tif (ptr->flags & FD_RAW_MORE) {\n\t\trcmd = &(ptr->next);\n\t\tptr->rate &= 0x43;\n\t\tgoto loop;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-754", "label": "754"} -{"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": "200"} -{"code": "static int logi_dj_ll_raw_request(struct hid_device *hid,\n\t\t\t\t unsigned char reportnum, __u8 *buf,\n\t\t\t\t size_t count, unsigned char report_type,\n\t\t\t\t int reqtype)\n{\n\tstruct dj_device *djdev = hid->driver_data;\n\tstruct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev;\n\tu8 *out_buf;\n\tint ret;\n\n\tif (buf[0] != REPORT_TYPE_LEDS)\n\t\treturn -EINVAL;\n\n\tout_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC);\n\tif (!out_buf)\n\t\treturn -ENOMEM;\n\n\tif (count < DJREPORT_SHORT_LENGTH - 2)\n\t\tcount = DJREPORT_SHORT_LENGTH - 2;\n\n\tout_buf[0] = REPORT_ID_DJ_SHORT;\n\tout_buf[1] = djdev->device_index;\n\tmemcpy(out_buf + 2, buf, count);\n\n\tret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf,\n\t\tDJREPORT_SHORT_LENGTH, report_type, reqtype);\n\n\tkfree(out_buf);\n\treturn ret;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,\n\t\t\t struct btrfs_path *path,\n\t\t\t const char *name, int name_len)\n{\n\tstruct btrfs_dir_item *dir_item;\n\tunsigned long name_ptr;\n\tu32 total_len;\n\tu32 cur = 0;\n\tu32 this_len;\n\tstruct extent_buffer *leaf;\n\n\tleaf = path->nodes[0];\n\tdir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);\n\tif (verify_dir_item(root, leaf, dir_item))\n\t\treturn NULL;\n\n\ttotal_len = btrfs_item_size_nr(leaf, path->slots[0]);\n\twhile (cur < total_len) {\n\t\tthis_len = sizeof(*dir_item) +\n\t\t\tbtrfs_dir_name_len(leaf, dir_item) +\n\t\t\tbtrfs_dir_data_len(leaf, dir_item);\n\t\tname_ptr = (unsigned long)(dir_item + 1);\n\n\t\tif (btrfs_dir_name_len(leaf, dir_item) == name_len &&\n\t\t memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0)\n\t\t\treturn dir_item;\n\n\t\tcur += this_len;\n\t\tdir_item = (struct btrfs_dir_item *)((char *)dir_item +\n\t\t\t\t\t\t this_len);\n\t}\n\treturn NULL;\n}", "label_name": "CWE-362", "label": "362"} -{"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": "119"} -{"code": "get_matching_model_microcode(int cpu, unsigned long start,\n\t\t\t void *data, size_t size,\n\t\t\t struct mc_saved_data *mc_saved_data,\n\t\t\t unsigned long *mc_saved_in_initrd,\n\t\t\t struct ucode_cpu_info *uci)\n{\n\tu8 *ucode_ptr = data;\n\tunsigned int leftover = size;\n\tenum ucode_state state = UCODE_OK;\n\tunsigned int mc_size;\n\tstruct microcode_header_intel *mc_header;\n\tstruct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];\n\tunsigned int mc_saved_count = mc_saved_data->mc_saved_count;\n\tint i;\n\n\twhile (leftover) {\n\t\tmc_header = (struct microcode_header_intel *)ucode_ptr;\n\n\t\tmc_size = get_totalsize(mc_header);\n\t\tif (!mc_size || mc_size > leftover ||\n\t\t\tmicrocode_sanity_check(ucode_ptr, 0) < 0)\n\t\t\tbreak;\n\n\t\tleftover -= mc_size;\n\n\t\t/*\n\t\t * Since APs with same family and model as the BSP may boot in\n\t\t * the platform, we need to find and save microcode patches\n\t\t * with the same family and model as the BSP.\n\t\t */\n\t\tif (matching_model_microcode(mc_header, uci->cpu_sig.sig) !=\n\t\t\t UCODE_OK) {\n\t\t\tucode_ptr += mc_size;\n\t\t\tcontinue;\n\t\t}\n\n\t\t_save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count);\n\n\t\tucode_ptr += mc_size;\n\t}\n\n\tif (leftover) {\n\t\tstate = UCODE_ERROR;\n\t\tgoto out;\n\t}\n\n\tif (mc_saved_count == 0) {\n\t\tstate = UCODE_NFOUND;\n\t\tgoto out;\n\t}\n\n\tfor (i = 0; i < mc_saved_count; i++)\n\t\tmc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start;\n\n\tmc_saved_data->mc_saved_count = mc_saved_count;\nout:\n\treturn state;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static bool blk_kick_flush(struct request_queue *q, struct blk_flush_queue *fq)\n{\n\tstruct list_head *pending = &fq->flush_queue[fq->flush_pending_idx];\n\tstruct request *first_rq =\n\t\tlist_first_entry(pending, struct request, flush.list);\n\tstruct request *flush_rq = fq->flush_rq;\n\n\t/* C1 described at the top of this file */\n\tif (fq->flush_pending_idx != fq->flush_running_idx || list_empty(pending))\n\t\treturn false;\n\n\t/* C2 and C3 */\n\tif (!list_empty(&fq->flush_data_in_flight) &&\n\t time_before(jiffies,\n\t\t\tfq->flush_pending_since + FLUSH_PENDING_TIMEOUT))\n\t\treturn false;\n\n\t/*\n\t * Issue flush and toggle pending_idx. This makes pending_idx\n\t * different from running_idx, which means flush is in flight.\n\t */\n\tfq->flush_pending_idx ^= 1;\n\n\tblk_rq_init(q, flush_rq);\n\n\t/*\n\t * Borrow tag from the first request since they can't\n\t * be in flight at the same time.\n\t */\n\tif (q->mq_ops) {\n\t\tflush_rq->mq_ctx = first_rq->mq_ctx;\n\t\tflush_rq->tag = first_rq->tag;\n\t}\n\n\tflush_rq->cmd_type = REQ_TYPE_FS;\n\tflush_rq->cmd_flags = WRITE_FLUSH | REQ_FLUSH_SEQ;\n\tflush_rq->rq_disk = first_rq->rq_disk;\n\tflush_rq->end_io = flush_end_io;\n\n\treturn blk_flush_queue_rq(flush_rq, false);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static void bt_for_each(struct blk_mq_hw_ctx *hctx,\n\t\tstruct blk_mq_bitmap_tags *bt, unsigned int off,\n\t\tbusy_iter_fn *fn, void *data, bool reserved)\n{\n\tstruct request *rq;\n\tint bit, i;\n\n\tfor (i = 0; i < bt->map_nr; i++) {\n\t\tstruct blk_align_bitmap *bm = &bt->map[i];\n\n\t\tfor (bit = find_first_bit(&bm->word, bm->depth);\n\t\t bit < bm->depth;\n\t\t bit = find_next_bit(&bm->word, bm->depth, bit + 1)) {\n\t\t \trq = blk_mq_tag_to_rq(hctx->tags, off + bit);\n\t\t\tif (rq->q == hctx->queue)\n\t\t\t\tfn(hctx, rq, data, reserved);\n\t\t}\n\n\t\toff += (1 << bt->bits_per_word);\n\t}\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static inline bool is_flush_request(struct request *rq,\n\t\tstruct blk_flush_queue *fq, unsigned int tag)\n{\n\treturn ((rq->cmd_flags & REQ_FLUSH_SEQ) &&\n\t\t\tfq->flush_rq->tag == tag);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static noinline void key_gc_unused_keys(struct list_head *keys)\n{\n\twhile (!list_empty(keys)) {\n\t\tstruct key *key =\n\t\t\tlist_entry(keys->next, struct key, graveyard_link);\n\t\tlist_del(&key->graveyard_link);\n\n\t\tkdebug(\"- %u\", key->serial);\n\t\tkey_check(key);\n\n\t\t/* Throw away the key data */\n\t\tif (key->type->destroy)\n\t\t\tkey->type->destroy(key);\n\n\t\tsecurity_key_free(key);\n\n\t\t/* deal with the user's key tracking and quota */\n\t\tif (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {\n\t\t\tspin_lock(&key->user->lock);\n\t\t\tkey->user->qnkeys--;\n\t\t\tkey->user->qnbytes -= key->quotalen;\n\t\t\tspin_unlock(&key->user->lock);\n\t\t}\n\n\t\tatomic_dec(&key->user->nkeys);\n\t\tif (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))\n\t\t\tatomic_dec(&key->user->nikeys);\n\n\t\tkey_user_put(key->user);\n\n\t\tkfree(key->description);\n\n#ifdef KEY_DEBUGGING\n\t\tkey->magic = KEY_DEBUG_MAGIC_X;\n#endif\n\t\tkmem_cache_free(key_jar, key);\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void sock_release(struct socket *sock)\n{\n\tif (sock->ops) {\n\t\tstruct module *owner = sock->ops->owner;\n\n\t\tsock->ops->release(sock);\n\t\tsock->ops = NULL;\n\t\tmodule_put(owner);\n\t}\n\n\tif (rcu_dereference_protected(sock->wq, 1)->fasync_list)\n\t\tpr_err(\"%s: fasync list not empty!\\n\", __func__);\n\n\tif (!sock->file) {\n\t\tiput(SOCK_INODE(sock));\n\t\treturn;\n\t}\n\tsock->file = NULL;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "unsigned paravirt_patch_call(void *insnbuf,\n\t\t\t const void *target, u16 tgt_clobbers,\n\t\t\t unsigned long addr, u16 site_clobbers,\n\t\t\t unsigned len)\n{\n\tstruct branch *b = insnbuf;\n\tunsigned long delta = (unsigned long)target - (addr+5);\n\n\tif (tgt_clobbers & ~site_clobbers)\n\t\treturn len;\t/* target would clobber too much for this site */\n\tif (len < 5)\n\t\treturn len;\t/* call too long for patch site */\n\n\tb->opcode = 0xe8; /* call */\n\tb->delta = delta;\n\tBUILD_BUG_ON(sizeof(*b) != 5);\n\n\treturn 5;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "static void smp_task_done(struct sas_task *task)\n{\n\tif (!del_timer(&task->slow_task->timer))\n\t\treturn;\n\tcomplete(&task->slow_task->completion);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static int crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_kpp rkpp;\n\n\tstrlcpy(rkpp.type, \"kpp\", sizeof(rkpp.type));\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_KPP,\n\t\t sizeof(struct crypto_report_kpp), &rkpp))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "static inline u32 net_hash_mix(const struct net *net)\n{\n#ifdef CONFIG_NET_NS\n\treturn (u32)(((unsigned long)net) >> ilog2(sizeof(*net)));\n#else\n\treturn 0;\n#endif\n}", "label_name": "CWE-326", "label": "326"} -{"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": "362"} -{"code": "int irssi_ssl_handshake(GIOChannel *handle)\n{\n\tGIOSSLChannel *chan = (GIOSSLChannel *)handle;\n\tint ret, err;\n\tX509 *cert;\n\tconst char *errstr;\n\n\tret = SSL_connect(chan->ssl);\n\tif (ret <= 0) {\n\t\terr = SSL_get_error(chan->ssl, ret);\n\t\tswitch (err) {\n\t\t\tcase SSL_ERROR_WANT_READ:\n\t\t\t\treturn 1;\n\t\t\tcase SSL_ERROR_WANT_WRITE:\n\t\t\t\treturn 3;\n\t\t\tcase SSL_ERROR_ZERO_RETURN:\n\t\t\t\tg_warning(\"SSL handshake failed: %s\", \"server closed connection\");\n\t\t\t\treturn -1;\n\t\t\tcase SSL_ERROR_SYSCALL:\n\t\t\t\terrstr = ERR_reason_error_string(ERR_get_error());\n\t\t\t\tif (errstr == NULL && ret == -1)\n\t\t\t\t\terrstr = strerror(errno);\n\t\t\t\tg_warning(\"SSL handshake failed: %s\", errstr != NULL ? errstr : \"server closed connection unexpectedly\");\n\t\t\t\treturn -1;\n\t\t\tdefault:\n\t\t\t\terrstr = ERR_reason_error_string(ERR_get_error());\n\t\t\t\tg_warning(\"SSL handshake failed: %s\", errstr != NULL ? errstr : \"unknown SSL error\");\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\n\tcert = SSL_get_peer_certificate(chan->ssl);\n\tif (cert == NULL) {\n\t\tg_warning(\"SSL server supplied no certificate\");\n\t\treturn -1;\n\t}\n\tret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, cert);\n\tX509_free(cert);\n\treturn ret ? 0 : -1;\n}", "label_name": "CWE-20", "label": "20"} -{"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": "119"} -{"code": "CURLcode Curl_urldecode(struct SessionHandle *data,\n const char *string, size_t length,\n char **ostring, size_t *olen,\n bool reject_ctrl)\n{\n size_t alloc = (length?length:strlen(string))+1;\n char *ns = malloc(alloc);\n unsigned char in;\n size_t strindex=0;\n unsigned long hex;\n CURLcode res;\n\n if(!ns)\n return CURLE_OUT_OF_MEMORY;\n\n while(--alloc > 0) {\n in = *string;\n if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {\n /* this is two hexadecimal digits following a '%' */\n char hexstr[3];\n char *ptr;\n hexstr[0] = string[1];\n hexstr[1] = string[2];\n hexstr[2] = 0;\n\n hex = strtoul(hexstr, &ptr, 16);\n\n in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */\n\n res = Curl_convert_from_network(data, &in, 1);\n if(res) {\n /* Curl_convert_from_network calls failf if unsuccessful */\n free(ns);\n return res;\n }\n\n string+=2;\n alloc-=2;\n }\n if(reject_ctrl && (in < 0x20)) {\n free(ns);\n return CURLE_URL_MALFORMAT;\n }\n\n ns[strindex++] = in;\n string++;\n }\n ns[strindex]=0; /* terminate it */\n\n if(olen)\n /* store output size */\n *olen = strindex;\n\n if(ostring)\n /* store output string */\n *ostring = ns;\n\n return CURLE_OK;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)\n{\n\tPyObject *logical = NULL;\t/* input string encoded in utf-8 */\n\tPyObject *visual = NULL;\t/* output string encoded in utf-8 */\n\tPyObject *result = NULL;\t/* unicode output string */\n\n\tint length = PyUnicode_GET_SIZE (unicode);\n\n\tlogical = PyUnicode_AsUTF8String (unicode);\n\tif (logical == NULL)\n\t\tgoto cleanup;\n\n\tvisual = log2vis_utf8 (logical, length, base_direction, clean, reordernsm);\n\tif (visual == NULL)\n\t\tgoto cleanup;\n\n\tresult = PyUnicode_DecodeUTF8 (PyString_AS_STRING (visual),\n\t\t\t\t PyString_GET_SIZE (visual), \"strict\");\n\n cleanup:\n\tPy_XDECREF (logical);\n\tPy_XDECREF (visual);\n\n\treturn result;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int dsOpen(void) {\n struct stat sb;\n int retval;\n char *path = server.diskstore_path;\n\n if ((retval = stat(path,&sb) == -1) && errno != ENOENT) {\n redisLog(REDIS_WARNING, \"Error opening disk store at %s: %s\",\n path, strerror(errno));\n return REDIS_ERR;\n }\n\n /* Directory already in place. Assume everything is ok. */\n if (retval == 0 && S_ISDIR(sb.st_mode)) return REDIS_OK;\n\n /* File exists but it's not a directory */\n if (retval == 0 && !S_ISDIR(sb.st_mode)) {\n redisLog(REDIS_WARNING,\"Disk store at %s is not a directory\", path);\n return REDIS_ERR;\n }\n\n /* New disk store, create the directory structure now, as creating\n * them in a lazy way is not a good idea, after very few insertions\n * we'll need most of the 65536 directories anyway. */\n if (mkdir(path) == -1) {\n redisLog(REDIS_WARNING,\"Disk store init failed creating dir %s: %s\",\n path, strerror(errno));\n return REDIS_ERR;\n }\n return REDIS_OK;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int CLASS parse_jpeg(int offset)\n{\n int len, save, hlen, mark;\n fseek(ifp, offset, SEEK_SET);\n if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)\n return 0;\n\n while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)\n {\n order = 0x4d4d;\n len = get2() - 2;\n save = ftell(ifp);\n if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)\n {\n fgetc(ifp);\n raw_height = get2();\n raw_width = get2();\n }\n order = get2();\n hlen = get4();\n if (get4() == 0x48454150) /* \"HEAP\" */\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n#endif\n parse_ciff(save + hlen, len - hlen, 0);\n }\n if (parse_tiff(save + 6))\n apply_tiff();\n fseek(ifp, save + len, SEEK_SET);\n }\n return 1;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static void mspack_fmap_free(void *mem)\n{\n\tfree(mem);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void mk_request_free(struct session_request *sr)\n{\n if (sr->fd_file > 0) {\n mk_vhost_close(sr);\n }\n\n if (sr->headers.location) {\n mk_mem_free(sr->headers.location);\n }\n\n if (sr->uri_processed.data != sr->uri.data) {\n mk_ptr_free(&sr->uri_processed);\n }\n\n if (sr->real_path.data != sr->real_path_static) {\n mk_ptr_free(&sr->real_path);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"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": "119"} -{"code": "static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)\n{\n\tchar *ksep, *vsep, *val;\n\tsize_t klen, vlen;\n\t/* FIXME: string-size_t */\n\tunsigned int new_vlen;\n\n\tif (var->ptr >= var->end) {\n\t\treturn 0;\n\t}\n\n\tvsep = memchr(var->ptr, '&', var->end - var->ptr);\n\tif (!vsep) {\n\t\tif (!eof) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tvsep = var->end;\n\t\t}\n\t}\n\n\tksep = memchr(var->ptr, '=', vsep - var->ptr);\n\tif (ksep) {\n\t\t*ksep = '\\0';\n\t\t/* \"foo=bar&\" or \"foo=&\" */\n\t\tklen = ksep - var->ptr;\n\t\tvlen = vsep - ++ksep;\n\t} else {\n\t\tksep = \"\";\n\t\t/* \"foo&\" */\n\t\tklen = vsep - var->ptr;\n\t\tvlen = 0;\n\t}\n\n\tphp_url_decode(var->ptr, klen);\n\n\tval = estrndup(ksep, vlen);\n\tif (vlen) {\n\t\tvlen = php_url_decode(val, vlen);\n\t}\n\n\tif (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {\n\t\tphp_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);\n\t}\n\tefree(val);\n\n\tvar->ptr = vsep + (vsep != var->end);\n\treturn 1;\n}", "label_name": "CWE-400", "label": "400"} -{"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": "119"} -{"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": "119"} -{"code": "horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\tTIFFPredictorState* sp = PredictorState(tif);\n\ttmsize_t stride = sp->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\twp += wc - 1;\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": "119"} -{"code": "do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,\n size_t noff, size_t doff, int *flags)\n{\n\tif (namesz == 4 && strcmp((char *)&nbuf[noff], \"GNU\") == 0 &&\n\t type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {\n\t\tuint8_t desc[20];\n\t\tconst char *btype;\n\t\tuint32_t i;\n\t\t*flags |= FLAGS_DID_BUILD_ID;\n\t\tswitch (descsz) {\n\t\tcase 8:\n\t\t btype = \"xxHash\";\n\t\t break;\n\t\tcase 16:\n\t\t btype = \"md5/uuid\";\n\t\t break;\n\t\tcase 20:\n\t\t btype = \"sha1\";\n\t\t break;\n\t\tdefault:\n\t\t btype = \"unknown\";\n\t\t break;\n\t\t}\n\t\tif (file_printf(ms, \", BuildID[%s]=\", btype) == -1)\n\t\t\treturn 1;\n\t\t(void)memcpy(desc, &nbuf[doff], descsz);\n\t\tfor (i = 0; i < descsz; i++)\n\t\t if (file_printf(ms, \"%02x\", desc[i]) == -1)\n\t\t\treturn 1;\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static void dtls1_clear_queues(SSL *s)\n\t{\n pitem *item = NULL;\n hm_fragment *frag = NULL;\n\tDTLS1_RECORD_DATA *rdata;\n\n while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL)\n {\n\t\trdata = (DTLS1_RECORD_DATA *) item->data;\n\t\tif (rdata->rbuf.buf)\n\t\t\t{\n\t\t\tOPENSSL_free(rdata->rbuf.buf);\n\t\t\t}\n OPENSSL_free(item->data);\n pitem_free(item);\n }\n\n while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL)\n {\n\t\trdata = (DTLS1_RECORD_DATA *) item->data;\n\t\tif (rdata->rbuf.buf)\n\t\t\t{\n\t\t\tOPENSSL_free(rdata->rbuf.buf);\n\t\t\t}\n OPENSSL_free(item->data);\n pitem_free(item);\n }\n\n while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL)\n {\n frag = (hm_fragment *)item->data;\n OPENSSL_free(frag->fragment);\n OPENSSL_free(frag);\n pitem_free(item);\n }\n\n while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL)\n {\n frag = (hm_fragment *)item->data;\n OPENSSL_free(frag->fragment);\n OPENSSL_free(frag);\n pitem_free(item);\n }\n\n\twhile ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL)\n\t\t{\n\t\tfrag = (hm_fragment *)item->data;\n\t\tOPENSSL_free(frag->fragment);\n\t\tOPENSSL_free(frag);\n\t\tpitem_free(item);\n\t\t}\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)\n\t{\n\tDTLS1_RECORD_DATA *rdata;\n\tpitem *item;\n\n\t/* Limit the size of the queue to prevent DOS attacks */\n\tif (pqueue_size(queue->q) >= 100)\n\t\treturn 0;\n\t\t\n\trdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));\n\titem = pitem_new(priority, rdata);\n\tif (rdata == NULL || item == NULL)\n\t\t{\n\t\tif (rdata != NULL) OPENSSL_free(rdata);\n\t\tif (item != NULL) pitem_free(item);\n\t\t\n\t\tSSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);\n\t\treturn(0);\n\t\t}\n\t\n\trdata->packet = s->packet;\n\trdata->packet_length = s->packet_length;\n\tmemcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));\n\tmemcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));\n\n\titem->data = rdata;\n\n#ifndef OPENSSL_NO_SCTP\n\t/* Store bio_dgram_sctp_rcvinfo struct */\n\tif (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&\n\t (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) {\n\t\tBIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo);\n\t}\n#endif\n\n\ts->packet = NULL;\n\ts->packet_length = 0;\n\tmemset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));\n\tmemset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));\n\t\n\tif (!ssl3_setup_buffers(s))\n\t\t{\n\t\tSSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);\n\t\tOPENSSL_free(rdata);\n\t\tpitem_free(item);\n\t\treturn(0);\n\t\t}\n\n\t/* insert should not fail, since duplicates are dropped */\n\tif (pqueue_insert(queue->q, item) == NULL)\n\t\t{\n\t\tSSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);\n\t\tOPENSSL_free(rdata);\n\t\tpitem_free(item);\n\t\treturn(0);\n\t\t}\n\n\treturn(1);\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "void IGDstartelt(void * d, const char * name, int l)\n{\n\tstruct IGDdatas * datas = (struct IGDdatas *)d;\n\tmemcpy( datas->cureltname, name, l);\n\tdatas->cureltname[l] = '\\0';\n\tdatas->level++;\n\tif( (l==7) && !memcmp(name, \"service\", l) ) {\n\t\tdatas->tmp.controlurl[0] = '\\0';\n\t\tdatas->tmp.eventsuburl[0] = '\\0';\n\t\tdatas->tmp.scpdurl[0] = '\\0';\n\t\tdatas->tmp.servicetype[0] = '\\0';\n\t}\n}", "label_name": "CWE-119", "label": "119"} -{"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": "119"} -{"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": "119"} -{"code": "id3_skip (SF_PRIVATE * psf)\n{\tunsigned char\tbuf [10] ;\n\n\tmemset (buf, 0, sizeof (buf)) ;\n\tpsf_binheader_readf (psf, \"pb\", 0, buf, 10) ;\n\n\tif (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')\n\t{\tint\toffset = buf [6] & 0x7f ;\n\t\toffset = (offset << 7) | (buf [7] & 0x7f) ;\n\t\toffset = (offset << 7) | (buf [8] & 0x7f) ;\n\t\toffset = (offset << 7) | (buf [9] & 0x7f) ;\n\n\t\tpsf_log_printf (psf, \"ID3 length : %d\\n--------------------\\n\", offset) ;\n\n\t\t/* Never want to jump backwards in a file. */\n\t\tif (offset < 0)\n\t\t\treturn 0 ;\n\n\t\t/* Calculate new file offset and position ourselves there. */\n\t\tpsf->fileoffset += offset + 10 ;\n\t\tpsf_binheader_readf (psf, \"p\", psf->fileoffset) ;\n\n\t\treturn 1 ;\n\t\t} ;\n\n\treturn 0 ;\n} /* id3_skip */", "label_name": "CWE-119", "label": "119"} -{"code": "header_put_le_3byte (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 3)\n\t{\tpsf->header [psf->headindex++] = x ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\t} ;\n} /* header_put_le_3byte */", "label_name": "CWE-119", "label": "119"} -{"code": "header_put_be_short (SF_PRIVATE *psf, int x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 2)\n\t{\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = x ;\n\t\t} ;\n} /* header_put_be_short */", "label_name": "CWE-119", "label": "119"} -{"code": "sf_open_fd\t(int fd, int mode, SF_INFO *sfinfo, int close_desc)\n{\tSF_PRIVATE \t*psf ;\n\n\tif ((SF_CONTAINER (sfinfo->format)) == SF_FORMAT_SD2)\n\t{\tsf_errno = SFE_SD2_FD_DISALLOWED ;\n\t\treturn\tNULL ;\n\t\t} ;\n\n\tif ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)\n\t{\tsf_errno = SFE_MALLOC_FAILED ;\n\t\treturn\tNULL ;\n\t\t} ;\n\n\tpsf_init_files (psf) ;\n\tcopy_filename (psf, \"\") ;\n\n\tpsf->file.mode = mode ;\n\tpsf_set_file (psf, fd) ;\n\tpsf->is_pipe = psf_is_pipe (psf) ;\n\tpsf->fileoffset = psf_ftell (psf) ;\n\n\tif (! close_desc)\n\t\tpsf->file.do_not_close_descriptor = SF_TRUE ;\n\n\treturn psf_open_file (psf, sfinfo) ;\n} /* sf_open_fd */", "label_name": "CWE-119", "label": "119"} -{"code": "static void mark_commit(struct commit *c, void *data)\n{\n\tmark_object(&c->object, NULL, NULL, data);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "char *path_name(struct strbuf *path, const char *name)\n{\n\tstruct strbuf ret = STRBUF_INIT;\n\tif (path)\n\t\tstrbuf_addbuf(&ret, path);\n\tstrbuf_addstr(&ret, name);\n\treturn strbuf_detach(&ret, NULL);\n}", "label_name": "CWE-119", "label": "119"} -{"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": "119"} -{"code": "static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,\n jas_stream_t *in)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tunsigned int i;\n\tuint_fast8_t tmp;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tif (jpc_getuint16(in, &siz->caps) ||\n\t jpc_getuint32(in, &siz->width) ||\n\t jpc_getuint32(in, &siz->height) ||\n\t jpc_getuint32(in, &siz->xoff) ||\n\t jpc_getuint32(in, &siz->yoff) ||\n\t jpc_getuint32(in, &siz->tilewidth) ||\n\t jpc_getuint32(in, &siz->tileheight) ||\n\t jpc_getuint32(in, &siz->tilexoff) ||\n\t jpc_getuint32(in, &siz->tileyoff) ||\n\t jpc_getuint16(in, &siz->numcomps)) {\n\t\treturn -1;\n\t}\n\tif (!siz->width || !siz->height || !siz->tilewidth ||\n\t !siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {\n\t\treturn -1;\n\t}\n\tif (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {\n\t\tjas_eprintf(\"all tiles are outside the image area\\n\");\n\t\treturn -1;\n\t}\n\tif (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {\n\t\treturn -1;\n\t}\n\tfor (i = 0; i < siz->numcomps; ++i) {\n\t\tif (jpc_getuint8(in, &tmp) ||\n\t\t jpc_getuint8(in, &siz->comps[i].hsamp) ||\n\t\t jpc_getuint8(in, &siz->comps[i].vsamp)) {\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tif (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {\n\t\t\tjas_eprintf(\"invalid XRsiz value %d\\n\", siz->comps[i].hsamp);\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tif (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {\n\t\t\tjas_eprintf(\"invalid YRsiz value %d\\n\", siz->comps[i].vsamp);\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tsiz->comps[i].sgnd = (tmp >> 7) & 1;\n\t\tsiz->comps[i].prec = (tmp & 0x7f) + 1;\n\t}\n\tif (jas_stream_eof(in)) {\n\t\tjas_free(siz->comps);\n\t\treturn -1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 8, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)\n{\n\tjpc_streamlist_t *streams;\n\tuchar *dataptr;\n\tuint_fast32_t datacnt;\n\tuint_fast32_t tpcnt;\n\tjpc_ppxstabent_t *ent;\n\tint entno;\n\tjas_stream_t *stream;\n\tint n;\n\n\tif (!(streams = jpc_streamlist_create())) {\n\t\tgoto error;\n\t}\n\n\tif (!tab->numents) {\n\t\treturn streams;\n\t}\n\n\tentno = 0;\n\tent = tab->ents[entno];\n\tdataptr = ent->data;\n\tdatacnt = ent->len;\n\tfor (;;) {\n\n\t\t/* Get the length of the packet header data for the current\n\t\t tile-part. */\n\t\tif (datacnt < 4) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(stream = jas_stream_memopen(0, 0))) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),\n\t\t stream)) {\n\t\t\tgoto error;\n\t\t}\n\t\ttpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)\n\t\t | dataptr[3];\n\t\tdatacnt -= 4;\n\t\tdataptr += 4;\n\n\t\t/* Get the packet header data for the current tile-part. */\n\t\twhile (tpcnt) {\n\t\t\tif (!datacnt) {\n\t\t\t\tif (++entno >= tab->numents) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tent = tab->ents[entno];\n\t\t\t\tdataptr = ent->data;\n\t\t\t\tdatacnt = ent->len;\n\t\t\t}\n\t\t\tn = JAS_MIN(tpcnt, datacnt);\n\t\t\tif (jas_stream_write(stream, dataptr, n) != n) {\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\ttpcnt -= n;\n\t\t\tdataptr += n;\n\t\t\tdatacnt -= n;\n\t\t}\n\t\tjas_stream_rewind(stream);\n\t\tif (!datacnt) {\n\t\t\tif (++entno >= tab->numents) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tent = tab->ents[entno];\n\t\t\tdataptr = ent->data;\n\t\t\tdatacnt = ent->len;\n\t\t}\n\t}\n\n\treturn streams;\n\nerror:\n\tif (streams) {\n\t\tjpc_streamlist_destroy(streams);\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int jpg_validate(jas_stream_t *in)\n{\n\tuchar buf[JPG_MAGICLEN];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= JPG_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, JPG_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 < JPG_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Does this look like JPEG? */\n\tif (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "mm_sshpam_init_ctx(Authctxt *authctxt)\n{\n\tBuffer m;\n\tint success;\n\n\tdebug3(\"%s\", __func__);\n\tbuffer_init(&m);\n\tbuffer_put_cstring(&m, authctxt->user);\n\tmm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);\n\tdebug3(\"%s: waiting for MONITOR_ANS_PAM_INIT_CTX\", __func__);\n\tmm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);\n\tsuccess = buffer_get_int(&m);\n\tif (success == 0) {\n\t\tdebug3(\"%s: pam_init_ctx failed\", __func__);\n\t\tbuffer_free(&m);\n\t\treturn (NULL);\n\t}\n\tbuffer_free(&m);\n\treturn (authctxt);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int rm_rf_child(int fd, const char *name, RemoveFlags flags) {\n\n /* Removes one specific child of the specified directory */\n\n if (fd < 0)\n return -EBADF;\n\n if (!filename_is_valid(name))\n return -EINVAL;\n\n if ((flags & (REMOVE_ROOT|REMOVE_MISSING_OK)) != 0) /* Doesn't really make sense here, we are not supposed to remove 'fd' anyway */\n return -EINVAL;\n\n if (FLAGS_SET(flags, REMOVE_ONLY_DIRECTORIES|REMOVE_SUBVOLUME))\n return -EINVAL;\n\n return rm_rf_children_inner(fd, name, -1, flags, NULL);\n}", "label_name": "CWE-674", "label": "674"} -{"code": "CAMLprim value caml_alloc_dummy_float (value size)\n{\n mlsize_t wosize = Int_val(size) * Double_wosize;\n\n if (wosize == 0) return Atom(0);\n return caml_alloc (wosize, 0);\n}", "label_name": "CWE-200", "label": "200"} -{"code": "mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)\n{\n\tif (size == 0 || ncount == 0 || ncount > SIZE_MAX / size)\n\t\tfatal(\"%s: mm_zalloc(%u, %u)\", __func__, ncount, size);\n\n\treturn mm_malloc(mm, size * ncount);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,\n void *(*allocfunc)(void *, u_int, u_int),\n void (*freefunc)(void *, void *))\n{\n\tssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;\n\tssh->state->compression_out_stream.zfree = (free_func)freefunc;\n\tssh->state->compression_out_stream.opaque = ctx;\n\tssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;\n\tssh->state->compression_in_stream.zfree = (free_func)freefunc;\n\tssh->state->compression_in_stream.opaque = ctx;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "userauth_gssapi(struct ssh *ssh)\n{\n\tAuthctxt *authctxt = ssh->authctxt;\n\tgss_OID_desc goid = {0, NULL};\n\tGssctxt *ctxt = NULL;\n\tint r, present;\n\tu_int mechs;\n\tOM_uint32 ms;\n\tsize_t len;\n\tu_char *doid = NULL;\n\n\tif (!authctxt->valid || authctxt->user == NULL)\n\t\treturn (0);\n\n\tif ((r = sshpkt_get_u32(ssh, &mechs)) != 0)\n\t\tfatal(\"%s: %s\", __func__, ssh_err(r));\n\n\tif (mechs == 0) {\n\t\tdebug(\"Mechanism negotiation is not supported\");\n\t\treturn (0);\n\t}\n\n\tdo {\n\t\tmechs--;\n\n\t\tfree(doid);\n\n\t\tpresent = 0;\n\t\tif ((r = sshpkt_get_string(ssh, &doid, &len)) != 0)\n\t\t\tfatal(\"%s: %s\", __func__, ssh_err(r));\n\n\t\tif (len > 2 && doid[0] == SSH_GSS_OIDTYPE &&\n\t\t doid[1] == len - 2) {\n\t\t\tgoid.elements = doid + 2;\n\t\t\tgoid.length = len - 2;\n\t\t\tssh_gssapi_test_oid_supported(&ms, &goid, &present);\n\t\t} else {\n\t\t\tlogit(\"Badly formed OID received\");\n\t\t}\n\t} while (mechs > 0 && !present);\n\n\tif (!present) {\n\t\tfree(doid);\n\t\tauthctxt->server_caused_failure = 1;\n\t\treturn (0);\n\t}\n\n\tif (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) {\n\t\tif (ctxt != NULL)\n\t\t\tssh_gssapi_delete_ctx(&ctxt);\n\t\tfree(doid);\n\t\tauthctxt->server_caused_failure = 1;\n\t\treturn (0);\n\t}\n\n\tauthctxt->methoddata = (void *)ctxt;\n\n\t/* Return the OID that we received */\n\tif ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 ||\n\t (r = sshpkt_put_string(ssh, doid, len)) != 0 ||\n\t (r = sshpkt_send(ssh)) != 0)\n\t\tfatal(\"%s: %s\", __func__, ssh_err(r));\n\n\tfree(doid);\n\n\tssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);\n\tssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);\n\tauthctxt->postponed = 1;\n\n\treturn (0);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static bool glfs_check_config(const char *cfgstring, char **reason)\n{\n\tchar *path;\n\tglfs_t *fs = NULL;\n\tglfs_fd_t *gfd = NULL;\n\tgluster_server *hosts = NULL; /* gluster server defination */\n\tbool result = true;\n\n\tpath = strchr(cfgstring, '/');\n\tif (!path) {\n\t\tif (asprintf(reason, \"No path found\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto done;\n\t}\n\tpath += 1; /* get past '/' */\n\n\tfs = tcmu_create_glfs_object(path, &hosts);\n\tif (!fs) {\n\t\ttcmu_err(\"tcmu_create_glfs_object failed\\n\");\n\t\tgoto done;\n\t}\n\n\tgfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS);\n\tif (!gfd) {\n\t\tif (asprintf(reason, \"glfs_open failed: %m\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto unref;\n\t}\n\n\tif (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) {\n\t\tif (asprintf(reason, \"glfs_access file not present, or not writable\") == -1)\n\t\t\t*reason = NULL;\n\t\tresult = false;\n\t\tgoto unref;\n\t}\n\n\tgoto done;\n\nunref:\n\tgluster_cache_refresh(fs, path);\n\ndone:\n\tif (gfd)\n\t\tglfs_close(gfd);\n\tgluster_free_server(&hosts);\n\n\treturn result;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "AcpiNsTerminate (\n void)\n{\n ACPI_STATUS Status;\n\n\n ACPI_FUNCTION_TRACE (NsTerminate);\n\n\n#ifdef ACPI_EXEC_APP\n {\n ACPI_OPERAND_OBJECT *Prev;\n ACPI_OPERAND_OBJECT *Next;\n\n /* Delete any module-level code blocks */\n\n Next = AcpiGbl_ModuleCodeList;\n while (Next)\n {\n Prev = Next;\n Next = Next->Method.Mutex;\n Prev->Method.Mutex = NULL; /* Clear the Mutex (cheated) field */\n AcpiUtRemoveReference (Prev);\n }\n }\n#endif\n\n /*\n * Free the entire namespace -- all nodes and all objects\n * attached to the nodes\n */\n AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode);\n\n /* Delete any objects attached to the root node */\n\n Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);\n if (ACPI_FAILURE (Status))\n {\n return_VOID;\n }\n\n AcpiNsDeleteNode (AcpiGbl_RootNode);\n (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);\n\n ACPI_DEBUG_PRINT ((ACPI_DB_INFO, \"Namespace freed\\n\"));\n return_VOID;\n}", "label_name": "CWE-755", "label": "755"} -{"code": "void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset) {\n\tbloc = *offset;\n\tsend(huff->loc[ch], NULL, fout);\n\t*offset = bloc;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int MSG_ReadBits( msg_t *msg, int bits ) {\n\tint\t\t\tvalue;\n\tint\t\t\tget;\n\tqboolean\tsgn;\n\tint\t\t\ti, nbits;\n//\tFILE*\tfp;\n\n\tvalue = 0;\n\n\tif ( bits < 0 ) {\n\t\tbits = -bits;\n\t\tsgn = qtrue;\n\t} else {\n\t\tsgn = qfalse;\n\t}\n\n\tif (msg->oob) {\n\t\tif(bits==8)\n\t\t{\n\t\t\tvalue = msg->data[msg->readcount];\n\t\t\tmsg->readcount += 1;\n\t\t\tmsg->bit += 8;\n\t\t}\n\t\telse if(bits==16)\n\t\t{\n\t\t\tshort temp;\n\t\t\t\n\t\t\tCopyLittleShort(&temp, &msg->data[msg->readcount]);\n\t\t\tvalue = temp;\n\t\t\tmsg->readcount += 2;\n\t\t\tmsg->bit += 16;\n\t\t}\n\t\telse if(bits==32)\n\t\t{\n\t\t\tCopyLittleLong(&value, &msg->data[msg->readcount]);\n\t\t\tmsg->readcount += 4;\n\t\t\tmsg->bit += 32;\n\t\t}\n\t\telse\n\t\t\tCom_Error(ERR_DROP, \"can't read %d bits\", bits);\n\t} else {\n\t\tnbits = 0;\n\t\tif (bits&7) {\n\t\t\tnbits = bits&7;\n\t\t\tfor(i=0;idata, &msg->bit)<data, &msg->bit);\n//\t\t\t\tfwrite(&get, 1, 1, fp);\n\t\t\t\tvalue |= (get<<(i+nbits));\n\t\t\t}\n//\t\t\tfclose(fp);\n\t\t}\n\t\tmsg->readcount = (msg->bit>>3)+1;\n\t}\n\tif ( sgn && bits > 0 && bits < 32 ) {\n\t\tif ( value & ( 1 << ( bits - 1 ) ) ) {\n\t\t\tvalue |= -1 ^ ( ( 1 << bits ) - 1 );\n\t\t}\n\t}\n\n\treturn value;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static void oidc_scrub_headers(request_rec *r) {\n\toidc_cfg *cfg = ap_get_module_config(r->server->module_config,\n\t\t\t&auth_openidc_module);\n\n\tif (cfg->scrub_request_headers != 0) {\n\n\t\t/* scrub all headers starting with OIDC_ first */\n\t\toidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX,\n\t\t\t\toidc_cfg_dir_authn_header(r));\n\n\t\t/*\n\t\t * then see if the claim headers need to be removed on top of that\n\t\t * (i.e. the prefix does not start with the default OIDC_)\n\t\t */\n\t\tif ((strstr(cfg->claim_prefix, OIDC_DEFAULT_HEADER_PREFIX)\n\t\t\t\t!= cfg->claim_prefix)) {\n\t\t\toidc_scrub_request_headers(r, cfg->claim_prefix, NULL);\n\t\t}\n\t}\n}", "label_name": "CWE-287", "label": "287"} -{"code": "static pyc_object *get_array_object_generic(RBuffer *buffer, ut32 size) {\n\tpyc_object *tmp = NULL;\n\tpyc_object *ret = NULL;\n\tut32 i = 0;\n\n\tret = R_NEW0 (pyc_object);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\tret->data = r_list_newf ((RListFree)free_object);\n\tif (!ret->data) {\n\t\tfree (ret);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < size; i++) {\n\t\ttmp = get_object (buffer);\n\t\tif (!tmp) {\n\t\t\tr_list_free (ret->data);\n\t\t\tR_FREE (ret);\n\t\t\treturn NULL;\n\t\t}\n\t\tif (!r_list_append (ret->data, tmp)) {\n\t\t\tfree_object (tmp);\n\t\t\tr_list_free (ret->data);\n\t\t\tfree (ret);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\treturn ret;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static st64 buf_format(RBuffer *dst, RBuffer *src, const char *fmt, int n) {\n\tst64 res = 0;\n\tint i;\n\tfor (i = 0; i < n; i++) {\n\t\tint j;\n\t\tint m = 1;\n\t\tint tsize = 2;\n\t\tbool bigendian = true;\n\n\t\tfor (j = 0; fmt[j]; j++) {\n\t\t\tswitch (fmt[j]) {\n\t\t\tcase '0':\n\t\t\tcase '1':\n\t\t\tcase '2':\n\t\t\tcase '3':\n\t\t\tcase '4':\n\t\t\tcase '5':\n\t\t\tcase '6':\n\t\t\tcase '7':\n\t\t\tcase '8':\n\t\t\tcase '9':\n\t\t\t\tif (m == 1) {\n\t\t\t\t\tm = r_num_get (NULL, &fmt[j]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\tcase 's': tsize = 2; bigendian = false; break;\n\t\t\tcase 'S': tsize = 2; bigendian = true; break;\n\t\t\tcase 'i': tsize = 4; bigendian = false; break;\n\t\t\tcase 'I': tsize = 4; bigendian = true; break;\n\t\t\tcase 'l': tsize = 8; bigendian = false; break;\n\t\t\tcase 'L': tsize = 8; bigendian = true; break;\n\t\t\tcase 'c': tsize = 1; bigendian = false; break;\n\t\t\tdefault: return -1;\n\t\t\t}\n\n\t\t\tint k;\n\t\t\tfor (k = 0; k < m; k++) {\n\t\t\t\tut8 tmp[sizeof (ut64)];\n\t\t\t\tut8 d1;\n\t\t\t\tut16 d2;\n\t\t\t\tut32 d3;\n\t\t\t\tut64 d4;\n\t\t\t\tst64 r = r_buf_read (src, tmp, tsize);\n\t\t\t\tif (r < tsize) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tswitch (tsize) {\n\t\t\t\tcase 1:\n\t\t\t\t\td1 = r_read_ble8 (tmp);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d1, 1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\td2 = r_read_ble16 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d2, 2);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\td3 = r_read_ble32 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d3, 4);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\td4 = r_read_ble64 (tmp, bigendian);\n\t\t\t\t\tr = r_buf_write (dst, (ut8 *)&d4, 8);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (r < 0) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tres += r;\n\t\t\t}\n\t\t\tm = 1;\n\t\t}\n\t}\n\treturn res;\n}", "label_name": "CWE-400", "label": "400"} -{"code": "void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub)\n{\n int width = decoder_info->width;\n int height = decoder_info->height;\n stream_t *stream = decoder_info->stream;\n frame_type_t frame_type = decoder_info->frame_info.frame_type;\n int split_flag = 0;\n\n if (yposY >= height || xposY >= width)\n return;\n\n int decode_this_size = (yposY + size <= height) && (xposY + size <= width);\n int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME;\n\n int bit_start = stream->bitcnt;\n\n int mode = MODE_SKIP;\n \n block_context_t block_context;\n TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts);\n decoder_info->block_context = &block_context;\n\n split_flag = decode_super_mode(decoder_info,size,decode_this_size);\n mode = decoder_info->mode;\n \n /* Read delta_qp and set block-level qp */\n if (size == (1<log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) {\n /* Read delta_qp */\n int delta_qp = read_delta_qp(stream);\n int prev_qp;\n if (yposY == 0 && xposY == 0)\n prev_qp = decoder_info->frame_info.qp;\n else\n prev_qp = decoder_info->frame_info.qpb;\n decoder_info->frame_info.qpb = prev_qp + delta_qp;\n }\n\n decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start);\n\n if (split_flag){\n int new_size = size/2;\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub);\n }\n else if (decode_this_size || decode_rectangular_size){\n decode_block(decoder_info,size,yposY,xposY,sub);\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode)\n{\n\tM_fs_info_t *info = NULL;\n\tchar *pold = NULL;\n\tchar *pnew = NULL;\n\tM_fs_type_t type;\n\tM_bool ret = M_TRUE;\n\n\tif (mode & M_FS_FILE_MODE_OVERWRITE)\n\t\treturn M_TRUE;\n\n\t/* If we're not overwriting we need to verify existance.\n \t *\n \t * For files we need to check if the file name exists in the\n\t * directory it's being copied to.\n\t *\n\t * For directories we need to check if the directory name\n\t * exists in the directory it's being copied to.\n\t */\n\n\tif (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS)\n\t\treturn M_FALSE;\n\n\ttype = M_fs_info_get_type(info);\n\tM_fs_info_destroy(info);\n\n\tif (type != M_FS_TYPE_DIR) {\n\t\t/* File exists at path. */\n\t\tif (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS)\n\t\t{\n\t\t\tret = M_FALSE;\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t/* Is dir */\n\tpold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO);\n\tpnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO);\n\tif (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {\n\t\tret = M_FALSE;\n\t\tgoto done;\n\t}\n\ndone:\n\tM_free(pnew);\n\tM_free(pold);\n\treturn ret;\n}", "label_name": "CWE-732", "label": "732"} -{"code": "M_bool M_fs_path_ishidden(const char *path, M_fs_info_t *info)\n{\n\tM_list_str_t *path_parts;\n\tsize_t len;\n\tM_bool ret = M_FALSE;\n\n\t(void)info;\n\n\tif (path == NULL || *path == '\\0') {\n\t\treturn M_FALSE;\n\t}\n\n\t/* Hidden. Check if the first character of the last part of the path. Either the file or directory name itself\n \t * starts with a '.'. */\n\tpath_parts = M_fs_path_componentize_path(path, M_FS_SYSTEM_UNIX);\n\tlen = M_list_str_len(path_parts);\n\tif (len > 0) {\n\t\tif (*M_list_str_at(path_parts, len-1) == '.') {\n\t\t\tret = M_TRUE;\n\t\t}\n\t}\n\tM_list_str_destroy(path_parts);\n\n\treturn ret;\n}", "label_name": "CWE-732", "label": "732"} -{"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": "119"} -{"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": "119"} -{"code": "static int read_private_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tconst sc_acl_entry_t *e;\n\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I0012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\tif (e == NULL || e->method == SC_AC_NEVER)\n\t\treturn 10;\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_private_key(p, keysize, rsa);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static int read_private_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tconst sc_acl_entry_t *e;\n\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I0012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\tif (e == NULL || e->method == SC_AC_NEVER)\n\t\treturn 10;\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_private_key(p, keysize, rsa);\n}", "label_name": "CWE-119", "label": "119"} -{"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": "119"} -{"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": "119"} -{"code": "char *url_decode_r(char *to, char *url, size_t size) {\n char *s = url, // source\n *d = to, // destination\n *e = &to[size - 1]; // destination end\n\n while(*s && d < e) {\n if(unlikely(*s == '%')) {\n if(likely(s[1] && s[2])) {\n *d++ = from_hex(s[1]) << 4 | from_hex(s[2]);\n s += 2;\n }\n }\n else if(unlikely(*s == '+'))\n *d++ = ' ';\n\n else\n *d++ = *s;\n\n s++;\n }\n\n *d = '\\0';\n\n return to;\n}", "label_name": "CWE-116", "label": "116"} -{"code": "ber_parse_header(STREAM s, int tagval, int *length)\n{\n\tint tag, len;\n\n\tif (tagval > 0xff)\n\t{\n\t\tin_uint16_be(s, tag);\n\t}\n\telse\n\t{\n\t\tin_uint8(s, tag);\n\t}\n\n\tif (tag != tagval)\n\t{\n\t\tlogger(Core, Error, \"ber_parse_header(), expected tag %d, got %d\", tagval, tag);\n\t\treturn False;\n\t}\n\n\tin_uint8(s, len);\n\n\tif (len & 0x80)\n\t{\n\t\tlen &= ~0x80;\n\t\t*length = 0;\n\t\twhile (len--)\n\t\t\tnext_be(s, *length);\n\t}\n\telse\n\t\t*length = len;\n\n\treturn s_check(s);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "find_auth_end (FlatpakProxyClient *client, Buffer *buffer)\n{\n guchar *match;\n int i;\n\n /* First try to match any leftover at the start */\n if (client->auth_end_offset > 0)\n {\n gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset;\n gsize to_match = MIN (left, buffer->pos);\n /* Matched at least up to to_match */\n if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0)\n {\n client->auth_end_offset += to_match;\n\n /* Matched all */\n if (client->auth_end_offset == strlen (AUTH_END_STRING))\n return to_match;\n\n /* Matched to end of buffer */\n return -1;\n }\n\n /* Did not actually match at start */\n client->auth_end_offset = -1;\n }\n\n /* Look for whole match inside buffer */\n match = memmem (buffer, buffer->pos,\n AUTH_END_STRING, strlen (AUTH_END_STRING));\n if (match != NULL)\n return match - buffer->data + strlen (AUTH_END_STRING);\n\n /* Record longest prefix match at the end */\n for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--)\n {\n if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0)\n {\n client->auth_end_offset = i;\n break;\n }\n }\n\n return -1;\n}", "label_name": "CWE-436", "label": "436"} -{"code": "SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )\n{\n SQLWCHAR *chr;\n int len = 0;\n\n if ( !in )\n {\n return in;\n }\n \n while ( in[ len ] != 0 || in[ len + 1 ] != 0 )\n {\n len ++;\n }\n\n chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));\n\n len = 0;\n while ( in[ len ] != 0 || in[ len + 1 ] != 0 )\n {\n chr[ len ] = in[ len ];\n len ++;\n }\n chr[ len ++ ] = 0;\n chr[ len ++ ] = 0;\n\n return chr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static void prefetch_enc(void)\n{\n prefetch_table((const void *)encT, sizeof(encT));\n}", "label_name": "CWE-668", "label": "668"} -{"code": "escapes(cp, tp)\nconst char\t*cp;\nchar *tp;\n{\n while (*cp) {\n\tint\tcval = 0, meta = 0;\n\n\tif (*cp == '\\\\' && cp[1] && index(\"mM\", cp[1]) && cp[2]) {\n\t\tmeta = 1;\n\t\tcp += 2;\n\t}\n\tif (*cp == '\\\\' && cp[1] && index(\"0123456789xXoO\", cp[1]) && cp[2]) {\n\t NEARDATA const char hex[] = \"00112233445566778899aAbBcCdDeEfF\";\n\t const char *dp;\n\t int dcount = 0;\n\n\t cp++;\n\t if (*cp == 'x' || *cp == 'X')\n\t\tfor (++cp; *cp && (dp = index(hex, *cp)) && (dcount++ < 2); cp++)\n\t\t cval = (cval * 16) + ((int)(dp - hex) / 2);\n\t else if (*cp == 'o' || *cp == 'O')\n\t\tfor (++cp; *cp && (index(\"01234567\",*cp)) && (dcount++ < 3); cp++)\n\t\t cval = (cval * 8) + (*cp - '0');\n\t else\n\t\tfor (; *cp && (index(\"0123456789\",*cp)) && (dcount++ < 3); cp++)\n\t\t cval = (cval * 10) + (*cp - '0');\n\t} else if (*cp == '\\\\' && cp[1]) {\t/* C-style character escapes */\n\t switch (*++cp) {\n\t case '\\\\': cval = '\\\\'; break;\n\t case 'n': cval = '\\n'; break;\n\t case 't': cval = '\\t'; break;\n\t case 'b': cval = '\\b'; break;\n\t case 'r': cval = '\\r'; break;\n\t default: cval = *cp;\n\t }\n\t cp++;\n\t} else if (*cp == '^' && cp[1]) { /* expand control-character syntax */\n\t cval = (*++cp & 0x1f);\n\t cp++;\n\t} else\n\t cval = *cp++;\n\n\tif (meta)\n\t cval |= 0x80;\n\t*tp++ = cval;\n }\n *tp = '\\0';\n}", "label_name": "CWE-269", "label": "269"} -{"code": "fixExec2Error(int action,\n u_char * var_val,\n u_char var_val_type,\n size_t var_val_len,\n u_char * statP, oid * name, size_t name_len)\n{\n netsnmp_old_extend *exten = NULL;\n unsigned int idx;\n\n idx = name[name_len-1] -1;\n exten = &compatability_entries[ idx ];\n\n#ifndef NETSNMP_NO_WRITE_SUPPORT\n switch (action) {\n case MODE_SET_RESERVE1:\n if (var_val_type != ASN_INTEGER) {\n snmp_log(LOG_ERR, \"Wrong type != int\\n\");\n return SNMP_ERR_WRONGTYPE;\n }\n idx = *((long *) var_val);\n if (idx != 1) {\n snmp_log(LOG_ERR, \"Wrong value != 1\\n\");\n return SNMP_ERR_WRONGVALUE;\n }\n if (!exten || !exten->efix_entry) {\n snmp_log(LOG_ERR, \"No command to run\\n\");\n return SNMP_ERR_GENERR;\n }\n return SNMP_ERR_NOERROR;\n\n case MODE_SET_COMMIT:\n netsnmp_cache_check_and_reload( exten->efix_entry->cache );\n }\n#endif /* !NETSNMP_NO_WRITE_SUPPORT */\n return SNMP_ERR_NOERROR;\n}", "label_name": "CWE-269", "label": "269"} -{"code": "ChunkedDecode(Request *reqPtr, bool update)\n{\n const Tcl_DString *bufPtr;\n const char *end, *chunkStart;\n bool success = NS_TRUE;\n\n NS_NONNULL_ASSERT(reqPtr != NULL);\n\n bufPtr = &reqPtr->buffer;\n end = bufPtr->string + bufPtr->length;\n chunkStart = bufPtr->string + reqPtr->chunkStartOff;\n\n while (reqPtr->chunkStartOff < (size_t)bufPtr->length) {\n char *p = strstr(chunkStart, \"\\r\\n\");\n size_t chunk_length;\n\n if (p == NULL) {\n Ns_Log(DriverDebug, \"ChunkedDecode: chunk did not find end-of-line\");\n success = NS_FALSE;\n break;\n }\n\n *p = '\\0';\n chunk_length = (size_t)strtol(chunkStart, NULL, 16);\n *p = '\\r';\n\n if (p + 2 + chunk_length > end) {\n Ns_Log(DriverDebug, \"ChunkedDecode: chunk length past end of buffer\");\n success = NS_FALSE;\n break;\n }\n if (update) {\n char *writeBuffer = bufPtr->string + reqPtr->chunkWriteOff;\n\n memmove(writeBuffer, p + 2, chunk_length);\n reqPtr->chunkWriteOff += chunk_length;\n *(writeBuffer + chunk_length) = '\\0';\n }\n reqPtr->chunkStartOff += (size_t)(p - chunkStart) + 4u + chunk_length;\n chunkStart = bufPtr->string + reqPtr->chunkStartOff;\n }\n\n return success;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "error_t am335xEthAddVlanAddrEntry(uint_t port, uint_t vlanId, MacAddr *macAddr)\n{\n error_t error;\n uint_t index;\n Am335xAleEntry entry;\n\n //Ensure that there are no duplicate address entries in the ALE table\n index = am335xEthFindVlanAddrEntry(vlanId, macAddr);\n\n //No matching entry found?\n if(index >= CPSW_ALE_MAX_ENTRIES)\n {\n //Find a free entry in the ALE table\n index = am335xEthFindFreeEntry();\n }\n\n //Sanity check\n if(index < CPSW_ALE_MAX_ENTRIES)\n {\n //Set up a VLAN/address table entry\n entry.word2 = 0;\n entry.word1 = CPSW_ALE_WORD1_ENTRY_TYPE_VLAN_ADDR;\n entry.word0 = 0;\n\n //Multicast address?\n if(macIsMulticastAddr(macAddr))\n {\n //Set port mask\n entry.word2 |= CPSW_ALE_WORD2_SUPER |\n CPSW_ALE_WORD2_PORT_LIST(1 << port) |\n CPSW_ALE_WORD2_PORT_LIST(1 << CPSW_CH0);\n\n //Set multicast forward state\n entry.word1 |= CPSW_ALE_WORD1_MCAST_FWD_STATE(0);\n }\n\n //Set VLAN identifier\n entry.word1 |= CPSW_ALE_WORD1_VLAN_ID(vlanId);\n\n //Copy the upper 16 bits of the unicast address\n entry.word1 |= (macAddr->b[0] << 8) | macAddr->b[1];\n\n //Copy the lower 32 bits of the unicast address\n entry.word0 |= (macAddr->b[2] << 24) | (macAddr->b[3] << 16) |\n (macAddr->b[4] << 8) | macAddr->b[5];\n\n //Add a new entry to the ALE table\n am335xEthWriteEntry(index, &entry);\n\n //Sucessful processing\n error = NO_ERROR;\n }\n else\n {\n //The ALE table is full\n error = ERROR_FAILURE;\n }\n\n //Return status code\n return error;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void lpc546xxEthEnableIrq(NetInterface *interface)\n{\n //Enable Ethernet MAC interrupts\n NVIC_EnableIRQ(ETHERNET_IRQn);\n\n //Valid Ethernet PHY or switch driver?\n if(interface->phyDriver != NULL)\n {\n //Enable Ethernet PHY interrupts\n interface->phyDriver->enableIrq(interface);\n }\n else if(interface->switchDriver != NULL)\n {\n //Enable Ethernet switch interrupts\n interface->switchDriver->enableIrq(interface);\n }\n else\n {\n //Just for sanity\n }\n}", "label_name": "CWE-20", "label": "20"} -{"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": "20"} -{"code": "void rza1EthEventHandler(NetInterface *interface)\n{\n error_t error;\n\n //Packet received?\n if((ETHER.EESR0 & ETHER_EESR0_FR) != 0)\n {\n //Clear FR interrupt flag\n ETHER.EESR0 = ETHER_EESR0_FR;\n\n //Process all pending packets\n do\n {\n //Read incoming packet\n error = rza1EthReceivePacket(interface);\n\n //No more data in the receive buffer?\n } while(error != ERROR_BUFFER_EMPTY);\n }\n\n //Re-enable EDMAC interrupts\n ETHER.EESIPR0 = ETHER_EESIPR0_TWBIP | ETHER_EESIPR0_FRIP;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "add_link_ref(\n\tstruct link_ref **references,\n\tconst uint8_t *name, size_t name_size)\n{\n\tstruct link_ref *ref = calloc(1, sizeof(struct link_ref));\n\n\tif (!ref)\n\t\treturn NULL;\n\n\tref->id = hash_link_ref(name, name_size);\n\tref->next = references[ref->id % REF_TABLE_SIZE];\n\n\treferences[ref->id % REF_TABLE_SIZE] = ref;\n\treturn ref;\n}", "label_name": "CWE-327", "label": "327"} -{"code": "int main(int argc, char **argv, char **envp)\n{\n\tint opt;\n\n\twhile ((opt = getopt(argc, argv, \"b:h:k:p:q:w:z:xv\")) != -1) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\ttmate_settings->bind_addr = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\ttmate_settings->tmate_host = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\ttmate_settings->keys_dir = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\ttmate_settings->ssh_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\ttmate_settings->ssh_port_advertized = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\ttmate_settings->websocket_hostname = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\ttmate_settings->websocket_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\ttmate_settings->use_proxy_protocol = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\ttmate_settings->log_level++;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tinit_logging(tmate_settings->log_level);\n\n\tsetup_locale();\n\n\tif (!tmate_settings->tmate_host)\n\t\ttmate_settings->tmate_host = get_full_hostname();\n\n\tcmdline = *argv;\n\tcmdline_end = *envp;\n\n\ttmate_preload_trace_lib();\n\ttmate_catch_sigsegv();\n\ttmate_init_rand();\n\n\tif ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/sessions\", 0703) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\t/* The websocket server needs to access the /session dir to rename sockets */\n\tif ((chmod(TMATE_WORKDIR, 0701) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/sessions\", 0703) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\ttmate_ssh_server_main(tmate_session,\n\t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n\treturn 0;\n}", "label_name": "CWE-732", "label": "732"} -{"code": "uint16_t mesg_id (void) {\n\tstatic uint16_t id = 0;\n\n\tif (!id) {\n\t\tsrandom (time (NULL));\n\t\tid = random ();\n\t}\n\tid++;\n\n\tif (T.debug > 4)\n\t\tsyslog (LOG_DEBUG, \"mesg_id() = %d\", id);\n\treturn id;\n}", "label_name": "CWE-330", "label": "330"} -{"code": " def __init__(self, formats=None, content_types=None, datetime_formatting=None):\n self.supported_formats = []\n self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601')\n \n if formats is not None:\n self.formats = formats\n \n if content_types is not None:\n self.content_types = content_types\n \n if datetime_formatting is not None:\n self.datetime_formatting = datetime_formatting\n \n for format in self.formats:\n try:\n self.supported_formats.append(self.content_types[format])\n except KeyError:\n raise ImproperlyConfigured(\"Content type for specified type '%s' not found. Please provide it at either the class level or via the arguments.\" % format)", "label_name": "CWE-20", "label": "20"} -{"code": " def get_mime_for_format(self, format):\n \"\"\"\n Given a format, attempts to determine the correct MIME type.\n \n If not available on the current ``Serializer``, returns\n ``application/json`` by default.\n \"\"\"\n try:\n return self.content_types[format]\n except KeyError:\n return 'application/json'", "label_name": "CWE-20", "label": "20"} -{"code": "def intermediate_dir():\n \"\"\" Location in temp dir for storing .cpp and .o files during\n builds.\n \"\"\"\n python_name = \"python%d%d_intermediate\" % tuple(sys.version_info[:2])\n path = os.path.join(tempfile.gettempdir(),\"%s\"%whoami(),python_name)\n if not os.path.exists(path):\n os.makedirs(path, mode=0o700)\n return path", "label_name": "CWE-269", "label": "269"} -{"code": " def generic_visit(self, node):\n if type(node) not in SAFE_NODES:\n #raise Exception(\"invalid expression (%s) type=%s\" % (expr, type(node)))\n raise Exception(\"invalid expression (%s)\" % expr)\n super(CleansingNodeVisitor, self).generic_visit(node)", "label_name": "CWE-74", "label": "74"} -{"code": " def __init__(self, conn=None, host=None, result=None, \n comm_ok=True, diff=dict()):\n\n # which host is this ReturnData about?\n if conn is not None:\n self.host = conn.host\n delegate = getattr(conn, 'delegate', None)\n if delegate is not None:\n self.host = delegate\n\n else:\n self.host = host\n\n self.result = result\n self.comm_ok = comm_ok\n\n # if these values are set and used with --diff we can show\n # changes made to particular files\n self.diff = diff\n\n if type(self.result) in [ str, unicode ]:\n self.result = utils.parse_json(self.result)\n\n\n if self.host is None:\n raise Exception(\"host not set\")\n if type(self.result) != dict:\n raise Exception(\"dictionary result expected\")", "label_name": "CWE-20", "label": "20"} -{"code": " def test_patch_bot_role(self) -> None:\n self.login(\"desdemona\")\n\n email = \"default-bot@zulip.com\"\n user_profile = self.get_bot_user(email)\n\n do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile)\n\n req = dict(role=UserProfile.ROLE_GUEST)\n\n result = self.client_patch(f\"/json/bots/{self.get_bot_user(email).id}\", req)\n self.assert_json_success(result)\n\n user_profile = self.get_bot_user(email)\n self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST)\n\n # Test for not allowing a non-owner user to make assign a bot an owner role\n desdemona = self.example_user(\"desdemona\")\n do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)\n\n req = dict(role=UserProfile.ROLE_REALM_OWNER)\n\n result = self.client_patch(f\"/json/bots/{self.get_bot_user(email).id}\", req)\n self.assert_json_error(result, \"Must be an organization owner\")", "label_name": "CWE-285", "label": "285"} -{"code": " def _checkPolkitPrivilege(self, sender, conn, privilege):\n # from jockey\n \"\"\"\n Verify that sender has a given PolicyKit privilege.\n\n sender is the sender's (private) D-BUS name, such as \":1:42\"\n (sender_keyword in @dbus.service.methods). conn is\n the dbus.Connection object (connection_keyword in\n @dbus.service.methods). privilege is the PolicyKit privilege string.\n\n This method returns if the caller is privileged, and otherwise throws a\n PermissionDeniedByPolicy exception.\n \"\"\"\n if sender is None and conn is None:\n # called locally, not through D-BUS\n return\n if not self.enforce_polkit:\n # that happens for testing purposes when running on the session\n # bus, and it does not make sense to restrict operations here\n return\n\n info = SenderInfo(sender, conn)\n\n # get peer PID\n pid = info.connectionPid()\n\n # query PolicyKit\n self._initPolkit()\n try:\n # we don't need is_challenge return here, since we call with AllowUserInteraction\n (is_auth, _, details) = self.polkit.CheckAuthorization(\n ('unix-process', {'pid': dbus.UInt32(pid, variant_level=1),\n 'start-time': dbus.UInt64(0, variant_level=1)}),\n privilege, {'': ''}, dbus.UInt32(1), '', timeout=3000)\n except dbus.DBusException as e:\n if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':\n # polkitd timed out, connect again\n self.polkit = None\n return self._checkPolkitPrivilege(sender, conn, privilege)\n else:\n raise\n\n if not is_auth:\n raise PermissionDeniedByPolicy(privilege)", "label_name": "CWE-362", "label": "362"} -{"code": " def read_config(self, config, **kwargs):\n consent_config = config.get(\"user_consent\")\n self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]\n\n if consent_config is None:\n return\n self.user_consent_version = str(consent_config[\"version\"])\n self.user_consent_template_dir = self.abspath(consent_config[\"template_dir\"])\n if not path.isdir(self.user_consent_template_dir):\n raise ConfigError(\n \"Could not find template directory '%s'\"\n % (self.user_consent_template_dir,)\n )\n self.user_consent_server_notice_content = consent_config.get(\n \"server_notice_content\"\n )\n self.block_events_without_consent_error = consent_config.get(\n \"block_events_error\"\n )\n self.user_consent_server_notice_to_guests = bool(\n consent_config.get(\"send_server_notice_to_guests\", False)\n )\n self.user_consent_at_registration = bool(\n consent_config.get(\"require_at_registration\", False)\n )\n self.user_consent_policy_name = consent_config.get(\n \"policy_name\", \"Privacy Policy\"\n )", "label_name": "CWE-74", "label": "74"} -{"code": "def safe_text(raw_text: str) -> jinja2.Markup:\n \"\"\"\n Process text: treat it as HTML but escape any tags (ie. just escape the\n HTML) then linkify it.\n \"\"\"\n return jinja2.Markup(\n bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False))\n )", "label_name": "CWE-74", "label": "74"} -{"code": " def render_POST(self, request):\n \"\"\"\n Register with the Identity Server\n \"\"\"\n send_cors(request)\n\n args = get_args(request, ('matrix_server_name', 'access_token'))\n\n result = yield self.client.get_json(\n \"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s\" % (\n args['matrix_server_name'], urllib.parse.quote(args['access_token']),\n ),\n 1024 * 5,\n )\n if 'sub' not in result:\n raise Exception(\"Invalid response from homeserver\")\n\n user_id = result['sub']\n tok = yield issueToken(self.sydent, user_id)\n\n # XXX: `token` is correct for the spec, but we released with `access_token`\n # for a substantial amount of time. Serve both to make spec-compliant clients\n # happy.\n defer.returnValue({\n \"access_token\": tok,\n \"token\": tok,\n })", "label_name": "CWE-20", "label": "20"} -{"code": "def _wsse_username_token(cnonce, iso_now, password):\n return base64.b64encode(\n _sha(\"%s%s%s\" % (cnonce, iso_now, password)).digest()\n ).strip()", "label_name": "CWE-400", "label": "400"} -{"code": "def _parse_www_authenticate(headers, headername=\"www-authenticate\"):\n \"\"\"Returns a dictionary of dictionaries, one dict\n per auth_scheme.\"\"\"\n retval = {}\n if headername in headers:\n try:\n\n authenticate = headers[headername].strip()\n www_auth = (\n USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED\n )\n while authenticate:\n # Break off the scheme at the beginning of the line\n if headername == \"authentication-info\":\n (auth_scheme, the_rest) = (\"digest\", authenticate)\n else:\n (auth_scheme, the_rest) = authenticate.split(\" \", 1)\n # Now loop over all the key value pairs that come after the scheme,\n # being careful not to roll into the next scheme\n match = www_auth.search(the_rest)\n auth_params = {}\n while match:\n if match and len(match.groups()) == 3:\n (key, value, the_rest) = match.groups()\n auth_params[key.lower()] = UNQUOTE_PAIRS.sub(\n r\"\\1\", value\n ) # '\\\\'.join([x.replace('\\\\', '') for x in value.split('\\\\\\\\')])\n match = www_auth.search(the_rest)\n retval[auth_scheme.lower()] = auth_params\n authenticate = the_rest.strip()\n\n except ValueError:\n raise MalformedHeader(\"WWW-Authenticate\")\n return retval", "label_name": "CWE-400", "label": "400"} -{"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": "400"} -{"code": "def test_basic():\n # Test Basic Authentication\n http = httplib2.Http()\n password = tests.gen_password()\n handler = tests.http_reflect_with_auth(\n allow_scheme=\"basic\", allow_credentials=((\"joe\", password),)\n )\n with tests.server_request(handler, request_count=3) as uri:\n response, content = http.request(uri, \"GET\")\n assert response.status == 401\n http.add_credentials(\"joe\", password)\n response, content = http.request(uri, \"GET\")\n assert response.status == 200", "label_name": "CWE-400", "label": "400"} -{"code": " def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n if user is None:\n return FormattedResponse(status=HTTP_401_UNAUTHORIZED, d={'reason': 'login_failed'}, m='login_failed')\n\n if not user.has_2fa():\n return FormattedResponse(status=HTTP_401_UNAUTHORIZED, d={'reason': '2fa_not_enabled'}, m='2fa_not_enabled')\n\n token = serializer.data['tfa']\n\n if len(token) == 6:\n if user.totp_device is not None and user.totp_device.validate_token(token):\n return self.issue_token(user)\n elif len(token) == 8:\n for code in user.backup_codes:\n if token == code.code:\n code.delete()\n return self.issue_token(user)\n\n return self.issue_token(user)", "label_name": "CWE-287", "label": "287"} -{"code": " def validate(self, data):\n user = providers.get_provider('login').login_user(**data, context=self.context)\n if user is not None:\n data['user'] = user\n return data", "label_name": "CWE-287", "label": "287"} -{"code": " def _ensureSnapshotsFolder(self, subdir=None):\n \"\"\" Ensure that the appropriate snapshot folder exists.\n \"\"\"\n path = ['snapshots', self._snapshot_id]\n\n if subdir is not None:\n path.extend(subdir.split('/'))\n\n current = self._tool\n\n for element in path:\n\n if element not in current.objectIds():\n # No Unicode IDs!\n current._setObject(str(element), Folder(element))\n\n current = current._getOb(element)\n\n return current", "label_name": "CWE-200", "label": "200"} -{"code": " def auth_user_registration(self):\n return self.appbuilder.get_app.config[\"AUTH_USER_REGISTRATION\"]", "label_name": "CWE-287", "label": "287"} -{"code": " def auth_ldap_use_tls(self):\n return self.appbuilder.get_app.config[\"AUTH_LDAP_USE_TLS\"]", "label_name": "CWE-287", "label": "287"} -{"code": " def auth_role_public(self):\n return self.appbuilder.get_app.config[\"AUTH_ROLE_PUBLIC\"]", "label_name": "CWE-287", "label": "287"} -{"code": "def verify_password(plain_password, user_password):\n if plain_password == user_password:\n LOG.debug(\"password true\")\n return True\n return False", "label_name": "CWE-287", "label": "287"} -{"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": "285"} -{"code": " def test_with_admins(self) -> None:\n no_admins = InstanceConfig(admins=None)\n with_admins = InstanceConfig(admins=[UUID(int=0)])\n with_admins_2 = InstanceConfig(admins=[UUID(int=1)])\n\n no_admins.update(with_admins)\n self.assertEqual(no_admins.admins, None)\n\n with_admins.update(with_admins_2)\n self.assertEqual(with_admins.admins, with_admins_2.admins)", "label_name": "CWE-346", "label": "346"} -{"code": "def test_change_response_class_to_text():\n mw = _get_mw()\n req = SplashRequest('http://example.com/', magic_response=True)\n req = mw.process_request(req, None)\n # Such response can come when downloading a file,\n # or returning splash:html(): the headers say it's binary,\n # but it can be decoded so it becomes a TextResponse.\n resp = TextResponse('http://mysplash.example.com/execute',\n headers={b'Content-Type': b'application/pdf'},\n body=b'ascii binary data',\n encoding='utf-8')\n resp2 = mw.process_response(req, resp, None)\n assert isinstance(resp2, TextResponse)\n assert resp2.url == 'http://example.com/'\n assert resp2.headers == {b'Content-Type': [b'application/pdf']}\n assert resp2.body == b'ascii binary data'", "label_name": "CWE-200", "label": "200"} -{"code": "def _get_mw():\n crawler = _get_crawler({})\n return SplashMiddleware.from_crawler(crawler)", "label_name": "CWE-200", "label": "200"} -{"code": " def load(self):\n config_type = type(self).__name__.lower()\n try:\n with self.path.open(encoding=UTF8) as f:\n try:\n data = json.load(f)\n except ValueError as e:\n raise ConfigFileError(\n f'invalid {config_type} file: {e} [{self.path}]'\n )\n self.update(data)\n except FileNotFoundError:\n pass\n except OSError as e:\n raise ConfigFileError(f'cannot read {config_type} file: {e}')", "label_name": "CWE-200", "label": "200"} -{"code": " def cookies(self, jar: RequestsCookieJar):\n # \n stored_attrs = ['value', 'path', 'secure', 'expires']\n self['cookies'] = {}\n for cookie in jar:\n self['cookies'][cookie.name] = {\n attname: getattr(cookie, attname)\n for attname in stored_attrs\n }", "label_name": "CWE-200", "label": "200"} -{"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": "119"} -{"code": "def _register_function_args(context: Context, sig: FunctionSignature) -> List[IRnode]:\n ret = []\n\n # the type of the calldata\n base_args_t = TupleType([arg.typ for arg in sig.base_args])\n\n # tuple with the abi_encoded args\n if sig.is_init_func:\n base_args_ofst = IRnode(0, location=DATA, typ=base_args_t, encoding=Encoding.ABI)\n else:\n base_args_ofst = IRnode(4, location=CALLDATA, typ=base_args_t, encoding=Encoding.ABI)\n\n for i, arg in enumerate(sig.base_args):\n\n arg_ir = get_element_ptr(base_args_ofst, i)\n\n if _should_decode(arg.typ):\n # allocate a memory slot for it and copy\n p = context.new_variable(arg.name, arg.typ, is_mutable=False)\n dst = IRnode(p, typ=arg.typ, location=MEMORY)\n\n copy_arg = make_setter(dst, arg_ir)\n copy_arg.source_pos = getpos(arg.ast_source)\n ret.append(copy_arg)\n else:\n # leave it in place\n context.vars[arg.name] = VariableRecord(\n name=arg.name,\n pos=arg_ir,\n typ=arg.typ,\n mutable=False,\n location=arg_ir.location,\n encoding=Encoding.ABI,\n )\n\n return ret", "label_name": "CWE-119", "label": "119"} -{"code": " def test_captcha_validate_value(self):\n captcha = FlaskSessionCaptcha(self.app)\n _default_routes(captcha, self.app)\n\n with self.app.test_request_context('/'):\n captcha.generate()\n answer = captcha.get_answer()\n assert not captcha.validate(value=\"wrong\")\n captcha.generate()\n answer = captcha.get_answer()\n assert captcha.validate(value=answer)", "label_name": "CWE-754", "label": "754"} -{"code": " def test_okp_ed25519_should_reject_non_string_key(self):\n algo = OKPAlgorithm()\n\n with pytest.raises(TypeError):\n algo.prepare_key(None)\n\n with open(key_path(\"testkey_ed25519\")) as keyfile:\n algo.prepare_key(keyfile.read())\n\n with open(key_path(\"testkey_ed25519.pub\")) as keyfile:\n algo.prepare_key(keyfile.read())", "label_name": "CWE-327", "label": "327"} -{"code": " public UserCause(User user, String message) {\n super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(\n user!=null ? user.getId() : Jenkins.ANONYMOUS.getName(),\n message != null ? \" : \" + message : \"\"\n ));\n this.user = user;\n }", "label_name": "CWE-200", "label": "200"} -{"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": "287"} -{"code": " public static void endRequest() {\n final List result = CACHE.get();\n CACHE.remove();\n if (result != null) {\n for (final RequestScopedItem item : result) {\n item.invalidate();\n }\n }\n }", "label_name": "CWE-362", "label": "362"} -{"code": " public OHttpSession removeSession(final String iSessionId) {\r\n acquireExclusiveLock();\r\n try {\r\n return sessions.remove(iSessionId);\r\n\r\n } finally {\r\n releaseExclusiveLock();\r\n }\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " public OHttpSession getSession(final String iId) {\r\n acquireSharedLock();\r\n try {\r\n\r\n final OHttpSession sess = sessions.get(iId);\r\n if (sess != null)\r\n sess.updateLastUpdatedOn();\r\n return sess;\r\n\r\n } finally {\r\n releaseSharedLock();\r\n }\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " protected void parseModuleConfigFile(Digester digester, String path)\n throws UnavailableException {\n\n InputStream input = null;\n try {\n URL url = getServletContext().getResource(path);\n\n // If the config isn't in the servlet context, try the class loader\n // which allows the config files to be stored in a jar\n if (url == null) {\n url = getClass().getResource(path);\n }\n \n if (url == null) {\n String msg = internal.getMessage(\"configMissing\", path);\n log.error(msg);\n throw new UnavailableException(msg);\n }\n\t \n InputSource is = new InputSource(url.toExternalForm());\n input = url.openStream();\n is.setByteStream(input);\n digester.parse(is);\n\n } catch (MalformedURLException e) {\n handleConfigException(path, e);\n } catch (IOException e) {\n handleConfigException(path, e);\n } catch (SAXException e) {\n handleConfigException(path, e);\n } finally {\n if (input != null) {\n try {\n input.close();\n } catch (IOException e) {\n throw new UnavailableException(e.getMessage());\n }\n }\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {\n\n // send a GET request to the ExampleService factory to populate auth cache on each peer.\n // since factory is not OWNER_SELECTION service, request goes to the specified node.\n for (VerificationHost peer : this.host.getInProcessHostMap().values()) {\n peer.setAuthorizationContext(authContext);\n\n // based on the role created in test, all users have access to ExampleService\n this.host.sendAndWaitExpectSuccess(\n Operation.createGet(UriUtils.buildStatsUri(peer, ExampleService.FACTORY_LINK)));\n }\n\n this.host.waitFor(\"Timeout waiting for correct auth cache state\",\n () -> checkCacheInAllPeers(authContext.getToken(), true));\n }", "label_name": "CWE-732", "label": "732"} -{"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": "200"} -{"code": "\tprivate void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm) {\n\t\tIntent intent = new Intent(this, ConversationsActivity.class);\n\t\tintent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);\n\t\tintent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());\n\t\tif (text != null) {\n\t\t\tintent.putExtra(Intent.EXTRA_TEXT, text);\n\t\t\tif (asQuote) {\n\t\t\t\tintent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);\n\t\t\t}\n\t\t}\n\t\tif (nick != null) {\n\t\t\tintent.putExtra(ConversationsActivity.EXTRA_NICK, nick);\n\t\t\tintent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);\n\t\t}\n\t\tintent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);\n\t\tstartActivity(intent);\n\t\tfinish();\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic void switchToConversation(Conversation conversation, String text) {\n\t\tswitchToConversation(conversation, text, false, null, false);\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic void onTurnEnded(TurnEndedEvent event) {\n\t\tsuper.onTurnEnded(event);\n\n\t\tfinal String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();\n\n\t\tif (out.contains(\"access denied (java.net.SocketPermission\")\n\t\t\t\t|| out.contains(\"access denied (\\\"java.net.SocketPermission\\\"\")) {\n\t\t\tmessagedAccessDenied = true;\t\n\t\t}\t\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " final void addObject(CharSequence name, Object... values) {\n final AsciiString normalizedName = normalizeName(name);\n requireNonNull(values, \"values\");\n for (Object v : values) {\n requireNonNullElement(values, v);\n addObject(normalizedName, v);\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " final void add(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 add0(h, i, normalizedName, value);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testPseudoHeadersWithClearDoesNotLeak() {\n final HttpHeadersBase headers = newHttp2Headers();\n\n assertThat(headers.isEmpty()).isFalse();\n headers.clear();\n assertThat(headers.isEmpty()).isTrue();\n\n // Combine 2 headers together, make sure pseudo headers stay up front.\n headers.add(\"name1\", \"value1\");\n headers.scheme(\"nothing\");\n verifyPseudoHeadersFirst(headers);\n\n final HttpHeadersBase other = newEmptyHeaders();\n other.add(\"name2\", \"value2\");\n other.authority(\"foo\");\n verifyPseudoHeadersFirst(other);\n\n headers.add(other);\n verifyPseudoHeadersFirst(headers);\n\n // Make sure the headers are what we expect them to be, and no leaking behind the scenes.\n assertThat(headers.size()).isEqualTo(4);\n assertThat(headers.get(\"name1\")).isEqualTo(\"value1\");\n assertThat(headers.get(\"name2\")).isEqualTo(\"value2\");\n assertThat(headers.scheme()).isEqualTo(\"nothing\");\n assertThat(headers.authority()).isEqualTo(\"foo\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testSetOrdersPseudoHeadersCorrectly() {\n final HttpHeadersBase headers = newHttp2Headers();\n final HttpHeadersBase other = newEmptyHeaders();\n other.add(\"name2\", \"value2\");\n other.add(\"name3\", \"value3\");\n other.add(\"name4\", \"value4\");\n other.authority(\"foo\");\n\n final int headersSizeBefore = headers.size();\n headers.set(other);\n verifyPseudoHeadersFirst(headers);\n verifyAllPseudoHeadersPresent(headers);\n assertThat(headers.size()).isEqualTo(headersSizeBefore + 1);\n assertThat(headers.authority()).isEqualTo(\"foo\");\n assertThat(headers.get(\"name2\")).isEqualTo(\"value2\");\n assertThat(headers.get(\"name3\")).isEqualTo(\"value3\");\n assertThat(headers.get(\"name4\")).isEqualTo(\"value4\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void headersWithSameNamesButDifferentValuesShouldNotBeEquivalent() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n final HttpHeadersBase headers2 = newEmptyHeaders();\n headers1.add(\"name1\", \"value2\");\n assertThat(headers1).isNotEqualTo(headers2);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void emptyHeadersShouldBeEqual() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n final HttpHeadersBase headers2 = newEmptyHeaders();\n assertThat(headers2).isEqualTo(headers1);\n assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode());\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testClearResetsPseudoHeaderDivision() {\n final HttpHeadersBase http2Headers = newHttp2Headers();\n http2Headers.method(HttpMethod.POST);\n http2Headers.set(\"some\", \"value\");\n http2Headers.clear();\n http2Headers.method(HttpMethod.GET);\n assertThat(http2Headers.names()).containsExactly(HttpHeaderNames.METHOD);\n assertThat(http2Headers.getAll(HttpHeaderNames.METHOD)).containsExactly(\"GET\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void overridingSubClassExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new OverridingExample())))\n .isEmpty();\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void validateFail2(ViolationCollector col) {\n col.addViolation(FAILED + \"2\");\n }", "label_name": "CWE-74", "label": "74"} -{"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": "74"} -{"code": " public static SocketFactory getSocketFactory(Properties info) throws PSQLException {\n // Socket factory\n String socketFactoryClassName = PGProperty.SOCKET_FACTORY.get(info);\n if (socketFactoryClassName == null) {\n return SocketFactory.getDefault();\n }\n try {\n return (SocketFactory) ObjectFactory.instantiate(socketFactoryClassName, info, true,\n PGProperty.SOCKET_FACTORY_ARG.get(info));\n } catch (Exception e) {\n throw new PSQLException(\n GT.tr(\"The SocketFactory class provided {0} could not be instantiated.\",\n socketFactoryClassName),\n PSQLState.CONNECTION_FAILURE, e);\n }\n }", "label_name": "CWE-665", "label": "665"} -{"code": " public boolean isValid(Object value, ConstraintValidatorContext context) {\n if (value != null && StringUtils.isNotEmpty(String.valueOf(value))) {\n return true;\n }\n String errorMessage = String.format(\"Expected not empty value, got '%s'\", value);\n LOG.warn(errorMessage);\n\n context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();\n return false;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void add(File fileToAdd) {\n String[] args = new String[]{\"add\", fileToAdd.getName()};\n CommandLine gitAdd = gitWd().withArgs(args);\n runOrBomb(gitAdd);\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void shouldGetLatestModifications() throws Exception {\n List actual = hgCommand.latestOneModificationAsModifications();\n assertThat(actual.size(), is(1));\n final Modification modification = actual.get(0);\n assertThat(modification.getComment(), is(\"test\"));\n assertThat(modification.getUserName(), is(\"cruise\"));\n assertThat(modification.getModifiedFiles().size(), is(1));\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExistsOnParentSpace() 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.Y.Z&name=W&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n String spaceReferenceString = \"X.Y.Z\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(spaceReferenceString);\n when(mockRequest.getParameter(\"name\")).thenReturn(\"W\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider that allows usage in one of the target space's parents (top level in this\n // case).\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 or its children, be it a terminal or a non-terminal\n // document\n // Note2: We are creating X.Y.Z.W and using the template extracted from the template provider.\n verify(mockURLFactory).createURL(\"X.Y.Z.W\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=W\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void newDocumentWebHomeFromURL() throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // 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: The bebavior is the same for both a top level space and a child space WebHome.\n // Note2: The title is not \"WebHome\", but \"Y\" (the space's name) to avoid exposing \"WebHome\" in the UI.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null,\n \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void newDocumentButNonTerminalFromURL() throws Exception\n {\n // new document = xwiki:X.Y\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\"), \"Y\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Pass the tocreate=nonterminal request parameter\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"nonterminal\");\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 verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null,\n \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void existingDocumentFromUITemplateProviderSpecifiedTerminalOverridenFromUIToNonTerminal() 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 when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"nonterminal\");\n\n // Mock 1 existing template provider that creates terminal documents.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, true);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y.WebHome as non-terminal, even if the template provider says otherwise.\n // Also using a template, as specified in the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void existingDocumentFromUITopLevelDocument() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI name=Y\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y.WebHome since we default to non-terminal documents.\n verify(mockURLFactory).createURL(\"Y\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void existingDocumentNonTerminalFromUIDeprecatedIgnoringPage() 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&tocreate=space\n when(mockRequest.getParameter(\"space\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"page\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"space\");\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.WebHome instead of X.Y because the tocreate parameter says \"space\" and the page\n // parameter is ignored.\n verify(mockURLFactory).createURL(\"X\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=X\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void newDocumentFromURLTemplateProviderSpecifiedButNotAllowed() throws Exception\n {\n // new document = xwiki:X.Y\n DocumentReference documentReference =\n new DocumentReference(\"Y\", new SpaceReference(\"X\", new WikiReference(\"xwiki\")));\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"),\n Arrays.asList(\"AnythingButX\"));\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify that the create template is rendered, so the UI is displayed for the user to see the error.\n assertEquals(\"create\", result);\n\n // Check that the exception is properly set in the context for the UI to display.\n XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute(\"createException\");\n assertNotNull(exception);\n assertEquals(XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE, exception.getCode());\n\n // We should not get this far so no redirect should be done, just the template will be rendered.\n verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),\n any(), any(XWikiContext.class));\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void existingDocumentFromUITemplateProviderSpecifiedTerminal() 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 creates terminal documents.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, true);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y as terminal and using a template, as specified in the template\n // provider.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\",\n null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButNotAllowed() throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"),\n Arrays.asList(\"AnythingButX\"));\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify that the create template is rendered, so the UI is displayed for the user to see the error.\n assertEquals(\"create\", result);\n\n // Check that the exception is properly set in the context for the UI to display.\n XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute(\"createException\");\n assertNotNull(exception);\n assertEquals(XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE, exception.getCode());\n\n // We should not get this far so no redirect should be done, just the template will be rendered.\n verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),\n any(), any(XWikiContext.class));\n }", "label_name": "CWE-862", "label": "862"} -{"code": " void validSaveNewTranslation() throws Exception\n {\n when(mockForm.getLanguage()).thenReturn(\"fr\");\n when(mockClonedDocument.getTranslatedDocument(\"fr\", this.context)).thenReturn(mockClonedDocument);\n when(mockClonedDocument.getDocumentReference()).thenReturn(new DocumentReference(\"xwiki\", \"My\", \"Page\"));\n when(mockClonedDocument.getStore()).thenReturn(this.oldcore.getMockStore());\n when(xWiki.getStore()).thenReturn(this.oldcore.getMockStore());\n context.put(\"ajax\", true);\n when(xWiki.isMultiLingual(this.context)).thenReturn(true);\n when(mockRequest.getParameter(\"previousVersion\")).thenReturn(\"1.1\");\n when(mockRequest.getParameter(\"isNew\")).thenReturn(\"true\");\n assertFalse(saveAction.save(this.context));\n assertEquals(new Version(\"1.1\"), this.context.get(\"SaveAction.savedObjectVersion\"));\n verify(this.xWiki).checkSavingDocument(eq(USER_REFERENCE), any(XWikiDocument.class), eq(\"\"),\n eq(false), eq(this.context));\n verify(this.xWiki).saveDocument(any(XWikiDocument.class), eq(\"\"), eq(false), eq(this.context));\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void translate(EmoteListPacket packet, GeyserSession session) {\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {\n return;\n }\n\n session.refreshEmotes(packet.getPieceIds());\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(MapInfoRequestPacket packet, GeyserSession session) {\n long mapId = packet.getUniqueMapId();\n\n ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);\n if (mapPacket != null) {\n // Delay the packet 100ms to prevent the client from ignoring the packet\n GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),\n 100, TimeUnit.MILLISECONDS);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(MobEquipmentPacket packet, GeyserSession session) {\n if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||\n packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {\n // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention\n return;\n }\n\n // Send book update before switching hotbar slot\n session.getBookEditCache().checkForSend();\n\n session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());\n\n ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());\n session.sendDownstreamPacket(changeHeldItemPacket);\n\n if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {\n // Activate shield since we are already sneaking\n // (No need to send a release item packet - Java doesn't do this when swapping items)\n // Required to do it a tick later or else it doesn't register\n session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),\n 50, TimeUnit.MILLISECONDS);\n }\n\n // Java sends a cooldown indicator whenever you switch an item\n CooldownUtils.sendCooldown(session);\n\n // Update the interactive tag, if an entity is present\n if (session.getMouseoverEntity() != null) {\n InteractiveTagManager.updateTag(session, session.getMouseoverEntity());\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {\n PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket();\n broadcastPacket.setTrackingId(packet.getTrackingId());\n\n // Fetch the stored Loadstone\n LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());\n\n // If we don't have data for that ID tell the client its not found\n if (pos == null) {\n broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);\n session.sendUpstreamPacket(broadcastPacket);\n return;\n }\n\n broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);\n\n // Build the nbt data for the update\n NbtMapBuilder builder = NbtMap.builder();\n builder.putInt(\"dim\", DimensionUtils.javaToBedrock(pos.getDimension()));\n builder.putString(\"id\", String.format(\"%08X\", packet.getTrackingId()));\n\n builder.putByte(\"version\", (byte) 1); // Not sure what this is for\n builder.putByte(\"status\", (byte) 0); // Not sure what this is for\n\n // Build the position for the update\n IntList posList = new IntArrayList();\n posList.add(pos.getX());\n posList.add(pos.getY());\n posList.add(pos.getZ());\n builder.putList(\"pos\", NbtType.INT, posList);\n broadcastPacket.setTag(builder.build());\n\n session.sendUpstreamPacket(broadcastPacket);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(ServerEntityRemoveEffectPacket packet, GeyserSession session) {\n Entity entity;\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n session.getEffectCache().removeEffect(packet.getEffect());\n } else {\n entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n }\n if (entity == null)\n return;\n\n MobEffectPacket mobEffectPacket = new MobEffectPacket();\n mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE);\n mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());\n mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));\n session.sendUpstreamPacket(mobEffectPacket);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(ServerEntityTeleportPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n }\n if (entity == null) return;\n\n entity.teleport(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), packet.isOnGround());\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(ServerEntityVelocityPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n }\n if (entity == null) return;\n\n entity.setMotion(Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ()));\n\n if (entity == session.getRidingVehicleEntity() && entity instanceof AbstractHorseEntity) {\n // Horses for some reason teleport back when a SetEntityMotionPacket is sent while\n // a player is riding on them. Java clients seem to ignore it anyways.\n return;\n }\n\n if (entity instanceof ItemEntity) {\n // Don't bother sending entity motion packets for items\n // since the client doesn't seem to care\n return;\n }\n\n SetEntityMotionPacket entityMotionPacket = new SetEntityMotionPacket();\n entityMotionPacket.setRuntimeEntityId(entity.getGeyserId());\n entityMotionPacket.setMotion(entity.getMotion());\n\n session.sendUpstreamPacket(entityMotionPacket);\n }", "label_name": "CWE-287", "label": "287"} -{"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": "287"} -{"code": " public void translate(ServerMultiBlockChangePacket packet, GeyserSession session) {\n for (BlockChangeRecord record : packet.getRecords()) {\n ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition());\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {\n JsonNode certData;\n try {\n certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());\n } catch (IOException ex) {\n throw new RuntimeException(\"Certificate JSON can not be read.\");\n }\n\n JsonNode certChainData = certData.get(\"chain\");\n if (certChainData.getNodeType() != JsonNodeType.ARRAY) {\n throw new RuntimeException(\"Certificate data is not valid\");\n }\n\n encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);\n }", "label_name": "CWE-287", "label": "287"} -{"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": "20"} -{"code": " public static synchronized InitialContext getInitialContext() throws NamingException {\n if (context == null) {\n try {\n context = new InitialContext();\n } catch (Exception e) {\n throw handleException(e);\n }\n }\n return context;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public String accessToken(String username) {\n Algorithm algorithm = Algorithm.HMAC256(SECRET);\n\n return JWT.create()\n .withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME))\n .withIssuer(ISSUER)\n .withClaim(\"username\", username)\n .sign(algorithm);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static final String getRevision() {\n return \"a\";\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public static T throw0(Throwable throwable) {\n if (throwable == null) throw new NullPointerException();\n getUnsafe().throwException(throwable);\n throw new RuntimeException();\n }", "label_name": "CWE-200", "label": "200"} -{"code": "inline typename V::VariantType FBUnserializer::unserialize(\n folly::StringPiece serialized) {\n\n FBUnserializer unserializer(serialized);\n return unserializer.unserializeThing();\n}", "label_name": "CWE-674", "label": "674"} -{"code": "inline typename V::MapType FBUnserializer::unserializeMap() {\n p_ += CODE_SIZE;\n\n typename V::MapType ret = V::createMap();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n switch (code) {\n case FB_SERIALIZE_VARCHAR:\n case FB_SERIALIZE_STRING:\n {\n auto key = unserializeString();\n auto value = unserializeThing();\n V::mapSet(ret, std::move(key), std::move(value));\n }\n break;\n default:\n {\n auto key = unserializeInt64();\n auto value = unserializeThing();\n V::mapSet(ret, std::move(key), std::move(value));\n }\n }\n\n code = nextCode();\n }\n p_ += CODE_SIZE;\n\n return ret;\n}", "label_name": "CWE-674", "label": "674"} -{"code": "bool DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)\n\t{\n\tif ( ! target_len )\n\t\treturn true;\n\n\tint to_copy = min(*len, target_len - endp->buffer_len);\n\n\tmemcpy(endp->buffer + endp->buffer_len, *data, to_copy);\n\t*data += to_copy;\n\t*len -= to_copy;\n\tendp->buffer_len += to_copy;\n\n\treturn endp->buffer_len == target_len;\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)\n{\n tTcpIpPacketParsingResult res = _res;\n ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);\n res.xxpStatus = ppresXxpIncomplete;\n res.TcpUdp = ppresIsUDP;\n res.XxpIpHeaderSize = udpDataStart;\n if (len >= udpDataStart)\n {\n UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);\n USHORT datagramLength = swap_short(pUdpHeader->udp_length);\n res.xxpStatus = ppresXxpKnown;\n // may be full or not, but the datagram length is known\n DPrintf(2, (\"udp: len %d, datagramLength %d\\n\", len, datagramLength));\n }\n return res;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)\n{\n tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);\n PrintOutParsingResult(res, 1, caller);\n return res;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static inline long decode_twos_comp(ulong c, int prec)\n{\n\tlong result;\n\tassert(prec >= 2);\n\tjas_eprintf(\"warning: support for signed data is untested\\n\");\n\t// NOTE: Is this correct?\n\tresult = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));\n\treturn result;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t*data = val;\n\t\t\t}\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void jas_matrix_divpow2(jas_matrix_t *matrix, int n)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t*data = (*data >= 0) ? ((*data) >> n) :\n\t\t\t\t (-((-(*data)) >> n));\n\t\t\t}\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void UTFstring::UpdateFromUTF8()\n{\n delete [] _Data;\n // find the size of the final UCS-2 string\n size_t i;\n for (_Length=0, i=0; i(UTF8string[i]);\n if (lead < 0x80)\n i++;\n else if ((lead >> 5) == 0x6)\n i += 2;\n else if ((lead >> 4) == 0xe)\n i += 3;\n else if ((lead >> 3) == 0x1e)\n i += 4;\n else\n // Invalid size?\n break;\n }\n _Data = new wchar_t[_Length+1];\n size_t j;\n for (j=0, i=0; i(UTF8string[i]);\n if (lead < 0x80) {\n _Data[j] = lead;\n i++;\n } else if ((lead >> 5) == 0x6) {\n _Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);\n i += 2;\n } else if ((lead >> 4) == 0xe) {\n _Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);\n i += 3;\n } else if ((lead >> 3) == 0x1e) {\n _Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);\n i += 4;\n } else\n // Invalid char?\n break;\n }\n _Data[j] = 0;\n}", "label_name": "CWE-200", "label": "200"} -{"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": "119"} -{"code": "bool CSecurityTLS::processMsg(CConnection* cc)\n{\n rdr::InStream* is = cc->getInStream();\n rdr::OutStream* os = cc->getOutStream();\n client = cc;\n\n initGlobal();\n\n if (!session) {\n if (!is->checkNoWait(1))\n return false;\n\n if (is->readU8() == 0) {\n rdr::U32 result = is->readU32();\n CharArray reason;\n if (result == secResultFailed || result == secResultTooMany)\n reason.buf = is->readString();\n else\n reason.buf = strDup(\"Authentication failure (protocol error)\");\n throw AuthFailureException(reason.buf);\n }\n\n if (gnutls_init(&session, GNUTLS_CLIENT) != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_init failed\");\n\n if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_set_default_priority failed\");\n\n setParam();\n }\n\n rdr::TLSInStream *tlsis = new rdr::TLSInStream(is, session);\n rdr::TLSOutStream *tlsos = new rdr::TLSOutStream(os, session);\n\n int err;\n err = gnutls_handshake(session);\n if (err != GNUTLS_E_SUCCESS) {\n delete tlsis;\n delete tlsos;\n\n if (!gnutls_error_is_fatal(err))\n return false;\n\n vlog.error(\"TLS Handshake failed: %s\\n\", gnutls_strerror (err));\n shutdown(false);\n throw AuthFailureException(\"TLS Handshake failed\");\n }\n\n checkSession();\n\n cc->setStreams(fis = tlsis, fos = tlsos);\n\n return true;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "bool SSecurityTLS::processMsg(SConnection *sc)\n{\n rdr::InStream* is = sc->getInStream();\n rdr::OutStream* os = sc->getOutStream();\n\n vlog.debug(\"Process security message (session %p)\", session);\n\n if (!session) {\n initGlobal();\n\n if (gnutls_init(&session, GNUTLS_SERVER) != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_init failed\");\n\n if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_set_default_priority failed\");\n\n try {\n setParams(session);\n }\n catch(...) {\n os->writeU8(0);\n throw;\n }\n\n os->writeU8(1);\n os->flush();\n }\n\n rdr::TLSInStream *tlsis = new rdr::TLSInStream(is, session);\n rdr::TLSOutStream *tlsos = new rdr::TLSOutStream(os, session);\n\n int err;\n err = gnutls_handshake(session);\n if (err != GNUTLS_E_SUCCESS) {\n delete tlsis;\n delete tlsos;\n\n if (!gnutls_error_is_fatal(err)) {\n vlog.debug(\"Deferring completion of TLS handshake: %s\", gnutls_strerror(err));\n return false;\n }\n vlog.error(\"TLS Handshake failed: %s\", gnutls_strerror (err));\n shutdown();\n throw AuthFailureException(\"TLS Handshake failed\");\n }\n\n vlog.debug(\"Handshake completed\");\n\n sc->setStreams(fis = tlsis, fos = tlsos);\n\n return true;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) {\n\tut64 sz = 0;\n\tif (evp == NULL) {\n\t\treturn sz;\n\t}\n\t// evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur);\n\tsz += 2;\n\t// evp->value = r_bin_java_element_value_new (bin, offset+2);\n\tif (evp->value) {\n\t\tsz += r_bin_java_element_value_calc_size (evp->value);\n\t}\n\treturn sz;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 offset = 0;\n\tif (buf_offset + 8 > sz) {\n\t\treturn NULL;\n\t}\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR;\n\t\tattr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tattr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);\n\t\tfor (i = 0; i < attr->info.annotation_array.num_annotations; i++) {\n\t\t\tif (offset >= sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (annotation) {\n\t\t\t\toffset += annotation->size;\n\t\t\t\tr_list_append (attr->info.annotation_array.annotations, (void *) annotation);\n\t\t\t}\n\t\t}\n\t\tattr->size = offset;\n\t}\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "Http::Response AbstractWebApplication::processRequest(const Http::Request &request, const Http::Environment &env)\n{\n session_ = 0;\n request_ = request;\n env_ = env;\n\n clear(); // clear response\n\n sessionInitialize();\n if (!sessionActive() && !isAuthNeeded())\n sessionStart();\n\n if (isBanned()) {\n status(403, \"Forbidden\");\n print(QObject::tr(\"Your IP address has been banned after too many failed authentication attempts.\"), Http::CONTENT_TYPE_TXT);\n }\n else {\n processRequest();\n }\n\n return response();\n}", "label_name": "CWE-20", "label": "20"} -{"code": "bool ContentSettingsObserver::AllowScript(bool enabled_per_settings) {\n if (!enabled_per_settings)\n return false;\n if (IsScriptDisabledForPreview(render_frame()))\n return false;\n if (is_interstitial_page_)\n return true;\n\n blink::WebLocalFrame* frame = render_frame()->GetWebFrame();\n const auto it = cached_script_permissions_.find(frame);\n if (it != cached_script_permissions_.end())\n return it->second;\n\n // Evaluate the content setting rules before\n // IsWhitelistedForContentSettings(); if there is only the default rule\n // allowing all scripts, it's quicker this way.\n bool allow = true;\n if (content_setting_rules_) {\n ContentSetting setting = GetContentSettingFromRules(\n content_setting_rules_->script_rules, frame,\n url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL());\n allow = setting != CONTENT_SETTING_BLOCK;\n }\n allow = allow || IsWhitelistedForContentSettings();\n\n cached_script_permissions_[frame] = allow;\n return allow;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteDevicePropertiesWidget::checkSaveable()\n{\n RemoteFsDevice::Details det=details();\n modified=det!=orig;\n saveable=!det.isEmpty();\n if (saveable && Type_SambaAvahi==type->itemData(type->currentIndex()).toInt()) {\n saveable=!smbAvahiName->text().trimmed().isEmpty();\n }\n emit updated();\n}", "label_name": "CWE-20", "label": "20"} -{"code": "RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const DeviceOptions &options, const Details &d)\n : FsDevice(m, d.name, createUdi(d.name))\n , mountToken(0)\n , currentMountStatus(false)\n , details(d)\n , proc(0)\n , mounterIface(0)\n , messageSent(false)\n{\n opts=options;\n// details.path=Utils::fixPath(details.path);\n load();\n mount();\n icn=MonoIcon::icon(details.isLocalFile()\n ? FontAwesome::foldero\n : constSshfsProtocol==details.url.scheme()\n ? FontAwesome::linux_os\n : FontAwesome::windows, Utils::monoIconColor());\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static inline bool isMountable(const RemoteFsDevice::Details &d)\n{\n return RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static inline bool isValid(const RemoteFsDevice::Details &d)\n{\n return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void TensorSliceReader::LoadShard(int shard) const {\n CHECK_LT(shard, sss_.size());\n if (sss_[shard] || !status_.ok()) {\n return; // Already loaded, or invalid.\n }\n string value;\n SavedTensorSlices sts;\n const string fname = fnames_[shard];\n VLOG(1) << \"Reading meta data from file \" << fname << \"...\";\n Table* table;\n Status s = open_function_(fname, &table);\n if (!s.ok()) {\n status_ = errors::DataLoss(\"Unable to open table file \", fname, \": \",\n s.ToString());\n return;\n }\n sss_[shard].reset(table);\n if (!(table->Get(kSavedTensorSlicesKey, &value) &&\n ParseProtoUnlimited(&sts, value))) {\n status_ = errors::Internal(\n \"Failed to find the saved tensor slices at the beginning of the \"\n \"checkpoint file: \",\n fname);\n return;\n }\n status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,\n TF_CHECKPOINT_VERSION_MIN_PRODUCER, \"Checkpoint\",\n \"checkpoint\");\n if (!status_.ok()) return;\n for (const SavedSliceMeta& ssm : sts.meta().tensor()) {\n TensorShape ssm_shape(ssm.shape());\n for (const TensorSliceProto& tsp : ssm.slice()) {\n TensorSlice ss_slice(tsp);\n status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,\n ss_slice, &tensors_);\n if (!status_.ok()) return;\n }\n }\n}", "label_name": "CWE-345", "label": "345"} -{"code": "ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {\n if (streamId == 0) {\n goawayErrorMessage_ = folly::to(\n \"GOAWAY error: received streamID=\", streamId,\n \" as invalid new stream for lastStreamID_=\", lastStreamID_);\n VLOG(4) << goawayErrorMessage_;\n return ErrorCode::PROTOCOL_ERROR;\n }\n parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);\n if (parsingDownstreamTrailers_) {\n VLOG(4) << \"Parsing downstream trailers streamId=\" << streamId;\n }\n\n if (sessionClosing_ != ClosingState::CLOSED) {\n lastStreamID_ = streamId;\n }\n\n if (isInitiatedStream(streamId)) {\n // this stream should be initiated by us, not by peer\n goawayErrorMessage_ = folly::to(\n \"GOAWAY error: invalid new stream received with streamID=\", streamId);\n VLOG(4) << goawayErrorMessage_;\n return ErrorCode::PROTOCOL_ERROR;\n } else {\n return ErrorCode::NO_ERROR;\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {\n const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);\n if (!r)\n return BadHdr;\n return *r;\n}", "label_name": "CWE-116", "label": "116"} -{"code": "void HeaderMapImpl::insertByKey(HeaderString&& key, HeaderString&& value) {\n EntryCb cb = ConstSingleton::get().find(key.getStringView());\n if (cb) {\n key.clear();\n StaticLookupResponse ref_lookup_response = cb(*this);\n if (*ref_lookup_response.entry_ == nullptr) {\n maybeCreateInline(ref_lookup_response.entry_, *ref_lookup_response.key_, std::move(value));\n } else {\n appendToHeader((*ref_lookup_response.entry_)->value(), value.getStringView());\n value.clear();\n }\n } else {\n std::list::iterator i = headers_.insert(std::move(key), std::move(value));\n i->entry_ = i;\n }\n}", "label_name": "CWE-400", "label": "400"} -{"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": "400"} -{"code": "int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name,\n HeaderString&& value) {\n StreamImpl* stream = getStream(frame->hd.stream_id);\n if (!stream) {\n // We have seen 1 or 2 crashes where we get a headers callback but there is no associated\n // stream data. I honestly am not sure how this can happen. However, from reading the nghttp2\n // code it looks possible that inflate_header_block() can safely inflate headers for an already\n // closed stream, but will still call the headers callback. Since that seems possible, we should\n // ignore this case here.\n // TODO(mattklein123): Figure out a test case that can hit this.\n stats_.headers_cb_no_stream_.inc();\n return 0;\n }\n\n stream->saveHeader(std::move(name), std::move(value));\n if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) {\n // This will cause the library to reset/close the stream.\n stats_.header_overflow_.inc();\n return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;\n } else {\n return 0;\n }\n}", "label_name": "CWE-400", "label": "400"} -{"code": "static void HeaderMapImplGetByteSize(benchmark::State& state) {\n HeaderMapImpl headers;\n addDummyHeaders(headers, state.range(0));\n uint64_t size = 0;\n for (auto _ : state) {\n size += headers.byteSize();\n }\n benchmark::DoNotOptimize(size);\n}", "label_name": "CWE-400", "label": "400"} -{"code": "IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse(\n const Http::TestHeaderMapImpl& request_headers, uint32_t request_body_size,\n const Http::TestHeaderMapImpl& response_headers, uint32_t response_size, int upstream_index) {\n ASSERT(codec_client_ != nullptr);\n // Send the request to Envoy.\n IntegrationStreamDecoderPtr response;\n if (request_body_size) {\n response = codec_client_->makeRequestWithBody(request_headers, request_body_size);\n } else {\n response = codec_client_->makeHeaderOnlyRequest(request_headers);\n }\n waitForNextUpstreamRequest(upstream_index);\n // Send response headers, and end_stream if there is no response body.\n upstream_request_->encodeHeaders(response_headers, response_size == 0);\n // Send any response data, with end_stream true.\n if (response_size) {\n upstream_request_->encodeData(response_size, true);\n }\n // Wait for the response to be read by the codec client.\n response->waitForEndStream();\n return response;\n}", "label_name": "CWE-400", "label": "400"} -{"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": "674"} -{"code": "TEST_F(SQLiteUtilTests, test_column_type_determination) {\n // Correct identification of text and ints\n testTypesExpected(\"select path, inode from file where path like '%'\",\n TypeMap({{\"path\", TEXT_TYPE}, {\"inode\", INTEGER_TYPE}}));\n // Correctly treating BLOBs as text\n testTypesExpected(\"select CAST(seconds AS BLOB) as seconds FROM time\",\n TypeMap({{\"seconds\", TEXT_TYPE}}));\n // Correctly treating ints cast as double as doubles\n testTypesExpected(\"select CAST(seconds AS DOUBLE) as seconds FROM time\",\n TypeMap({{\"seconds\", DOUBLE_TYPE}}));\n // Correctly treating bools as ints\n testTypesExpected(\"select CAST(seconds AS BOOLEAN) as seconds FROM time\",\n TypeMap({{\"seconds\", INTEGER_TYPE}}));\n // Correctly recognizing values from columns declared double as double, even\n // if they happen to have integer value. And also test multi-statement\n // queries.\n testTypesExpected(\n \"CREATE TABLE test_types_table (username varchar(30) primary key, age \"\n \"double);INSERT INTO test_types_table VALUES (\\\"mike\\\", 23); SELECT age \"\n \"from test_types_table\",\n TypeMap({{\"age\", DOUBLE_TYPE}}));\n}", "label_name": "CWE-77", "label": "77"} -{"code": "void SocketLineReader::dataReceived()\n{\n while (m_socket->canReadLine()) {\n const QByteArray line = m_socket->readLine();\n if (line.length() > 1) { //we don't want a single \\n\n m_packets.enqueue(line);\n }\n }\n\n //If we still have things to read from the socket, call dataReceived again\n //We do this manually because we do not trust readyRead to be emitted again\n //So we call this method again just in case.\n if (m_socket->bytesAvailable() > 0) {\n QMetaObject::invokeMethod(this, \"dataReceived\", Qt::QueuedConnection);\n return;\n }\n\n //If we have any packets, tell it to the world.\n if (!m_packets.isEmpty()) {\n Q_EMIT readyRead();\n }\n}", "label_name": "CWE-400", "label": "400"} -{"code": " void Init(void)\n {\n for(int i = 0;i < 15;i++) {\n X[i].Init();\n M[i].Init();\n }\n }", "label_name": "CWE-119", "label": "119"} -{"code": " void Init(void)\n {\n for(int i = 0;i < 19;i++) {\n#ifdef DEBUG_QMCODER\n char string[5] = \"X0 \";\n string[1] = (i / 10) + '0';\n string[2] = (i % 10) + '0';\n X[i].Init(string);\n string[0] = 'M';\n M[i].Init(string);\n#else\n X[i].Init();\n M[i].Init();\n#endif\n }\n }", "label_name": "CWE-119", "label": "119"} -{"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": "119"} -{"code": " def build_query(path, details)\n query = @pattern.dup\n query.gsub!(/\\:prefix(\\/)?/, path.prefix.empty? ? \"\" : \"#{path.prefix}\\\\1\") # prefix can be empty...\n query.gsub!(/\\:action/, path.partial? ? \"_#{path.name}\" : path.name)\n\n details.each do |ext, variants|\n query.gsub!(/\\:#{ext}/, \"{#{variants.compact.uniq.join(',')}}\")\n end\n\n File.expand_path(query, @path)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def deliver!(mail)\n envelope_from = mail.return_path || mail.sender || mail.from_addrs.first\n return_path = \"-f \\\"#{envelope_from.to_s.gsub('\"', '\\\"')}\\\"\" if envelope_from\n\n arguments = [settings[:arguments], return_path].compact.join(\" \")\n\n Sendmail.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(\" \"), mail)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def split_path(request)\n # Reparse the configuration if necessary.\n readconfig\n\n mount_name, path = request.key.split(File::Separator, 2)\n\n raise(ArgumentError, \"Cannot find file: Invalid path '#{mount_name}'\") unless mount_name =~ %r{^[-\\w]+$}\n\n return nil unless mount = find_mount(mount_name, request.environment)\n if mount.name == \"modules\" and mount_name != \"modules\"\n # yay backward-compatibility\n path = \"#{mount_name}/#{path}\"\n end\n\n if path == \"\"\n path = nil\n elsif path\n # Remove any double slashes that might have occurred\n path = path.gsub(/\\/+/, \"/\")\n end\n\n return mount, path\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"should choose :rest when the Settings name isn't 'puppet'\" do\n @request.stubs(:protocol).returns \"puppet\"\n @request.stubs(:server).returns \"foo\"\n Puppet.settings.stubs(:value).with(:name).returns \"foo\"\n @object.select_terminus(@request).should == :rest\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def verify_active_session\n if !request.post? && params[:status].blank? && User.exists?(session[:user].presence)\n warning _(\"You have already logged in\")\n redirect_back_or_to hosts_path\n return\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_destroy\n auth_source_ldap = AuthSourceLdap.first\n User.where(:auth_source_id => auth_source_ldap.id).update_all(:auth_source_id => nil)\n delete :destroy, {:id => auth_source_ldap}, set_session_user\n assert_redirected_to auth_source_ldaps_url\n assert !AuthSourceLdap.exists?(auth_source_ldap.id)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_update_invalid\n Domain.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => Domain.first.to_param, :domain => {:name => Domain.first.name }}, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_update_valid\n Medium.any_instance.stubs(:valid?).returns(true)\n put :update, {:id => Medium.first, :medium => {:name => \"MyUpdatedMedia\"}}, set_session_user\n assert_redirected_to media_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_destroy\n subnet = Subnet.first\n subnet.hosts.clear\n subnet.interfaces.clear\n subnet.domains.clear\n delete :destroy, {:id => subnet}, set_session_user\n assert_redirected_to subnets_url\n assert !Subnet.exists?(subnet.id)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"recognizes and generates #destroy\" do\n { :delete => \"/users/1\" }.should route_to(:controller => \"users\", :action => \"destroy\", :id => \"1\")\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def __bson_dump__(io, key)\n io << Types::OBJECT_ID\n io << key\n io << NULL_BYTE\n io << data.pack('C12')\n end", "label_name": "CWE-20", "label": "20"} -{"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-400", "label": "400"} -{"code": " def secondaries\n servers.select(&:secondary?)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def sync\n known = known_addresses.shuffle\n seen = {}\n\n sync_seed = ->(seed) do\n server = Server.new seed\n\n unless seen[server.resolved_address]\n seen[server.resolved_address] = true\n\n hosts = sync_server(server)\n\n hosts.each do |host|\n sync_seed[host]\n end\n end\n end\n\n known.each do |seed|\n sync_seed[seed]\n end\n\n unless servers.empty?\n @dynamic_seeds = servers.map(&:address)\n end\n\n true\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def remove(server)\n servers.delete(server)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def more?\n @get_more_op.cursor_id != 0\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def more?\n @get_more_op.cursor_id != 0\n end", "label_name": "CWE-400", "label": "400"} -{"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-20", "label": "20"} -{"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": "20"} -{"code": " def simple_query(query)\n query.limit = -1\n\n query(query).documents.first\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def initialize(seeds, options = {})\n @cluster = Cluster.new(seeds)\n @options = options\n @options[:consistency] ||= :eventual\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def socket_for(mode)\n if options[:retain_socket]\n @socket ||= cluster.socket_for(mode)\n else\n cluster.socket_for(mode)\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"has an empty list of servers\" do\n cluster.servers.should be_empty\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"raises no exception\" do\n lambda do\n cluster.sync_server server\n end.should_not raise_exception\n end", "label_name": "CWE-400", "label": "400"} -{"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-400", "label": "400"} -{"code": " it \"syncs each seed node\" do\n server = Moped::Server.allocate\n Moped::Server.should_receive(:new).with(\"127.0.0.1:27017\").and_return(server)\n\n cluster.should_receive(:sync_server).with(server).and_return([])\n cluster.sync\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a new Query\" do\n Moped::Query.should_receive(:new).\n with(collection, selector).and_return(query)\n collection.find(selector).should eq query\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"creates an index with the provided name\" do\n indexes.create(key, name: \"custom_index_name\")\n indexes[key][\"name\"].should eq \"custom_index_name\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"creates an index with a generated name\" do\n indexes.create(key)\n indexes[key][\"name\"].should eq \"location.latlong_2d_name_1_age_-1\"\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"updates to a mongo advanced selector\" do\n query.explain\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$explain\" => true,\n \"$orderby\" => { _id: 1 }\n )\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"updates all records matching selector with change\" do\n query.should_receive(:update).with(change, [:multi])\n query.update_all change\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the document\" do\n session.simple_query(query).should eq(a: 1)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"raises a QueryFailure exception\" do\n expect {\n session.query(query)\n }.to raise_exception(Moped::Errors::QueryFailure)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets slave_ok on the query flags\" do\n session.stub(socket_for: socket)\n socket.should_receive(:execute) do |query|\n query.flags.should include :slave_ok\n end\n\n session.query(query)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"delegates to the current database\" do\n database = mock(Moped::Database)\n session.should_receive(:current_database).and_return(database)\n database.should_receive(:drop)\n session.drop\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns the result of the block\" do\n session.with(new_options) { false }.should eq false\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def private_message_reset_new\n topic_query = TopicQuery.new(current_user, limit: false)\n\n if params[:topic_ids].present?\n unless Array === params[:topic_ids]\n raise Discourse::InvalidParameters.new(\n \"Expecting topic_ids to contain a list of topic ids\"\n )\n end\n\n topic_scope = topic_query\n .private_messages_for(current_user, :all)\n .where(\"topics.id IN (?)\", params[:topic_ids].map(&:to_i))\n else\n params.require(:inbox)\n inbox = params[:inbox].to_s\n filter = private_message_filter(topic_query, inbox)\n topic_scope = topic_query.filter_private_message_new(current_user, filter)\n end\n\n topic_ids = TopicsBulkAction.new(\n current_user,\n topic_scope.distinct(false).pluck(:id),\n type: \"dismiss_topics\"\n ).perform!\n\n render json: success_json.merge(topic_ids: topic_ids)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def build_actions(actions, guardian, args)\n return unless pending?\n\n if guardian.can_approve?(target) || args[:approved_by_invite]\n actions.add(:approve_user) do |a|\n a.icon = 'user-plus'\n a.label = \"reviewables.actions.approve_user.title\"\n end\n end\n\n delete_user_actions(actions, require_reject_reason: !is_a_suspect_user?)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it 'should return a second factor prompt' do\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n response_body = CGI.unescapeHTML(response.body)\n\n expect(response_body).to include(I18n.t(\n \"login.second_factor_title\"\n ))\n\n expect(response_body).to_not include(I18n.t(\n \"login.invalid_second_factor_code\"\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"fails when user is suspended\" do\n user.update!(\n suspended_till: 2.days.from_now,\n suspended_at: Time.zone.now\n )\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to include(I18n.t(\"login.suspended\",\n date: I18n.l(user.suspended_till, format: :date_only)\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def decode_compact_serialized(input, private_key_or_secret, algorithms = nil, encryption_methods = nil, _allow_blank_payload = false)\n unless input.count('.') + 1 == NUM_OF_SEGMENTS\n raise InvalidFormat.new(\"Invalid JWE Format. JWE should include #{NUM_OF_SEGMENTS} segments.\")\n end\n jwe = new\n _header_json_, jwe.jwe_encrypted_key, jwe.iv, jwe.cipher_text, jwe.authentication_tag = input.split('.').collect do |segment|\n begin\n Base64.urlsafe_decode64 segment\n rescue ArgumentError\n raise DecryptionFailed\n end\n end\n jwe.auth_data = input.split('.').first\n jwe.header = JSON.parse(_header_json_).with_indifferent_access\n unless private_key_or_secret == :skip_decryption\n jwe.decrypt! private_key_or_secret, algorithms, encryption_methods\n end\n jwe\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def valid?(user, password)\n\n return false if user.blank?\n\n if PasswordHash.legacy?(user.password, password)\n update_password(user, password)\n return true\n end\n\n PasswordHash.verified?(user.password, password)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"returns only published articles\" do\n article = create(:article)\n create(:comment, article: article)\n unpublished_article = create(:article, state: \"draft\")\n create(:comment, article: unpublished_article)\n expect(described_class.published).to eq([article])\n expect(described_class.bestof).to eq([article])\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def create_clamp_code(nbits, signed)\n if signed == :signed\n max = (1 << (nbits - 1)) - 1\n min = -(max + 1)\n else\n max = (1 << nbits) - 1\n min = 0\n end\n\n \"val = (val < #{min}) ? #{min} : (val > #{max}) ? #{max} : val\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def set_inboxes\n @inbox_ids = if params[:inbox_id]\n current_account.inboxes.where(id: params[:inbox_id])\n else\n @current_user.assigned_inboxes.pluck(:id)\n end", "label_name": "CWE-269", "label": "269"} -{"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": "20"} -{"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": "285"} -{"code": "func (r *schemaResolver) UpdateSavedSearch(ctx context.Context, args *struct {\n\tID graphql.ID\n\tDescription string\n\tQuery string\n\tNotifyOwner bool\n\tNotifySlack bool\n\tOrgID *graphql.ID\n\tUserID *graphql.ID\n}) (*savedSearchResolver, error) {\n\tvar userID, orgID *int32\n\t// \ud83d\udea8 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org.\n\tif args.UserID != nil {\n\t\tu, err := unmarshalSavedSearchID(*args.UserID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tuserID = &u\n\t\tif err := backend.CheckSiteAdminOrSameUser(ctx, r.db, u); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if args.OrgID != nil {\n\t\to, err := unmarshalSavedSearchID(*args.OrgID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\torgID = &o\n\t\tif err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, o); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\treturn nil, errors.New(\"failed to update saved search: no Org ID or User ID associated with saved search\")\n\t}\n\n\tid, err := unmarshalSavedSearchID(args.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !queryHasPatternType(args.Query) {\n\t\treturn nil, errMissingPatternType\n\t}\n\n\tss, err := r.db.SavedSearches().Update(ctx, &types.SavedSearch{\n\t\tID: id,\n\t\tDescription: args.Description,\n\t\tQuery: args.Query,\n\t\tNotify: args.NotifyOwner,\n\t\tNotifySlack: args.NotifySlack,\n\t\tUserID: userID,\n\t\tOrgID: orgID,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.toSavedSearchResolver(*ss), nil\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {\n\tadded, err := cs.addVote(vote, peerID)\n\tif err != nil {\n\t\t// If the vote height is off, we'll just ignore it,\n\t\t// But if it's a conflicting sig, add it to the cs.evpool.\n\t\t// If it's otherwise invalid, punish peer.\n\t\t// nolint: gocritic\n\t\tif voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {\n\t\t\tif cs.privValidatorPubKey == nil {\n\t\t\t\treturn false, errPubKeyIsNotSet\n\t\t\t}\n\n\t\t\tif bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {\n\t\t\t\tcs.Logger.Error(\n\t\t\t\t\t\"Found conflicting vote from ourselves. Did you unsafe_reset a validator?\",\n\t\t\t\t\t\"height\",\n\t\t\t\t\tvote.Height,\n\t\t\t\t\t\"round\",\n\t\t\t\t\tvote.Round,\n\t\t\t\t\t\"type\",\n\t\t\t\t\tvote.Type)\n\t\t\t\treturn added, err\n\t\t\t}\n\t\t\tvar timestamp time.Time\n\t\t\tif voteErr.VoteA.Height == cs.state.InitialHeight {\n\t\t\t\ttimestamp = cs.state.LastBlockTime // genesis time\n\t\t\t} else {\n\t\t\t\ttimestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators)\n\t\t\t}\n\t\t\tev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators)\n\t\t\tevidenceErr := cs.evpool.AddEvidenceFromConsensus(ev)\n\t\t\tif evidenceErr != nil {\n\t\t\t\tcs.Logger.Error(\"Failed to add evidence to the evidence pool\", \"err\", evidenceErr)\n\t\t\t}\n\t\t\treturn added, err\n\t\t} else if err == types.ErrVoteNonDeterministicSignature {\n\t\t\tcs.Logger.Debug(\"Vote has non-deterministic signature\", \"err\", err)\n\t\t} else {\n\t\t\t// Either\n\t\t\t// 1) bad peer OR\n\t\t\t// 2) not a bad peer? this can also err sometimes with \"Unexpected step\" OR\n\t\t\t// 3) tmkms use with multiple validators connecting to a single tmkms instance\n\t\t\t// \t\t(https://github.com/tendermint/tendermint/issues/3839).\n\t\t\tcs.Logger.Info(\"Error attempting to add vote\", \"err\", err)\n\t\t\treturn added, ErrAddingVote\n\t\t}\n\t}\n\treturn added, nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func generateHMAC(data []byte, key *[32]byte) []byte {\n\th := hmac.New(sha512.New512_256, key[:])\n\th.Write(data)\n\treturn h.Sum(nil)\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (svc *Service) ListHostDeviceMapping(ctx context.Context, id uint) ([]*fleet.HostDeviceMapping, error) {\n\tif !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {\n\t\tif err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thost, err := svc.ds.HostLite(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, ctxerr.Wrap(ctx, err, \"get host\")\n\t\t}\n\n\t\t// Authorize again with team loaded now that we have team_id\n\t\tif err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn svc.ds.ListHostDeviceMapping(ctx, id)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (svc Service) ListSoftware(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// default sort order to hosts_count descending\n\tif opt.OrderKey == \"\" {\n\t\topt.OrderKey = \"hosts_count\"\n\t\topt.OrderDirection = fleet.OrderDescending\n\t}\n\topt.WithHostCounts = true\n\treturn svc.ds.ListSoftware(ctx, opt)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func handleCollectedUplink(ctx context.Context, uplinkFrame gw.UplinkFrame, rxPacket models.RXPacket) error {\n\tvar uplinkIDs []uuid.UUID\n\tfor _, p := range rxPacket.RXInfoSet {\n\t\tuplinkIDs = append(uplinkIDs, helpers.GetUplinkID(p))\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"uplink_ids\": uplinkIDs,\n\t\t\"mtype\": rxPacket.PHYPayload.MHDR.MType,\n\t\t\"ctx_id\": ctx.Value(logging.ContextIDKey),\n\t}).Info(\"uplink: frame(s) collected\")\n\n\t// update the gateway meta-data\n\tif err := gateway.UpdateMetaDataInRxInfoSet(ctx, storage.DB(), rxPacket.RXInfoSet); err != nil {\n\t\tlog.WithError(err).Error(\"uplink: update gateway meta-data in rx-info set error\")\n\t}\n\n\t// log the frame for each receiving gateway.\n\tif err := framelog.LogUplinkFrameForGateways(ctx, ns.UplinkFrameLog{\n\t\tPhyPayload: uplinkFrame.PhyPayload,\n\t\tTxInfo: rxPacket.TXInfo,\n\t\tRxInfo: rxPacket.RXInfoSet,\n\t}); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"ctx_id\": ctx.Value(logging.ContextIDKey),\n\t\t}).WithError(err).Error(\"uplink: log uplink frames for gateways error\")\n\t}\n\n\t// handle the frame based on message-type\n\tswitch rxPacket.PHYPayload.MHDR.MType {\n\tcase lorawan.JoinRequest:\n\t\treturn join.Handle(ctx, rxPacket)\n\tcase lorawan.RejoinRequest:\n\t\treturn rejoin.Handle(ctx, rxPacket)\n\tcase lorawan.UnconfirmedDataUp, lorawan.ConfirmedDataUp:\n\t\treturn data.Handle(ctx, rxPacket)\n\tcase lorawan.Proprietary:\n\t\treturn proprietary.Handle(ctx, rxPacket)\n\tdefault:\n\t\treturn nil\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": "func (p *GitLabProvider) addGroupsToSession(ctx context.Context, s *sessions.SessionState) {\n\t// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user\n\tfor _, group := range p.Groups {\n\t\ts.Groups = append(s.Groups, fmt.Sprintf(\"group:%s\", group))\n\t}\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func Test_buildControlPlanePrefixRoute(t *testing.T) {\n\tb := &Builder{filemgr: filemgr.NewManager()}\n\troute, err := b.buildControlPlanePrefixRoute(\"/hello/world/\", false)\n\trequire.NoError(t, err)\n\ttestutil.AssertProtoJSONEqual(t, `\n\t\t{\n\t\t\t\"name\": \"pomerium-prefix-/hello/world/\",\n\t\t\t\"match\": {\n\t\t\t\t\"prefix\": \"/hello/world/\"\n\t\t\t},\n\t\t\t\"route\": {\n\t\t\t\t\"cluster\": \"pomerium-control-plane-http\"\n\t\t\t},\n\t\t\t\"typedPerFilterConfig\": {\n\t\t\t\t\"envoy.filters.http.ext_authz\": {\n\t\t\t\t\t\"@type\": \"type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute\",\n\t\t\t\t\t\"disabled\": true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, route)\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func Test_buildControlPlanePathRoute(t *testing.T) {\n\tb := &Builder{filemgr: filemgr.NewManager()}\n\troute, err := b.buildControlPlanePathRoute(\"/hello/world\", false)\n\trequire.NoError(t, err)\n\ttestutil.AssertProtoJSONEqual(t, `\n\t\t{\n\t\t\t\"name\": \"pomerium-path-/hello/world\",\n\t\t\t\"match\": {\n\t\t\t\t\"path\": \"/hello/world\"\n\t\t\t},\n\t\t\t\"route\": {\n\t\t\t\t\"cluster\": \"pomerium-control-plane-http\"\n\t\t\t},\n\t\t\t\"typedPerFilterConfig\": {\n\t\t\t\t\"envoy.filters.http.ext_authz\": {\n\t\t\t\t\t\"@type\": \"type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute\",\n\t\t\t\t\t\"disabled\": true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, route)\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (cn *clusterNode) resurrect() {\n\tgRPCServer, err := comm_utils.NewGRPCServer(cn.bindAddress, cn.serverConfig)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"failed starting gRPC server: %v\", err))\n\t}\n\tcn.srv = gRPCServer\n\torderer.RegisterClusterServer(gRPCServer.Server(), cn)\n\tgo cn.srv.Start()\n}", "label_name": "CWE-20", "label": "20"} -{"code": " static buildMintOpReturn(config: configBuildMintOpReturn, type = 0x01) {\n return SlpTokenType1.buildMintOpReturn(\n config.tokenIdHex,\n config.batonVout,\n config.mintQuantity, \n type\n )\n }", "label_name": "CWE-20", "label": "20"} -{"code": " parseGraphQLServer._getGraphQLOptions = async (req) => {\n expect(req.info).toBeDefined();\n expect(req.config).toBeDefined();\n expect(req.auth).toBeDefined();\n checked = true;\n return await originalGetGraphQLOptions.bind(parseGraphQLServer)(req);\n };", "label_name": "CWE-863", "label": "863"} -{"code": "export function getExtensionPath(): string {\n\treturn extensionPath;\n}", "label_name": "CWE-863", "label": "863"} -{"code": " create = (profile) => {\n const rockUpdateFields = this.mapApollosFieldsToRock(profile);\n return this.post('/People', {\n Gender: 0, // required by Rock. Listed first so it can be overridden.\n ...rockUpdateFields,\n IsSystem: false, // required by rock\n });\n };", "label_name": "CWE-287", "label": "287"} -{"code": " .on(\"finished\", () => {\n if (doTraceChunk) {\n // tslint:disable-next-line: no-console\n warningLog(\n timestamp(),\n \" <$$ \",\n msgType,\n \"nbChunk = \" + nbChunks.toString().padStart(3),\n \"totalLength = \" + totalSize.toString().padStart(8),\n \"l=\",\n binSize.toString().padStart(6)\n );\n }\n if (totalSize > this.maxMessageSize) {\n errorLog(`[NODE-OPCUA-E55] message size ${totalSize} exceeds the negotiated message size ${this.maxMessageSize} nb chunks ${nbChunks}`);\n }\n messageChunkCallback(null);\n });", "label_name": "CWE-400", "label": "400"} -{"code": " on(eventName: \"message\", eventHandler: (message: Buffer) => void): this;", "label_name": "CWE-400", "label": "400"} -{"code": " function sendResponse(response1: Response) {\n try {\n assert(response1 instanceof ResponseClass);\n if (message.session) {\n const counterName = ResponseClass.name.replace(\"Response\", \"\");\n message.session.incrementRequestTotalCounter(counterName);\n }\n return channel.send_response(\"MSG\", response1, message);\n } catch (err) {\n warningLog(err);\n // istanbul ignore next\n if (err instanceof Error) {\n // istanbul ignore next\n errorLog(\n \"Internal error in issuing response\\nplease contact support@sterfive.com\",\n message.request.toString(),\n \"\\n\",\n response1.toString()\n );\n }\n // istanbul ignore next\n throw err;\n }\n }", "label_name": "CWE-400", "label": "400"} -{"code": "export async function validateTransfer(\n connection: Connection,\n signature: TransactionSignature,\n { recipient, amount, splToken, reference, memo }: ValidateTransferFields,\n options?: { commitment?: Finality }\n): Promise {\n const response = await connection.getTransaction(signature, options);\n if (!response) throw new ValidateTransferError('not found');\n\n const message = response.transaction.message;\n const meta = response.meta;\n if (!meta) throw new ValidateTransferError('missing meta');\n if (meta.err) throw meta.err;\n\n const [preAmount, postAmount] = splToken\n ? await validateSPLTokenTransfer(message, meta, recipient, splToken)\n : await validateSystemTransfer(message, meta, recipient);\n\n if (postAmount.minus(preAmount).lt(amount)) throw new ValidateTransferError('amount not transferred');\n\n if (reference) {\n if (!Array.isArray(reference)) {\n reference = [reference];\n }\n\n for (const pubkey of reference) {\n if (!message.accountKeys.some((accountKey) => accountKey.equals(pubkey)))\n throw new ValidateTransferError('reference not found');\n }\n }\n\n // FIXME: add memo check\n\n return response;\n}", "label_name": "CWE-670", "label": "670"} +{"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}