diff --git "a/test.jsonl" "b/test.jsonl" new file mode 100644--- /dev/null +++ "b/test.jsonl" @@ -0,0 +1,573 @@ +{"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"}