diff --git "a/test.jsonl" "b/test.jsonl" --- "a/test.jsonl" +++ "b/test.jsonl" @@ -1,1153 +1,1153 @@ -{"code": "function layout_navbar() {\n\t$t_logo_url = config_get('logo_url');\n\n\techo '
';\n\techo '
';\n\n\techo '';\n\n\techo '
';\n\techo '';\n\techo ' ';\n\techo config_get('window_title');\n\techo ' ';\n\techo '';\n\n\t$t_toggle_class = (OFF == config_get('show_avatar') ? 'navbar-toggle' : 'navbar-toggle-img');\n\techo '';\n\n\techo '
';\n\n\techo '
';\n\techo '
    ';\n\tif (auth_is_user_authenticated()) {\n\t\t# shortcuts button bar\n\t\tlayout_navbar_button_bar();\n\t\t# projects dropdown menu\n\t\tlayout_navbar_projects_menu();\n\t\t# user buttons such as messages, notifications and user menu\n\t\tlayout_navbar_user_menu();\n\t}\n\techo '
';\n\techo '
';\n\n\techo '
';\n\techo '
';\n}", "label_name": "CWE-79", "label": 79} -{"code": "function PMA_importAjaxStatus($id)\n{\n header('Content-type: application/json');\n echo json_encode(\n $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getUploadStatus($id)\n );\n}", "label_name": "CWE-79", "label": 79} -{"code": "function get_abs_item($dir, $item) {\t\t// get absolute file+path\n\treturn get_abs_dir($dir).DIRECTORY_SEPARATOR.$item;\n}", "label_name": "CWE-22", "label": 22} -{"code": " function get_allowed_files_extensions_for_upload($fileTypes = 'images', $returnAsArray = false)\n {\n\n $are_allowed = '';\n switch ($fileTypes) {\n\n case 'img':\n case 'image':\n case 'images':\n $are_allowed .= ',png,gif,jpg,jpeg,tiff,bmp,svg,webp,ico';\n break;\n case 'audio':\n case 'audios':\n $are_allowed .= ',mp3,mp4,ogg,wav,flac';\n break;\n case 'video':\n case 'videos':\n $are_allowed .= ',avi,asf,mpg,mpeg,mp4,flv,mkv,webm,ogg,ogv,3gp,3g2,wma,mov,wmv';\n break;\n case 'file':\n case 'files':\n $are_allowed .= ',css,json,zip,gzip,csv,7z';\n break;\n case 'documents':\n case 'doc':\n $are_allowed .= ',doc,docx,pdf,odt,pages,rtf,txt,pps,ppt,pptx,xls,xlsx';\n break;\n case 'archives':\n case 'arc':\n case 'arch':\n $are_allowed .= ',zip,zipx,gzip,rar,gz,7z,cbr,tar.gz';\n break;\n case 'all':\n $are_allowed .= ',*';\n break;\n case '*':\n $are_allowed .= ',*';\n break;\n default:\n $are_allowed .= ',' . $fileTypes;\n }\n\n if($are_allowed){\n $are_allowed = explode(',',$are_allowed);\n array_unique($are_allowed);\n $are_allowed = array_filter($are_allowed);\n\n if ($returnAsArray) {\n return $are_allowed;\n }\n\n $are_allowed = implode(',', $are_allowed);\n }\n\n if ($returnAsArray) {\n return [];\n }\n\n return $are_allowed;\n }", "label_name": "CWE-79", "label": 79} -{"code": "function prepareExchangedData($data, $type)\n{\n global $SETTINGS;\n\n //load ClassLoader\n require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';\n //Load AES\n $aes = new SplClassLoader('Encryption\\Crypt', '../includes/libraries');\n $aes->register();\n\n if ($type == \"encode\") {\n if (isset($SETTINGS['encryptClientServer'])\n && $SETTINGS['encryptClientServer'] === \"0\"\n ) {\n return json_encode(\n $data,\n JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP\n );\n } else {\n return Encryption\\Crypt\\aesctr::encrypt(\n json_encode(\n $data,\n JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP\n ),\n $_SESSION['key'],\n 256\n );\n }\n } elseif ($type == \"decode\") {\n if (isset($SETTINGS['encryptClientServer'])\n && $SETTINGS['encryptClientServer'] === \"0\"\n ) {\n return json_decode(\n $data,\n true\n );\n } else {\n return json_decode(\n Encryption\\Crypt\\aesctr::decrypt(\n $data,\n $_SESSION['key'],\n 256\n ),\n true\n );\n }\n }\n}", "label_name": "CWE-434", "label": 434} -{"code": "function teampass_decrypt_pw($encrypted, $salt, $rand_key, $itcount = 2072)\n{\n $encrypted = base64_decode($encrypted);\n $pass_salt = substr($encrypted, -64);\n $encrypted = substr($encrypted, 0, -64);\n $key = teampass_pbkdf2_hash($salt, $pass_salt, $itcount, 16, 32);\n $iv = base64_decode(substr($encrypted, 0, 43) . '==');\n $encrypted = substr($encrypted, 43);\n $mac = substr($encrypted, -64);\n $encrypted = substr($encrypted, 0, -64);\n if ($mac !== hash_hmac('sha256', $encrypted, $salt)) return null;\n return substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), \"\\0\\4\"), strlen($rand_key));\n}", "label_name": "CWE-79", "label": 79} -{"code": "function teampass_whitelist() {\n $bdd = teampass_connect();\n\t$apiip_pool = teampass_get_ips();\n\tif (count($apiip_pool) > 0 && !array_search($_SERVER['REMOTE_ADDR'], $apiip_pool)) {\n\t\trest_error('IPWHITELIST');\n\t}\n}", "label_name": "CWE-89", "label": 89} -{"code": "function _getHtmlHeaderColumn($title, $name, $pageName, $entityIds, $listorder, $orderdirection, $showColumn = true)\n{\n $str = '';\n $entity = _getEntityString($entityIds);\n if ($listorder == $name) {\n if (($orderdirection == '') || ($orderdirection == 'down')) {\n $str = \"\";\n } else {\n $str = \"\";\n }\n }\n return $showColumn ? \"$title$str\" : '';\n}", "label_name": "CWE-79", "label": 79} -{"code": "function _getEntityString($entityIds)\n{\n $entity = '';\n if (!empty($entityIds)) {\n $entityArr = array();\n foreach ($entityIds as $entityId => $entityValue) {\n $entityArr[] = \"$entityId=$entityValue\";\n }\n $entity = implode('&',$entityArr) . '&';\n }\n\n return $entity;\n}", "label_name": "CWE-79", "label": 79} -{"code": " public function stripClean($str)\n {\n return $this->xssClean($this->stripTags($str));\n }", "label_name": "CWE-89", "label": 89} -{"code": " function ac_checkme($id, $name) {\n global $cms_db;\n\n $ret = true;\n $cquery = sprintf(\"select count(*) from %s where sid='%s' and name='%s'\",\n $cms_db['sessions'],\n $id,\n $name);\n $squery = sprintf(\"select sid from %s where sid = '%s' and name = '%s'\",\n $cms_db['sessions'],\n $id,\n addslashes($name));\n $this->db->query($squery);\n if ( $this->db->affected_rows() == 0\n && $this->db->query($cquery)\n\t && $this->db->next_record() && $this->db->f(0) == 0 ) {\n // nothing found here\n $ret = false;\n }\n return $ret;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function error ($vars=\"\") {\n if( isset($vars) && $vars != \"\" ) {\n include(GX_PATH.'/inc/lib/Control/Error/'.$vars.'.control.php');\n }else{\n include(GX_PATH.'/inc/lib/Control/Error/404.control.php');\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " $q = self::$mysqli->query($vars) ;\n if($q === false) {\n user_error(\"Query failed: \".self::$mysqli->error.\"
\\n$vars\"); \n return false; \n }\n }\n \n return $q;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function makeConfig ($file) {\n $config = \"getMessage();\n }\n \n return $config;\n }", "label_name": "CWE-89", "label": 89} -{"code": " function __construct()\n {\n # code...\n self::$smtphost = Options::get('smtphost');\n self::$smtpuser = Options::get('smtpuser');\n self::$smtppass = Options::get('smtppass');\n self::$smtpssl = Options::get('smtpssl');\n self::$siteemail = Options::get('siteemail');\n self::$sitename = Options::get('sitename');\n }", "label_name": "CWE-79", "label": 79} -{"code": " $logo = \"\";\n }else{\n $logo = \"\";\n }\n return $logo;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function go($input, $path, $allowed='', $uniq=false, $size='', $width = '', $height = ''){\n $filename = Typo::cleanX($_FILES[$input]['name']);\n $filename = str_replace(' ', '_', $filename);\n if(isset($_FILES[$input]) && $_FILES[$input]['error'] == 0){\n if($uniq == true){\n $uniqfile = sha1(microtime().$filename);\n }else{\n $uniqfile = '';\n }\n\n $extension = pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION);\n $filetmp = $_FILES[$input]['tmp_name'];\n $filepath = GX_PATH.$path.$uniqfile.$filename;\n\n if(!in_array(strtolower($extension), $allowed)){\n $result['error'] = 'File not allowed';\n }else{\n if(move_uploaded_file(\n $filetmp, \n $filepath)\n ){\n $result['filesize'] = filesize($filepath);\n $result['filename'] = $uniqfile.$filename;\n $result['path'] = $path.$uniqfile.$filename;\n $result['filepath'] = $filepath;\n $result['fileurl'] = Options::get('siteurl').$path.$uniqfile.$filename;\n\n }else{\n $result['error'] = 'Cannot upload to directory, please check \n if directory is exist or You had permission to write it.';\n }\n }\n\n \n }else{\n //$result['error'] = $_FILES[$input]['error'];\n $result['error'] = '';\n }\n\n return $result;\n\n }", "label_name": "CWE-79", "label": 79} -{"code": " public static function sitemap() {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/sitemap\".GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?page=sitemap\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function page($vars) {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/\".self::slug($vars).GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?page={$vars}\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-79", "label": 79} -{"code": " }elseif ($k == 'lang') {\r\n\r\n self::incFront('default');\r\n\r\n }elseif($k == \"error\"){\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function local($date, $format=''){\r\n setlocale(LC_TIME, Options::v('country_id'));\r\n (empty($format))? $format = \"%#d %B %Y %H:%M %p\" : $format = $format;\r\n $timezone = Options::v('timezone');\r\n $date = new DateTime($date);\r\n $date->setTimezone(new DateTimeZone($timezone));\r\n $newdate = $date->format(\"Y/m/j H:i:s\");\r\n $newdate = strftime($format, strtotime($newdate));\r\n return $newdate.\" \".$date->format(\"T\");\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $vars = self::$mysqli->escape_string($vars);\r\n }else{\r\n $vars = $vars;\r\n }\r\n return $vars;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function add() {\r\n \r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public function __construct () {\r\n\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function makeConfig ($file) {\r\n $config = \"getMessage();\r\n }\r\n\r\n return $config;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public function __construct () {\r\n self::setActive();\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function url($mod) {\r\n $url = Site::$url.\"/inc/mod/\".$mod;\r\n return $url;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public function __construct() {\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $posts_arr = json_decode(json_encode($posts), FALSE);\r\n // $posts[] = $posts;\r\n $post_arr[] = $posts_arr;\r\n $post = $post_arr;\r\n }\r\n }else{\r\n $post = $post;\r\n }\r\n\r\n }else{\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function existParam($param, $post_id) {\r\n $sql = \"SELECT * FROM `posts_param` WHERE `post_id` = '{$post_id}' AND `param` = '{$param}' LIMIT 1\";\r\n $q = Db::result($sql);\r\n if (Db::$num_rows > 0) {\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " function __construct () {\r\n\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function options($var) {\r\n if (self::optionsExist($var)) {\r\n include(GX_THEME.$var.'/options.php');\r\n }\r\n\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function flag($vars) {\r\n switch (SMART_URL) {\r\n case true:\r\n $lang = '?lang=' . $vars;\r\n if (isset($_GET['lang'])) {\r\n\r\n $uri = explode('?', $_SERVER['REQUEST_URI']);\r\n $uri = $uri[0];\r\n }else{\r\n $uri = $_SERVER['REQUEST_URI'];\r\n }\r\n $url = $uri . $lang;\r\n\r\n break;\r\n\r\n default:\r\n // print_r($_GET);\r\n if (!empty($_GET)) {\r\n\r\n $val = '';\r\n foreach ($_GET as $key => $value) {\r\n if ($key == 'lang') {\r\n $val .= '&lang='.$vars;\r\n }else{\r\n $val .= $key . '=' . $value;\r\n }\r\n }\r\n }else{\r\n $val = \"lang=\".$vars;\r\n }\r\n $lang = !isset($_GET['lang'])? '&lang=' . $vars: $val;\r\n $url = Site::$url . '/?' . $lang;\r\n break;\r\n\r\n }\r\n\r\n return $url;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function custom($vars) {\r\n $url = $vars;\r\n return $url;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function email($id){\r\n $usr = Db::result(\r\n sprintf(\"SELECT * FROM `user` WHERE `id` = '%d' OR `userid` = '%s' LIMIT 1\", \r\n Typo::int($id), \r\n Typo::cleanX($id)\r\n )\r\n );\r\n return $usr[0]->email;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public function __toString()\n {\n $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';\n foreach ($this->data as $k => $v) {\n if ($k != 'Name' && $k != 'Value' && $v !== null && $v !== false) {\n if ($k == 'Expires') {\n $str .= 'Expires=' . gmdate('D, d M Y H:i:s \\G\\M\\T', $v) . '; ';\n } else {\n $str .= ($v === true ? $k : \"{$k}={$v}\") . '; ';\n }\n }\n }\n\n return rtrim($str, '; ');\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function hasHeader($header)\n {\n return isset($this->headers[strtolower($header)]);\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function getRequestTarget()\n {\n if ($this->requestTarget !== null) {\n return $this->requestTarget;\n }\n\n $target = $this->uri->getPath();\n if ($target == null) {\n $target = '/';\n }\n if ($this->uri->getQuery()) {\n $target .= '?' . $this->uri->getQuery();\n }\n\n return $target;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function getPath()\n {\n return $this->path == null ? '' : $this->path;\n }", "label_name": "CWE-89", "label": 89} -{"code": "function parse_request($message)\n{\n $data = _parse_message($message);\n $matches = [];\n if (!preg_match('/^[a-zA-Z]+\\s+([a-zA-Z]+:\\/\\/|\\/).*/', $data['start-line'], $matches)) {\n throw new \\InvalidArgumentException('Invalid request string');\n }\n $parts = explode(' ', $data['start-line'], 3);\n $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';\n\n $request = new Request(\n $parts[0],\n $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1],\n $data['headers'],\n $data['body'],\n $version\n );\n\n return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);\n}", "label_name": "CWE-89", "label": 89} -{"code": " public function testNewInstanceWhenAddingHeaderThatWasNotThereBefore()\n {\n $r = new Response(200, ['Foo' => 'Bar']);\n $r2 = $r->withAddedHeader('Baz', 'Bam');\n $this->assertNotSame($r, $r2);\n $this->assertEquals('Bam', $r2->getHeaderLine('Baz'));\n $this->assertEquals('Bar', $r2->getHeaderLine('Foo'));\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function testAlwaysReturnsBody()\n {\n $r = new Response();\n $this->assertInstanceOf('Psr\\Http\\Message\\StreamInterface', $r->getBody());\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function testSameInstanceWhenSameBody()\n {\n $r = new Response(200, [], 'foo');\n $b = $r->getBody();\n $this->assertSame($r, $r->withBody($b));\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function testCompletePurchaseCustomOptions()\n {\n\n $this->setMockHttpResponse('ExpressPurchaseSuccess.txt');\n\n // Those values should not be used if custom token or payerid are passed\n $this->getHttpRequest()->query->replace(array(\n 'token' => 'GET_TOKEN',\n 'PayerID' => 'GET_PAYERID',\n ));\n\n $response = $this->gateway->completePurchase(array(\n 'amount' => '10.00',\n 'currency' => 'BYR',\n 'token' => 'CUSTOM_TOKEN',\n 'payerid' => 'CUSTOM_PAYERID'\n ))->send();\n\n $httpRequests = $this->getMockedRequests();\n $httpRequest = $httpRequests[0];\n $queryArguments = $httpRequest->getQuery()->toArray();\n $this->assertSame('CUSTOM_TOKEN', $queryArguments['TOKEN']);\n $this->assertSame('CUSTOM_PAYERID', $queryArguments['PAYERID']);\n\n }", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic static function sessionWrite() {\n\t\t$this->session->close();\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\t protected function curl_get_contents( &$url, $timeout, $redirect_max, $ua, $outfp ){\n\t\t$ch = curl_init();\n\t\tcurl_setopt( $ch, CURLOPT_URL, $url );\n\t\tcurl_setopt( $ch, CURLOPT_HEADER, false );\n\t\tif ($outfp) {\n\t\t\tcurl_setopt( $ch, CURLOPT_FILE, $outfp );\n\t\t} else {\n\t\t\tcurl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );\n\t\t\tcurl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );\n\t\t}\n\t\tcurl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 1 );\n\t\tcurl_setopt( $ch, CURLOPT_LOW_SPEED_TIME, $timeout );\n\t\tcurl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );\n\t\tcurl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);\n\t\tcurl_setopt( $ch, CURLOPT_MAXREDIRS, $redirect_max);\n\t\tcurl_setopt( $ch, CURLOPT_USERAGENT, $ua);\n\t\t$result = curl_exec( $ch );\n\t\t$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);\n\t\tcurl_close( $ch );\n\t\treturn $outfp? $outfp : $result;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tprivate function deleteDir($dirPath)\n\t{\n\t\tif (!is_dir($dirPath)) {\n\t\t\t$success = unlink($dirPath);\n\t\t} else {\n\t\t\t$success = true;\n\t\t\tforeach (array_reverse(elFinderVolumeFTP::listFilesInDirectory($dirPath, false)) as $path) {\n\t\t\t\t$path = $dirPath . DIRECTORY_SEPARATOR . $path;\n\t\t\t\tif(is_link($path)) {\n\t\t\t\t\tunlink($path);\n\t\t\t\t} else if (is_dir($path)) {\n\t\t\t\t\t$success = rmdir($path);\n\t\t\t\t} else {\n\t\t\t\t\t$success = unlink($path);\n\t\t\t\t}\n\t\t\t\tif (!$success) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($success) {\n\t\t\t\t$success = rmdir($dirPath);\n\t\t\t}\n\t\t}\n\t\tif(!$success) {\n\t\t\t$this->setError(elFinder::ERROR_RM, $dirPath);\n\t\t\treturn false;\n\t\t}\n\t\treturn $success;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tprotected function connect() {\n\t\tif (!($this->connect = @ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {\n\t\t\treturn $this->setError('Unable to connect to FTP server '.$this->options['host']);\n\t\t}\n\t\tif (!@ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {\n\t\t\t$this->umount();\n\t\t\treturn $this->setError('Unable to login into '.$this->options['host']);\n\t\t}\n\t\t\n\t\t// try switch utf8 mode\n\t\tif ($this->encoding) {\n\t\t\t@ftp_exec($this->connect, 'OPTS UTF8 OFF');\n\t\t} else {\n\t\t\t@ftp_exec($this->connect, 'OPTS UTF8 ON' );\n\t\t}\n\t\t\n\t\t// switch off extended passive mode - may be usefull for some servers\n\t\t@ftp_exec($this->connect, 'epsv4 off' );\n\t\t// enter passive mode if required\n\t\t$pasv = ($this->options['mode'] == 'passive');\n\t\tif (! ftp_pasv($this->connect, $pasv)) {\n\t\t\tif ($pasv) {\n\t\t\t\t$this->options['mode'] = 'active';\n\t\t\t}\n\t\t}\n\n\t\t// enter root folder\n\t\tif (! @ftp_chdir($this->connect, $this->root) \n\t\t|| $this->root != @ftp_pwd($this->connect)) {\n\t\t\t$this->umount();\n\t\t\treturn $this->setError('Unable to open root folder.');\n\t\t}\n\t\t\n\t\t// check for MLST support\n\t\t$features = ftp_raw($this->connect, 'FEAT');\n\t\tif (!is_array($features)) {\n\t\t\t$this->umount();\n\t\t\treturn $this->setError('Server does not support command FEAT.');\n\t\t}\n\n\t\tforeach ($features as $feat) {\n\t\t\tif (strpos(trim($feat), 'MLST') === 0) {\n\t\t\t\t$this->MLSTsupprt = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tprotected function _save($fp, $dir, $name, $stat) {\n\t\t$this->clearcache();\n\t\t\n\t\t$mime = $stat['mime'];\n\t\t$w = !empty($stat['width']) ? $stat['width'] : 0;\n\t\t$h = !empty($stat['height']) ? $stat['height'] : 0;\n\t\t\n\t\t$id = $this->_joinPath($dir, $name);\n\t\trewind($fp);\n\t\t$stat = fstat($fp);\n\t\t$size = $stat['size'];\n\t\t\n\t\tif (($tmpfile = tempnam($this->tmpPath, $this->id))) {\n\t\t\tif (($trgfp = fopen($tmpfile, 'wb')) == false) {\n\t\t\t\tunlink($tmpfile);\n\t\t\t} else {\n\t\t\t\twhile (!feof($fp)) {\n\t\t\t\t\tfwrite($trgfp, fread($fp, 8192));\n\t\t\t\t}\n\t\t\t\tfclose($trgfp);\n\t\t\t\tchmod($tmpfile, 0644);\n\t\t\t\t\n\t\t\t\t$sql = $id > 0\n\t\t\t\t\t? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, \"%s\", LOAD_FILE(\"%s\"), %d, %d, \"%s\", %d, %d)'\n\t\t\t\t\t: 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, \"%s\", LOAD_FILE(\"%s\"), %d, %d, \"%s\", %d, %d)';\n\t\t\t\t$sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->loadFilePath($tmpfile), $size, time(), $mime, $w, $h);\n\n\t\t\t\t$res = $this->query($sql);\n\t\t\t\tunlink($tmpfile);\n\t\t\t\t\n\t\t\t\tif ($res) {\n\t\t\t\t\treturn $id > 0 ? $id : $this->db->insert_id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\n\t\t$content = '';\n\t\trewind($fp);\n\t\twhile (!feof($fp)) {\n\t\t\t$content .= fread($fp, 8192);\n\t\t}\n\t\t\n\t\t$sql = $id > 0\n\t\t\t? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, \"%s\", \"%s\", %d, %d, \"%s\", %d, %d)'\n\t\t\t: 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, \"%s\", \"%s\", %d, %d, \"%s\", %d, %d)';\n\t\t$sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->db->real_escape_string($content), $size, time(), $mime, $w, $h);\n\t\t\n\t\tunset($content);\n\n\t\tif ($this->query($sql)) {\n\t\t\treturn $id > 0 ? $id : $this->db->insert_id;\n\t\t}\n\t\t\n\t\treturn false;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tprotected function make($path, $name, $mime) {\n\t\t$sql = 'INSERT INTO %s (`parent_id`, `name`, `size`, `mtime`, `mime`, `content`, `read`, `write`) VALUES (\"%s\", \"%s\", 0, %d, \"%s\", \"\", \"%d\", \"%d\")';\n\t\t$sql = sprintf($sql, $this->tbf, $path, $this->db->real_escape_string($name), time(), $mime, $this->defaults['read'], $this->defaults['write']);\n\t\t// echo $sql;\n\t\treturn $this->query($sql) && $this->db->affected_rows > 0;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tprotected function _fopen($path, $mode='rb') {\n\t\t$fp = $this->tmbPath\n\t\t\t? @fopen($this->getTempFile($path), 'w+')\n\t\t\t: @tmpfile();\n\t\t\n\t\t\n\t\tif ($fp) {\n\t\t\tif (($res = $this->query('SELECT content FROM '.$this->tbf.' WHERE id=\"'.$path.'\"'))\n\t\t\t&& ($r = $res->fetch_assoc())) {\n\t\t\t\tfwrite($fp, $r['content']);\n\t\t\t\trewind($fp);\n\t\t\t\treturn $fp;\n\t\t\t} else {\n\t\t\t\t$this->_fclose($fp, $path);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\t\t$args['name'][$i] = $this->sanitizeFileName($name, $opts);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$args['name'] = $this->sanitizeFileName($args['name'], $opts);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "label_name": "CWE-89", "label": 89} -{"code": " call_user_func($listener, $event, $eventName, $this);\n if ($event->isPropagationStopped()) {\n break;\n }\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function getIterator()\n {\n @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be removed in 3.0.', E_USER_DEPRECATED);\n\n return new \\ArrayIterator($this->all());\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function regenerate($destroy = false, $lifetime = null)\n {\n // Cannot regenerate the session ID for non-active sessions.\n if (PHP_VERSION_ID >= 50400 && \\PHP_SESSION_ACTIVE !== session_status()) {\n return false;\n }\n\n // Check if session ID exists in PHP 5.3\n if (PHP_VERSION_ID < 50400 && '' === session_id()) {\n return false;\n }\n\n if (null !== $lifetime) {\n ini_set('session.cookie_lifetime', $lifetime);\n }\n\n if ($destroy) {\n $this->metadataBag->stampNew();\n }\n\n $isRegenerated = session_regenerate_id($destroy);\n\n // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.\n // @see https://bugs.php.net/bug.php?id=70013\n $this->loadSession();\n\n return $isRegenerated;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function setActive($flag)\n {\n if (PHP_VERSION_ID >= 50400) {\n throw new \\LogicException('This method is disabled in PHP 5.4.0+');\n }\n\n $this->active = (bool) $flag;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function testGetDeepWithInvalidPaths($path)\n {\n $bag = new ParameterBag(array('foo' => array('bar' => 'moo')));\n\n $bag->get($path, null, true);\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function testSetSaveHandler54()\n {\n $this->iniSet('session.save_handler', 'files');\n $storage = $this->getStorage();\n $storage->setSaveHandler();\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(null);\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler()));\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new NativeSessionHandler());\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new NullSessionHandler());\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n }", "label_name": "CWE-89", "label": 89} -{"code": " foreach ($usr as $u) {\r\n # code...\r\n $msgs = str_replace('{{userid}}', $u->userid, $msg);\r\n $vars = array(\r\n 'to' => $u->email,\r\n 'to_name' => $u->userid,\r\n 'message' => $msgs,\r\n 'subject' => $subject,\r\n 'msgtype' => $_POST['type']\r\n );\r\n $mailsend = Mail::send($vars);\r\n if($mailsend !== null){\r\n $alermailsend[] = $mailsend;\r\n }\r\n sleep(3);\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " foreach ($post as $p) {\n if ($p->id != $id) {\n $title = (strlen($p->title) > 40) ? substr($p->title, 0, 38).'...' : $p->title;\n $img = self::getImage(Typo::Xclean($p->content));\n if ($img != '') {\n $img = Url::thumb($img, 'square', 200);\n } else {\n $img = Url::thumb('assets/images/noimage.png', '', 200);\n }\n $related .= '
  • id).'\">\n '.$title.'

  • ';\n } else {\n $related .= '';\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " $resultItem['qtip'] = $item->getDescription() ? $item->getDescription() : ' ';\n $result[] = $resultItem;\n }\n\n return $this->adminJson($result);\n }", "label_name": "CWE-79", "label": 79} -{"code": " protected function renderText ($field, $makeLinks, $textOnly, $encode) {\n $fieldName = $field->fieldName;\n $value = preg_replace(\"/(\\
    )|\\n/\",\" \",$this->owner->$fieldName);\n return Yii::app()->controller->convertUrls($this->render ($value, $encode));\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function getItems2 (\n $prefix='', $page=0, $limit=20, $valueAttr='name', $nameAttr='name') {\n\n $modelClass = get_class ($this->owner);\n $model = CActiveRecord::model ($modelClass);\n $table = $model->tableName ();\n $offset = intval ($page) * intval ($limit);\n\n AuxLib::coerceToArray ($valueAttr);\n $modelClass::checkThrowAttrError (array_merge ($valueAttr, array ($nameAttr)));\n $params = array ();\n if ($prefix !== '') {\n $params[':prefix'] = $prefix . '%';\n }\n $offset = abs ((int) $offset);\n $limit = abs ((int) $limit);\n $command = Yii::app()->db->createCommand (\"\n SELECT \" . implode (',', $valueAttr) . \", $nameAttr as __name\n FROM $table\n WHERE \" . ($prefix === '' ? \n '1=1' : ($nameAttr . ' LIKE :prefix')\n ) . \"\n ORDER BY __name\n LIMIT $offset, $limit\n \");", "label_name": "CWE-79", "label": 79} -{"code": " public function AddBCC($address, $name = '') {\n return $this->AddAnAddress('bcc', $address, $name);\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function IsMail() {\n $this->Mailer = 'mail';\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function getViewFileParams () {\n if (!isset ($this->_viewFileParams)) {\n $this->_viewFileParams = array_merge (\n parent::getViewFileParams (),\n array (\n 'chartType' => $this->chartType,\n\t\t\t 'chartSettingsDataProvider' => self::getChartSettingsProvider (\n $this->chartType),\n 'eventTypes' =>\n array ('all'=>Yii::t('app', 'All Events')) + Events::$eventLabels,\n 'socialSubtypes' => json_decode (\n\t\t\t Dropdowns::model()->findByPk(113)->options,true),\n 'visibilityFilters' => array (\n '1'=>'Public',\n '0'=>'Private',\n ),\n 'suppressChartSettings' => false,\n 'chartType' => 'usersChart',\n 'widgetUID' => $this->widgetUID,\n 'metricTypes' => User::getUserOptions (),\n )\n );\n }\n return $this->_viewFileParams;\n }", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function paramRules() {\n\t\treturn array(\n\t\t\t'title' => Yii::t('studio',$this->title),\n\t\t\t'info' => Yii::t('studio',$this->info),\n\t\t\t'modelRequired' => 'Contacts',\n\t\t\t'options' => array(\n\t\t\t\tarray(\n 'name'=>'listId',\n 'label'=>Yii::t('studio','List'),\n 'type'=>'link',\n 'linkType'=>'X2List',\n 'linkSource'=>Yii::app()->createUrl(\n\t\t\t\t\t CActiveRecord::model('X2List')->autoCompleteSource\n\t\t\t\t )\n ),\n\t\t\t));\n\t}", "label_name": "CWE-79", "label": 79} -{"code": " public function actionHideWidget() {\n if (isset($_POST['name'])) {\n $name = $_POST['name'];\n\n $layout = Yii::app()->params->profile->getLayout();\n\n // the widget could be in any of the blocks in the page, so check all of them\n foreach ($layout as $b => &$block) {\n if (isset($block[$name])) {\n if ($b == 'right') {\n $layout['hiddenRight'][$name] = $block[$name];\n } else {\n $layout['hidden'][$name] = $block[$name];\n }\n unset($block[$name]);\n Yii::app()->params->profile->saveLayout($layout);\n break;\n }\n }\n\n // make a list of hidden widgets, using
  • , to send back to the browser\n $list = \"\";\n foreach ($layout['hidden'] as $name => $widget) {\n $list .= \"
  • {$widget['title']}
  • \";\n }\n foreach ($layout['hiddenRight'] as $name => $widget) {\n $list .= \"
  • {$widget['title']}
  • \";\n }\n\n echo Yii::app()->params->profile->getWidgetMenu();\n }\n }", "label_name": "CWE-79", "label": 79} -{"code": " $layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair\n $changed = true;\n }\n\n // remove obsolete widgets\n $arrayDiff =\n array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));\n foreach($arrayDiff as $elem){\n if(in_array ($elem, array_keys ($layout[$position]))) {\n unset($layout[$position][$elem]);\n $changed = true;\n } else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {\n unset($layout['hidden'][$elem]);\n $changed = true;\n }\n }\n\n\n // ensure that widget properties are the same as those in the default layout\n foreach($layout[$position] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n if ($position === 'center') {\n foreach($layout['hidden'] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n }\n\n if($changed){\n $this->layout = json_encode($layout);\n $this->update(array('layout'));\n }\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function actionGetItems() {\n $sql = 'SELECT id, name as value FROM x2_accounts WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'] . '%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('calendar', 'Calendar');\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function actionGetItems(){\n $model = X2Model::model ($this->modelClass);\n if (isset ($model)) {\n $tableName = $model->tableName ();\n $sql = \n 'SELECT id, fileName as value\n FROM '.$tableName.' \n WHERE associationType!=\"theme\" and fileName LIKE :qterm \n ORDER BY fileName ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function search(){\n // Warning: Please modify the following code to remove attributes that\n // should not be searched.\n\n $criteria = new CDbCriteria;\n $username = Yii::app()->user->name;\n $criteria->addCondition(\"uploadedBy='$username' OR private=0 OR private=null\");\n $criteria->addCondition(\"associationType != 'theme'\");\n return $this->searchBase($criteria);\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function actionGetItems(){\n // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.\n $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-79", "label": 79} -{"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-79", "label": 79} -{"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-829", "label": 829} -{"code": "\tfunction check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {\n\t\tif ( -1 == $action ) {\n\t\t\t_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2.0' );\n\t\t}\n\n\t\t$adminurl = strtolower( admin_url() );\n\t\t$referer = strtolower( wp_get_referer() );\n\t\t$result = isset( $_REQUEST[ $query_arg ] ) ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action ) : false;\n\n\t\t/**\n\t\t * Fires once the admin request has been validated or not.\n\t\t *\n\t\t * @since 1.5.1\n\t\t *\n\t\t * @param string $action The nonce action.\n\t\t * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between\n\t\t * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.\n\t\t */\n\t\tdo_action( 'check_admin_referer', $action, $result );\n\n\t\tif ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {\n\t\t\twp_nonce_ays( $action );\n\t\t\tdie();\n\t\t}\n\n\t\treturn $result;\n\t}", "label_name": "CWE-843", "label": 843} -{"code": "\tpublic function column_title( $post ) {\n\t\tlist( $mime ) = explode( '/', $post->post_mime_type );\n\n\t\t$title = _draft_or_post_title();\n\t\t$thumb = wp_get_attachment_image( $post->ID, array( 60, 60 ), true, array( 'alt' => '' ) );\n\t\t$link_start = $link_end = '';\n\n\t\tif ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {\n\t\t\t$link_start = sprintf(\n\t\t\t\t'',\n\t\t\t\tget_edit_post_link( $post->ID ),\n\t\t\t\t/* translators: %s: attachment title */\n\t\t\t\tesc_attr( sprintf( __( '“%s” (Edit)' ), $title ) )\n\t\t\t);\n\t\t\t$link_end = '';\n\t\t}\n\n\t\t$class = $thumb ? ' class=\"has-media-icon\"' : '';\n\t\t?>\n\t\t>\n\t\t\t\n\t\t\t\t\">\n\t\t\t\n\t\t\n\t\t

    \n\t\t\t \n\t\t\tID );\n\t\t\techo wp_basename( $file );\n\t\t\t?>\n\t\t

    \n\t\tprocess_fields( $table, $data, $format );\n\t\tif ( false === $data ) {\n\t\t\treturn false;\n\t\t}\n\t\t$where = $this->process_fields( $table, $where, $where_format );\n\t\tif ( false === $where ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$fields = $conditions = $values = array();\n\t\tforeach ( $data as $field => $value ) {\n\t\t\tif ( is_null( $value['value'] ) ) {\n\t\t\t\t$fields[] = \"`$field` = NULL\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$fields[] = \"`$field` = \" . $value['format'];\n\t\t\t$values[] = $value['value'];\n\t\t}\n\t\tforeach ( $where as $field => $value ) {\n\t\t\tif ( is_null( $value['value'] ) ) {\n\t\t\t\t$conditions[] = \"`$field` IS NULL\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$conditions[] = \"`$field` = \" . $value['format'];\n\t\t\t$values[] = $value['value'];\n\t\t}\n\n\t\t$fields = implode( ', ', $fields );\n\t\t$conditions = implode( ' AND ', $conditions );\n\n\t\t$sql = \"UPDATE `$table` SET $fields WHERE $conditions\";\n\t\t\n\t\t$this->check_current_query = false;\n\t\treturn $this->query( $this->prepare( $sql, $values ) );\n\t}", "label_name": "CWE-89", "label": 89} -{"code": " public function index($id)\n {\n\n //check permissions\n $template = $this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), false);\n if (!$this->_isSiteAdmin() && !$template) {\n throw new MethodNotAllowedException('No template with the provided ID exists, or you are not authorised to see it.');\n }\n\n $templateElements = $this->TemplateElement->find('all', array(\n 'conditions' => array(\n 'template_id' => $id,\n ),\n 'contain' => array(\n 'TemplateElementAttribute',\n 'TemplateElementText',\n 'TemplateElementFile'\n ),\n 'order' => array('TemplateElement.position ASC')\n ));\n $this->loadModel('Attribute');\n $this->set('validTypeGroups', $this->Attribute->validTypeGroups);\n $this->set('id', $id);\n $this->layout = 'ajaxTemplate';\n $this->set('elements', $templateElements);\n $mayModify = false;\n if ($this->_isSiteAdmin() || $template['Template']['org'] == $this->Auth->user('Organisation')['name']) {\n $mayModify = true;\n }\n $this->set('mayModify', $mayModify);\n $this->render('ajax/ajaxIndex');\n }", "label_name": "CWE-79", "label": 79} -{"code": "\t\t\tform_selectable_cell(filter_value($vdef['name'], get_request_var('filter'), 'vdef.php?action=edit&id=' . $vdef['id']), $vdef['id']);\n form_selectable_cell($disabled ? __('No'):__('Yes'), $vdef['id'], '', 'text-align:right');\n form_selectable_cell(number_format_i18n($vdef['graphs'], '-1'), $vdef['id'], '', 'text-align:right');\n form_selectable_cell(number_format_i18n($vdef['templates'], '-1'), $vdef['id'], '', 'text-align:right');\n form_checkbox_cell($vdef['name'], $vdef['id'], $disabled);\n form_end_row();\n }", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function meta_box_subject() {\n\n\t\t$placeholder = __( 'What is your conversation about?', 'supportflow' );\n\t\techo '

    ' . __( 'Subject', 'supportflow' ) . '

    ';\n\t\techo '';\n\t\techo '

    ' . __( 'Please describe what this ticket is about in several words', 'supportflow' ) . '

    ';\n\n\t}", "label_name": "CWE-79", "label": 79} -{"code": " foreach ($value as $valueKey => $valueValue) {\n if (\\is_int($valueKey)) {\n $filteredKey = $valueKey;\n } else {\n $filteredKey = self::filterValue($valueKey, $regex, $stripTags);\n }\n\n if ($filteredKey === '' || $filteredKey === null) {\n continue;\n }\n\n $filteredValue = $valueValue;\n\n if (\\is_array($valueValue)) {\n $filteredValue = self::filterArrayValue($valueValue, $regex, $stripTags);\n }\n\n if (\\is_string($valueValue)) {\n $filteredValue = self::filterValue($valueValue, $regex, $stripTags);\n }\n\n $newReturn[$filteredKey] = $filteredValue;\n }", "label_name": "CWE-79", "label": 79} -{"code": " public static function filterValue($value, $regex, $stripTags = true)\n {\n if (empty($value)) {\n return $value;\n }\n\n if ($stripTags) {\n $value = strip_tags($value);\n }\n\n if (preg_match($regex, $value)) {\n return null;\n }\n\n return $value;\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function setArticles($articles)\n {\n $return = $this->setOneToMany($articles, Article::class, 'articles', 'container');\n $this->setType('ctArticles');\n\n return $return;\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function buildCurrentUrl() {\n $url = URL_BASE;\n if ($this->url_style == 'sef') {\n $url .= substr(PATH_RELATIVE,0,-1).$this->sefPath;\n } else {\n $url .= urldecode((empty($_SERVER['REQUEST_URI'])) ? $_ENV['REQUEST_URI'] : $_SERVER['REQUEST_URI']);\n }\n return expString::sanitize($url);\n }", "label_name": "CWE-89", "label": 89} -{"code": " $module_views[$key]['name'] = gt($value['name']);\n }\n\n // look for a config form for this module's current view \n// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }\n \n // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);\n\n if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);\n\n return $views;\n}", "label_name": "CWE-89", "label": 89} -{"code": " function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {\n\n if ($is_revisioned) {\n $object->revision_id++;\n //if ($table==\"text\") eDebug($object);\n $res = $this->insertObject($object, $table);\n //if ($table==\"text\") eDebug($object,true); \n $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);\n return $res;\n }\n $sql = \"UPDATE \" . $this->prefix . \"$table SET \";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n //if($is_revisioned && $var=='revision_id') $val++;\n if ($var{0} != '_') {\n if (is_array($val) || is_object($val)) {\n $val = serialize($val); \n $sql .= \"`$var`='\".$val.\"',\";\n } else {\n $sql .= \"`$var`='\" . $this->escapeString($val) . \"',\";\n }\n }\n }\n $sql = substr($sql, 0, -1) . \" WHERE \";\n if ($where != null)\n $sql .= $this->injectProof($where);\n else\n $sql .= \"`\" . $identifier . \"`=\" . $object->$identifier;\n //if ($table == 'text') eDebug($sql,true); \n $res = (@mysqli_query($this->connection, $sql) != false);\n return $res;\n }", "label_name": "CWE-89", "label": 89} -{"code": " private function runCallback() {\n foreach ($this->records as &$record) {\n if (isset($record->ref_type)) {\n $refType = $record->ref_type;\n if (class_exists($record->ref_type)) {\n $type = new $refType();\n $classinfo = new ReflectionClass($type);\n if ($classinfo->hasMethod('paginationCallback')) {\n $item = new $type($record->original_id);\n $item->paginationCallback($record);\n }\n }\n }\n } \n }", "label_name": "CWE-89", "label": 89} -{"code": " $count += $db->dropTable($basename);\n }\n \n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-89", "label": 89} -{"code": " public function toolbar() {\n// global $user;\n\n $menu = array();\n\t\t$dirs = array(\n\t\t\tBASE.'framework/modules/administration/menus',\n\t\t\tBASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'\n\t\t);\n\n\t\tforeach ($dirs as $dir) {\n\t\t if (is_readable($dir)) {\n\t\t\t $dh = opendir($dir);\n\t\t\t while (($file = readdir($dh)) !== false) {\n\t\t\t\t if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {\n\t\t\t\t\t $menu[substr($file,0,-4)] = include($dir.'/'.$file);\n if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t}\n\n // sort the top level menus alphabetically by filename\n\t\tksort($menu);\t\t\n\t\t$sorted = array();\n\t\tforeach($menu as $m) $sorted[] = $m;\n \n // slingbar position\n if (isset($_COOKIE['slingbar-top'])){\n $top = $_COOKIE['slingbar-top'];\n } else {\n $top = SLINGBAR_TOP;\n }\n \n\t\tassign_to_template(array(\n 'menu'=>(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function configure() {\n $this->config['defaultbanner'] = array();\n if (!empty($this->config['defaultbanner_id'])) {\n $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);\n } \n\t parent::configure();\n\t $banners = $this->banner->find('all', null, 'companies_id');\n\t assign_to_template(array(\n 'banners'=>$banners,\n 'title'=>static::displayname()\n ));\n\t}", "label_name": "CWE-89", "label": 89} -{"code": " function reset_stats() {\n// global $db;\n\n // reset the counters\n// $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');\n banner::resetImpressions();\n// $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');\n banner::resetClicks();\n \n // let the user know we did stuff. \n flash('message', gt(\"Banner statistics reset.\"));\n expHistory::back();\n }", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"code": "\tpublic function approve() {\n\t expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n\t \n\t $comment = new expComment($this->params['id']);\n\t assign_to_template(array(\n 'comment'=>$comment\n ));\n\t}", "label_name": "CWE-89", "label": 89} -{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\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 $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\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-89", "label": 89} -{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\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 $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\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-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tfunction selectBillingOptions() {\n\t\t\n\t}", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": " function edit_optiongroup_master() {\n expHistory::set('editable', $this->params);\n \n $id = isset($this->params['id']) ? $this->params['id'] : null;\n $record = new optiongroup_master($id); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

    ' . $result->message);\n expHistory::back();\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function manage() {\n expHistory::set('viewable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'rank',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n //'columns'=>array('Name'=>'title')\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function manage_messages() {\n expHistory::set('manageable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'body',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n ));\n\n //eDebug($page);\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": " static function displayname() {\n return gt(\"e-Commerce Category Manager\");\n }", "label_name": "CWE-89", "label": 89} -{"code": " function edit() {\r\n global $template;\r\n\r\n parent::edit();\r\n $allforms = array();\r\n $allforms[\"\"] = gt('Disallow Feedback');\r\n // calculate which event date is the one being edited\r\n $event_key = 0;\r\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\r\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\r\n \t}\r\n\r\n assign_to_template(array(\r\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\r\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\r\n 'event_key' => $event_key,\r\n ));\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " } elseif (!empty($this->params['src'])) {\r\n if ($this->params['src'] == $loc->src) {\r\n $this->config = $config->config;\r\n break;\r\n }\r\n }\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " function searchName() {\r\n return gt(\"Calendar Event\");\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " 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", "label_name": "CWE-89", "label": 89} -{"code": " static function author() {\r\n return \"Dave Leffler\";\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $date->delete(); // event automatically deleted if all assoc eventdates are deleted\r\n }\r\n expHistory::back();\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $body = str_replace(array(\"\\n\"), \"
    \", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function canImportData() {\r\n return true;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " static function description() {\r\n return \"Manage events and schedules, and optionally publish them.\";\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt 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 echo json_encode($file); //FIXME we exit before hitting this\n } ", "label_name": "CWE-89", "label": 89} -{"code": " public function upload() {\n \n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n } ", "label_name": "CWE-89", "label": 89} -{"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": "\tpublic function update_version() {\n\t // get the current version\n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-89", "label": 89} -{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label_name": "CWE-89", "label": 89} -{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " static function description() { return gt(\"Places navigation links/menus on the page.\"); }\r", "label_name": "CWE-89", "label": 89} -{"code": " function process_subsections($parent_section, $subtpl) {\r\n global $db, $router;\r\n\r\n $section = new stdClass();\r\n $section->parent = $parent_section->id;\r\n $section->name = $subtpl->name;\r\n $section->sef_name = $router->encode($section->name);\r\n $section->subtheme = $subtpl->subtheme;\r\n $section->active = $subtpl->active;\r\n $section->public = $subtpl->public;\r\n $section->rank = $subtpl->rank;\r\n $section->page_title = $subtpl->page_title;\r\n $section->keywords = $subtpl->keywords;\r\n $section->description = $subtpl->description;\r\n $section->id = $db->insertObject($section, 'section');\r\n self::process_section($section, $subtpl);\r\n }\r", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"code": " self::removeLevel($kid->id);\r\n }\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"code": " static function displayname() { return gt(\"Navigation\"); }\r", "label_name": "CWE-89", "label": 89} -{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\r\n if (expPermissions::check('manage', $loc)) return true;\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function isPublic($s) {\r\n if ($s == null) {\r\n return false;\r\n }\r\n while ($s->public && $s->parent > 0) {\r\n $s = new section($s->parent);\r\n }\r\n $lineage = (($s->public) ? 1 : 0);\r\n return $lineage;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " function searchName() { return gt('Webpage'); }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function getTemplateHierarchyFlat($parent, $depth = 1) {\r\n global $db;\r\n\r\n $arr = array();\r\n $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');\r\n//\t\t$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));\r\n for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {\r\n $page = $kids[$i];\r\n $page->depth = $depth;\r\n $page->first = ($i == 0 ? 1 : 0);\r\n $page->last = ($i == count($kids) - 1 ? 1 : 0);\r\n $arr[] = $page;\r\n $arr = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));\r\n }\r\n return $arr;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $section = new section(intval($page));\r\n if ($section) {\r\n// self::deleteLevel($section->id);\r\n $section->delete();\r\n }\r\n }\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " function edit_section() {\r\n global $db, $user;\r\n\r\n $parent = new section($this->params['parent']);\r\n if (empty($parent->id)) $parent->id = 0;\r\n assign_to_template(array(\r\n 'haveStandalone' => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),\r\n 'parent' => $parent,\r\n 'isAdministrator' => $user->isAdmin(),\r\n ));\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " static function isSearchable() { return true; }\r", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {\n $limit = '0';\n }\n $order = isset($this->config['order']) ? $this->config['order'] : \"rank\";\n $page = new expPaginator(array(\n 'model'=>'photo',\n 'where'=>$this->aggregateWhereClause(),\n 'limit'=>$limit,\n 'order'=>$order,\n 'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],\n 'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),\n 'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),\n 'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-89", "label": 89} -{"code": " function productFeed() {\n// global $db;\n //check query password to avoid DDOS\n /*\n * condition = new\n * description \n * id - SKU \n * link \n * price \n * title \n * brand - manufacturer \n * image link - fullsized image, up to 10, comma seperated \n * product type - category - \"Electronics > Audio > Audio Accessories MP3 Player Accessories\",\"Health & Beauty > Healthcare > Biometric Monitors > Pedometers\" \n */\n $out = '\"id\",\"condition\",\"description\",\"like\",\"price\",\"title\",\"brand\",\"image link\",\"product type\"' . chr(13) . chr(10);\n\n $p = new product();\n $prods = $p->find('all', 'parent_id=0 AND ');\n //$prods = $db->selectObjects('product','parent_id=0 AND');\n }", "label_name": "CWE-89", "label": 89} -{"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-89", "label": 89} -{"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-89", "label": 89} -{"code": "\tpublic function jsonError(Exception $exception) {\n\t\t$message = $exception->getMessage();\n\t\t$code = $this->getHttpStatusCode($exception);\n\n\t\treturn new JSONResponse(\n\t\t\t[\n\t\t\t\t'message' => $message . ' (' . $code . ')',\n\t\t\t\t'success' => false\n\t\t\t],\n\t\t\t$code\n\t\t);\n\t}", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function testGetFilesWithBrokenSetup() {\n\t\t$location = '';\n\t\t$features = '';\n\t\t$etag = 1111222233334444;\n\t\t$mediatypes = 'image/png';\n\t\t$exceptionMessage = 'A\u00efe!';\n\t\t$this->searchFolderService->expects($this->once())\n\t\t\t\t\t\t\t\t ->method('getCurrentFolder')\n\t\t\t\t\t\t\t\t ->with(\n\t\t\t\t\t\t\t\t\t $location,\n\t\t\t\t\t\t\t\t\t [$features]\n\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t ->willThrowException(new ServiceException($exceptionMessage));\n\t\t// Default status code when something breaks\n\t\t$status = Http::STATUS_INTERNAL_SERVER_ERROR;\n\t\t$errorMessage = [\n\t\t\t'message' => $exceptionMessage . ' (' . $status . ')',\n\t\t\t'success' => false\n\t\t];\n\t\t/** @type JSONResponse $response */\n\t\t$response = $this->controller->getList($location, $features, $etag, $mediatypes);\n\n\t\t$this->assertEquals($errorMessage, $response->getData());\n\t}", "label_name": "CWE-79", "label": 79} -{"code": "\tprotected function LoadSize($blob)\n\t{\n\t\tif (!$blob)\n\t\t\treturn;\n\n\t\t$args = array();\n\t\t$args[] = '-s';\n\t\t$args[] = $blob->GetHash();\n\n\t\treturn $this->exe->Execute($blob->GetProject()->GetPath(), GIT_CAT_FILE, $args);\n\t}", "label_name": "CWE-78", "label": 78} -{"code": "\t\t\t$trimmed = trim($line);\n\n\t\t\tif ((strlen($trimmed) > 0) || ($readInitialData === true)) {\n\t\t\t\t$comment[] = $line;\n\t\t\t}\n\t\t\t$readInitialData = true;\n\n\t\t}\n\n\t\tswitch ($type) {\n\t\t\tcase 'commit':\n\t\t\t\t$object = $objectHash;\n\t\t\t\t$commitHash = $objectHash;\n\t\t\t\tbreak;\n\t\t\tcase 'tag':\n\t\t\t\t$args = array();\n\t\t\t\t$args[] = 'tag';\n\t\t\t\t$args[] = $objectHash;\n\t\t\t\t$ret = $this->exe->Execute($tag->GetProject()->GetPath(), GIT_CAT_FILE, $args);\n\t\t\t\t$lines = explode(\"\\n\", $ret);\n\t\t\t\tforeach ($lines as $i => $line) {\n\t\t\t\t\tif (preg_match('/^tag (.+)$/', $line, $regs)) {\n\t\t\t\t\t\t$name = trim($regs[1]);\n\t\t\t\t\t\t$object = $name;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'blob':\n\t\t\t\t$object = $objectHash;\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn array(\n\t\t\t$type,\n\t\t\t$object,\n\t\t\t$commitHash,\n\t\t\t$tagger,\n\t\t\t$taggerEpoch,\n\t\t\t$taggerTimezone,\n\t\t\t$comment\n\t\t);\n\n\t}", "label_name": "CWE-78", "label": 78} -{"code": " return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2'] = new \\Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2(${($_ = isset($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3']) ? $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3'] : ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3'] = new \\Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3())) && false ?: '_'});", "label_name": "CWE-89", "label": 89} -{"code": " protected function getFooService()\n {\n $a = new \\App\\Bar();\n\n $b = new \\App\\Baz($a);\n $b->bar = $a;\n\n $this->services['App\\Foo'] = $instance = new \\App\\Foo($b);\n\n $a->foo = $instance;\n\n return $instance;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $category = $this->getCategory();\n\n if ($this->categoryModel->remove($category['id'])) {\n $this->flash->success(t('Category removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this category.'));\n }\n\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 639} -{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-639", "label": 639} -{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-639", "label": 639} -{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function save()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->categoryValidator->validateCreation($values);\n\n if ($valid) {\n if ($this->categoryModel->create($values) !== false) {\n $this->flash->success(t('Your category have been created successfully.'));\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);\n return;\n } else {\n $errors = array('name' => array(t('Another category with the same name exists in this project')));\n }\n }\n\n $this->create($values, $errors);\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 639} -{"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-639", "label": 639} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($this->tagModel->remove($tag_id)) {\n $this->flash->success(t('Tag removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-639", "label": 639} -{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane();\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"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-639", "label": 639} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-639", "label": 639} -{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-639", "label": 639} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getTaskLink();\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 639} -{"code": "function shibboleth_login_form() {\n\t$login_url = add_query_arg('action', 'shibboleth');\n\t$login_url = remove_query_arg('reauth', $login_url);\n\techo '

    ' . __('Login with Shibboleth', 'shibboleth') . '

    ';\n}", "label_name": "CWE-79", "label": 79} -{"code": " public function delete($fileName = null)\n {\n $this->validateFileName();\n\n list($name, $extension) = $this->model->getFileNameParts();\n\n return $this->datasource->delete(\n $this->model->getObjectTypeDirName(),\n $name,\n $extension\n );\n }", "label_name": "CWE-22", "label": 22} -{"code": " public function get($columns = ['*'])\n {\n if (!is_null($this->cacheMinutes)) {\n $results = $this->getCached($columns);\n }\n else {\n $results = $this->getFresh($columns);\n }\n\n $models = $this->getModels($results ?: []);\n\n return $this->model->newCollection($models);\n }", "label_name": "CWE-79", "label": 79} -{"code": "function sqlrequest($database,$sql,$id=false){\n\n\t// Get the global value\n\tglobal $database_host;\n\tglobal $database_username;\n\tglobal $database_password;\n\n\t$connexion = mysqli_connect($database_host, $database_username, $database_password, $database);\n\tif (!$connexion) {\n\t\techo \"\";\n\t\texit(1);\n\t}\n\n\tif ( $database == \"eonweb\" ) {\n\t\t// Force UTF-8\n\t\tmysqli_query($connexion, \"SET NAMES 'utf8'\");\n\t}\n\t$result=mysqli_query($connexion, \"$sql\");\n\n\tif($id==true)\n\t\t$result=mysqli_insert_id($connexion);\n\t\t\n\tmysqli_close($connexion);\n\treturn $result;\n}", "label_name": "CWE-78", "label": 78} -{"code": "function editEvent($selected_events, $queue, $comments)\n{\n\tglobal $database_ged;\n\n\t// get all needed infos into variables\n\t$value_parts = explode(\":\", $selected_events);\n\t$id = $value_parts[0];\n\t$ged_type = $value_parts[1];\n\n\t// format comment string to avoid errors\n\t$comments = str_replace(\"'\", \"\\'\", $comments);\n\t$comments = str_replace(\"#\", \"\\#\", $comments);\n\n\t$sql = \"UPDATE \".$ged_type.\"_queue_\".$queue.\" SET comments='$comments' WHERE id = $id\";\n\t$result = sqlrequest($database_ged, $sql);\n\tif($result){\n\t\tmessage(11, \" : \".getLabel(\"message.event_edited\"), \"ok\");\n\t} else {\n\t\tmessage(11, \" : \".getLabel(\"message.event_edited_error\"), \"danger\");\n\t}\n}", "label_name": "CWE-78", "label": 78} -{"code": "\tpublic function set_controller($controller, $action)\n\t{\n\t\tinclude CLASS_DIR . 'module.php';\n\n\t\t$module = new Module($controller);\n\n\t\tdefine ('MODULE_NAME', $module->get_name());\n\n\t\t$class_file = APP_DIR . 'controller/' . MODULE_NAME . '.php';\n\t\t$class_name = ucfirst(MODULE_NAME) . '_Controller';\n\t\t$class_method = ucfirst($action) . '_Action';\n\n\t\t// tworzy obiekt kontrolera:\n\n\t\tif (file_exists($class_file))\n\t\t{\n\t\t\tinclude $class_file;\n\n\t\t\tif (class_exists($class_name))\n\t\t\t{\n\t\t\t\t$this->controller_object = new $class_name($this);\n\n\t\t\t\t$this->set_acl($this);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdie ('Class:

    '.$class_name.'

    not found.');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdie ('File:

    '.$class_file.'

    not found.');\n\t\t}\n\n\t\t// tworzy obiekt modelu:\n\n\t\t$this->set_model_object(MODULE_NAME);\n\n\t\t// tworzy obiekt widoku:\n\n\t\t$this->set_view_object(MODULE_NAME);\n\n\t\t// wywo\u0142uje akcj\u0119 (metod\u0119) kontrolera:\n\n\t\tif (method_exists($class_name, $class_method))\n\t\t{\n\t\t\t$this->controller_object->{$class_method}();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdie ('Method:

    '.$class_method.'

    in class:

    '.$class_name.'

    not found.');\n\t\t}\n\t}", "label_name": "CWE-79", "label": 79} -{"code": " public function dispatch($messages, $final)\n {\n $targetErrors = [];\n foreach ($this->targets as $target) {\n if ($target->enabled) {\n try {\n $target->collect($messages, $final);\n } catch (\\Exception $e) {\n $target->enabled = false;\n $targetErrors[] = [\n 'Unable to send log via ' . get_class($target) . ': ' . ErrorHandler::convertExceptionToString($e),\n Logger::LEVEL_WARNING,\n __METHOD__,\n microtime(true),\n [],\n ];\n }\n }\n }\n\n if (!empty($targetErrors)) {\n $this->dispatch($targetErrors, true);\n }\n }", "label_name": "CWE-79", "label": 79} -{"code": " public static function remove_spam()\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n $count = $DB->query_single(\r\n\t 'count(*) as total',\r\n\t 'nv_comments',\r\n\t 'website = '.protect($website->id).' AND status = 3'\r\n );\r\n\r\n $ok = $DB->execute('\r\n\t\t\tDELETE FROM nv_comments\r\n WHERE website = '.protect($website->id).'\r\n AND status = 3\r\n ');\r\n\r\n if($ok)\r\n return $count;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function remove($id)\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n if(empty($id))\r\n return 'invalid_id';\r\n\r\n $DB->execute('\r\n DELETE FROM nv_notes\r\n WHERE website = '.protect($website->id).'\r\n AND id = '.protect($id).'\r\n LIMIT 1'\r\n );\r\n\r\n return 'true';\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public function load_lines()\r\n {\r\n global $DB;\r\n\r\n $DB->query('\r\n SELECT * \r\n FROM nv_orders_lines \r\n WHERE `order` = '.protect($this->id).' \r\n ORDER BY position ASC'\r\n );\r\n $this->lines = $DB->result();\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function find_by_reference($reference, $website_id=null)\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n if(empty($website_id))\r\n $website_id = $website->id;\r\n\r\n $order_id = $DB->query_single(\r\n 'id',\r\n 'nv_orders',\r\n 'reference = '.protect($reference).' AND website = \"'.$website_id.'\"'\r\n );\r\n\r\n return $order_id;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": " public static function country_name_by_code($code, $language=\"\")\r\n {\r\n global $DB;\r\n\r\n $lang = core_get_language($language);\r\n\r\n $DB->query('SELECT name\r\n\t\t\t\t\tFROM nv_countries\r\n\t\t \t\t\tWHERE lang = '.protect($lang).'\r\n\t\t\t\t\t AND country_code = '.protect($code));\r\n\r\n $row = $DB->first();\r\n\r\n return $row->name;\r\n }\r", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic static function countries_regions($country_id=\"\")\r\n\t{\r\n\t\tglobal $DB;\r\n\r\n\t\t// note: regions have no translation to any language right now\r\n\r\n $country_query = \" 1=1 \";\r\n if(!empty($country_id))\r\n $country_query = ' AND r.country = '.protect($country_id);\r\n\r\n\t\t$DB->query('\r\n SELECT r.`numeric` AS region_id, c.country_code, r.name\r\n FROM nv_countries c, nv_countries_regions r\r\n WHERE c.lang = \"en\" AND\r\n c.`numeric` = r.country AND\r\n r.lang = \"\" AND\r\n '.$country_query.'\r\n ORDER BY name ASC\r\n ');\r\n\r\n\t\t$rs = $DB->result();\r\n\r\n\t\treturn $rs;\r\n\t}\r", "label_name": "CWE-89", "label": 89} -{"code": " AND lang = '.protect($lang).'\r\n AND subtype IN ('.implode(\",\", array_map(function($k){ return protect($k);}, $subtypes)).')'\r\n );\r", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic static function object_votes_by_score($object, $object_id)\r\n\t{\r\n\t\tglobal $DB;\r\n\t\tglobal $website;\r\n\t\t\r\n\t\t$DB->query('\r\n\t\t\tSELECT value, COUNT(*) as votes\r\n\t\t\t FROM nv_webuser_votes\r\n WHERE website = '.protect($website->id).'\r\n\t\t\t AND object = '.protect($object).'\r\n AND object_id = '.protect($object_id).'\r\n\t\t\t GROUP BY value\r\n\t\t\t ORDER BY value ASC\r\n\t\t ');\r\n\t\t\t\t\t \r\n\t\t$data = $DB->result();\r\n\t\t\r\n\t\treturn $data;\r\n\t}\r", "label_name": "CWE-89", "label": 89} -{"code": "\tpublic function update()\r\n\t{\r\n\t\tglobal $DB;\r\n\t\tglobal $events;\r\n\r\n\t\tif(!is_array($this->categories))\r\n\t\t\t$this->categories = array();\r\n\t\t\t\r\n\t\t$ok = $DB->execute(' \r\n \t\t\tUPDATE nv_feeds\r\n\t\t\t SET categories = :categories, format = :format, image = :image, entries = :entries, \r\n\t\t\t \t content = :content, views = :views, permission = :permission, enabled = :enabled\r\n\t\t\tWHERE id = :id\tAND\twebsite = :website',\r\n\t\t\tarray(\r\n\t\t\t\t'id' => $this->id,\r\n\t\t\t\t'website' => $this->website,\r\n\t\t\t\t'categories' => implode(',', $this->categories),\r\n\t\t\t\t'format' => $this->format,\r\n\t\t\t\t'image' => value_or_default($this->image, 0),\r\n\t\t\t\t'entries' => value_or_default($this->entries, 10),\r\n\t\t\t\t'content' => $this->content,\r\n\t\t\t\t'views' => value_or_default($this->views, 0),\r\n\t\t\t\t'permission' => value_or_default($this->permission, 0),\r\n\t\t\t\t'enabled' => value_or_default($this->enabled, 0)\r\n\t\t\t)\r\n\t\t);\r\n\t\t\t\t\t\t\t \r\n\t\tif(!$ok)\r\n\t\t throw new Exception($DB->get_last_error());\r\n\t\t\r\n\t\twebdictionary::save_element_strings('feed', $this->id, $this->dictionary);\r\n\t\tpath::saveElementPaths('feed', $this->id, $this->paths);\r\n\r\n if(method_exists($events, 'trigger'))\r\n {\r\n $events->trigger(\r\n 'feed',\r\n 'save',\r\n array(\r\n 'feed' => $this\r\n )\r\n );\r\n }\r\n\t\t\r\n\t\treturn true;\r\n\t}\r", "label_name": "CWE-79", "label": 79} -{"code": "\t\t\tforeach($fields as $field)\r\n\t\t\t{\r\n\t\t\t\tif(substr($key, 0, strlen($field.'-'))==$field.'-')\r\n {\r\n $this->dictionary[substr($key, strlen($field.'-'))][$field] = $value;\r\n }\r\n\t\t\t}\r", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function load_from_post()\r\n\t{\r\n\t\tif(intval($_REQUEST['parent'])!=$this->id)\t// protection against selecting this same category as parent of itself\r\n {\r\n $this->parent \t\t= intval($_REQUEST['parent']);\r\n }\r\n\t\t\t\r\n\t\t$this->template \t= $_REQUEST['template'];\r\n\t\t$this->access\t\t= intval($_REQUEST['access']);\r\n\r\n $this->groups\t = $_REQUEST['groups'];\r\n if($this->access < 3)\r\n {\r\n $this->groups = array();\r\n }\r\n\r\n\t\t$this->permission\t= intval($_REQUEST['permission']);\t\t\r\n\t\t$this->visible\t\t= intval($_REQUEST['visible']);\t\t\r\n\t\t\r\n\t\t$this->date_published\t= (empty($_REQUEST['date_published'])? '' : core_date2ts($_REQUEST['date_published']));\t\r\n\t\t$this->date_unpublish\t= (empty($_REQUEST['date_unpublish'])? '' : core_date2ts($_REQUEST['date_unpublish']));\t\r\n\t\t\r\n\t\t// language strings and options\r\n\t\t$this->dictionary = array();\r\n\t\t$this->paths = array();\r\n\r\n\t\t$fields = array('title', 'action-type', 'action-jump-item', 'action-jump-branch', 'action-new-window', 'action-masked-redirect'); //, 'path', 'visible');\r\n\t\tforeach($_REQUEST as $key => $value)\r\n\t\t{\r\n\t\t\tif(empty($value))\r\n {\r\n continue;\r\n }\r\n\t\t\t\r\n\t\t\tforeach($fields as $field)\r\n\t\t\t{\r\n\t\t\t\tif(substr($key, 0, strlen($field.'-'))==$field.'-')\r\n {\r\n $this->dictionary[substr($key, strlen($field.'-'))][$field] = $value;\r\n }\r\n\t\t\t}\r\n\t\t\r\n\t\t\tif(substr($key, 0, strlen('path-'))=='path-')\r\n {\r\n $this->paths[substr($key, strlen('path-'))] = $value;\r\n }\r\n\t\t}\t\t\r\n\t}\r", "label_name": "CWE-79", "label": 79} -{"code": " $sort = in_array(strtolower($val), array('asc', 'desc')) ? ' ' . $val : '';\n $array[] = $this->parseKey($key, true) . $sort;\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function display_sdm_stats_meta_box($post) { //Stats metabox\n\t$old_count = get_post_meta($post->ID, 'sdm_count_offset', true);\n\t$value = isset($old_count) && $old_count != '' ? $old_count : '0';\n\n\t// Get checkbox for \"disable download logging\"\n\t$no_logs = get_post_meta($post->ID, 'sdm_item_no_log', true);\n\t$checked = isset($no_logs) && $no_logs === 'on' ? 'checked=\"checked\"' : '';\n\n\t_e('These are the statistics for this download item.', 'simple-download-monitor');\n\techo '

    ';\n\n\tglobal $wpdb;\n\t$wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'sdm_downloads WHERE post_id=%s', $post->ID));\n\n\techo '
    ';\n\t_e('Number of Downloads:', 'simple-download-monitor');\n\techo ' ' . $wpdb->num_rows . '';\n\techo '
    ';\n\n\techo '
    ';\n\t_e('Offset Count: ', 'simple-download-monitor');\n\techo '
    ';\n\techo ' ';\n\techo '

    ' . __('Enter any positive or negative numerical value; to offset the download count shown to the visitors (when using the download counter shortcode).', 'simple-download-monitor') . '

    ';\n\techo '
    ';\n\n\techo '
    ';\n\techo '
    ';\n\techo '';\n\techo '';\n\t_e('Disable download logging for this item.', 'simple-download-monitor');\n\techo '
    ';\n\n\twp_nonce_field('sdm_count_offset_nonce', 'sdm_count_offset_nonce_check');\n }", "label_name": "CWE-79", "label": 79} -{"code": "function init_args()\n{\n\t$_REQUEST=strings_stripSlashes($_REQUEST);\n\t\n\n\t$args = new stdClass();\n\t$args->req_spec_id = isset($_REQUEST['req_spec_id']) ? $_REQUEST['req_spec_id'] : 0;\n\t$args->doCompare = isset($_REQUEST['doCompare']) ? true : false;\n\t$args->left_item_id = isset($_REQUEST['left_item_id']) ? intval($_REQUEST['left_item_id']) : -1;\n\t$args->right_item_id = isset($_REQUEST['right_item_id']) ? intval($_REQUEST['right_item_id']) : -1;\n\t$args->tproject_id = isset($_SESSION['testprojectID']) ? $_SESSION['testprojectID'] : 0;\n\t$args->useDaisyDiff = (isset($_REQUEST['diff_method']) && ($_REQUEST['diff_method'] == 'htmlCompare')) ? 1 : 0;\n\t\n\n\t$diffEngineCfg = config_get(\"diffEngine\");\n\t$args->context = null;\n\tif( !isset($_REQUEST['context_show_all'])) \n\t{\n\t\t$args->context = (isset($_REQUEST['context']) && is_numeric($_REQUEST['context'])) ? $_REQUEST['context'] : $diffEngineCfg->context;\n\t}\n\t\n\treturn $args;\n}", "label_name": "CWE-89", "label": 89} -{"code": "function init_args() {\n\t\n\t$args = new stdClass();\n\t\n\t$_REQUEST = strings_stripSlashes($_REQUEST);\n\t\n\t$args->build_id = isset($_REQUEST['build_id']) ? $_REQUEST['build_id'] : 0;\n\t$args->confirmed = isset($_REQUEST['confirmed']) && $_REQUEST['confirmed'] == 'yes' ? true : false;\n\t\n\t$args->user_id = $_SESSION['userID'];\n\t$args->testproject_id = $_SESSION['testprojectID'];\n\t$args->testproject_name = $_SESSION['testprojectName'];\n\t\n\t$args->refreshTree = isset($_SESSION['setting_refresh_tree_on_action']) ?\n\t $_SESSION['setting_refresh_tree_on_action'] : false;\n\t\n\treturn $args;\n}", "label_name": "CWE-89", "label": 89} -{"code": " public function getRawRevisionsAndCount($limit, PFUser $author)\n {\n return svn_get_revisions(\n $this->project,\n 0,\n $limit,\n '',\n $author->getUserName(),\n '',\n '',\n 0,\n false\n );\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function getQueryGroupby()\n {\n return '';\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function getQuerySelect()\n {\n return \"a.per_tracker_artifact_id AS `\" . $this->name . \"`\";\n }", "label_name": "CWE-89", "label": 89} -{"code": " $parent = $dIF->getItemFromDb($item->getParentId());\n $content .= '';\n $content .= '' . 'getId() . '\">' . $item->getTitle() . '';\n $content .= '';\n if ($parent === null || $dIF->isRoot($parent)) {\n $content .= '';\n } else {\n $content .= 'defaultUrl . '&action=show&id=' . $parent->getId() . '\">' . $parent->getTitle() . '';\n }\n $content .= '' . $hp->purify($uH->getDisplayNameFromUserId($row['user_id'])) . '';\n $content .= '' . format_date($GLOBALS['Language']->getText('system', 'datefmt'), $row['lock_date']) . '';\n $content .= '';\n }\n }", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function column_description( $item ) {\n\t\t$return = $item->object_name;\n\t\t\n\t\tswitch ( $item->object_type ) {\n\t\t\tcase 'Post' :\n\t\t\t\t$return = sprintf( '%s', get_edit_post_link( $item->object_id ), $item->object_name );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'Taxonomy' :\n\t\t\t\tif ( ! empty( $item->object_id ) )\n\t\t\t\t\t$return = sprintf( '%s', get_edit_term_link( $item->object_id, $item->object_subtype ), $item->object_name );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'Comments' :\n\t\t\t\tif ( ! empty( $item->object_id ) && $comment = get_comment( $item->object_id ) ) {\n\t\t\t\t\t$return = sprintf( '%s #%d', get_edit_comment_link( $item->object_id ), $item->object_name, $item->object_id );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'Export' :\n\t\t\t\tif ( 'all' === $item->object_name ) {\n\t\t\t\t\t$return = __( 'All', 'aryo-activity-log' );\n\t\t\t\t} else {\n\t\t\t\t\t$pt = get_post_type_object( $item->object_name );\n\t\t\t\t\t$return = ! empty( $pt->label ) ? $pt->label : $item->object_name;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'Options' :\n\t\t\tcase 'Core' :\n\t\t\t\t$return = __( $item->object_name, 'aryo-activity-log' );\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\t$return = apply_filters( 'aal_table_list_column_description', $return, $item );\n\t\t\n\t\treturn $return;\n\t}", "label_name": "CWE-79", "label": 79} -{"code": " protected function itemLock($hashes, $autoUnlock = true)\n {\n if (!elFinder::$commonTempPath) {\n return;\n }\n if (!is_array($hashes)) {\n $hashes = array($hashes);\n }\n foreach ($hashes as $hash) {\n $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';\n if ($this->itemLocked($hash)) {\n $cnt = file_get_contents($lock) + 1;\n } else {\n $cnt = 1;\n }\n if (file_put_contents($lock, $cnt, LOCK_EX)) {\n if ($autoUnlock) {\n $this->autoUnlocks[] = $hash;\n }\n }\n }\n }", "label_name": "CWE-918", "label": 918} -{"code": " $files[$i] = '.' . DIRECTORY_SEPARATOR . basename($file);\n }\n $files = array_map('escapeshellarg', $files);\n\n $cmd = $arc['cmd'] . ' ' . $arc['argc'] . ' ' . escapeshellarg($name) . ' ' . implode(' ', $files);\n $err_out = '';\n $this->procExec($cmd, $o, $c, $err_out, $dir);\n chdir($cwd);\n } else {\n return false;\n }\n }\n $path = $dir . DIRECTORY_SEPARATOR . $name;\n return file_exists($path) ? $path : false;\n }", "label_name": "CWE-78", "label": 78} -{"code": " protected function remove($path, $force = false)\n {\n $stat = $this->stat($path);\n\n if (empty($stat)) {\n return $this->setError(elFinder::ERROR_RM, $path, elFinder::ERROR_FILE_NOT_FOUND);\n }\n\n $stat['realpath'] = $path;\n $this->rmTmb($stat);\n $this->clearcache();\n\n if (!$force && !empty($stat['locked'])) {\n return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));\n }\n\n if ($stat['mime'] == 'directory' && empty($stat['thash'])) {\n $ret = $this->delTree($this->convEncIn($path));\n $this->convEncOut();\n if (!$ret) {\n return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));\n }\n } else {\n if ($this->convEncOut(!$this->_unlink($this->convEncIn($path)))) {\n return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));\n }\n $this->clearstatcache();\n }\n\n $this->removed[] = $stat;\n return true;\n }", "label_name": "CWE-918", "label": 918} -{"code": " protected function _copy($source, $targetDir, $name)\n {\n $res = false;\n\n $target = $this->_joinPath($targetDir, $name);\n if ($this->tmp) {\n $local = $this->getTempFile();\n\n if ($this->connect->get($source, $local)\n && $this->connect->put($target, $local, NET_SFTP_LOCAL_FILE)) {\n $res = true;\n }\n unlink($local);\n } else {\n //not memory efficient\n $res = $this->_filePutContents($target, $this->_getContents($source));\n }\n\n return $res;\n }", "label_name": "CWE-918", "label": 918} -{"code": " protected function _mkfile($path, $name)\n {\n $path = $this->_joinPath($path, $name);\n return $this->connect->put($path, '') ? $path : false;\n/*\n if ($this->tmp) {\n $path = $this->_joinPath($path, $name);\n $local = $this->getTempFile();\n $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);\n unlink($local);\n return $res ? $path : false;\n }\n\n return false;\n */\n }", "label_name": "CWE-22", "label": 22} -{"code": " protected function _mkfile($path, $name)\n {\n $path = $this->_joinPath($path, $name);\n return $this->connect->put($path, '') ? $path : false;\n/*\n if ($this->tmp) {\n $path = $this->_joinPath($path, $name);\n $local = $this->getTempFile();\n $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);\n unlink($local);\n return $res ? $path : false;\n }\n\n return false;\n */\n }", "label_name": "CWE-918", "label": 918} -{"code": " protected function _save($fp, $dir, $name, $stat)\n {\n //TODO optionally encrypt $fp before uploading if mime is not already encrypted type\n $path = $this->_joinPath($dir, $name);\n return $this->connect->put($path, $fp)\n ? $path\n : false;\n }", "label_name": "CWE-78", "label": 78} -{"code": " function prepareInputForAdd($input) {\n\n if (isset($input[\"passwd\"])) {\n if (empty($input[\"passwd\"])) {\n unset($input[\"passwd\"]);\n } else {\n $input[\"passwd\"] = Toolbox::encrypt(stripslashes($input[\"passwd\"]), GLPIKEY);\n }\n }\n\n if (isset($input['mail_server']) && !empty($input['mail_server'])) {\n $input[\"host\"] = Toolbox::constructMailServerConfig($input);\n }\n\n if (!NotificationMailing::isUserAddressValid($input['name'])) {\n Session::addMessageAfterRedirect(__('Invalid email address'), false, ERROR);\n }\n\n return $input;\n }", "label_name": "CWE-798", "label": 798} -{"code": " public function boot()\n {\n // Configure the debugbar\n Config::set('debugbar', Config::get('rainlab.debugbar::config'));\n\n // Service provider\n App::register('\\Barryvdh\\Debugbar\\ServiceProvider');\n\n // Register alias\n $alias = AliasLoader::getInstance();\n $alias->alias('Debugbar', '\\Barryvdh\\Debugbar\\Facade');\n\n // Register middleware\n if (Config::get('app.debugAjax', false)) {\n $this->app['Illuminate\\Contracts\\Http\\Kernel']->pushMiddleware('\\RainLab\\Debugbar\\Middleware\\Debugbar');\n }\n\n Event::listen('cms.page.beforeDisplay', function ($controller, $url, $page) {\n // Only show for authenticated backend users\n if (!BackendAuth::check()) {\n Debugbar::disable();\n }\n\n // Twig extensions\n $twig = $controller->getTwig();\n if (!$twig->hasExtension(\\Barryvdh\\Debugbar\\Twig\\Extension\\Debug::class)) {\n $twig->addExtension(new \\Barryvdh\\Debugbar\\Twig\\Extension\\Debug($this->app));\n $twig->addExtension(new \\Barryvdh\\Debugbar\\Twig\\Extension\\Stopwatch($this->app));\n }\n });\n }", "label_name": "CWE-532", "label": 532} -{"code": " public function redirect($route, $code = null)\n {\n /** @var Uri $uri */\n $uri = $this['uri'];\n\n //Check for code in route\n $regex = '/.*(\\[(30[1-7])\\])$/';\n preg_match($regex, $route, $matches);\n if ($matches) {\n $route = str_replace($matches[1], '', $matches[0]);\n $code = $matches[2];\n }\n\n if ($code === null) {\n $code = $this['config']->get('system.pages.redirect_default_code', 302);\n }\n\n if (isset($this['session'])) {\n $this['session']->close();\n }\n\n if ($uri->isExternal($route)) {\n $url = $route;\n } else {\n $url = rtrim($uri->rootUrl(), '/') . '/';\n\n if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {\n $url .= trim($route, '/'); // Remove trailing slash\n } else {\n $url .= ltrim($route, '/'); // Support trailing slash default routes\n }\n }\n\n header(\"Location: {$url}\", true, $code);\n exit();\n }", "label_name": "CWE-601", "label": 601} -{"code": " $contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('manufacturers.php', 'page=' . $_GET['page'] . '&mID=' . (int)$mInfo->manufacturers_id), null, null, 'btn-light')];", "label_name": "CWE-79", "label": 79} -{"code": " $contents = ['form' => tep_draw_form('reviews', 'reviews.php', 'page=' . $_GET['page'] . '&rID=' . $rInfo->reviews_id . '&action=deleteconfirm')];", "label_name": "CWE-79", "label": 79} -{"code": " $contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, null, null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('tax_classes.php', 'page=' . $_GET['page']), null, null, 'btn-light')];", "label_name": "CWE-79", "label": 79} -{"code": " $contents = ['form' => tep_draw_form('zones', 'zones.php', 'page=' . $_GET['page'] . '&action=insert')];", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function admin_log($mode = '')\n\t{\n\t\t$errorLogPath = TMP . 'logs' . DS . 'error.log';\n\t\tswitch($mode) {\n\t\t\tcase 'download':\n\t\t\t\tset_time_limit(0);\n\t\t\t\tif ($this->_downloadErrorLog()) {\n\t\t\t\t\texit();\n\t\t\t\t}\n\t\t\t\t$this->BcMessage->setInfo('\u30a8\u30e9\u30fc\u30ed\u30b0\u304c\u5b58\u5728\u3057\u307e\u305b\u3093\u3002');\n\t\t\t\t$this->redirect(['action' => 'log']);\n\t\t\t\tbreak;\n\t\t\tcase 'delete':\n\t\t\t\t$this->_checkSubmitToken();\n\t\t\t\tif (file_exists($errorLogPath)) {\n\t\t\t\t\tif (unlink($errorLogPath)) {\n\t\t\t\t\t\t$messages[] = __d('baser', '\u30a8\u30e9\u30fc\u30ed\u30b0\u3092\u524a\u9664\u3057\u307e\u3057\u305f\u3002');\n\t\t\t\t\t\t$error = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$messages[] = __d('baser', '\u30a8\u30e9\u30fc\u30ed\u30b0\u304c\u524a\u9664\u3067\u304d\u307e\u305b\u3093\u3067\u3057\u305f\u3002');\n\t\t\t\t\t\t$error = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$messages[] = __d('baser', '\u30a8\u30e9\u30fc\u30ed\u30b0\u304c\u5b58\u5728\u3057\u307e\u305b\u3093\u3002');\n\t\t\t\t\t$error = false;\n\t\t\t\t}\n\n\t\t\t\tif ($messages) {\n\t\t\t\t\t$this->BcMessage->set(implode(\"\\n\", $messages), $error);\n\t\t\t\t}\n\t\t\t\t$this->redirect(['action' => 'log']);\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\t$fileSize = 0;\n\t\tif (file_exists($errorLogPath)) {\n\t\t\t$fileSize = filesize($errorLogPath);\n\t\t}\n\n\t\t$this->pageTitle = __d('baser', '\u30c7\u30fc\u30bf\u30e1\u30f3\u30c6\u30ca\u30f3\u30b9');\n\t\t$this->help = 'tools_log';\n\t\t$this->set('fileSize', $fileSize);\n\t}", "label_name": "CWE-78", "label": 78} -{"code": "\tpublic function admin_write_schema()\n\t{\n\t\t$path = TMP . 'schemas' . DS;\n\n\t\t/* \u8868\u793a\u8a2d\u5b9a */\n\t\t$this->pageTitle = __d('baser', '\u30b9\u30ad\u30fc\u30de\u30d5\u30a1\u30a4\u30eb\u751f\u6210');\n\t\t$this->help = 'tools_write_schema';\n\n\t\tif (!$this->request->data) {\n\t\t\t$this->request->data['Tool']['connection'] = 'core';\n\t\t\treturn;\n\t\t}\n\n\t\tif (empty($this->request->data['Tool'])) {\n\t\t\t$this->BcMessage->setError(__d('baser', '\u30c6\u30fc\u30d6\u30eb\u3092\u9078\u629e\u3057\u3066\u304f\u3060\u3055\u3044\u3002'));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!$this->_resetTmpSchemaFolder()) {\n\t\t\t$this->BcMessage->setError('\u30d5\u30a9\u30eb\u30c0\uff1a' . $path . ' \u304c\u5b58\u5728\u3059\u308b\u304b\u78ba\u8a8d\u3057\u3001\u5b58\u5728\u3059\u308b\u5834\u5408\u306f\u3001\u524a\u9664\u3059\u308b\u304b\u66f8\u8fbc\u6a29\u9650\u3092\u4e0e\u3048\u3066\u304f\u3060\u3055\u3044\u3002');\n\t\t\t$this->redirect(['action' => 'write_schema']);\n\t\t}\n\t\tif (!$this->Tool->writeSchema($this->request->data, $path)) {\n\t\t\t$this->BcMessage->setError(__d('baser', '\u30b9\u30ad\u30fc\u30de\u30d5\u30a1\u30a4\u30eb\u306e\u751f\u6210\u306b\u5931\u6557\u3057\u307e\u3057\u305f\u3002'));\n\t\t\treturn;\n\t\t}\n\n\t\t$Simplezip = new Simplezip();\n\t\t$Simplezip->addFolder($path);\n\t\t$Simplezip->download('schemas');\n\t\texit();\n\t}", "label_name": "CWE-78", "label": 78} -{"code": " protected function redirectToOperator(Thread $thread, $operator_id)\n {\n if ($thread->state != Thread::STATE_CHATTING) {\n // We can redirect only threads which are in proggress now.\n return false;\n }\n\n // Redirect the thread\n $thread->state = Thread::STATE_WAITING;\n $thread->nextAgent = $operator_id;\n $thread->agentId = 0;\n\n // Check if the target operator belongs to the current thread's group.\n // If not reset the current thread's group.\n if ($thread->groupId != 0) {\n $db = Database::getInstance();\n list($groups_count) = $db->query(\n (\"SELECT count(*) AS count \"\n . \"FROM {operatortoopgroup} \"\n . \"WHERE operatorid = ? AND groupid = ?\"),\n array($operator_id, $thread->groupId),\n array(\n 'return_rows' => Database::RETURN_ONE_ROW,\n 'fetch_type' => Database::FETCH_NUM,\n )\n );\n if ($groups_count === 0) {\n $thread->groupId = 0;\n }\n }\n\n $thread->save();\n\n // Send notification message\n $thread->postMessage(\n Thread::KIND_EVENTS,\n getlocal(\n 'Operator {0} redirected you to another operator. Please wait a while.',\n array(get_operator_name($this->getOperator())),\n $thread->locale,\n true\n )\n );\n\n return true;\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function rename(){\n\n if($this->request->isMethod('POST')){\n\n if(\\Storage::move($this->request->input('old_file'), $this->request->input('new_file'))){\n if($this->request->ajax()){\n return response()->json(['success' => trans('File successfully renamed!')]);\n }\n }else{\n if($this->request->ajax()){\n return response()->json(['danger' => trans('message.something_went_wrong')]);\n }\n }\n\n }\n\n }", "label_name": "CWE-434", "label": 434} -{"code": " public static function loadFrom(Db $zdb, $id, $mailing, $new = true)\n {\n try {\n $select = $zdb->select(self::TABLE);\n $select->where('mailing_id = ' . $id);\n\n $results = $zdb->execute($select);\n $result = $results->current();\n\n return $mailing->loadFromHistory($result, $new);\n } catch (Throwable $e) {\n Analog::log(\n 'Unable to load mailing model #' . $id . ' | ' .\n $e->getMessage(),\n Analog::WARNING\n );\n throw $e;\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " public static function loadFieldType(Db $zdb, $id)\n {\n try {\n $select = $zdb->select(self::TABLE);\n $select->where('field_id = ' . $id);\n\n $results = $zdb->execute($select);\n $result = $results->current();\n if ($result) {\n $field_type = $result->field_type;\n $field_type = self::getFieldType($zdb, $field_type);\n $field_type->loadFromRs($result);\n return $field_type;\n }\n } catch (Throwable $e) {\n Analog::log(\n __METHOD__ . ' | Unable to retrieve field `' . $id .\n '` information | ' . $e->getMessage(),\n Analog::ERROR\n );\n return false;\n }\n return false;\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function load($id)\n {\n try {\n $select = $this->zdb->select($this->table);\n $select->where($this->fpk . ' = ' . $id);\n\n $results = $this->zdb->execute($select);\n if ($results->count() > 0) {\n $result = $results->current();\n $this->loadFromRS($result);\n\n return true;\n } else {\n Analog::log(\n 'Unknown ID ' . $id,\n Analog::ERROR\n );\n return false;\n }\n } catch (Throwable $e) {\n Analog::log(\n 'Cannot load ' . $this->getType() . ' from id `' . $id . '` | ' .\n $e->getMessage(),\n Analog::WARNING\n );\n throw $e;\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function delete($id)\n {\n $ret = $this->get($id);\n if (!$ret) {\n /* get() already logged */\n return self::ID_NOT_EXITS;\n }\n\n if ($this->isUsed($id)) {\n $this->errors[] = _T(\"Cannot delete this label: it's still used\");\n return false;\n }\n\n try {\n $this->zdb->connection->beginTransaction();\n $delete = $this->zdb->delete($this->table);\n $delete->where($this->fpk . ' = ' . $id);\n\n $this->zdb->execute($delete);\n $this->deleteTranslation($ret->{$this->flabel});\n\n Analog::log(\n $this->getType() . ' ' . $id . ' deleted successfully.',\n Analog::INFO\n );\n\n $this->zdb->connection->commit();\n return true;\n } catch (Throwable $e) {\n $this->zdb->connection->rollBack();\n Analog::log(\n 'Unable to delete ' . $this->getType() . ' ' . $id .\n ' | ' . $e->getMessage(),\n Analog::ERROR\n );\n throw $e;\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": " $subgroup->remove(true);\n }\n }\n\n Analog::log(\n 'Cascading remove ' . $this->group_name .\n '. Members and managers will be detached.',\n Analog::INFO\n );\n\n //delete members\n $delete = $zdb->delete(self::GROUPSUSERS_TABLE);\n $delete->where(\n self::PK . ' = ' . $this->id\n );\n $zdb->execute($delete);\n\n //delete managers\n $delete = $zdb->delete(self::GROUPSMANAGERS_TABLE);\n $delete->where(\n self::PK . ' = ' . $this->id\n );\n $zdb->execute($delete);\n }\n\n //delete group itself\n $delete = $zdb->delete(self::TABLE);\n $delete->where(\n self::PK . ' = ' . $this->id\n );\n $zdb->execute($delete);\n\n //commit all changes\n if ($transaction) {\n $zdb->connection->commit();\n }\n\n return true;\n } catch (Throwable $e) {\n if ($transaction) {\n $zdb->connection->rollBack();\n }\n if ($e->getCode() == 23000) {\n Analog::log(\n str_replace(\n '%group',\n $this->group_name,\n 'Group \"%group\" still have members!'\n ),\n Analog::WARNING\n );\n $this->isempty = false;\n } else {\n Analog::log(\n 'Unable to delete group ' . $this->group_name .\n ' (' . $this->id . ') |' . $e->getMessage(),\n Analog::ERROR\n );\n throw $e;\n }\n return false;\n }\n }", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\t\t\tunset($return[$key]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn @array_change_key_case($return, CASE_UPPER);\n}", "label_name": "CWE-22", "label": 22} -{"code": "function db_properties($table)\n{\n\tglobal $DatabaseType, $DatabaseUsername;\n\n\tswitch ($DatabaseType) {\n\t\tcase 'mysqli':\n\t\t\t$result = DBQuery(\"SHOW COLUMNS FROM $table\");\n\t\t\twhile ($row = db_fetch_row($result)) {\n\t\t\t\t$properties[strtoupper($row['FIELD'])]['TYPE'] = strtoupper($row['TYPE'], strpos($row['TYPE'], '('));\n\t\t\t\tif (!$pos = strpos($row['TYPE'], ','))\n\t\t\t\t\t$pos = strpos($row['TYPE'], ')');\n\t\t\t\telse\n\t\t\t\t\t$properties[strtoupper($row['FIELD'])]['SCALE'] = substr($row['TYPE'], $pos + 1);\n\n\t\t\t\t$properties[strtoupper($row['FIELD'])]['SIZE'] = substr($row['TYPE'], strpos($row['TYPE'], '(') + 1, $pos);\n\n\t\t\t\tif ($row['NULL'] != '')\n\t\t\t\t\t$properties[strtoupper($row['FIELD'])]['NULL'] = \"Y\";\n\t\t\t\telse\n\t\t\t\t\t$properties[strtoupper($row['FIELD'])]['NULL'] = \"N\";\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn $properties;\n}", "label_name": "CWE-79", "label": 79} -{"code": "function DateInputAY($value, $name, $counter = 1, $placeholder = _enterDate)\n{\n\n $show = \"\";\n $date_sep = \"\";\n $monthVal = \"\";\n $yearVal = \"\";\n $dayVal = \"\";\n $display = \"\";\n\n if ($value != '')\n return '
    ' . ProperDateAY($value) . '     
    ';\n else {\n if ($counter == 2)\n return '';\n else\n return '';\n }\n}", "label_name": "CWE-22", "label": 22} -{"code": "function db_case($array)\n{\n global $DatabaseType;\n\n $counter = 0;\n if ($DatabaseType == 'mysqli') {\n $array_count = count($array);\n $string = \" CASE WHEN $array[0] =\";\n $counter++;\n $arr_count = count($array);\n for ($i = 1; $i < $arr_count; $i++) {\n $value = $array[$i];\n\n if ($value == \"''\" && substr($string, -1) == '=') {\n $value = ' IS NULL';\n $string = substr($string, 0, -1);\n }\n\n $string .= \"$value\";\n if ($counter == ($array_count - 2) && $array_count % 2 == 0)\n $string .= \" ELSE \";\n elseif ($counter == ($array_count - 1))\n $string .= \" END \";\n elseif ($counter % 2 == 0)\n $string .= \" WHEN $array[0]=\";\n elseif ($counter % 2 == 1)\n $string .= \" THEN \";\n\n $counter++;\n }\n }\n\n return $string;\n}", "label_name": "CWE-79", "label": 79} -{"code": "function singleQuoteReplace($param1 = false, $param2 = false, $param3)\n{\n return str_replace(\"'\", \"''\", str_replace(\"\\'\", \"'\", $param3));\n}", "label_name": "CWE-22", "label": 22} -{"code": " $percent = round($percent, 0);\n } else {\n $percent = round($percent, 2); // school default\n }\n if ($ret == '%')\n return $percent;\n\n if (!$_openSIS['_makeLetterGrade']['grades'][$grade_scale_id])\n $_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] = DBGet(DBQuery('SELECT TITLE,ID,BREAK_OFF FROM report_card_grades WHERE SYEAR=\\'' . $cp[1]['SYEAR'] . '\\' AND SCHOOL_ID=\\'' . $cp[1]['SCHOOL_ID'] . '\\' AND GRADE_SCALE_ID=\\'' . $grade_scale_id . '\\' ORDER BY BREAK_OFF IS NOT NULL DESC,BREAK_OFF DESC,SORT_ORDER'));\n\n foreach ($_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] as $grade) {\n if ($does_breakoff == 'Y' ? $percent >= $programconfig[$staff_id][$course_period_id . '-' . $grade['ID']] && is_numeric($programconfig[$staff_id][$course_period_id . '-' . $grade['ID']]) : $percent >= $grade['BREAK_OFF'])\n return $ret == 'ID' ? $grade['ID'] : $grade['TITLE'];\n }\n}", "label_name": "CWE-22", "label": 22} -{"code": "function db_start()\n{\n global $DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort, $DatabaseType;\n\n switch ($DatabaseType) {\n case 'mysqli':\n $connection = new mysqli($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);\n break;\n }\n\n // Error code for both.\n if ($connection === false) {\n switch ($DatabaseType) {\n case 'mysqli':\n $errormessage = mysqli_error($connection);\n break;\n }\n db_show_error(\"\", \"\" . _couldNotConnectToDatabase . \": $DatabaseServer\", $errormessage);\n }\n return $connection;\n}", "label_name": "CWE-79", "label": 79} -{"code": "function db_seq_nextval($seqname)\n{\n global $DatabaseType;\n\n if ($DatabaseType == 'mysqli')\n $seq = \"fn_\" . strtolower($seqname) . \"()\";\n\n return $seq;\n}", "label_name": "CWE-79", "label": 79} -{"code": " echo '' . htmlentities($value_arr['LANGUAGE']) . '';\n foreach ($value_arr['ENROLLMENT_INFO'] as $eid => $ed) {\n echo '';\n echo '' . htmlentities($ed['SCHOOL_ID']) . '';\n echo '' . htmlentities($ed['CALENDAR']) . '';\n echo '' . htmlentities($ed['GRADE']) . '';\n echo '
    ' . htmlentities($ed['SECTION']) . '
    ';\n echo '' . htmlentities($ed['START_DATE']) . '';\n echo '' . htmlentities($ed['DROP_DATE']) . '';\n echo '' . htmlentities($ed['ENROLLMENT_CODE']) . '';\n echo '' . htmlentities($ed['DROP_CODE']) . '';\n echo '
    ';\n }\n echo '';\n }\n echo '';\n }", "label_name": "CWE-79", "label": 79} -{"code": " foreach($course_RET as $period_day)\n {\n $period_days_append_sql .=\"(sp.start_time<='$period_day[END_TIME]' AND '$period_day[START_TIME]'<=sp.end_time AND DAYS LIKE '%$period_day[DAYS]%') OR \";\n }", "label_name": "CWE-22", "label": 22} -{"code": "function _makeMpName($value) {\n if ($value != '') {\n $get_name = DBGet(DBQuery('SELECT TITLE FROM marking_periods WHERE marking_period_id=' . $value));\n return $get_name[1]['TITLE'];\n } else\n return ''._customCoursePeriod.'';\n}", "label_name": "CWE-22", "label": 22} -{"code": " foreach ($value as $i => $j) {\n\n\n $column_check = explode('_', $i);\n if ($column_check[0] == 'CUSTOM') {\n $check_validity = DBGet(DBQuery('SELECT COUNT(*) as REC_EX FROM school_custom_fields WHERE ID=' . $column_check[1] . ' AND (SCHOOL_ID=' . $get_school_info[$key]['ID'].' OR SCHOOL_ID=0)'));\n if ($check_validity[1]['REC_EX'] == 0)\n $j = 'NOT_AVAILABLE_FOR';\n }\n $get_school_info[$key][$i] = trim($j);\n }", "label_name": "CWE-22", "label": 22} -{"code": " public function __construct($message, $code = 0, Exception $previous = null)\n {\n parent::__construct($message, $code, $previous);\n }", "label_name": "CWE-307", "label": 307} -{"code": " public function __construct($message, $code = 0, Exception $previous = null)\n {\n parent::__construct($message, $code, $previous);\n }", "label_name": "CWE-307", "label": 307} -{"code": " public function pageToContainedHtml(Page $page)\n {\n $page->html = (new PageContent($page))->render();\n $pageHtml = view('pages.export', [\n 'page' => $page,\n 'format' => 'html',\n ])->render();\n\n return $this->containHtml($pageHtml);\n }", "label_name": "CWE-79", "label": 79} -{"code": " protected function configure()\n {\n $this\n ->setName('kimai:version')\n ->setDescription('Receive version information')\n ->setHelp('This command allows you to fetch various version information about Kimai.')\n ->addOption('name', null, InputOption::VALUE_NONE, 'Display the major release name')\n ->addOption('candidate', null, InputOption::VALUE_NONE, 'Display the current version candidate (e.g. \"stable\" or \"dev\")')\n ->addOption('short', null, InputOption::VALUE_NONE, 'Display the version only')\n ->addOption('semver', null, InputOption::VALUE_NONE, 'Semantical versioning (SEMVER) compatible version string')\n ;\n }", "label_name": "CWE-1236", "label": 1236} -{"code": " public function testBuild()\n {\n $version = Constants::VERSION;\n $versionParts = explode('.', $version);\n $major = (int) $versionParts[0];\n $minor = (int) $versionParts[1];\n $patch = isset($versionParts[2]) ? (int) $versionParts[2] : 0;\n\n $expectedId = $major * 10000 + $minor * 100 + $patch;\n\n self::assertEquals('1.14', Constants::VERSION, 'Invalid release number');\n self::assertTrue(\\in_array(Constants::STATUS, ['dev', 'stable']), 'Invalid status');\n self::assertEquals($expectedId, Constants::VERSION_ID, 'Invalid version ID');\n }", "label_name": "CWE-1236", "label": 1236} -{"code": " public function uploadCompanyLogo(Request $request)\n {\n $company = Company::find($request->header('company'));\n\n $this->authorize('manage company', $company);\n\n $data = json_decode($request->company_logo);\n\n if ($data) {\n $company = Company::find($request->header('company'));\n\n if ($company) {\n $company->clearMediaCollection('logo');\n\n $company->addMediaFromBase64($data->data)\n ->usingFileName($data->name)\n ->toMediaCollection('logo');\n }\n }\n\n return response()->json([\n 'success' => true,\n ]);\n }", "label_name": "CWE-434", "label": 434} -{"code": "\t\t\tlist($h, $m) = explode('.', $row['RunAt']);\n\n\t\t\t$main .= '
    ';\n\t\t\t$main .= '

    ' . $row['Title'] . '

    ';\n\n\t\t\tif(!empty($systems_for_schedule))\n\t\t\t{\n\t\t\t\tif($row['RunAt'] > date('H.i'))\n\t\t\t\t{\n\t\t\t\t\t$run_in_future = true;\n\t\t\t\t\t$main .= '

    Runs In ' . pts_strings::format_time((($h * 60) + $m) - ((date('H') * 60) + date('i')), 'MINUTES') . '

    ';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$run_in_future = false;\n\t\t\t\t\t$main .= '

    Triggered ' . pts_strings::format_time(max(1, (date('H') * 60) + date('i') - (($h * 60) + $m)), 'MINUTES') . ' Ago

    ';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach($systems_for_schedule as $system_id)\n\t\t\t{\n\t\t\t\t$pprid = self::result_match($row['ScheduleID'], $system_id, date('Y-m-d'));\n\n\t\t\t\tif($pprid)\n\t\t\t\t\t$main .= '';\n\n\t\t\t\t$main .= phoromatic_server::system_id_to_name($system_id);\n\n\t\t\t\tif($pprid)\n\t\t\t\t\t$main .= '';\n\t\t\t\telse if(!$run_in_future)\n\t\t\t\t{\n\t\t\t\t\t$sys_info = self::system_info($system_id);\n\t\t\t\t\t$last_comm_diff = time() - strtotime($sys_info['LastCommunication']);\n\n\t\t\t\t\t$main .= ' ';\n\t\t\t\t\tif($last_comm_diff > 3600)\n\t\t\t\t\t{\n\t\t\t\t\t\t$main .= 'Last Communication: ' . pts_strings::format_time($last_comm_diff, 'SECONDS', true, 60) . ' Ago';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$main .= $sys_info['CurrentTask'];\n\t\t\t\t\t}\n\t\t\t\t\t$main .= '';\n\t\t\t\t}\n\t\t\t\t$main .= '
    ';\n\t\t\t}\n\n\t\t\t$main .= '
    ';\n\t\t}\n\t\t$main .= '';\n\n\t\t$main .= '';\n\n\t\techo '
    ' . $main . '
    ';\n\t\t//echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());\n\t\techo phoromatic_webui_footer();\n\t}", "label_name": "CWE-79", "label": 79} -{"code": "function phoromatic_account_id_to_group_name($account_id)\n{\n\t// XXX deprecated\n\treturn phoromatic_server::account_id_to_group_name($account_id);\n}", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function testDolEval()\n\t{\n\t\tglobal $conf,$user,$langs,$db;\n\t\t$conf=$this->savconf;\n\t\t$user=$this->savuser;\n\t\t$langs=$this->savlangs;\n\t\t$db=$this->savdb;\n\n\t\t$result=dol_eval('1==1', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertTrue($result);\n\n\t\t$result=dol_eval('1==2', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertFalse($result);\n\n\t\tinclude_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';\n\t\tinclude_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';\n\t\t$result=dol_eval('(($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref: \"Parent project not found\"', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertEquals('Parent project not found', $result);\n\n\t\t$result=dol_eval('$a=function() { }; $a;', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('$a=exec(\"ls\");', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('$a=exec (\"ls\")', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('$a=\"test\"; $$a;', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('`ls`', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\t}", "label_name": "CWE-94", "label": 94} -{"code": " private function section($nodes, $id, $filters, $start, $end, $otag, $ctag, $level)\n {\n $source = var_export(substr($this->source, $start, $end - $start), true);\n $callable = $this->getCallable();\n\n if ($otag !== '{{' || $ctag !== '}}') {\n $delimTag = var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);\n $helper = sprintf('$this->lambdaHelper->withDelimiters(%s)', $delimTag);\n $delims = ', ' . $delimTag;\n } else {\n $helper = '$this->lambdaHelper';\n $delims = '';\n }\n\n $key = ucfirst(md5($delims . \"\\n\" . $source));\n\n if (!isset($this->sections[$key])) {\n $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $helper, $delims, $this->walk($nodes, 2));\n }\n\n $method = $this->getFindMethod($id);\n $id = var_export($id, true);\n $filters = $this->getFilters($filters, $level);\n\n return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $method, $id, $filters, $key);\n }", "label_name": "CWE-1336", "label": 1336} -{"code": " public static function getIconName($module)\n {\n return isset(static::$iconNames[$module])\n ? static::$iconNames[$module]\n : strtolower(str_replace('_', '-', $module));\n }", "label_name": "CWE-89", "label": 89} -{"code": " public function tableCleanup(int $maxInactiveMinutes = 30)\n {\n $now = new \\DateTime();\n $minutesBack = new \\DateInterval('PT' . $maxInactiveMinutes . 'M');\n $timestamp = $now->sub($minutesBack)->format('Y-m-d H:i:s');\n\n $sql = 'DELETE FROM '.TBL_SESSIONS.'\n WHERE ses_timestamp < ? -- $timestamp\n AND ses_session_id <> ? -- $this->getValue(\\'ses_session_id\\')';\n $this->db->queryPrepared($sql, array($timestamp, $this->getValue('ses_session_id')));\n }", "label_name": "CWE-613", "label": 613} -{"code": "\tpublic function addTab($array)\n\t{\n\t\tif (!$array) {\n\t\t\t$this->setAPIResponse('error', 'no data was sent', 422);\n\t\t\treturn null;\n\t\t}\n\t\t$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);\n\t\t$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();\n\t\t$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();\n\t\t$array['enabled'] = ($array['enabled']) ?? 0;\n\t\t$array['default'] = ($array['default']) ?? 0;\n\t\t$array['type'] = ($array['type']) ?? 1;\n\t\t$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;\n\t\tif (array_key_exists('name', $array)) {\n\t\t\t$array['name'] = htmlspecialchars($array['name']);\n\t\t\tif ($this->isTabNameTaken($array['name'])) {\n\t\t\t\t$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\t$this->setAPIResponse('error', 'Tab name was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('image', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab image was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\t$response = [\n\t\t\tarray(\n\t\t\t\t'function' => 'query',\n\t\t\t\t'query' => array(\n\t\t\t\t\t'INSERT INTO [tabs]',\n\t\t\t\t\t$array\n\t\t\t\t)\n\t\t\t),\n\t\t];\n\t\t$this->setAPIResponse(null, 'Tab added');\n\t\t$this->setLoggerChannel('Tab Management');\n\t\t$this->logger->debug('Added Tab for [' . $array['name'] . ']');\n\t\treturn $this->processQueries($response);\n\t}", "label_name": "CWE-434", "label": 434} -{"code": "\tpublic function addTab($array)\n\t{\n\t\tif (!$array) {\n\t\t\t$this->setAPIResponse('error', 'no data was sent', 422);\n\t\t\treturn null;\n\t\t}\n\t\t$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);\n\t\t$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();\n\t\t$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();\n\t\t$array['enabled'] = ($array['enabled']) ?? 0;\n\t\t$array['default'] = ($array['default']) ?? 0;\n\t\t$array['type'] = ($array['type']) ?? 1;\n\t\t$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;\n\t\tif (array_key_exists('name', $array)) {\n\t\t\t$array['name'] = htmlspecialchars($array['name']);\n\t\t\tif ($this->isTabNameTaken($array['name'])) {\n\t\t\t\t$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\t$this->setAPIResponse('error', 'Tab name was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('image', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab image was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\t$response = [\n\t\t\tarray(\n\t\t\t\t'function' => 'query',\n\t\t\t\t'query' => array(\n\t\t\t\t\t'INSERT INTO [tabs]',\n\t\t\t\t\t$array\n\t\t\t\t)\n\t\t\t),\n\t\t];\n\t\t$this->setAPIResponse(null, 'Tab added');\n\t\t$this->setLoggerChannel('Tab Management');\n\t\t$this->logger->debug('Added Tab for [' . $array['name'] . ']');\n\t\treturn $this->processQueries($response);\n\t}", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic function updateTab($id, $array)\n\t{\n\t\tif (!$id || $id == '') {\n\t\t\t$this->setAPIResponse('error', 'id was not set', 422);\n\t\t\treturn null;\n\t\t}\n\t\tif (!$array) {\n\t\t\t$this->setAPIResponse('error', 'no data was sent', 422);\n\t\t\treturn null;\n\t\t}\n\t\t$tabInfo = $this->getTabById($id);\n\t\tif ($tabInfo) {\n\t\t\t$array = $this->checkKeys($tabInfo, $array);\n\t\t} else {\n\t\t\t$this->setAPIResponse('error', 'No tab info found', 404);\n\t\t\treturn false;\n\t\t}\n\t\tif (array_key_exists('name', $array)) {\n\t\t\t$array['name'] = htmlspecialchars($array['name']);\n\t\t\tif ($this->isTabNameTaken($array['name'], $id)) {\n\t\t\t\t$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (array_key_exists('default', $array)) {\n\t\t\tif ($array['default']) {\n\t\t\t\t$this->clearTabDefault();\n\t\t\t}\n\t\t}\n\t\t$response = [\n\t\t\tarray(\n\t\t\t\t'function' => 'query',\n\t\t\t\t'query' => array(\n\t\t\t\t\t'UPDATE tabs SET',\n\t\t\t\t\t$array,\n\t\t\t\t\t'WHERE id = ?',\n\t\t\t\t\t$id\n\t\t\t\t)\n\t\t\t),\n\t\t];\n\t\t$this->setAPIResponse(null, 'Tab info updated');\n\t\t$this->setLoggerChannel('Tab Management');\n\t\t$this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');\n\t\treturn $this->processQueries($response);\n\t}", "label_name": "CWE-79", "label": 79} -{"code": "function URLEscape( $string )\n{\n\t$string = preg_replace_callback(\n\t\t// Match both decimal & hex code (although hex codes can contain a-f letters).\n\t\t// Should be enough as the alphabet hex codes only have numbers.\n\t\t\"/(&#x?[0-9]+;?)/i\",\n\t\tfunction( $match ) {\n\t\t\tif ( mb_substr( $match[1], -1 ) !== ';' )\n\t\t\t{\n\t\t\t\t// Fix stored XSS security issue: add semicolon to HTML entity so it can be decoded.\n\t\t\t\t// @link https://www.php.net/manual/en/function.html-entity-decode.php#104617\n\t\t\t\t$match[1] .= ';';\n\t\t\t}\n\n\t\t\treturn $match[1];\n\t\t},\n\t\t$string\n\t);\n\n\t// Fix stored XSS security issue: decode HTML entities from URL.\n\t$string = html_entity_decode( (string) $string );\n\n\t$remove = [\n\t\t// Fix stored XSS security issue: remove inline JS from URL.\n\t\t'javascript:',\n\t];\n\n\tforeach ( $remove as $remove_string )\n\t{\n\t\twhile ( strpos( $string, $remove_string ) !== false )\n\t\t{\n\t\t\t$string = str_ireplace( $remove, '', $string );\n\t\t}\n\t}\n\n\t$entities = [\n\t\t'%21',\n\t\t'%2A',\n\t\t'%27',\n\t\t'%28',\n\t\t'%29',\n\t\t'%3B',\n\t\t'%3A',\n\t\t'%40',\n\t\t'%26',\n\t\t'%3D',\n\t\t'%2B',\n\t\t'%24',\n\t\t'%2C',\n\t\t'%2F',\n\t\t'%3F',\n\t\t'%25',\n\t\t'%23',\n\t\t'%5B',\n\t\t'%5D',\n\t];\n\n\t$replacements = [\n\t\t'!',\n\t\t'*',\n\t\t\"'\",\n\t\t'(',\n\t\t')',\n\t\t';',\n\t\t':',\n\t\t'@',\n\t\t'&',\n\t\t'=',\n\t\t'+',\n\t\t'$',\n\t\t',',\n\t\t'/',\n\t\t'?',\n\t\t'%',\n\t\t'#',\n\t\t'[',\n\t\t']',\n\t];\n\n\treturn str_replace(\n\t\t$entities,\n\t\t$replacements,\n\t\trawurlencode( $string )\n\t);\n}", "label_name": "CWE-79", "label": 79} -{"code": " public function store(CreateAppointmentCalendarRequest $request)\n {\n \n $client_id = null;\n $user = User::where('external_id', $request->user)->first();\n\n if ($request->client_external_id) {\n $client_id = Client::where('external_id', $request->client_external_id)->first()->id;\n if (!$client_id) {\n return response(__(\"Client not found\"), 422);\n }\n }\n\n $request_type = null;\n $request_id = null;\n if ($request->source_type && $request->source_external_id) {\n $request_type = $request->source_type;\n\n $entry = $request_type::whereExternalId($request->source_external_id);\n $request_id = $entry->id;\n }\n\n if (!$user) {\n return response(__(\"User not found\"), 422);\n }\n\n $startTime = str_replace([\"am\", \"pm\", ' '], \"\", $request->start_time) . ':00';\n $endTime = str_replace([\"am\", \"pm\", ' '], \"\", $request->end_time) . ':00';\n\n \n\n $appointment = Appointment::create([\n 'external_id' => Uuid::uuid4()->toString(),\n 'source_type' => $request_type,\n 'source_id' => $request_id,\n 'client_id' => $client_id,\n 'title' => $request->title,\n 'start_at' => Carbon::parse($request->start_date . \" \" . $startTime),\n 'end_at' => Carbon::parse($request->end_date . \" \" . $endTime),\n 'user_id' => $user->id,\n 'color' => $request->color\n ]);\n $appointment->user_external_id = $user->external_id;\n $appointment->start_at = $appointment->start_at;\n\n return response($appointment);\n }", "label_name": "CWE-521", "label": 521} -{"code": " public function anyData()\n {\n $tasks = Task::with(['user', 'status', 'client'])->select(\n collect(['external_id', 'title', 'created_at', 'deadline', 'user_assigned_id', 'status_id', 'client_id'])\n ->map(function ($field) {\n return (new Task())->qualifyColumn($field);\n })\n ->all()\n );\n\n return Datatables::of($tasks)\n ->addColumn('titlelink', '{{$title}}')\n ->editColumn('client', function ($projects) {\n return $projects->client->company_name;\n })\n ->editColumn('created_at', function ($tasks) {\n return $tasks->created_at ? with(new Carbon($tasks->created_at))\n ->format(carbonDate()) : '';\n })\n ->editColumn('deadline', function ($tasks) {\n return $tasks->created_at ? with(new Carbon($tasks->deadline))\n ->format(carbonDate()) : '';\n })\n ->editColumn('user_assigned_id', function ($tasks) {\n return $tasks->user->name;\n })\n ->editColumn('status_id', function ($tasks) {\n return 'status->color . '\"> ' .\n $tasks->status->title . '';\n })\n ->addColumn('view', function ($tasks) {\n return 'external_id) . '\" class=\"btn btn-link\">' . __('View') .''\n . 'external_id) . '\" data-title=\"'. $tasks->title . '\" data-target=\"#deletion\" class=\"btn btn-link\">' . __('Delete') .''\n ;\n })\n ->rawColumns(['titlelink','view', 'status_id'])\n ->make(true);\n }", "label_name": "CWE-79", "label": 79} -{"code": " public function testInfoWithoutUrl()\n {\n $this->assertRequestIsRedirect('info');\n }", "label_name": "CWE-601", "label": 601} -{"code": " public function testInfoWithoutUrl()\n {\n $this->assertRequestIsRedirect('info');\n }", "label_name": "CWE-918", "label": 918} -{"code": "function updateBasicSettings(PDFStructure &$structure) {\n\t// set headline\n\tif (isset($_POST['headline'])) {\n\t\t$structure->setTitle(str_replace('<', '', str_replace('>', '', $_POST['headline'])));\n\t}\n\t// set logo\n\tif (isset($_POST['logoFile'])) {\n\t\t$structure->setLogo($_POST['logoFile']);\n\t}\n\t// set folding marks\n\tif (isset($_POST['foldingmarks'])) {\n\t\t$structure->setFoldingMarks($_POST['foldingmarks']);\n\t}\n}", "label_name": "CWE-79", "label": 79} -{"code": " function get(&$dbh, $proposalId, $handle)\n {\n $sql = \"SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = \". $dbh->quoteSmart($proposalId) .\" AND user_handle= \". $dbh->quoteSmart($handle);\n $res = $dbh->query($sql);\n if (DB::isError($res)) {\n return $res;\n }\n if (!$res->numRows()) {\n return null;\n }\n $set = $res->fetchRow(DB_FETCHMODE_ASSOC);\n $set['reviews'] = unserialize($set['reviews']);\n $vote = new ppVote($set);\n return $vote;\n }", "label_name": "CWE-640", "label": 640} -{"code": "\t\thtml: function (token, attrs, content) {\n\t\t\tvar size = $.inArray(attrs.defaultattr, mybbCmd.fsStr) + 1;\n\t\t\tif (!isNaN(attrs.defaultattr)) {\n\t\t\t\tsize = attrs.defaultattr;\n\t\t\t\tif (size > 7)\n\t\t\t\t\tsize = 7;\n\t\t\t\tif (size < 1)\n\t\t\t\t\tsize = 1;\n\t\t\t}\n\t\t\tif (size < 0) {\n\t\t\t\tsize = 0;\n\t\t\t}\n\t\t\treturn '' + content + '';\n\t\t}", "label_name": "CWE-79", "label": 79} -{"code": " function ComponentRawSourceDialogController(scope, $mdDialog) {\n scope.close = function() {\n $mdDialog.hide();\n };\n }", "label_name": "CWE-79", "label": 79} -{"code": " var url2FilePath = function(url){\n var subPath = url.substr(\"/tests/frontend\".length);\n if (subPath == \"\"){\n subPath = \"index.html\"\n }\n subPath = subPath.split(\"?\")[0];\n\n var filePath = path.normalize(npm.root + \"/../tests/frontend/\")\n filePath += subPath.replace(\"..\", \"\");\n return filePath;\n }", "label_name": "CWE-22", "label": 22} -{"code": " Tooltip.prototype.hide = function (callback) {\n var that = this\n var $tip = $(this.$tip)\n var e = $.Event('hide.bs.' + this.type)\n\n function complete() {\n if (that.hoverState != 'in') $tip.detach()\n that.$element\n .removeAttr('aria-describedby')\n .trigger('hidden.bs.' + that.type)\n callback && callback()\n }\n\n this.$element.trigger(e)\n\n if (e.isDefaultPrevented()) return\n\n $tip.removeClass('in')\n\n $.support.transition && $tip.hasClass('fade') ?\n $tip\n .one('bsTransitionEnd', complete)\n .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :\n complete()\n\n this.hoverState = null\n\n return this\n }", "label_name": "CWE-89", "label": 89} -{"code": "\t_removeCurrentsFromItems: function() {\n\n\t\tvar list = this.currentItem.find(\":data(\" + this.widgetName + \"-item)\");\n\n\t\tthis.items = $.grep(this.items, function (item) {\n\t\t\tfor (var j=0; j < list.length; j++) {\n\t\t\t\tif(list[j] === item.item[0]) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\n\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\tupdate: function(container, p) {\n\n\t\t\t\t\t// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that\n\t\t\t\t\t// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified\n\t\t\t\t\tif(className && !o.forcePlaceholderSize) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item\n\t\t\t\t\tif(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css(\"paddingTop\")||0, 10) - parseInt(that.currentItem.css(\"paddingBottom\")||0, 10)); }\n\t\t\t\t\tif(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css(\"paddingLeft\")||0, 10) - parseInt(that.currentItem.css(\"paddingRight\")||0, 10)); }\n\t\t\t\t}", "label_name": "CWE-89", "label": 89} -{"code": "function hd(a,b,c,d){var e={m:[\"eine Minute\",\"einer Minute\"],h:[\"eine Stunde\",\"einer Stunde\"],d:[\"ein Tag\",\"einem Tag\"],dd:[a+\" Tage\",a+\" Tagen\"],M:[\"ein Monat\",\"einem Monat\"],MM:[a+\" Monate\",a+\" Monaten\"],y:[\"ein Jahr\",\"einem Jahr\"],yy:[a+\" Jahre\",a+\" Jahren\"]};return b?e[c][0]:e[c][1]}", "label_name": "CWE-89", "label": 89} -{"code": "function Md(a,b,c,d){var e=a+\" \";switch(c){case\"s\":return b||d?\"nekaj sekund\":\"nekaj sekundami\";case\"m\":return b?\"ena minuta\":\"eno minuto\";case\"mm\":return e+=1===a?b?\"minuta\":\"minuto\":2===a?b||d?\"minuti\":\"minutama\":5>a?b||d?\"minute\":\"minutami\":b||d?\"minut\":\"minutami\";case\"h\":return b?\"ena ura\":\"eno uro\";case\"hh\":return e+=1===a?b?\"ura\":\"uro\":2===a?b||d?\"uri\":\"urama\":5>a?b||d?\"ure\":\"urami\":b||d?\"ur\":\"urami\";case\"d\":return b||d?\"en dan\":\"enim dnem\";case\"dd\":return e+=1===a?b||d?\"dan\":\"dnem\":2===a?b||d?\"dni\":\"dnevoma\":b||d?\"dni\":\"dnevi\";case\"M\":return b||d?\"en mesec\":\"enim mesecem\";case\"MM\":return e+=1===a?b||d?\"mesec\":\"mesecem\":2===a?b||d?\"meseca\":\"mesecema\":5>a?b||d?\"mesece\":\"meseci\":b||d?\"mesecev\":\"meseci\";case\"y\":return b||d?\"eno leto\":\"enim letom\";case\"yy\":return e+=1===a?b||d?\"leto\":\"letom\":2===a?b||d?\"leti\":\"letoma\":5>a?b||d?\"leta\":\"leti\":b||d?\"let\":\"leti\"}}function Nd(a){var b=a;return b=-1!==a.indexOf(\"jaj\")?b.slice(0,-3)+\"leS\":-1!==a.indexOf(\"jar\")?b.slice(0,-3)+\"waQ\":-1!==a.indexOf(\"DIS\")?b.slice(0,-3)+\"nem\":b+\" pIq\"}function Od(a){var b=a;return b=-1!==a.indexOf(\"jaj\")?b.slice(0,-3)+\"Hu\u2019\":-1!==a.indexOf(\"jar\")?b.slice(0,-3)+\"wen\":-1!==a.indexOf(\"DIS\")?b.slice(0,-3)+\"ben\":b+\" ret\"}function Pd(a,b,c,d){var e=Qd(a);switch(c){case\"mm\":return e+\" tup\";case\"hh\":return e+\" rep\";case\"dd\":return e+\" jaj\";case\"MM\":return e+\" jar\";case\"yy\":return e+\" DIS\"}}function Qd(a){var b=Math.floor(a%1e3/100),c=Math.floor(a%100/10),d=a%10,e=\"\";return b>0&&(e+=Sg[b]+\"vatlh\"),c>0&&(e+=(\"\"!==e?\" \":\"\")+Sg[c]+\"maH\"),d>0&&(e+=(\"\"!==e?\" \":\"\")+Sg[d]),\"\"===e?\"pagh\":e}function Rd(a,b,c,d){var e={s:[\"viensas secunds\",\"'iensas secunds\"],m:[\"'n m\u00edut\",\"'iens m\u00edut\"],mm:[a+\" m\u00eduts\",\"\"+a+\" m\u00eduts\"],h:[\"'n \u00feora\",\"'iensa \u00feora\"],hh:[a+\" \u00feoras\",\"\"+a+\" \u00feoras\"],d:[\"'n ziua\",\"'iensa ziua\"],dd:[a+\" ziuas\",\"\"+a+\" ziuas\"],M:[\"'n mes\",\"'iens mes\"],MM:[a+\" mesen\",\"\"+a+\" mesen\"],y:[\"'n ar\",\"'iens ar\"],yy:[a+\" ars\",\"\"+a+\" ars\"]};return d?e[c][0]:b?e[c][0]:e[c][1]}", "label_name": "CWE-89", "label": 89} -{"code": "renderer:\"foundation\"});a.ext.renderer.pageButton.foundation=function(b,j,q,r,g,k){var l=new a.Api(b),s=b.oClasses,h=b.oLanguage.oPaginate,t=b.oLanguage.oAria.paginate||{},e,f,p=function(a,m){var i,n,o,c,j=function(a){a.preventDefault();!d(a.currentTarget).hasClass(\"unavailable\")&&l.page()!=a.data.action&&l.page(a.data.action).draw(\"page\")};i=0;for(n=m.length;i\").css({width:\"100%\",height:10}))).appendTo(\"body\"),d=c.children(),e=d.children();b.barWidth=d[0].offsetWidth-d[0].clientWidth;b.bScrollOversize=100===e[0].offsetWidth&&100!==d[0].clientWidth;b.bScrollbarLeft=1!==Math.round(e.offset().left);b.bBounding=c[0].getBoundingClientRect().width?!0:!1;c.remove()}h.extend(a.oBrowser,m.__browser);a.oScroll.iBarWidth=m.__browser.barWidth}function hb(a,b,c,d,e,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;d!==e;)a.hasOwnProperty(d)&&\n(g=j?b(g,a[d],d,a):a[d],j=!0,d+=f);return g}function Ga(a,b){var c=m.defaults.column,d=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:H.createElement(\"th\"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML:\"\",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.mData:d,idx:d});a.aoColumns.push(c);c=a.aoPreSearchCols;c[d]=h.extend({},m.models.oSearch,c[d]);la(a,d,h(b).data())}function la(a,b,c){var b=a.aoColumns[b],d=a.oClasses,e=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=e.attr(\"width\")||null;var f=", "label_name": "CWE-89", "label": 89} -{"code": "(function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case\"mousedown\":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,\"mousemove mouseup\",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&\"mousemove\":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)/g, '>');\n};", "label_name": "CWE-89", "label": 89} -{"code": "\t\tstart : function(e, ui) {\n\t\t\tvar targets = $.map(ui.helper.data('files')||[], function(h) { return h || null ;}),\n\t\t\tlocked = false,\n\t\t\tcnt, h;\n\t\t\tself.draggingUiHelper = ui.helper;\n\t\t\tcnt = targets.length;\n\t\t\twhile (cnt--) {\n\t\t\t\th = targets[cnt];\n\t\t\t\tif (files[h].locked) {\n\t\t\t\t\tlocked = true;\n\t\t\t\t\tui.helper.data('locked', true);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t!locked && self.trigger('lockfiles', {files : targets});\n\n\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\tthis.upload = function(files) {\n\t\t\treturn this.transport.upload(files, this);\n\t\t}", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\t\t\tfm.trigger('unlockfiles', {files : helper.data('files'), helper: helper});\n\t\t\t\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\tthis.diff = function(incoming, onlydir) {\n\t\tvar raw = {},\n\t\t\tadded = [],\n\t\t\tremoved = [],\n\t\t\tchanged = [],\n\t\t\tisChanged = function(hash) {\n\t\t\t\tvar l = changed.length;\n\n\t\t\t\twhile (l--) {\n\t\t\t\t\tif (changed[l].hash == hash) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t$.each(incoming, function(i, f) {\n\t\t\traw[f.hash] = f;\n\t\t});\n\t\t\t\n\t\t// find removed\n\t\t$.each(files, function(hash, f) {\n\t\t\tif (!onlydir || f.phash === onlydir) {\n\t\t\t\t!raw[hash] && removed.push(hash);\n\t\t\t}\n\t\t});\n\t\t\n\t\t// compare files\n\t\t$.each(raw, function(hash, file) {\n\t\t\tvar origin = files[hash];\n\n\t\t\tif (!origin) {\n\t\t\t\tadded.push(file);\n\t\t\t} else {\n\t\t\t\t$.each(file, function(prop) {\n\t\t\t\t\tif (file[prop] != origin[prop]) {\n\t\t\t\t\t\tchanged.push(file)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\t\n\t\t// parents of removed dirs mark as changed (required for tree correct work)\n\t\t$.each(removed, function(i, hash) {\n\t\t\tvar file = files[hash], \n\t\t\t\tphash = file.phash;\n\n\t\t\tif (phash \n\t\t\t&& file.mime == 'directory' \n\t\t\t&& $.inArray(phash, removed) === -1 \n\t\t\t&& raw[phash] \n\t\t\t&& !isChanged(phash)) {\n\t\t\t\tchanged.push(raw[phash]);\n\t\t\t}\n\t\t});\n\t\t\n\t\treturn {\n\t\t\tadded : added,\n\t\t\tremoved : removed,\n\t\t\tchanged : changed\n\t\t};\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\tthis.exec = function() {\n\t\tif (!this.dialog) {\n\t\t\tcontent.find('#apiver').text(this.fm.api);\n\t\t\tthis.dialog = this.fm.dialog(content, {title : this.title, width : 530, autoOpen : false, destroyOnClose : false});\n\t\t}\n\t\t\n\t\tthis.dialog.elfinderdialog('open').find('.ui-tabs-nav li a:first').click();\n\t};", "label_name": "CWE-89", "label": 89} -{"code": "elFinder.prototype.commands.forward = function() {\n\tthis.alwaysEnabled = true;\n\tthis.updateOnSelect = true;\n\tthis.shortcuts = [{\n\t\tpattern : 'ctrl+right'\n\t}];\n\t\n\tthis.getstate = function() {\n\t\treturn this.fm.history.canForward() ? 0 : -1;\n\t}\n\t\n\tthis.exec = function() {\n\t\treturn this.fm.history.forward();\n\t}\n\t\n}", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\tcancel = function() {\n\t\t\t\t\tvar close = function(){\n\t\t\t\t\t\tdfrd.reject();\n\t\t\t\t\t\tta.elfinderdialog('close');\n\t\t\t\t\t};\n\t\t\t\t\tta.editor && ta.editor.save(ta[0], ta.editor.instance);\n\t\t\t\t\tif (rtrim(old) !== rtrim(ta.val())) {\n\t\t\t\t\t\told = ta.val();\n\t\t\t\t\t\tfm.confirm({\n\t\t\t\t\t\t\ttitle : self.title,\n\t\t\t\t\t\t\ttext : 'confirmNotSave',\n\t\t\t\t\t\t\taccept : {\n\t\t\t\t\t\t\t\tlabel : 'btnSaveClose',\n\t\t\t\t\t\t\t\tcallback : function() {\n\t\t\t\t\t\t\t\t\tsave();\n\t\t\t\t\t\t\t\t\tclose();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcancel : {\n\t\t\t\t\t\t\t\tlabel : 'btnClose',\n\t\t\t\t\t\t\t\tcallback : close\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclose();\n\t\t\t\t\t}\n\t\t\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\t\t\t\ttop : parseInt(nav.scrollTop())+'px',\n\t\t\t\t\t\t\tleft : ltr ? 'auto' : parseInt(nav.scrollLeft() + offset),\n\t\t\t\t\t\t\tright: ltr ? parseInt(nav.scrollLeft() - offset) * -1 : 'auto'\n\t\t\t\t\t\t});", "label_name": "CWE-89", "label": 89} -{"code": "\t\tthis.trigger('resize', {width : node.width(), height : node.height()});\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\t\t\t\tleft : parseInt($(window).scrollLeft())+'px',\n\t\t\t\t\t\t\ttop : parseInt($(window).scrollTop()) +'px'\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\t.bind(self.resize, function(e) {\n\t\t\t\t\t\tself.preview.trigger('changesize');\n\t\t\t\t\t})\n\t\t\t\t\t.trigger(scroll)\n\t\t\t\t\t.trigger(self.resize);\n\t\t\t\t\t\n\t\t\t\t\twin.bind('mousemove', function(e) {\n\t\t\t\t\t\tnavbar.stop(true, true).show().delay(3000).fadeOut('slow');\n\t\t\t\t\t})\n\t\t\t\t\t.mousemove();\n\t\t\t\t\t\n\t\t\t\t\tnavbar.mouseenter(function() {\n\t\t\t\t\t\tnavbar.stop(true, true).show();\n\t\t\t\t\t})\n\t\t\t\t\t.mousemove(function(e) {\n\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t});\n\t\t\t\t}", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\ttext : fm.i18n('confirmUnmount', drive.name),\n\t\t\t\taccept : {\n\t\t\t\t\tlabel : 'btnUnmount',\n\t\t\t\t\tcallback : function() { \n\t\t\t\t\t\tfm.request({\n\t\t\t\t\t\t\tdata : {cmd : 'netmount', protocol : 'netunmount', host: drive.netkey, user : drive.hash, pass : 'dum'}, \n\t\t\t\t\t\t\tnotify : {type : 'netunmount', cnt : 1, hideCnt : true},\n\t\t\t\t\t\t\tpreventFail : true\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.fail(function(error) {\n\t\t\t\t\t\t\tdfrd.reject(error);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.done(function(data) {\n\t\t\t\t\t\t\tvar chDrive = (fm.root() == drive.hash);\n\t\t\t\t\t\t\tdata.removed = [ drive.hash ];\n\t\t\t\t\t\t\tfm.remove(data);\n\t\t\t\t\t\t\tif (chDrive) {\n\t\t\t\t\t\t\t\tvar files = fm.files();\n\t\t\t\t\t\t\t\tfor (var i in files) {\n\t\t\t\t\t\t\t\t\tif (fm.file(i).mime == 'directory') {\n\t\t\t\t\t\t\t\t\t\tfm.exec('open', i);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcancel : {\n\t\t\t\t\tlabel : 'btnCancel',\n\t\t\t\t\tcallback : function() { dfrd.reject(); }\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\t\n\t\treturn dfrd;\n\t};", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\tdoScan = function(items, isEntry) {\n\t\t\t\t\tvar dirReader, entry;\n\t\t\t\t\tentries = [];\n\t\t\t\t\tvar length = items.length;\n\t\t\t\t\tfor (var i = 0; i < length; i++) {\n\t\t\t\t\t\tif (! isEntry) {\n\t\t\t\t\t\t\tentry = !!items[i].getAsEntry? items[i].getAsEntry() : items[i].webkitGetAsEntry();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tentry = items[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (entry) {\n\t\t\t\t\t\t\tif (entry.isFile) {\n\t\t\t\t\t\t\t\tprocessing++;\n\t\t\t\t\t\t\t\tentry.file(function (file) {\n\t\t\t\t\t\t\t\t\tpaths.push('');\n\t\t\t\t\t\t\t\t\tfiles.push(file);\n\t\t\t\t\t\t\t\t\tprocessing--;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else if (entry.isDirectory) {\n\t\t\t\t\t\t\t\tif (fm.api >= 2.1) {\n\t\t\t\t\t\t\t\t\tif (processing > 0) {\n\t\t\t\t\t\t\t\t\t\tdirctorys.push(entry);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tprocessing = 0;\n\t\t\t\t\t\t\t\t\t\tdirReader = entry.createReader();\n\t\t\t\t\t\t\t\t\t\tprocessing++;\n\t\t\t\t\t\t\t\t\t\treadEntries(dirReader);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\tadd = function(files) {\n\t\t\t\tvar place = list ? cwd.find('tbody') : cwd,\n\t\t\t\t\tl = files.length, \n\t\t\t\t\tltmb = [],\n\t\t\t\t\tatmb = {},\n\t\t\t\t\tdirs = false,\n\t\t\t\t\tfindNode = function(file) {\n\t\t\t\t\t\tvar pointer = cwd.find('[id]:first'), file2;\n\n\t\t\t\t\t\twhile (pointer.length) {\n\t\t\t\t\t\t\tfile2 = fm.file(fm.cwdId2Hash(pointer.attr('id')));\n\t\t\t\t\t\t\tif (!pointer.hasClass('elfinder-cwd-parent') && file2 && fm.compare(file, file2) < 0) {\n\t\t\t\t\t\t\t\treturn pointer;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpointer = pointer.next('[id]');\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tfindIndex = function(file) {\n\t\t\t\t\t\tvar l = buffer.length, i;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (i =0; i < l; i++) {\n\t\t\t\t\t\t\tif (fm.compare(file, buffer[i]) < 0) {\n\t\t\t\t\t\t\t\treturn i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn l || -1;\n\t\t\t\t\t},\n\t\t\t\t\tfile, hash, node, ndx;\n\n\t\t\t\tl && wrapper.removeClass('elfinder-cwd-wrapper-empty');\n\t\t\t\t\n\t\t\t\twhile (l--) {\n\t\t\t\t\tfile = files[l];\n\t\t\t\t\thash = file.hash;\n\t\t\t\t\t\n\t\t\t\t\tif ($('#'+fm.cwdHash2Id(hash)).length) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ((node = findNode(file)) && node.length) {\n\t\t\t\t\t\tnode.before(itemhtml(file)); \n\t\t\t\t\t} else if ((ndx = findIndex(file)) >= 0) {\n\t\t\t\t\t\tbuffer.splice(ndx, 0, file);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tplace.append(itemhtml(file));\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ($('#'+fm.cwdHash2Id(hash)).length) {\n\t\t\t\t\t\tif (file.mime == 'directory') {\n\t\t\t\t\t\t\tdirs = true;\n\t\t\t\t\t\t} else if (file.tmb) {\n\t\t\t\t\t\t\tfile.tmb === 1 ? ltmb.push(hash) : (atmb[hash] = file.tmb);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbottomMarkerShow(place);\n\t\t\t\tattachThumbnails(atmb);\n\t\t\t\tltmb.length && loadThumbnails(ltmb);\n\t\t\t\tdirs && !mobile && makeDroppable();\n\t\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\tupdateDroppable = function(target) {\n\t\t\t\tvar limit = 100,\n\t\t\t\t\tnext;\n\t\t\t\t\n\t\t\t\tif (!target) {\n\t\t\t\t\ttree.find('div.'+uploadable).find(selNavdir+':not(.elfinder-ro,.elfinder-na)').addClass('native-droppable');\n\t\t\t\t\ttarget = tree.find('div.'+pastable).find(selNavdir+':not(.'+droppable+',.elfinder-ro,.elfinder-na)');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (target.length > limit) {\n\t\t\t\t\tnext = target.slice(limit);\n\t\t\t\t\ttarget = target.slice(0, limit);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttarget.droppable(droppableopts);\n\t\t\t\t\n\t\t\t\tif (next) {\n\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\tupdateDroppable(next);\n\t\t\t\t\t}, 20);\n\t\t\t\t}\n\t\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\tsetstat = function(files, cwd) {\n\t\t\t\tvar c = 0, \n\t\t\t\t\ts = 0;\n\n\t\t\t\t$.each(files, function(i, file) {\n\t\t\t\t\tif (!cwd || file.phash == cwd) {\n\t\t\t\t\t\tc++;\n\t\t\t\t\t\ts += parseInt(file.size)||0;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tsize.html(titleitems+': '+c+', '+titlesize+': '+fm.formatSize(s));\n\t\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\t\tmulti = function(files, num){\n\t\t\t\t\tvar sfiles = [], cid;\n\t\t\t\t\tif (!abort) {\n\t\t\t\t\t\twhile(files.length && sfiles.length < num) {\n\t\t\t\t\t\t\tsfiles.push(files.shift());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (sfiles.length) {\n\t\t\t\t\t\t\tfor (var i=0; i < sfiles.length; i++) {\n\t\t\t\t\t\t\t\tif (abort) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcid = isDataType? (sfiles[i][0][0]._cid || null) : (sfiles[i][0]._cid || null);\n\t\t\t\t\t\t\t\tif (!!failChunk[cid]) {\n\t\t\t\t\t\t\t\t\tlast--;\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfm.exec('upload', {\n\t\t\t\t\t\t\t\t\ttype: data.type,\n\t\t\t\t\t\t\t\t\tisDataType: isDataType,\n\t\t\t\t\t\t\t\t\tfiles: sfiles[i],\n\t\t\t\t\t\t\t\t\tchecked: true,\n\t\t\t\t\t\t\t\t\ttarget: target,\n\t\t\t\t\t\t\t\t\trenames: renames,\n\t\t\t\t\t\t\t\t\thashes: hashes,\n\t\t\t\t\t\t\t\t\tmultiupload: true})\n\t\t\t\t\t\t\t\t.fail(function(error) {\n\t\t\t\t\t\t\t\t\tif (cid) {\t\n\t\t\t\t\t\t\t\t\t\tfailChunk[cid] = true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.always(function(e) {\n\t\t\t\t\t\t\t\t\tif (e && e.added) added = $.merge(added, e.added);\n\t\t\t\t\t\t\t\t\tif (last <= ++done) {\n\t\t\t\t\t\t\t\t\t\tfm.trigger('multiupload', {added: added});\n\t\t\t\t\t\t\t\t\t\tnotifyto && clearTimeout(notifyto);\n\t\t\t\t\t\t\t\t\t\tif (checkNotify()) {\n\t\t\t\t\t\t\t\t\t\t\tself.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tmulti(files, 1); // Next one\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (sfiles.length < 1 || abort) {\n\t\t\t\t\t\tif (abort) {\n\t\t\t\t\t\t\tnotifyto && clearTimeout(notifyto);\n\t\t\t\t\t\t\tif (cid) {\n\t\t\t\t\t\t\t\tfailChunk[cid] = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdfrd.reject();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t\tself.uploads.xhrUploading = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\tshortcuts = function() {\n\t\t\tvar sh = fm.shortcuts();\n\t\t\t// shortcuts tab\n\t\t\thtml.push('
    ');\n\t\t\t\n\t\t\tif (sh.length) {\n\t\t\t\thtml.push('
    ');\n\t\t\t\t$.each(sh, function(i, s) {\n\t\t\t\t\thtml.push(stpl.replace(/\\{pattern\\}/, s[0]).replace(/\\{descrip\\}/, s[1]));\n\t\t\t\t});\n\t\t\t\n\t\t\t\thtml.push('
    ');\n\t\t\t} else {\n\t\t\t\thtml.push('
    '+fm.i18n('shortcutsof')+'
    ');\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\thtml.push('
    ');\n\t\t\t\n\t\t},", "label_name": "CWE-89", "label": 89} -{"code": "\t\t\treturn {changed : [this.normalizeFile(data.target, phash)]};\n\t\t}\n\t\t\n\t\tphash = data.cwd.hash;\n\t\t\n\t\tif (data.tree) {\n\t\t\t$.each(this.normalizeTree(data.tree), function(i, file) {\n\t\t\t\tfiles[file.hash] = file;\n\t\t\t});\n\t\t}\n\t\t\n\t\t$.each(data.cdc||[], function(i, file) {\n\t\t\tvar hash = file.hash;\n\n\t\t\tif (files[hash]) {\n\t\t\t\tfiles[hash].date = file.date;\n\t\t\t\tfiles[hash].locked = file.hash == phash ? true : file.rm === void(0) ? false : !file.rm;\n\t\t\t} else {\n\t\t\t\tfiles[hash] = self.normalizeFile(file, phash, data.tmb);\n\t\t\t}\n\t\t});\n\t\t\n\t\tif (!data.tree) {\n\t\t\t$.each(this.fm.files(), function(hash, file) {\n\t\t\t\tif (!files[hash] && file.phash != phash && file.mime == 'directory') {\n\t\t\t\t\tfiles[hash] = file;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\n\t\tif (cmd == 'open') {\n\t\t\treturn {\n\t\t\t\t\tcwd : files[phash] || this.normalizeFile(data.cwd),\n\t\t\t\t\tfiles : $.map(files, function(f) { return f }),\n\t\t\t\t\toptions : self.normalizeOptions(data),\n\t\t\t\t\tinit : !!data.params,\n\t\t\t\t\tdebug : data.debug\n\t\t\t\t};\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\treturn $.extend({\n\t\t\tcurrent : data.cwd.hash,\n\t\t\terror : data.error,\n\t\t\twarning : data.warning,\n\t\t\toptions : {tmb : !!data.tmb}\n\t\t}, this.fm.diff($.map(files, filter)));\n\t\t\n\t}", "label_name": "CWE-89", "label": 89} -{"code": "pimcore.helpers.grid.getTranslationColumnRenderer = function (value, metaData, record, rowIndex, colIndex, store) {\n return t(value);\n};", "label_name": "CWE-79", "label": 79} -{"code": "window.ocJSON=function(json){var jsonString=parse(json);return JSON.parse(jsonString);};}(window);", "label_name": "CWE-79", "label": 79} -{"code": "function uploadSizeError( up, file, over100mb ) {\n\tvar message;\n\n\tif ( over100mb )\n\t\tmessage = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '').replace('%2$s', '');\n\telse\n\t\tmessage = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);\n\n\tjQuery('#media-items').append('

    ' + message + '

    ');\n\tup.removeFile(file);\n}", "label_name": "CWE-79", "label": 79} -{"code": "\t\tsuccess:function (data, textStatus) {\n\t\t\tupdateIndex(context_id, context);\n\t\t\thandleGenericAjaxResponse(data);\n\t\t},", "label_name": "CWE-79", "label": 79} -{"code": "\t\tbeforeSend: function (XMLHttpRequest) {\n\t\t\t$(\".loading\").show();\n\t\t},", "label_name": "CWE-79", "label": 79} -{"code": "\t__uuidv4() {\n\t\treturn 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n\t\t\tvar r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n\t\t\treturn v.toString(16);\n\t\t});\n\t}", "label_name": "CWE-79", "label": 79} -{"code": " var policy = function (tagName, attribs) {\n if (!(html4.ELEMENTS[tagName] & html4.eflags.UNSAFE)) {\n return {\n 'attribs': sanitizeAttribs(tagName, attribs,\n noop, noop, record_messages)\n };\n } else {\n record_messages(tagName + \" removed\", {\n change: \"removed\",\n tagName: tagName\n });\n }\n };\n \n var sanitized = caja.sanitizeWithPolicy(html, policy);\n \n if (allow_css) {\n // sanitize style tags as stylesheets\n sanitized = sanitize_stylesheets(sanitized, policy);\n }\n \n return sanitized;\n };", "label_name": "CWE-79", "label": 79} -{"code": "LdapAuth.prototype._findUser = function (username, callback) {\n var self = this;\n if (!username) {\n return callback(\"empty username\");\n }\n\n var searchFilter = self.opts.searchFilter.replace(/{{username}}/g, username);\n var opts = {filter: searchFilter, scope: self.opts.searchScope};\n if (self.opts.searchAttributes) {\n opts.attributes = self.opts.searchAttributes;\n }\n\n self._search(self.opts.searchBase, opts, function (err, result) {\n if (err) {\n self.log && self.log.trace('ldap authenticate: user search error: %s %s %s', err.code, err.name, err.message);\n return callback(err);\n }\n\n switch (result.length) {\n case 0:\n return callback();\n case 1:\n return callback(null, result[0])\n default:\n return callback(format(\n 'unexpected number of matches (%s) for \"%s\" username',\n result.length, username));\n }\n });\n};", "label_name": "CWE-90", "label": 90} -{"code": "Note.renderNote = function(note) {\n if (!note) {\n return;\n }\n // title\n $(\"#noteTitle\").val(note.Title);\n\n // \u5f53\u524d\u6b63\u5728\u7f16\u8f91\u7684\n // tags\n Tag.input.setTags(note.Tags);\n};", "label_name": "CWE-79", "label": 79} -{"code": " function parseAssignment () {\n var name, args, value, valid;\n\n var node = parseConditional();\n\n if (token == '=') {\n if (type.isSymbolNode(node)) {\n // parse a variable assignment like 'a = 2/3'\n name = node.name;\n getTokenSkipNewline();\n value = parseAssignment();\n return new AssignmentNode(new SymbolNode(name), value);\n }\n else if (type.isAccessorNode(node)) {\n // parse a matrix subset assignment like 'A[1,2] = 4'\n getTokenSkipNewline();\n value = parseAssignment();\n return new AssignmentNode(node.object, node.index, value);\n }\n else if (type.isFunctionNode(node)) {\n // parse function assignment like 'f(x) = x^2'\n valid = true;\n args = [];\n\n name = node.name;\n node.args.forEach(function (arg, index) {\n if (type.isSymbolNode(arg)) {\n args[index] = arg.name;\n }\n else {\n valid = false;\n }\n });\n\n if (valid) {\n getTokenSkipNewline();\n value = parseAssignment();\n return new FunctionAssignmentNode(name, args, value);\n }\n }\n\n throw createSyntaxError('Invalid left hand side of assignment operator =');\n }\n\n return node;\n }", "label_name": "CWE-94", "label": 94} -{"code": " text: Ext.util.Format.htmlEncode(record.get('name')),\n qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),\n leaf: false,\n cls: 'felamimail-node-account',\n delimiter: record.get('delimiter'),\n ns_personal: record.get('ns_personal'),\n account_id: record.data.id,\n listeners: {\n scope: this,\n load: function(node) {\n var account = this.accountStore.getById(node.id);\n this.updateAccountStatus(account);\n }\n }\n });", "label_name": "CWE-79", "label": 79} -{"code": " qtip: Tine.Tinebase.common.doubleEncode(attr.name.name)\n });\n }\n \n // copy 'real' data to a node record NOTE: not a full record as we have no record reader here\n var nodeData = Ext.copyTo({}, attr, Tine.Filemanager.Model.Node.getFieldNames());\n attr.nodeRecord = new Tine.Filemanager.Model.Node(nodeData);\n },", "label_name": "CWE-79", "label": 79} -{"code": " text : Ext.util.Format.htmlEncode(this.app.i18n._hidden(attr.name)),\n qtip : Tine.Tinebase.common.doubleEncode(attr.description ? this.app.i18n._hidden(attr.description) + ' ' + addText : addText),\n selected : attr.id === this.selectedFilterId,\n id : attr.id,\n\n sorting : attr.sorting,\n draggable : true,\n allowDrop : false,\n\n leaf : attr.leaf === false ? attr.leaf : true,\n cls : 'tinebase-westpanel-node-favorite' + addClass\n });\n }", "label_name": "CWE-79", "label": 79} -{"code": " menuItemTemplate: function (item) {\n return `${item.string}`;\n },", "label_name": "CWE-79", "label": 79} -{"code": " $scope.save = function() {\n var form = this.fsForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(\n function() { // success\n growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.addRequisition = function() {\n bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {\n if (foreignSource) {\n RequisitionsService.addRequisition(foreignSource).then(\n function() { // success\n RequisitionsService.synchronizeRequisition(foreignSource, false).then(\n function() {\n growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');\n $scope.foreignSources.push(foreignSource);\n },\n $scope.errorHandler\n );\n },\n $scope.errorHandler\n );\n } else {\n window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?\n }\n });\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.add = function() {\n bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {\n if (foreignSource) {\n // Validate Requisition\n if (foreignSource.match(/[/\\\\?:&*'\"]/)) {\n bootbox.alert('Cannot add the requisition ' + foreignSource + ' because the following characters are invalid:
    :, /, \\\\, ?, &, *, \\', \"');\n return;\n }\n var r = $scope.requisitionsData.getRequisition(foreignSource);\n if (r) {\n bootbox.alert('Cannot add the requisition ' + foreignSource+ ' because there is already a requisition with that name');\n return;\n }\n // Create Requisition\n RequisitionsService.addRequisition(foreignSource).then(\n function(r) { // success\n growl.success('The requisition ' + r.foreignSource + ' has been created.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.clone = function(foreignSource) {\n var availableForeignSources = [];\n angular.forEach($scope.requisitionsData.requisitions, function(r) {\n if (r.foreignSource !== foreignSource) {\n availableForeignSources.push(r.foreignSource);\n }\n });\n var modalInstance = $uibModal.open({\n backdrop: 'static',\n keyboard: false,\n controller: 'CloneForeignSourceController',\n templateUrl: cloneForeignsourceView,\n resolve: {\n foreignSource: function() { return foreignSource; },\n availableForeignSources: function() { return availableForeignSources; }\n }\n });\n modalInstance.result.then(function(targetForeignSource) {\n bootbox.confirm('This action will override the existing foreign source definition for the requisition named ' + targetForeignSource + ', using ' + foreignSource + ' as a template. Are you sure you want to continue ? This cannot be undone.', function(ok) {\n if (!ok) {\n return;\n }\n RequisitionsService.startTiming();\n RequisitionsService.cloneForeignSourceDefinition(foreignSource, targetForeignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + foreignSource + ' has been cloned to ' + targetForeignSource);\n },\n $scope.errorHandler\n );\n });\n });\n };", "label_name": "CWE-79", "label": 79} -{"code": " synchronize: function(requisition, errorHandler) {\n /**\n * @param {object} requisition The requisition object\n * @param {string} rescanExisting true to perform a full scan, false to only add/remove nodes without scan, dbonly for all DB operations without scan\n */\n var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };\n bootbox.prompt({\n title: 'Synchronize Requisition ' + requisition.foreignSource,\n message: '

    Choose a scan option:

    ',\n inputType: 'radio',\n inputOptions: [\n {\n text: 'Scan all nodes',\n value: 'true',\n },\n {\n text: 'Scan added nodes only',\n value: 'false',\n },\n {\n text: 'No scanning',\n value: 'dbonly',\n }\n ],\n buttons: {\n confirm: {\n label: 'Synchronize',\n },\n cancel: {\n label: 'Cancel',\n }\n },\n swapButtonOrder: 'true',\n callback: function (result) {\n if (result !== null) {\n doSynchronize(requisition, result);\n }\n }\n });\n }", "label_name": "CWE-79", "label": 79} -{"code": " $scope.reset = function() {\n bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');\n $scope.initialize();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.refresh = function() {\n growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(\n function(node) { // success\n $scope.node = node;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.save = function() {\n var form = this.nodeForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveNode($scope.node).then(\n function() { // success\n growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.');\n $scope.foreignId = $scope.node.foreignId;\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.provision = function() {\n $scope.isSaving = true;\n growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));\n var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);\n RequisitionsService.quickAddNode($scope.node).then(\n function() { // success\n $scope.reset();\n bootbox.dialog({\n message: successMessage,\n title: 'Success',\n buttons: {\n main: {\n label: 'Ok',\n className: 'btn-secondary'\n }\n }\n });\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 79} -{"code": " $scope.deleteNode = function(node) {\n bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteNode(node).then(\n function() { // success\n var index = -1;\n for(var i = 0; i < $scope.filteredNodes.length; i++) {\n if ($scope.filteredNodes[i].foreignId === node.foreignId) {\n index = i;\n }\n }\n if (index > -1) {\n $scope.filteredNodes.splice(index,1);\n }\n growl.success('The node ' + node.nodeLabel + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-79", "label": 79} -{"code": " var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };", "label_name": "CWE-79", "label": 79} -{"code": "function dialog_form(a,b,c,e,d){\"undefined\"==typeof e&&(e=\"json\");a.submit(function(f){f.preventDefault();a.ajaxSubmit({context:a,dataType:e,beforeSerialize:function(a,b){\"undefined\"!=typeof d&&!1!==d&&d.call(this,a,b)},beforeSend:function(c,d,e){var f=0 \\\"\"+d+'\"\\n';else c=\"===>\"+a+\"<===(\"+typeof a+\")\";return c};(function(a){a.fn.fc_set_tab_list=function(b){var c={toggle_speed:300,fc_list_forms:a(\".fc_list_forms\"),fc_list_add:a(\"#fc_list_add\")};b=a.extend(c,b);return this.each(function(){var c=a(this),d=c.closest(\"ul\").children(\"li\"),f=\"fc_list_\"+c.children(\"input\").val(),g=a(\"#\"+f),h=a(\"#fc_install_new\");b.fc_list_forms.not(\":first\").slideUp(0);0===b.fc_list_add.size()?d.filter(\":first\").addClass(\"fc_active\"):b.fc_list_add.unbind().click(function(){d.removeClass(\"fc_active\");b.fc_list_forms.not(h).slideUp(0);", "label_name": "CWE-79", "label": 79} -{"code": "1;buttonsOpts.push({text:cattranslate(\"Yes\"),click:function(){$.ajax({type:d,context:k,url:c,dataType:f,data:e,cache:!1,beforeSend:function(a){a.process=set_activity(b);$(\".fc_popup\").dialog(\"destroy\").remove();\"undefined\"!=typeof g&&!1!==g&&g.call(this,a)},success:function(a,b,c){!0===a.success||0<$(a).find(\".fc_success_box\").size()?return_success(c.process,a.message):return_error(c.process,a.message);\"undefined\"!=typeof h&&!1!==h&&h.call(this,a)}})},\"class\":\"submit\"});buttonsOpts.push({text:cattranslate(\"No\"),", "label_name": "CWE-79", "label": 79} -{"code": "1;buttonsOpts.push({text:cattranslate(\"Yes\"),click:function(){$.ajax({type:d,context:k,url:c,dataType:f,data:e,cache:!1,beforeSend:function(a){a.process=set_activity(b);$(\".fc_popup\").dialog(\"destroy\").remove();\"undefined\"!=typeof g&&!1!==g&&g.call(this,a)},success:function(a,b,c){!0===a.success||0<$(a).find(\".fc_success_box\").size()?return_success(c.process,a.message):return_error(c.process,a.message);\"undefined\"!=typeof h&&!1!==h&&h.call(this,a)}})},\"class\":\"submit\"});buttonsOpts.push({text:cattranslate(\"No\"),\nclick:function(){$(\".fc_popup\").dialog(\"destroy\")},\"class\":\"reset\"});$(\".fc_popup\").dialog({modal:!0,show:\"fade\",closeOnEscape:!0,title:b,buttons:buttonsOpts})}", "label_name": "CWE-79", "label": 79} -{"code": "function stat(dir, files, cb) {\n var batch = new Batch();\n\n batch.concurrency(10);\n\n files.forEach(function(file, i){\n batch.push(function(done){\n fs.stat(join(dir, file), done);\n });\n });\n\n batch.end(cb);\n}", "label_name": "CWE-79", "label": 79} -{"code": "exports = module.exports = function directory(root, options){\n options = options || {};\n\n // root required\n if (!root) throw new Error('directory() root path required');\n var hidden = options.hidden\n , icons = options.icons\n , view = options.view || 'tiles'\n , filter = options.filter\n , root = normalize(root + sep)\n , template = options.template || defaultTemplate;\n\n return function directory(req, res, next) {\n if ('GET' != req.method && 'HEAD' != req.method) return next();\n\n var url = parse(req.url)\n , dir = decodeURIComponent(url.pathname)\n , path = normalize(join(root, dir))\n , originalUrl = parse(req.originalUrl)\n , originalDir = decodeURIComponent(originalUrl.pathname)\n , showUp = path != root;\n\n // null byte(s), bad request\n if (~path.indexOf('\\0')) return next(utils.error(400));\n\n // malicious path, forbidden\n if (0 != path.indexOf(root)) return next(utils.error(403));\n\n // check if we have a directory\n fs.stat(path, function(err, stat){\n if (err) return 'ENOENT' == err.code\n ? next()\n : next(err);\n\n if (!stat.isDirectory()) return next();\n\n // fetch files\n fs.readdir(path, function(err, files){\n if (err) return next(err);\n if (!hidden) files = removeHidden(files);\n if (filter) files = files.filter(filter);\n files.sort();\n\n // content-negotiation\n var type = new Negotiator(req).preferredMediaType(mediaTypes);\n\n // not acceptable\n if (!type) return next(utils.error(406));\n exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template);\n });\n });\n };\n};", "label_name": "CWE-79", "label": 79} -{"code": "function merge(target, obj) {\n for (var key in obj) {\n if (key === '__proto__' || !hasOwn(obj, key)) {\n continue;\n }\n\n var oldVal = obj[key];\n var newVal = target[key];\n\n if (isObject(newVal) && isObject(oldVal)) {\n target[key] = merge(newVal, oldVal);\n } else if (Array.isArray(newVal)) {\n target[key] = union([], newVal, oldVal);\n } else {\n target[key] = clone(oldVal);\n }\n }\n return target;\n}", "label_name": "CWE-915", "label": 915} -{"code": "function toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !url.host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n result += url.host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}", "label_name": "CWE-639", "label": 639} -{"code": "function main(){\n //Try using pkg-config, but if it fails and it is on Windows, try the fallback\n exec(\"pkg-config \" + opencv + \" \" + flag, function(error, stdout, stderr){\n if(error){\n if(process.platform === \"win32\"){\n fallback();\n }\n else{\n throw new Error(\"ERROR: failed to run: pkg-config\", opencv, flag);\n }\n }\n else{\n console.log(stdout);\n }\n });\n}", "label_name": "CWE-78", "label": 78} -{"code": "function main() {\r\n // adapter.subscribeForeignStates('*');\r\n // adapter.subscribeForeignObjects('*');\r\n\r\n adapter.config.defaultUser = adapter.config.defaultUser || 'admin';\r\n if (!adapter.config.defaultUser.match(/^system\\.user\\./)) {\r\n adapter.config.defaultUser = 'system.user.' + adapter.config.defaultUser;\r\n }\r\n\r\n if (adapter.config.secure) {\r\n // Load certificates\r\n adapter.getCertificates((err, certificates, leConfig) => {\r\n adapter.config.certificates = certificates;\r\n adapter.config.leConfig = leConfig;\r\n\r\n getData(() => webServer = new Web(adapter.config, adapter, initSocket));\r\n });\r\n } else {\r\n getData(() => webServer = new Web(adapter.config, adapter, initSocket));\r\n }\r\n\r\n patchRepos(() => {\r\n // By default update repository every 24 hours\r\n if (adapter.config.autoUpdate === undefined) {\r\n adapter.config.autoUpdate = 24;\r\n }\r\n adapter.config.autoUpdate = parseInt(adapter.config.autoUpdate, 10) || 0;\r\n if (adapter.config.autoUpdate) {\r\n setInterval(() => updateRegister(), adapter.config.autoUpdate * 3600000);\r\n updateRegister();\r\n }\r\n });\r\n}\r", "label_name": "CWE-22", "label": 22} -{"code": " main.unsubscribeStates = function (patterns) {\n if (!patterns) return;\n if (typeof patterns === 'object') {\n for (var s = 0; s < patterns.length; s++) {\n if (main.subscribesStates[patterns[s]]) {\n main.subscribesStates[patterns[s]]--;\n }\n if (main.subscribesStates[patterns[s]] === 0) {\n console.debug('Unsibscribe: ' + patterns[s]);\n main.socket.emit('unsubscribe', patterns[s]);\n delete main.subscribesStates[patterns[s]];\n }\n }\n } else {\n if (main.subscribesStates[patterns]) {\n main.subscribesStates[patterns]--;\n }\n if (main.subscribesStates[patterns] === 0) {\n console.debug('Unsibscribe: ' + patterns);\n main.socket.emit('unsubscribe', patterns);\n delete main.subscribesStates[patterns];\n }\n }\n };", "label_name": "CWE-22", "label": 22} -{"code": " main.getHostIcon = function (obj, classes) {\n var icon = '';\n var alt = '';\n\n if (obj && obj.common && obj.common.icon) {\n var result = getIconHtml(obj);\n icon = result.icon;\n alt = result.alt;\n }\n icon = icon || 'img/no-image.png';\n alt = alt || '';\n\n return '\"'';\n };", "label_name": "CWE-22", "label": 22} -{"code": " _delObject: function (idOrList, callback) {\n var id;\n if (!Array.isArray(idOrList)) {\n if (typeof idOrList !== 'string') return callback && callback('invalid idOrList parameter');\n idOrList = [idOrList];\n }\n\n function doIt() {\n if (idOrList.length === 0) {\n return callback && setTimeout(callback, 0, null, id);\n }\n id = idOrList.pop();\n if (main.objects[id] && main.objects[id].common && (main.objects[id].common['object-non-deletable'] || main.objects[id].common.dontDelete)) {\n main.showMessage (_ ('Cannot delete \"%s\" because not allowed', id), '', 'notifications');\n setTimeout(doIt, 0);\n } else {\n var obj = main.objects[id];\n main.socket.emit('delObject', id, function (err) {\n if (err && err !== 'Not exists') {\n main.showError (err);\n return callback(err);\n }\n if (obj && obj.type === 'state') {\n main.socket.emit ('delState', id, function (err) {\n if (err && err !== 'Not exists') {\n main.showError (err);\n return callback(err);\n }\n setTimeout(doIt, 0);\n });\n } else {\n setTimeout(doIt, 0);\n }\n });\n }\n }\n doIt();\n }, ", "label_name": "CWE-22", "label": 22} -{"code": " this.objectChange = function (id, obj) {\n // Update Adapter Table\n if (id.match(/^system\\.adapter\\.[a-zA-Z0-9-_]+$/)) {\n if (obj) {\n if (this.list.indexOf(id) === -1) this.list.push(id);\n } else {\n var j = this.list.indexOf(id);\n if (j !== -1) {\n this.list.splice(j, 1);\n }\n }\n\n if (typeof this.$grid !== 'undefined' && this.$grid[0]._isInited) {\n this.init(true);\n }\n }\n };", "label_name": "CWE-22", "label": 22} -{"code": " this.stateChange = function (id, state) {\n if (id && state) {\n var adapter = id.match(/^system\\.adapter\\.([\\w\\d-]+)\\.upload$/);\n if (adapter) {\n var $adapter = this.$tab.find('.adapter-upload-progress[data-adapter-name=\"' + adapter[1] + '\"]');\n var text = showUploadProgress(state.val);\n $adapter.html(text).css({opacity: state.val ? 0.7 : 0});\n this.$tab.find('.group-upload-progress[data-adapter-group=\"' + $adapter.data('adapter-group') + '\"]').html(text).css({opacity: state.val ? 0.7 : 0});\n }\n }\n };", "label_name": "CWE-22", "label": 22} -{"code": "function sanitizePath(id, name, callback) {\n if (name[0] === '/') name = name.substring(1);\n\n if (!id) {\n if (typeof callback === 'function') {\n callback('Empty ID');\n }\n return;\n }\n\n if (id) {\n id = id.replace(/\\.\\./g, ''); // do not allow to write in parent directories\n }\n\n if (name.indexOf('..') !== -1) {\n name = path.normalize(name);\n name = name.replace(/\\\\/g, '/');\n }\n if (name[0] === '/') name = name.substring(1); // do not allow absolute paths\n\n return {id: id, name: name};\n}", "label_name": "CWE-22", "label": 22} -{"code": "module.exports = function(path, opts, cb) {\n if (!cb) {\n cb = opts;\n opts = {};\n }\n\n var cmd = module.exports.cmd(path, opts);\n opts.timeout = opts.timeout || 5000;\n\n exec(cmd, opts, function(e, stdout, stderr) {\n if (e) { return cb(e); }\n if (stderr) { return cb(new Error(stderr)); }\n\n return cb(null, module.exports.parse(path, stdout, opts));\n });\n};", "label_name": "CWE-78", "label": 78} -{"code": "export function mergeConfig(...configs) {\n return configs.reduce((out, source) => {\n for (var key in source) {\n if (key === 'signals') {\n // for signals, we merge the signals arrays\n // source signals take precedence over\n // existing signals with the same name\n out.signals = mergeNamed(out.signals, source.signals);\n } else {\n // otherwise, merge objects subject to recursion constraints\n // for legend block, recurse for the layout entry only\n // for style block, recurse for all properties\n // otherwise, no recursion: objects overwrite, no merging\n var r = key === 'legend' ? {'layout': 1}\n : key === 'style' ? true\n : null;\n writeConfig(out, key, source[key], r);\n }\n }\n return out;\n }, {});\n}", "label_name": "CWE-915", "label": 915} -{"code": " setup: function () {\n var data = this.model.get('data');\n\n this.assignedUserId = data.assignedUserId || null;\n this.assignedUserName = data.assignedUserName || null;\n\n this.messageData['assignee'] = '' + data.assignedUserName + '';\n\n if (this.isUserStream) {\n if (this.assignedUserId) {\n if (this.assignedUserId == this.model.get('createdById')) {\n this.messageName += 'Self';\n } else {\n if (this.assignedUserId == this.getUser().id) {\n this.messageName += 'You';\n }\n }\n } else {\n this.messageName += 'Void';\n }\n } else {\n if (this.assignedUserId) {\n if (this.assignedUserId == this.model.get('createdById')) {\n this.messageName += 'Self';\n }\n } else {\n this.messageName += 'Void';\n }\n }\n\n this.createMessage();\n },", "label_name": "CWE-79", "label": 79} -{"code": " emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''\n }, Dep.prototype.data.call(this));\n },\n\n setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + data.emailName + '';\n\n this.messageName = 'emailReceived';\n\n if (data.isInitial) {\n this.messageName += 'Initial';\n }\n\n if (data.personEntityId) {\n this.messageName += 'From';\n this.messageData['from'] = '' + data.personEntityName + '';\n }\n\n if (this.model.get('parentType') === data.personEntityType && this.model.get('parentId') == data.personEntityId) {\n this.isThis = true;\n }\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },\n\n });\n});", "label_name": "CWE-79", "label": 79} -{"code": " setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + data.emailName + '';\n\n this.messageName = 'emailReceived';\n\n if (data.isInitial) {\n this.messageName += 'Initial';\n }\n\n if (data.personEntityId) {\n this.messageName += 'From';\n this.messageData['from'] = '' + data.personEntityName + '';\n }\n\n if (this.model.get('parentType') === data.personEntityType && this.model.get('parentId') == data.personEntityId) {\n this.isThis = true;\n }\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },", "label_name": "CWE-79", "label": 79} -{"code": " emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''\n }, Dep.prototype.data.call(this));\n },\n\n setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + data.emailName + '';\n\n this.messageName = 'emailSent';\n\n this.messageData['by'] = '' + data.personEntityName + '';\n\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },\n\n });\n});", "label_name": "CWE-79", "label": 79} -{"code": " value = value.replace(/src=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });", "label_name": "CWE-79", "label": 79} -{"code": " getItemHtml: function (value) {\n var translatedValue = this.translatedOptions[value] || value;\n\n var html = '' +\n '
    ' +\n '
    ' +\n '' +\n '
    ' +\n '
    ' +\n '' +\n '

    ' +\n '
    ';\n\n return html;\n },", "label_name": "CWE-79", "label": 79} -{"code": "exports.onAccountGetDepositAddress = function(req, res)\n{\n const dataParsed = url.parse(req.url);\n if (!dataParsed || !dataParsed.query || !req.headers['apisign'])\n return onError(req, res, 'Bad request');\n\n const queryStr = querystring.parse(dataParsed.query);\n if (!queryStr.apikey || !queryStr.nonce || !queryStr.currency)\n return onError(req, res, 'Bad request. Required parameter (apikey or nonce or currency) not found.');\n \n utils.GetCoinFromTicker(queryStr.currency, coin => {\n if (!coin || !coin.name) \n return onError(req, res, 'Coin ticker not found');\n\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n \n CheckAPIkey(queryStr.apikey, req.headers['apisign'], fullUrl, ret => {\n try\n {\n if (ret.success == false) throw new Error(ret.message);\n if (ret.key.read == 0) throw new Error('apikey disabled for read');\n \n wallet.GetAccountAddress(ret.key.userid, coin.name, ret => {\n if (ret.result != 'success' || !ret.data) \n return onError(req, res, ret.message);\n\n onSuccess(req, res, {Currency: coin.ticker, Address: ret.data});\n });\n }\n catch(e) {\n return onError(req, res, e.message);\n }\n })\n }); \n}", "label_name": "CWE-89", "label": 89} -{"code": " parsePath (rawPath, opts = {}) {\n let pathObj = {\n locale: WIKI.config.lang.code,\n path: 'home',\n private: false,\n privateNS: '',\n explicitLocale: false\n }\n\n // Clean Path\n rawPath = _.trim(qs.unescape(rawPath))\n if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }\n if (rawPath === '') { rawPath = 'home' }\n\n // Extract Info\n let pathParts = _.filter(_.split(rawPath, '/'), p => !_.isEmpty(p))\n if (pathParts[0].length === 1) {\n pathParts.shift()\n }\n if (localeSegmentRegex.test(pathParts[0])) {\n pathObj.locale = pathParts[0]\n pathObj.explicitLocale = true\n pathParts.shift()\n }\n\n // Strip extension\n if (opts.stripExt && pathParts.length > 0) {\n const lastPart = _.last(pathParts)\n if (lastPart.indexOf('.') > 0) {\n pathParts.pop()\n const lastPartMeta = path.parse(lastPart)\n pathParts.push(lastPartMeta.name)\n }\n }\n\n pathObj.path = _.join(pathParts, '/')\n return pathObj\n },", "label_name": "CWE-22", "label": 22} -{"code": "function usercheck_init_mod(i, opt) {\r\n var obj = document.getElementById('ajax_output_' + opt);\r\n obj.innerHTML = '';\r\n\r\n if (i.value.length < 1)\r\n return;\r\n\r\n var err = new Array();\r\n if (i.value.match(/[^A-Za-z0-9_]/))\r\n err[err.length] = 'Username can only contain letters, numbers and underscores';\r\n if (i.value.length < 3)\r\n err[err.length] = 'Username Too Short';\r\n if (err != '') {\r\n obj.style.color = '#ff0000';\r\n obj.innerHTML = err.join('
    ');\r\n return;\r\n }\r\n\r\n var pqr = i.value;\r\n\r\n if (opt == '1')\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_p, usercheck_error);\r\n\r\n if (opt == '2')\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_s, usercheck_error);\r\n}\r", "label_name": "CWE-22", "label": 22} -{"code": " reply: () => Promise.resolve()\n };\n const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);\n\n beforeEach(() => {\n sandbox = sinon.sandbox.create().usingPromise(Promise);\n\n sandbox.spy(mockClient, 'reply');\n sandbox.stub(ActiveConnector.prototype, 'setupConnection').resolves();\n });\n afterEach(() => {\n sandbox.restore();\n });\n\n it('// unsuccessful | no argument', () => {\n return cmdFn()\n .then(() => {\n expect(mockClient.reply.args[0][0]).to.equal(504);\n });\n });\n\n it('// unsuccessful | invalid argument', () => {\n return cmdFn({command: {arg: 'blah'}})\n .then(() => {\n expect(mockClient.reply.args[0][0]).to.equal(504);\n });\n });\n\n it('// successful IPv4', () => {\n return cmdFn({command: {arg: '|1|192.168.0.100|35286|'}})\n .then(() => {\n const [ip, port, family] = ActiveConnector.prototype.setupConnection.args[0];\n expect(mockClient.reply.args[0][0]).to.equal(200);\n expect(ip).to.equal('192.168.0.100');\n expect(port).to.equal('35286');\n expect(family).to.equal(4);\n });\n });\n\n it('// successful IPv6', () => {\n return cmdFn({command: {arg: '|2|8536:933f:e7f3:3e91:6dc1:e8c6:8482:7b23|35286|'}})\n .then(() => {\n const [ip, port, family] = ActiveConnector.prototype.setupConnection.args[0];\n expect(mockClient.reply.args[0][0]).to.equal(200);\n expect(ip).to.equal('8536:933f:e7f3:3e91:6dc1:e8c6:8482:7b23');\n expect(port).to.equal('35286');\n expect(family).to.equal(6);\n });\n });\n});", "label_name": "CWE-918", "label": 918} -{"code": "ServerStderr.prototype._write = function(data, encoding, cb) {\n var channel = this._channel;\n var sshstream = channel._client._sshstream;\n var outgoing = channel.outgoing;\n var packetSize = outgoing.packetSize;\n var id = outgoing.id;\n var window = outgoing.window;\n var len = data.length;\n var p = 0;\n var ret;\n var buf;\n var sliceLen;\n\n if (channel.outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n ret = sshstream.channelExtData(id, data.slice(p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n\n if (!ret) {\n channel._waitClientDrain = true;\n channel._chunkErr = undefined;\n channel._chunkcbErr = cb;\n break;\n }\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0) {\n // partial\n buf = Buffer.allocUnsafe(len - p);\n data.copy(buf, 0, p);\n channel._chunkErr = buf;\n } else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n if (!channel._waitClientDrain)\n cb();\n};", "label_name": "CWE-78", "label": 78} -{"code": " function onFinish() {\n self.eof();\n if (server || (!server && !self.allowHalfOpen))\n self.close();\n self.writable = false;\n }", "label_name": "CWE-78", "label": 78} -{"code": " function onError(err) {\n sftp.removeListener('ready', onReady);\n stream.removeListener('exit', onExit);\n cb(err);\n }", "label_name": "CWE-78", "label": 78} -{"code": " function reqCb(err) {\n if (err) {\n chan.close();\n return cb(err);\n }\n if (todo.length)\n todo.shift()();\n }", "label_name": "CWE-78", "label": 78} -{"code": " this._cbfinal = function(allowed, methodsLeft, isPartial) {\n if (!self._finalResponse) {\n self._finalResponse = true;\n cb(self, allowed, methodsLeft, isPartial);\n }\n };", "label_name": "CWE-78", "label": 78} -{"code": " function setReply(type, buf) {\n reply.type = type;\n reply.buf = buf;\n sendReplies();\n }", "label_name": "CWE-78", "label": 78} -{"code": "Server.createServer = function(cfg, listener) {\n return new Server(cfg, listener);\n};", "label_name": "CWE-78", "label": 78} -{"code": "AuthContext.prototype.accept = function() {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(true);\n};", "label_name": "CWE-78", "label": 78} -{"code": " { run: function() {\n var client;\n var server;\n var r;\n\n r = setup(\n this,\n { username: USER,\n privateKey: CLIENT_KEY_RSA_RAW\n },\n { hostKeys: [HOST_KEY_RSA] }\n );\n client = r.client;\n server = r.server;\n\n server.on('connection', function(conn) {\n conn.on('authentication', function(ctx) {\n if (ctx.method === 'none')\n return ctx.reject();\n assert(ctx.method === 'publickey',\n makeMsg('Unexpected auth method: ' + ctx.method));\n assert(ctx.username === USER,\n makeMsg('Unexpected username: ' + ctx.username));\n assert(ctx.key.algo === 'ssh-rsa',\n makeMsg('Unexpected key algo: ' + ctx.key.algo));\n assert.deepEqual(CLIENT_KEY_RSA.getPublicSSH(),\n ctx.key.data,\n makeMsg('Public key mismatch'));\n if (ctx.signature) {\n assert(CLIENT_KEY_RSA.verify(ctx.blob, ctx.signature) === true,\n makeMsg('Could not verify PK signature'));\n ctx.accept();\n } else\n ctx.accept();\n }).on('ready', function() {\n conn.end();\n });\n });\n },", "label_name": "CWE-78", "label": 78} -{"code": "function next() {\n if (Array.isArray(process._events.exit))\n process._events.exit = process._events.exit[1];\n if (++t === tests.length)\n return;\n\n var v = tests[t];\n v.run.call(v);\n}", "label_name": "CWE-78", "label": 78} -{"code": " sock: new net.Socket()\n },\n { hostKeys: [HOST_KEY_RSA] }\n );\n client = r.client;\n server = r.server;\n\n server.on('connection', function(conn) {\n conn.on('authentication', function(ctx) {\n ctx.accept();\n }).on('ready', function() {});\n });\n client.on('ready', function() {\n client.end();\n });\n },", "label_name": "CWE-78", "label": 78} -{"code": " clientcfg.debug = function() {\n var args = new Array(arguments.length + 1);\n args[0] = '[CLIENT]';\n for (var i = 0; i < arguments.length; ++i)\n args[i + 1] = arguments[i];\n console.log.apply(null, args);\n };", "label_name": "CWE-78", "label": 78} -{"code": " function onError(err) {\n var which = (arguments.length >= 3 ? 'client' : 'server');\n assert(false, makeMsg(self.what, 'Unexpected ' + which + ' error: ' + err));\n }", "label_name": "CWE-78", "label": 78} -{"code": "function cleanup() {\n\tclean('.');\n\tclean('async-execute');\n}", "label_name": "CWE-78", "label": 78} -{"code": "module.exports.commit = function (files, message, newVer, tagName, callback) {\n message = escapeQuotes(message.replace(\"%s\", newVer));\n files = files.map(escapeQuotes).join(\" \");\n var functionSeries = [\n function (done) {\n cp.exec(gitApp + \" add \" + files, gitExtra, done);\n },\n\n function (done) {\n cp.exec([gitApp, \"commit\", \"-m\", message].join(\" \"), gitExtra, done);\n },\n\n function (done) {\n cp.exec(\n [gitApp, \"tag\", \"-a\", tagName, \"-m\", message].join(\" \"),\n gitExtra,\n done\n );\n },\n ];\n contra.series(functionSeries, callback);\n};", "label_name": "CWE-78", "label": 78} -{"code": " function parsePaste()\n {\n // skip parsing if no text is given\n if (text === '') {\n return;\n }\n\n if (format === 'markdown') {\n const converter = new showdown.Converter({\n strikethrough: true,\n tables: true,\n tablesHeaderId: true,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true\n });\n // let showdown convert the HTML and sanitize HTML *afterwards*!\n $plainText.html(\n DOMPurify.sanitize(\n converter.makeHtml(text)\n )\n );\n // add table classes from bootstrap css\n $plainText.find('table').addClass('table-condensed table-bordered');\n } else {\n if (format === 'syntaxhighlighting') {\n // yes, this is really needed to initialize the environment\n if (typeof prettyPrint === 'function')\n {\n prettyPrint();\n }\n\n $prettyPrint.html(\n prettyPrintOne(\n Helper.htmlEntities(text), null, true\n )\n );\n } else {\n // = 'plaintext'\n $prettyPrint.text(text);\n }\n Helper.urls2links($prettyPrint);\n $prettyPrint.css('white-space', 'pre-wrap');\n $prettyPrint.css('word-break', 'normal');\n $prettyPrint.removeClass('prettyprint');\n }\n }", "label_name": "CWE-79", "label": 79} -{"code": "pushState:function pushState(condition) {\n this.begin(condition);\n },", "label_name": "CWE-94", "label": 94} -{"code": "!function(a,b){if(a){var c=function(){b(a.lazySizes),a.removeEventListener(\"lazyunveilread\",c,!0)};b=b.bind(null,a,a.document),\"object\"==typeof module&&module.exports?b(require(\"lazysizes\")):a.lazySizes?c():a.addEventListener(\"lazyunveilread\",c,!0)}}(\"undefined\"!=typeof window?window:0,function(a,b,c){\"use strict\";function d(c,d){var e=\"vimeoCallback\"+j,f=b.createElement(\"script\");c+=\"&callback=\"+e,j++,a[e]=function(b){f.parentNode.removeChild(f),delete a[e],d(b)},f.src=c,b.head.appendChild(f)}function e(a,b){d(p.replace(k,a),function(a){a&&a.thumbnail_url&&(b.style.backgroundImage=\"url(\"+a.thumbnail_url+\")\")}),b.addEventListener(\"click\",f)}function f(a){var b=a.currentTarget,c=b.getAttribute(\"data-vimeo\"),d=b.getAttribute(\"data-vimeoparams\")||\"\";d&&!m.test(d)&&(d=\"&\"+d),a.preventDefault(),b.innerHTML='',b.removeEventListener(\"click\",f)}function g(a,b){var d=b.getAttribute(\"data-thumb-size\")||c.cfg.ytThumb||\"hqdefault\";b.style.backgroundImage=\"url(\"+n.replace(k,a).replace(l,d)+\")\",b.addEventListener(\"click\",h)}function h(a){var b=a.currentTarget,c=b.getAttribute(\"data-youtube\"),d=b.getAttribute(\"data-ytparams\")||\"\";d&&!m.test(d)&&(d=\"&\"+d),a.preventDefault(),b.innerHTML='',b.removeEventListener(\"click\",h)}if(b.getElementsByClassName){var i=\"https:\"==location.protocol?\"https:\":\"http:\",j=Date.now(),k=/\\{\\{id}}/,l=/\\{\\{hqdefault}}/,m=/^&/,n=i+\"//img.youtube.com/vi/{{id}}/{{hqdefault}}.jpg\",o=i+\"//www.youtube.com/embed/{{id}}?autoplay=1\",p=i+\"//vimeo.com/api/oembed.json?url=https%3A//vimeo.com/{{id}}\",q=i+\"//player.vimeo.com/video/{{id}}?autoplay=1\";b.addEventListener(\"lazybeforeunveil\",function(a){if(a.detail.instance==c){var b=a.target,d=b.getAttribute(\"data-youtube\"),f=b.getAttribute(\"data-vimeo\");d&&b&&g(d,b),f&&b&&e(f,b)}})}});", "label_name": "CWE-79", "label": 79} -{"code": " replaceInValue: function(value, context) {\n return interpreter.replace(value, context, parseContext);\n }", "label_name": "CWE-915", "label": 915} -{"code": " var digest = function() {\n var updated = false;\n\n entries.forEach(function(e) {\n var interpreter = ConnieLang.firstInnermostInterpreterFromValue(e.value, context);\n if (!interpreter) return;\n\n var newValue = interpreter.replaceInValue(e.value, context);\n if (newValue !== e.value) {\n e.value = newValue;\n updated = true;\n }\n });\n\n return updated;\n };", "label_name": "CWE-915", "label": 915} -{"code": "Cache.prototype.clear = function() {\n this._size = 0\n this._values = Object.create(null)\n}", "label_name": "CWE-915", "label": 915} -{"code": " 'readYAML': function(test) {\n test.expect(4);\n var obj;\n obj = grunt.file.readYAML('test/fixtures/utf8.yaml');\n test.deepEqual(obj, this.object, 'file should be read as utf8 by default and parsed correctly.');\n\n obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml', {encoding: 'iso-8859-1'});\n test.deepEqual(obj, this.object, 'file should be read using the specified encoding.');\n\n test.throws(function() {\n obj = grunt.file.readYAML('test/fixtures/error.yaml');\n }, function(err) {\n return err.message.indexOf('undefined') === -1;\n }, 'error thrown should not contain undefined.');\n\n grunt.file.defaultEncoding = 'iso-8859-1';\n obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml');\n test.deepEqual(obj, this.object, 'changing the default encoding should work.');\n test.done();\n },", "label_name": "CWE-1188", "label": 1188} -{"code": "function createDefaultLogger(levels) {\n let levelMaxLen = 0;\n let levelNames = new Map();\n levels.forEach(level => {\n if (level.length > levelMaxLen) {\n levelMaxLen = level.length;\n }\n });\n\n levels.forEach(level => {\n let levelName = level.toUpperCase();\n if (levelName.length < levelMaxLen) {\n levelName += ' '.repeat(levelMaxLen - levelName.length);\n }\n levelNames.set(level, levelName);\n });\n\n let print = (level, entry, message, ...args) => {\n let prefix = '';\n if (entry) {\n if (entry.tnx === 'server') {\n prefix = 'S: ';\n } else if (entry.tnx === 'client') {\n prefix = 'C: ';\n }\n\n if (entry.sid) {\n prefix = '[' + entry.sid + '] ' + prefix;\n }\n\n if (entry.cid) {\n prefix = '[#' + entry.cid + '] ' + prefix;\n }\n }\n\n message = util.format(message, ...args);\n message.split(/\\r?\\n/).forEach(line => {\n console.log(\n '[%s] %s %s',\n new Date()\n .toISOString()\n .substr(0, 19)\n .replace(/T/, ' '),\n levelNames.get(level),\n prefix + line\n );\n });\n };\n\n let logger = {};\n levels.forEach(level => {\n logger[level] = print.bind(null, level);\n });\n\n return logger;\n}", "label_name": "CWE-88", "label": 88} -{"code": " getSocket(options, callback) {\n let socket = net.connect(PORT_NUMBER, 'localhost');\n let errHandler = function(err) {\n callback(err);\n };\n socket.on('error', errHandler);\n socket.on('connect', function() {\n socket.removeListener('error', errHandler);\n callback(null, {\n connection: socket\n });\n });\n }", "label_name": "CWE-88", "label": 88} -{"code": " getSocket(options, callback) {\n let socket = net.connect(PORT_NUMBER, 'localhost');\n let errHandler = function(err) {\n callback(err);\n };\n socket.on('error', errHandler);\n socket.on('connect', function() {\n socket.removeListener('error', errHandler);\n callback(null, {\n connection: socket\n });\n });\n }", "label_name": "CWE-88", "label": 88} -{"code": "OAuthServer.prototype.validateAccessToken = function(username, accessToken) {\n if (!this.users[username] || this.users[username].accessToken !== accessToken || this.users[username].expiresIn < Date.now()) {\n return false;\n } else {\n return true;\n }\n};", "label_name": "CWE-88", "label": 88} -{"code": "module.exports = function apply(doc, patch) {\n if (typeof patch !== OBJECT || patch === null || Array.isArray(patch)) {\n return patch;\n }\n\n if (typeof doc !== OBJECT || doc === null || Array.isArray(doc)) {\n doc = Object.create(null);\n }\n\n const keys = Object.keys(patch);\n for (const key of keys) {\n const v = patch[key];\n if (v === null) {\n delete doc[key];\n continue;\n }\n doc[key] = apply(doc[key], v);\n }\n\n return doc;\n};", "label_name": "CWE-915", "label": 915} -{"code": "\t\t\tfunction uploadFile(file) {\n\t\t\t\tif (file.size> attachmentMaxSize) {\n\t\t\t\t\tvar message = \"!!Upload should be less than \" + Math.round(attachmentMaxSize/1024/1024) + \" Mb!!\";\n\t\t\t\t\tonedev.server.markdown.updateUploadMessage($input, message);\n\t\t\t\t} else {\n\t\t\t\t\tvar xhr = new XMLHttpRequest();\n\t\t\t\t\tvar val = $input.val();\n\t\t\t\t\tvar i=1;\n\t\t\t\t\tvar message = \"[Uploading file...]\";\n\t\t\t\t\twhile (val.indexOf(message) != -1) {\n\t\t\t\t\t\tmessage = \"[Uploading file\" + (++i) + \"...]\";\n\t\t\t\t\t}\n\n\t\t\t\t\txhr.replaceMessage = message;\n\t\t\t\t\tif ($input.range().length == 0) {\n\t\t\t\t\t\t$input.caret(message);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$input.range(message);\n\t\t\t\t\t\t$input.caret($input.caret()+message.length);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\txhr.onload = function() {\n\t\t\t\t\t\tif (xhr.status == 200) { \n\t\t\t\t\t\t\tcallback(\"insertUrl\", xhr.responseText, xhr.replaceMessage);\n\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\tonedev.server.markdown.updateUploadMessage($input, \n\t\t\t\t\t\t\t\t\t\"!!\" + xhr.responseText + \"!!\", xhr.replaceMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\txhr.onerror = function() {\n\t\t\t\t\t\tonedev.server.markdown.updateUploadMessage($input, \n\t\t\t\t\t\t\t\t\"!!Unable to connect to server!!\", xhr.replaceMessage);\n\t\t\t\t\t};\n\t\t\t\t\txhr.open(\"POST\", \"/attachment_upload\", true);\n\t\t\t\t\txhr.setRequestHeader(\"File-Name\", encodeURIComponent(file.name));\n\t\t\t\t\txhr.setRequestHeader(\"Attachment-Support\", attachmentSupport);\n\t\t\t\t\txhr.send(file);\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-502", "label": 502} -{"code": " var update_selected_labels = function() {\n var count = 0;\n $(\".ui-selected\", div_all_tags).not(\".filtered\").each(function() {\n var $this = $(this);\n if ($this.hasClass('alltags-tagset')) {\n count += $this.nextUntil(\":not(.alltags-childtag)\").not(\n \".filtered, .ui-selected\").length;\n } else {\n count++;\n }\n });\n $(\"#id_tags_selected\").text(count ? count + \" selected\" : \"\");\n var tagset = get_selected_tagset();\n if (tagset) {\n $(\"#id_selected_tag_set\").html(\n \"Add a new tag in \" +\n tagset.text() + \" tag set and select it immediately:\");\n } else {\n $(\"#id_selected_tag_set\").text(\n \"Add a new tag and select it immediately:\");\n }\n };", "label_name": "CWE-79", "label": 79} -{"code": "String.prototype.escapeHTML = function(){\n /*\n HTML Escape Before Inserting Untrusted Data into HTML Element Content\n https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention\n _Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into\n _HTML_Element_Content\n */\n var s = this;\n if (!s) {\n return \"\";\n }\n s = s + \"\";\n return s.replace(/[\\&\"<>\\\\]/g, function(s) {\n switch(s) {\n case \"&\": return \"&\";\n case \"\\\\\": return \"\\";\n case '\"': return '\\\"';\n case \"<\": return \"<\";\n case \">\": return \">\";\n default: return s;\n }\n });\n};", "label_name": "CWE-79", "label": 79} -{"code": "\" \"+d.sSortDesc).addClass(\"asc\"==g[e]?d.sSortAsc:\"desc\"==g[e]?d.sSortDesc:c.sSortingClass),b.find(\"span.\"+d.sSortIcon).removeClass(d.sSortJUIAsc+\" \"+d.sSortJUIDesc+\" \"+d.sSortJUI+\" \"+d.sSortJUIAscAllowed+\" \"+d.sSortJUIDescAllowed).addClass(\"asc\"==g[e]?d.sSortJUIAsc:\"desc\"==g[e]?d.sSortJUIDesc:c.sSortingClassJUI))})}}});var yb=function(a){return\"string\"===typeof a?a.replace(/&/g,\"&\").replace(//g,\">\").replace(/\"/g,\""\"):a};u.render={number:function(a,b,c,d,e){return{display:function(h){if(\"number\"!==\ntypeof h&&\"string\"!==typeof h)return h;var f=0>h?\"-\":\"\",g=parseFloat(h);if(isNaN(g))return yb(h);g=g.toFixed(c);h=Math.abs(g);g=parseInt(h,10);h=c?b+(h-g).toFixed(c).substring(2):\"\";0===g&&0===parseFloat(h)&&(f=\"\");return f+(d||\"\")+g.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g,a)+h+(e||\"\")}}},text:function(){return{display:yb,filter:yb}}};l.extend(u.ext.internal,{_fnExternApiFunc:fc,_fnBuildAjax:Oa,_fnAjaxUpdate:Gb,_fnAjaxParameters:Pb,_fnAjaxUpdateDraw:Qb,_fnAjaxDataSrc:Aa,_fnAddColumn:Xa,_fnColumnOptions:Ga,", "label_name": "CWE-79", "label": 79} -{"code": "\tparse: function (text) {\r\n\t\t// not yet possible as we still return new type() JSON\r\n\t\t//\t\tif (!(!(/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/.test(\r\n\t\t//\t\ttext.replace(/\"(\\\\.|[^\"\\\\])*\"/g, ''))) ))\r\n\t\t//\t\t\tthrow new Error(\"Invalid characters in JSON parse string.\"); \r\n\t\tvar regEx = /(\\\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}.*?\\\")|(\\\"\\\\\\/Date\\(.*?\\)\\\\\\/\")/g;\r\n\t\ttext = text.replace(regEx, this.regExDate);\r\n\t\treturn eval('(' + text + ')');\r\n\t},\r", "label_name": "CWE-502", "label": 502} -{"code": "export function esc(value) {\n\tif (typeof value !== 'string') return value;\n\tlet last=ESCAPE.lastIndex=0, tmp=0, out='';\n\twhile (ESCAPE.test(value)) {\n\t\ttmp = ESCAPE.lastIndex - 1;\n\t\tout += value.substring(last, tmp) + CHARS[value[tmp]];\n\t\tlast = tmp + 1;\n\t}\n\treturn out + value.substring(last);\n}", "label_name": "CWE-79", "label": 79} -{"code": "function formcheck_Timetable_course_F4(this_DET) {\n var this_button_id = this_DET.id;\n\n var frmvalidator = new Validator(\"F4\", this_button_id);\n\n var subject_id = document.getElementById(\"subject_id_div\").value;\n if (subject_id == \"new\") {\n frmvalidator.addValidation(\n \"tables[course_subjects][new][TITLE]\",\n \"req\",\n \"Please enter the subject name\"\n );\n frmvalidator.addValidation(\n \"tables[course_subjects][new][TITLE]\",\n \"maxlen=100\",\n \"Max length for subject is 100 characters\"\n );\n } else {\n frmvalidator.addValidation(\n \"inputtables[course_subjects][\" + subject_id + \"][TITLE]\",\n \"req\",\n \"Please enter the course title \"\n );\n frmvalidator.addValidation(\n \"inputtables[course_subjects][\" + subject_id + \"][TITLE]\",\n \"maxlen=100\",\n \"Max length for course title is 100 characters\"\n );\n }\n}", "label_name": "CWE-22", "label": 22} -{"code": " queue.onData = function(paths, end) {\n var escapedPaths = paths.map(\n function(path) {\n return '\"' + path.replace(/\"/g, '\\\\\"') + '\"';\n }\n );\n var command = 'lsof -F n -- ' + escapedPaths.join(' ');\n var options = {\n encoding: 'utf-8',\n maxBuffer: 2 * 1024 * 1024\n };\n Node.child.exec(command, options,\n function(error, stdout, stderr) {\n // lsof returns an error and a status code of 1 if a file is not open:\n if (error && error.code === 1 && stderr.length === 0) error = undefined;\n if (error) {\n if (/No such file or directory/i.test(stderr)) {\n error.code = 'ENOENT';\n }\n return end(error);\n }\n var lines = stdout.split('\\n');\n for (var index = 0, length = lines.length; index < length; index++) {\n var line = lines[index];\n if (line[0] != 'n') continue;\n var candidate = self.unescape(line.slice(1));\n if (files.hasOwnProperty(candidate)) files[candidate] = true;\n }\n end();\n }\n );\n };", "label_name": "CWE-78", "label": 78} -{"code": "generate_mail_credentials = function() {\n var div = $('.mail-infoblock').clone();\n div.find('#mail_configuration').remove();\n var pass=div.find('#v_password').text();\n if (pass==\"\") div.find('#v_password').html(' ');\n var output = div.text();\n output=output.replace(/(?:\\r\\n|\\r|\\n|\\t)/g, \"|\");\n output=output.replace(/ /g, \"\");\n output=output.replace(/\\|\\|/g, \"|\");\n output=output.replace(/\\|\\|/g, \"|\");\n output=output.replace(/\\|\\|/g, \"|\");\n output=output.replace(/^\\|+/g, \"\");\n output=output.replace(/\\|$/, \"\");\n output=output.replace(/ $/, \"\");\n output=output.replace(/:\\|/g, \": \");\n output=output.replace(/\\|/g, \"\\n\");\n //console.log(output);\n $('#v_credentials').val(output);\n}", "label_name": "CWE-79", "label": 79} -{"code": " AnsiUp.prototype.escape_txt_for_html = function (txt) {\n return txt.replace(/[&<>]/gm, function (str) {\n if (str === \"&\")\n return \"&\";\n if (str === \"<\")\n return \"<\";\n if (str === \">\")\n return \">\";\n });\n };", "label_name": "CWE-79", "label": 79} -{"code": " attributeDisplayType(attributeValue) {\n if (this.isAttributeNumber(attributeValue)) {\n return 'number';\n }\n if (this.isAttributeLink(attributeValue)) {\n return 'link';\n }\n return 'text';\n },", "label_name": "CWE-79", "label": 79} -{"code": " notifies.prepare = function prepare() {\n\n var translate = client.translate;\n\n var html = '
    ';\n var messages = client.notifies.notifies;\n var messageCount = client.notifies.notifyCount;\n\n if (messages && messages.length > 0) {\n html += '

    ' + translate('You have administration messages') + '

    ';\n for(var i = 0 ; i < messages.length; i++) {\n /* eslint-disable-next-line security/detect-object-injection */ // verified false positive\n var m = messages[i];\n const ago = Math.round((Date.now() - m.lastRecorded) / 60000);\n html += wrapmessage(translate(m.title), translate(m.message), m.count, ago, m.persistent);\n }\n } else {\n if (messageCount > 0) {\n html = wrapmessage(translate('Admin messages in queue'), translate('Please sign in using the API_SECRET to see your administration messages'));\n } else {\n html = wrapmessage(translate('Queue empty'), translate('There are no admin messages in queue'));\n }\n }\n html += '
    ';\n notifies.drawer.html(html);\n }", "label_name": "CWE-79", "label": 79} -{"code": "http.ServerResponse.prototype.safeRedirect = function (url) {\n const fullURL = new URL(url, config.urlPrefix);\n if (!fullURL.toString().startsWith(config.urlPrefix)) return this.forbidden();\n this.redirect(url);\n};", "label_name": "CWE-601", "label": 601} -{"code": " language: this.getConfiguration('locale').replace('_', '-'),\n theme: \"bootstrap\",\n matcher: matcher\n }};\n\n const templateResultFunc = function (state) {\n console.log(state);\n return jQuery(' ' + state.text + '');\n };\n\n let optionsColor = {...options, ...{\n templateSelection: templateResultFunc,\n templateResult: templateResultFunc\n }};\n\n jQuery(selector + ' ' + elementSelector + ':not([data-renderer=color])').select2(options);\n jQuery(selector + ' ' + elementSelector + '[data-renderer=color]').select2(optionsColor);\n\n jQuery('body').on('reset', 'form', function(event){\n setTimeout(function() {\n jQuery(event.target).find(elementSelector).trigger('change');\n }, 10);\n });\n }", "label_name": "CWE-1236", "label": 1236} -{"code": "\tfunction imagePreview(src) {\n\t\timgPreview.getElement().setHtml('');\n\t\tif (isFReaderSupported) {\n\t\t\tvar fileI = t.getContentElement('tab-source', 'file');\n\t\t\tvar n = null;\n\t\t\ttry {\n\t\t\t\tn = fileI.getInputElement().$;\n\t\t\t} catch (e) {\n\t\t\t\tn = null;\n\t\t\t}\n\t\t\tif (n && 'files' in n && n.files && n.files.length > 0 && n.files[0]) {\n\t\t\t\tif ('type' in n.files[0] && !n.files[0].type.match('image.*')) return;\n\t\t\t\tif (!FileReader) return;\n\t\t\t\timgPreview.getElement().setHtml('Loading...');\n\t\t\t\tvar fr = new FileReader();\n\t\t\t\tfr.onload = (function (f) {\n\t\t\t\t\treturn function (e) {\n\t\t\t\t\t\timgPreview.getElement().setHtml('');\n\t\t\t\t\t\timagePreviewLoad(e.target.result);\n\t\t\t\t\t};\n\t\t\t\t})(n.files[0]);\n\t\t\t\tfr.onerror = function () {\n\t\t\t\t\timgPreview.getElement().setHtml('');\n\t\t\t\t};\n\t\t\t\tfr.onabort = function () {\n\t\t\t\t\timgPreview.getElement().setHtml('');\n\t\t\t\t};\n\t\t\t\tfr.readAsDataURL(n.files[0]);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-434", "label": 434} -{"code": "\t\ti.onload = function () {\n\t\t\t/* Remove preview */\n\t\t\timgPreview.getElement().setHtml('');\n\n\t\t\t/* Set attributes */\n\t\t\tif (orgWidth == null || orgHeight == null) {\n\t\t\t\tt.setValueOf('tab-properties', 'width', this.width);\n\t\t\t\tt.setValueOf('tab-properties', 'height', this.height);\n\t\t\t\timgScal = 1;\n\t\t\t\tif (this.height > 0 && this.width > 0) imgScal = this.width / this.height;\n\t\t\t\tif (imgScal <= 0) imgScal = 1;\n\t\t\t} else {\n\t\t\t\torgWidth = null;\n\t\t\t\torgHeight = null;\n\t\t\t}\n\t\t\tthis.id = editor.id + 'previewimage';\n\t\t\tthis.setAttribute('style', 'max-width:400px;max-height:100px;');\n\t\t\tthis.setAttribute('alt', '');\n\n\t\t\t/* Insert preview image */\n\t\t\ttry {\n\t\t\t\tvar p = imgPreview.getElement().$;\n\t\t\t\tif (p) p.appendChild(this);\n\t\t\t} catch (e) {}\n\t\t};", "label_name": "CWE-434", "label": 434} -{"code": " var filter = function(data) {\r\n if (data) {\r\n data = data.replace(new RegExp('', 'gsi'), '');\r\n }\r\n var span = document.createElement('span');\r\n span.innerHTML = data;\r\n parse(span);\r\n return span;\r\n } \r", "label_name": "CWE-79", "label": 79} -{"code": " var parse = function(element) {\r\n // Remove attributes\r\n if (element.attributes && element.attributes.length) {\r\n var image = null;\r\n var style = null;\r\n // Process style attribute\r\n var elementStyle = element.getAttribute('style');\r\n if (elementStyle) {\r\n style = [];\r\n var t = elementStyle.split(';');\r\n for (var j = 0; j < t.length; j++) {\r\n var v = t[j].trim().split(':');\r\n if (validStyle.indexOf(v[0].trim()) >= 0) {\r\n var k = v.shift();\r\n var v = v.join(':');\r\n style.push(k + ':' + v);\r\n }\r\n }\r\n }\r\n // Process image\r\n if (element.tagName == 'IMG') {\r\n if (! obj.options.acceptImages) {\r\n element.remove();\r\n } else {\r\n // Check if is data\r\n element.setAttribute('tabindex', '900');\r\n // Check attributes for persistance\r\n obj.addImage(element.src);\r\n }\r\n } else {\r\n // Remove attributes\r\n var numAttributes = element.attributes.length - 1;\r\n for (var i = numAttributes; i >= 0 ; i--) {\r\n element.removeAttribute(element.attributes[i].name);\r\n }\r\n }\r\n element.style = '';\r\n // Add valid style\r\n if (style && style.length) {\r\n element.setAttribute('style', style.join(';'));\r\n }\r\n }\r\n // Parse children\r\n if (element.children.length) {\r\n for (var i = 0; i < element.children.length; i++) {\r\n parse(element.children[i]);\r\n }\r\n }\r\n\r\n if (remove.indexOf(element.constructor) >= 0) {\r\n element.remove();\r\n }\r\n }\r", "label_name": "CWE-79", "label": 79} -{"code": " obj.refresh = function() {\r\n if (obj.options.responsive == true) {\r\n // Remove arrow\r\n toolbarArrow.remove();\r\n // Move all items to the toolbar\r\n while (toolbarFloating.firstChild) {\r\n toolbarContent.appendChild(toolbarFloating.firstChild);\r\n }\r\n // Width of the c\r\n var rect = el.parentNode.getBoundingClientRect();\r\n // Available parent space\r\n var available = rect.width;\r\n // Toolbar is larger than the parent, move elements to the floating element\r\n if (available < toolbarContent.offsetWidth) {\r\n // Give space to the floating element\r\n available -= 50;\r\n // Move to the floating option\r\n while (toolbarContent.lastChild && available < toolbarContent.offsetWidth) {\r\n toolbarFloating.insertBefore(toolbarContent.lastChild, toolbarFloating.firstChild);\r\n }\r\n }\r\n // Show arrow\r\n if (toolbarFloating.children.length > 0) {\r\n toolbarContent.appendChild(toolbarArrow);\r\n }\r\n }\r\n }\r", "label_name": "CWE-79", "label": 79} -{"code": " var parse = function(element) {\r\n // Remove attributes\r\n if (element.attributes && element.attributes.length) {\r\n var image = null;\r\n var style = null;\r\n // Process style attribute\r\n var elementStyle = element.getAttribute('style');\r\n if (elementStyle) {\r\n style = [];\r\n var t = elementStyle.split(';');\r\n for (var j = 0; j < t.length; j++) {\r\n var v = t[j].trim().split(':');\r\n if (validStyle.indexOf(v[0].trim()) >= 0) {\r\n var k = v.shift();\r\n var v = v.join(':');\r\n style.push(k + ':' + v);\r\n }\r\n }\r\n }\r\n // Process image\r\n if (element.tagName.toUpperCase() == 'IMG') {\r\n if (! obj.options.acceptImages) {\r\n element.parentNode.removeChild(element);\r\n } else {\r\n // Check if is data\r\n element.setAttribute('tabindex', '900');\r\n // Check attributes for persistance\r\n obj.addImage(element.src);\r\n }\r\n } else {\r\n // Remove attributes\r\n var numAttributes = element.attributes.length - 1;\r\n for (var i = numAttributes; i >= 0 ; i--) {\r\n element.removeAttribute(element.attributes[i].name);\r\n }\r\n }\r\n element.style = '';\r\n // Add valid style\r\n if (style && style.length) {\r\n element.setAttribute('style', style.join(';'));\r\n }\r\n }\r\n // Parse children\r\n if (element.children.length) {\r\n for (var i = 0; i < element.children.length; i++) {\r\n parse(element.children[i]);\r\n }\r\n }\r\n\r\n if (remove.indexOf(element.constructor) >= 0) {\r\n element.remove();\r\n }\r\n }\r", "label_name": "CWE-79", "label": 79} -{"code": " _mdEmStrong(str) {\n return str.replace(/(^|\\s|\")(\\\\?)(\\*+)(\\w[^<]*?)\\3/g, (all, b, esc, md, text) => {\n if (md.length == 1) return esc ? all.replace(/^\\\\/, '') : b + '' + text + '';\n if (md.length == 2) return esc ? all.replace(/^\\\\/, '') : b + '' + text + '';\n if (md.length == 3) return esc ? all.replace(/^\\\\/, '') : b + '' + text + '';\n return all;\n });\n }", "label_name": "CWE-79", "label": 79} -{"code": " function clean_data(data, text) {\n if (data === '') {\n return text;\n } else {\n return data.replace(/]/g, ']')\n .replace(/>/g, '>').replace(/W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||\nc(\"cursor\",{hide:!0})};b.addListener(\"shareCursorPositionChanged\",this.shareCursorPositionListener);this.selectionChangeListener=function(M,W){M=function(u){return null!=u?u.id:null};var U=null!=b.currentPage?b.currentPage.getId():null,X=W.getProperty(\"added\");W=W.getProperty(\"removed\");c(\"selectionChange\",{pageId:U,removed:X?X.map(M):[],added:W?W.map(M):[]})};l.getSelectionModel().addListener(mxEvent.CHANGE,this.selectionChangeListener);this.cursorHandler=mxUtils.bind(this,function(){for(var M in y)n(y[M])});", "label_name": "CWE-79", "label": 79} -{"code": "ca,la,ia){function ma(Ma,Ta){null==Ka?(Ia=Ma,Ia=/^https?:\\/\\//.test(Ia)&&!b.editor.isCorsEnabledForUrl(Ia)?PROXY_URL+\"?url=\"+encodeURIComponent(Ia):TEMPLATE_PATH+\"/\"+Ia,mxUtils.get(Ia,mxUtils.bind(this,function(Ua){200<=Ua.getStatus()&&299>=Ua.getStatus()&&(Ka=Ua.getText());Ta(Ka,Ia)}))):Ta(Ka,Ia)}function qa(Ma,Ta,Ua){if(null!=Ma&&mxUtils.isAncestorNode(document.body,na)){Ma=mxUtils.parseXml(Ma);Ma=Editor.parseDiagramNode(Ma.documentElement);var Za=new mxCodec(Ma.ownerDocument),Wa=new mxGraphModel;\nZa.decode(Ma,Wa);Ma=Wa.root.getChildAt(0).children;b.sidebar.createTooltip(na,Ma,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!=ya?mxResources.get(ya,null,ya):null,!0,new mxPoint(Ta,Ua),!0,function(){Ya=null!=b.sidebar.tooltip&&\"none\"!=b.sidebar.tooltip.style.display;z(na,null,null,oa,ha,ia)},!0,!1)}}function pa(Ma,Ta){null==oa||Ra||", "label_name": "CWE-79", "label": 79} -{"code": "document.createElement(\"div\");pa.className=\"geTempDlgNewDiagramCatItemLbl\";pa.innerHTML=qa;ma.appendChild(pa);Ca.appendChild(ma);mxEvent.addListener(ma,\"click\",function(){function Ka(){var Ra=Ia.querySelector(\".geTemplateDrawioCatLink\");null!=Ra?Ra.click():setTimeout(Ka,200)}Z=!0;var Ia=M.querySelector(\".geTemplatesList\");Ia.style.display=\"block\";Ba.style.width=\"\";Na.style.display=\"\";Na.value=\"\";ba=null;Ka()});fa.style.display=ha.length<=ca?\"none\":\"\"}function G(ha,da,ca){function la(Qa,Ya){var Ma=", "label_name": "CWE-79", "label": 79} -{"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-79", "label": 79} -{"code": "D=this.editor.graph.getModel().getStyle(D),this.styleInput.value=D||\"\",this.styleInput.style.visibility=\"visible\"):this.styleInput.style.visibility=\"hidden\"})));var L=this.isSelectionAllowed;this.isSelectionAllowed=function(D){return mxEvent.getSource(D)==this.styleInput?!0:L.apply(this,arguments)}}z=document.getElementById(\"geInfo\");null!=z&&z.parentNode.removeChild(z);if(Graph.fileSupport&&(!this.editor.chromeless||this.editor.editable)){var C=null;mxEvent.addListener(g.container,\"dragleave\",function(D){g.isEnabled()&&", "label_name": "CWE-79", "label": 79} -{"code": "urlParams.edge;Graph.prototype.hiddenTags=null;Graph.prototype.defaultMathEnabled=!1;var A=Graph.prototype.init;Graph.prototype.init=function(){function u(N){E=N}A.apply(this,arguments);this.hiddenTags=[];window.mxFreehand&&(this.freehand=new mxFreehand(this));var E=null;mxEvent.addListener(this.container,\"mouseenter\",u);mxEvent.addListener(this.container,\"mousemove\",u);mxEvent.addListener(this.container,\"mouseleave\",function(N){E=null});this.isMouseInsertPoint=function(){return null!=E};var J=this.getInsertPoint;", "label_name": "CWE-79", "label": 79} -{"code": "var GoogleSitesDialog=function(b,e){function f(){var D=null!=C&&null!=C.getTitle()?C.getTitle():this.defaultFilename;if(z.checked&&\"\"!=q.value){var G=\"https://www.draw.io/gadget.xml?type=4&diagram=\"+encodeURIComponent(mxUtils.htmlEntities(q.value));null!=D&&(G+=\"&title=\"+encodeURIComponent(D));0\")}var B=this.editor.graph.getGraphBounds(),I=this.getSelectedPageIndex();if(this.isExportToCanvas())this.editor.exportToCanvas(mxUtils.bind(this,function(z){var L=l?this.getFileData(!0):null;z=", "label_name": "CWE-79", "label": 79} -{"code": "function(e){var f=e.split(\"/\");return 1=u.length)){for(var Z=ea=0;ZmxUtils.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-79", "label": 79} -{"code": "\"rough\")?this.createComicCanvas(Q):this.createRoughCanvas(Q)};var J=mxImageShape.prototype.paintVertexShape;mxImageShape.prototype.paintVertexShape=function(Q,R,Y,ba,ea){null!=Q.handJiggle&&Q.handJiggle.passThrough||J.apply(this,arguments)};var T=mxShape.prototype.paint;mxShape.prototype.paint=function(Q){var R=Q.addTolerance,Y=!0;null!=this.style&&(Y=\"1\"==mxUtils.getValue(this.style,mxConstants.STYLE_POINTER_EVENTS,\"1\"));if(null!=Q.handJiggle&&Q.handJiggle.constructor==u&&!this.outline){Q.save();\nvar ba=this.fill,ea=this.stroke;this.stroke=this.fill=null;var Z=this.configurePointerEvents,fa=Q.setStrokeColor;Q.setStrokeColor=function(){};var aa=Q.setFillColor;Q.setFillColor=function(){};Y||null==ba||(this.configurePointerEvents=function(){});Q.handJiggle.passThrough=!0;T.apply(this,arguments);Q.handJiggle.passThrough=!1;Q.setFillColor=aa;Q.setStrokeColor=fa;this.configurePointerEvents=Z;this.stroke=ea;this.fill=ba;Q.restore();Y&&null!=ba&&(Q.addTolerance=function(){})}T.apply(this,arguments);\nQ.addTolerance=R};var N=mxShape.prototype.paintGlassEffect;mxShape.prototype.paintGlassEffect=function(Q,R,Y,ba,ea,Z){null!=Q.handJiggle&&Q.handJiggle.constructor==u?(Q.handJiggle.passThrough=!0,N.apply(this,arguments),Q.handJiggle.passThrough=!1):N.apply(this,arguments)}})();Editor.fastCompress=function(u){return null==u||0==u.length||\"undefined\"===typeof pako?u:Graph.arrayBufferToString(pako.deflateRaw(u))};Editor.fastDecompress=function(u){return null==u||0==u.length||\"undefined\"===typeof pako?", "label_name": "CWE-79", "label": 79} -{"code": "T.appendChild(T.importNode(u[0],!0)),T=T.documentElement));return T};Editor.getDiagramNodeXml=function(u){var E=mxUtils.getTextContent(u),J=null;0N){J=u.substring(N,ba);break}}10==Y&&(\"endobj\"==E?R=null:\"obj\"==E.substring(E.length-3,E.length)||\"xref\"==E||\"trailer\"==E?(R=[],Q[E.split(\" \")[0]]=R):null!=R&&R.push(E),\nE=\"\")}null==J&&(J=Editor.extractGraphModelFromXref(Q));null!=J&&(J=decodeURIComponent(J.replace(/\\\\\\(/g,\"(\").replace(/\\\\\\)/g,\")\")));return J};Editor.extractGraphModelFromXref=function(u){var E=u.trailer,J=null;null!=E&&(E=/.* \\/Info (\\d+) (\\d+) R/g.exec(E.join(\"\\n\")),null!=E&&0T.indexOf(\"mxPageSelector\")&&0q.length){A.view.validate();var ca=new mxFastOrganicLayout(A);ca.forceConstant=3*W;ca.disableEdgeStyle=!1;ca.resetEdges=!1;var la=ca.isVertexIgnored;ca.isVertexIgnored=function(ia){return la.apply(this,arguments)||0>mxUtils.indexOf(q,\nia)};this.executeLayout(function(){ca.execute(A.getDefaultParent());ya()},!0,u);u=null}}this.hideDialog()}finally{A.model.endUpdate()}null!=u&&u()}}catch(ia){this.handleError(ia)}};EditorUi.prototype.getSearch=function(d){var g=\"\";if(\"1\"!=urlParams.offline&&\"1\"!=urlParams.demo&&null!=d&&0mxUtils.indexOf(d,l)&&null!=urlParams[l]&&(g+=k+l+\"=\"+urlParams[l],k=\"&\")}else g=window.location.search;return g};EditorUi.prototype.getUrl=function(d){d=", "label_name": "CWE-79", "label": 79} -{"code": "function(K){var F=x.length;if(1===F%2||F>=f){var H=0,S=0,V,M=0;for(V=K;Vc&&!mxClient.IS_IOS?C.firstChild.nextSibling.setAttribute(\"title\",D.shortcut):l.apply(this,arguments)};var p=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){p.apply(this,arguments);if(null!=this.userElement){var C=this.userElement;C.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+C.style.display;C.className=\"geToolbarButton\";C.innerHTML=\"\";C.style.backgroundImage=\"url(\"+Editor.userImage+\")\";C.style.backgroundPosition=\"center center\";", "label_name": "CWE-79", "label": 79} -{"code": "function(J){mxEvent.isConsumed(J)||((mxEvent.isControlDown(J)||mxClient.IS_MAC&&mxEvent.isMetaDown(J))&&13==J.keyCode?(E.click(),mxEvent.consume(J)):27==J.keyCode&&(u.click(),mxEvent.consume(J)))}));E.focus();E.className=\"geCommentEditBtn gePrimaryBtn\";X.appendChild(E);F.insertBefore(X,M);W.style.display=\"none\";M.style.display=\"none\";U.focus()}function g(K,F){F.innerHTML=\"\";K=new Date(K.modifiedDate);var H=b.timeSince(K);null==H&&(H=mxResources.get(\"lessThanAMinute\"));mxUtils.write(F,mxResources.get(\"timeAgo\",\n[H],\"{1} ago\"));F.setAttribute(\"title\",K.toLocaleDateString()+\" \"+K.toLocaleTimeString())}function k(K){var F=document.createElement(\"img\");F.className=\"geCommentBusyImg\";F.src=IMAGE_PATH+\"/spin.gif\";K.appendChild(F);K.busyImg=F}function l(K){K.style.border=\"1px solid red\";K.removeChild(K.busyImg)}function p(K){K.style.border=\"\";K.removeChild(K.busyImg)}function q(K,F,H,S,V){function M(N,Q,R){var Y=document.createElement(\"li\");Y.className=\"geCommentAction\";var ba=document.createElement(\"a\");ba.className=", "label_name": "CWE-79", "label": 79} -{"code": "function(u,E,J,T){for(var N=0;N'+Graph.compress('')+\"\",qa(Ta,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma))):(b.sidebar.currentElt=\nna,Ra=!0,ma(oa,function(Ua){Ra&&b.sidebar.currentElt==na&&qa(Ua,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma));Ra=!1})))}var na=document.createElement(\"div\");na.className=\"geTemplate\";na.style.position=\"relative\";na.style.height=Ha+\"px\";na.style.width=ra+\"px\";var Ka=null,Ia=oa;Editor.isDarkMode()&&(na.style.filter=\"invert(100%)\");null!=ya?na.setAttribute(\"title\",mxResources.get(ya,null,ya)):null!=wa&&0ka.max&&(ja=ka.max);ja=encodeURIComponent((\"int\"==va?parseInt(ja):ja)+\"\");T(za,ja,ka)}var ba=document.createElement(\"input\");P(wa,ba,!0);ba.value=decodeURIComponent(ta);ba.className=\"gePropEditor\";\"int\"!=va&&\"float\"!=va||ka.allowAuto||(ba.type=\"number\",ba.step=\"int\"==va?\"1\":\"any\",null!=ka.min&&(ba.min=parseFloat(ka.min)),null!=ka.max&&(ba.max=parseFloat(ka.max)));p.appendChild(ba);mxEvent.addListener(ba,\"keypress\",function(ja){13==ja.keyCode&&ca()});ba.focus();mxEvent.addListener(ba,", "label_name": "CWE-79", "label": 79} -{"code": "this.startDrawing=function(){n(!0)};this.isDrawing=function(){return x};var y=mxUtils.bind(this,function(J){if(d){var E=c.length,H=A&&0c.length;H||D.push.apply(D,c);c=[];D.push(null);u.push(d);d=null;(H||k)&&this.stopDrawing();k&&2<=E&&this.startDrawing();mxEvent.consume(J)}}),K=new mxCell;K.edge=!0;var B=function(){var J=b.getCurrentCellStyle(K);J=mxUtils.getValue(b.currentVertexStyle,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(J,mxConstants.STYLE_STROKECOLOR,\"#000\"));\"default\"==", "label_name": "CWE-79", "label": 79} -{"code": "function(y){this.spinner.stop();this.handleError(y)})})))}}),mxUtils.bind(this,function(){this.hideDialog()}),mxResources.get(\"saveAs\"),mxResources.get(\"download\"),!1,!1,v,null,1=n.getStatus()?(this.updateDiagram(n.getText()),L()):this.handleError({message:mxResources.get(\"error\")+\" \"+n.getStatus()}))}),mxUtils.bind(this,function(n){this.handleError(n)}))}),L=mxUtils.bind(this,function(){window.clearTimeout(A);A=window.setTimeout(z,x)});this.editor.addListener(\"pageSelected\",mxUtils.bind(this,function(){L();z()}));L();z()}null!=e&&e()});null!=c.url&&0 Bob: Authentication Request\\nBob --\\x3e Alice: Authentication Response\\n\\nAlice -> Bob: Another authentication Request\\nAlice <-- Bob: Another authentication Response\\n@enduml\"==", "label_name": "CWE-79", "label": 79} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-79", "label": 79} -{"code": "d.executeLayoutList(K);d.customLayoutConfig=K}catch(B){d.handleError(B),null!=window.console&&console.error(B)}},null,null,null,null,null,!0,null,null,\"https://www.diagrams.net/doc/faq/apply-layouts\");d.showDialog(n.container,620,460,!0,!0);n.init()});k=this.get(\"layout\");var x=k.funct;k.funct=function(n,y){x.apply(this,arguments);n.addItem(mxResources.get(\"orgChart\"),null,function(){function K(){\"undefined\"!==typeof mxOrgChartLayout||d.loadingOrgChart||d.isOffline(!0)?J():d.spinner.spin(document.body,\nmxResources.get(\"loading\"))&&(d.loadingOrgChart=!0,\"1\"==urlParams.dev?mxscript(\"js/orgchart/bridge.min.js\",function(){mxscript(\"js/orgchart/bridge.collections.min.js\",function(){mxscript(\"js/orgchart/OrgChart.Layout.min.js\",function(){mxscript(\"js/orgchart/mxOrgChartLayout.js\",J)})})}):mxscript(\"js/extensions.min.js\",J))}var B=null,F=20,G=20,N=!0,J=function(){d.loadingOrgChart=!1;d.spinner.stop();if(\"undefined\"!==typeof mxOrgChartLayout&&null!=B&&N){var X=d.editor.graph,p=new mxOrgChartLayout(X,B,", "label_name": "CWE-79", "label": 79} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-79", "label": 79} -{"code": "Math.min(Y,Math.max(parseInt(aa.value),parseInt(ea.value))));ea.value=Math.max(1,Math.min(Y,Math.min(parseInt(aa.value),parseInt(ea.value))))}function T(ya){function va(Ha,Na,Pa){var Qa=Ha.useCssTransforms,Ya=Ha.currentTranslate,La=Ha.currentScale,Ta=Ha.view.translate,Ua=Ha.view.scale;Ha.useCssTransforms&&(Ha.useCssTransforms=!1,Ha.currentTranslate=new mxPoint(0,0),Ha.currentScale=1,Ha.view.translate=new mxPoint(0,0),Ha.view.scale=1);var Za=Ha.getGraphBounds(),Wa=0,bb=0,Va=pa.get(),ab=1/Ha.pageScale,\n$a=xa.checked;if($a){ab=parseInt(ta.value);var hb=parseInt(ka.value);ab=Math.min(Va.height*hb/(Za.height/Ha.view.scale),Va.width*ab/(Za.width/Ha.view.scale))}else ab=parseInt(Fa.value)/(100*Ha.pageScale),isNaN(ab)&&(ra=1/Ha.pageScale,Fa.value=\"100 %\");Va=mxRectangle.fromRectangle(Va);Va.width=Math.ceil(Va.width*ra);Va.height=Math.ceil(Va.height*ra);ab*=ra;!$a&&Ha.pageVisible?(Za=Ha.getPageLayout(),Wa-=Za.x*Va.width,bb-=Za.y*Va.height):$a=!0;if(null==Na){Na=PrintDialog.createPrintPreview(Ha,ab,Va,", "label_name": "CWE-79", "label": 79} -{"code": "A=this.editor.graph,z=null,L=null,M=null,n=null,y=null,K=null,B=null,F=\"whiteSpace=wrap;html=1;\",G=null,N=null,J=\"\",E=\"auto\",H=\"auto\",S=null,U=null,Q=40,W=40,V=100,X=0,p=function(){null!=e?e(ta):(A.setSelectionCells(ta),A.scrollCellToVisible(A.getSelectionCell()))},C=A.getFreeInsertPoint(),I=C.x,T=C.y;C=T;var P=null,O=\"auto\";N=null;for(var R=[],Y=null,da=null,ha=0;hae};EditorUi.prototype.resizeImage=function(c,e,g,k,m,q,v){m=null!=m?m:this.maxImageSize;var x=Math.max(1,c.width),A=Math.max(1,c.height);if(k&&this.isResampleImageSize(null!=v?v:e.length,q))try{var z=Math.max(x/m,A/m);if(1\");2<=S.length&&(N=J(S[0]),E=J(S[S.length-1]),S=new mxCell(2=Math.max(V.x,U.x)||S&&Math.min(V.y+V.height,U.y+U.height)>=Math.max(V.y,U.y))&&Q.push(V)}Q.sort(function(X,p){return S?X.x+X.width-p.x-p.width:X.y+X.height-\np.y-p.height})}return Q}function q(H,S){var U=c(H),Q=S==mxConstants.DIRECTION_EAST||S==mxConstants.DIRECTION_WEST;(U==mxConstants.DIRECTION_EAST||U==mxConstants.DIRECTION_WEST)==Q&&U!=S?v.actions.get(\"selectParent\").funct():U==S?(S=x.getOutgoingTreeEdges(H),null!=S&&0u;u++)for(var t=u,D=0;8>D;D++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[u]=t;Editor.updateCRC=function(p,C,I,T){for(var P=\n0;P>>8;return p};Editor.crc32=function(p){for(var C=-1,I=0;I>>8^Editor.crcTable[(C^p.charCodeAt(I))&255];return(C^-1)>>>0};Editor.writeGraphModelToPng=function(p,C,I,T,P){function O(Z,ea){var aa=da;da+=ea;return Z.substring(aa,da)}function R(Z){Z=O(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}p=p.substring(p.indexOf(\",\")+", "label_name": "CWE-79", "label": 79} -{"code": "ia){ja=fa.getAttribute(\"section\");ba=fa.getAttribute(\"subsection\");if(null==ja&&(ma=ia.indexOf(\"/\"),ja=ia.substring(0,ma),null==ba)){var qa=ia.indexOf(\"/\",ma+1);-1'),d.showDialog(y.container,450,240,!0,!0),y.init()):d.handleError({message:mxResources.get(\"invalidPublicUrl\")})})}));d.actions.put(\"embedImage\",", "label_name": "CWE-79", "label": 79} -{"code": "Ga),!0,null,!0);var Ha=document.createElement(\"div\");Ha.className=\"geTempDlgDialogMask\";Q.appendChild(Ha);var Na=b.sidebar.hideTooltip;b.sidebar.hideTooltip=function(){Ha&&(Q.removeChild(Ha),Ha=null,Na.apply(this,arguments),b.sidebar.hideTooltip=Na)};mxEvent.addListener(Ha,\"click\",function(){b.sidebar.hideTooltip()})}}var qa=null;if(Ca||b.sidebar.currentElt==ca)b.sidebar.hideTooltip();else{var oa=function(na){Ca&&b.sidebar.currentElt==ca&&ma(na,mxEvent.getClientX(ja),mxEvent.getClientY(ja));Ca=!1;\nba.src=\"/images/icon-search.svg\"};b.sidebar.hideTooltip();b.sidebar.currentElt=ca;Ca=!0;ba.src=\"/images/aui-wait.gif\";fa.isExt?e(fa,oa,function(){A(mxResources.get(\"cantLoadPrev\"));Ca=!1;ba.src=\"/images/icon-search.svg\"}):ia(fa.url,oa)}}function n(fa,ca,ba){if(null!=C){for(var ja=C.className.split(\" \"),ia=0;iamxUtils.indexOf(d,va))&&(Ca=mxUtils.setStyle(Ca,va,Ra))}Editor.simpleLabels&&(Ca=mxUtils.setStyle(mxUtils.setStyle(Ca,\"html\",null),\"whiteSpace\",null));Q.setStyle(J,Ca)}}finally{Q.endUpdate()}return I};n.addListener(\"cellsInserted\",function(I,V){q(V.getProperty(\"cells\"),null,null,null,null,!0,!0)});n.addListener(\"textInserted\",function(I,V){q(V.getProperty(\"cells\"),!0)});this.insertHandler=q;this.createDivs();this.createUi();this.refresh();var y=mxUtils.bind(this,", "label_name": "CWE-79", "label": 79} -{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-79", "label": 79} -{"code": "ma);H.moveCells(ma,N,W)},!0,u);u=null}else if(\"organic\"==P||\"auto\"==P&&ma.length>y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=u&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=", "label_name": "CWE-79", "label": 79} -{"code": "this.buttonContainer.style.top=\"6px\";this.editor.fireEvent(new mxEventObject(\"statusChanged\"))}};var E=Sidebar.prototype.getTooltipOffset;Sidebar.prototype.getTooltipOffset=function(O,X){if(null==this.editorUi.sidebarWindow||mxUtils.isAncestorNode(this.editorUi.picker,O)){var ea=mxUtils.getOffset(this.editorUi.picker);ea.x+=this.editorUi.picker.offsetWidth+4;ea.y+=O.offsetTop-X.height/2+16;return ea}var ka=E.apply(this,arguments);ea=mxUtils.getOffset(this.editorUi.sidebarWindow.window.div);ka.x+=\nea.x-16;ka.y+=ea.y;return ka};var C=Menus.prototype.createPopupMenu;Menus.prototype.createPopupMenu=function(O,X,ea){var ka=this.editorUi.editor.graph;O.smartSeparators=!0;C.apply(this,arguments);\"1\"==urlParams.sketch?ka.isEnabled()&&(O.addSeparator(),1==ka.getSelectionCount()&&this.addMenuItems(O,[\"-\",\"lockUnlock\"],null,ea)):1==ka.getSelectionCount()?(ka.isCellFoldable(ka.getSelectionCell())&&this.addMenuItems(O,ka.isCellCollapsed(X)?[\"expand\"]:[\"collapse\"],null,ea),this.addMenuItems(O,[\"collapsible\",", "label_name": "CWE-79", "label": 79} -{"code": "function(z){var L=null;null!=z&&0S.offsetTop-S.offsetHeight/2?\"70px\":\"10px\");else{for(var za=", "label_name": "CWE-79", "label": 79} -{"code": "S&&S(M)}}))}catch(L){null!=S&&S(L)}}),N,sa)}catch(Pa){null!=S&&S(Pa)}};Editor.crcTable=[];for(var D=0;256>D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=\nva;va+=Ba;return sa.substring(ta,va)}function Z(sa){sa=P(sa,4);return sa.charCodeAt(3)+(sa.charCodeAt(2)<<8)+(sa.charCodeAt(1)<<16)+(sa.charCodeAt(0)<<24)}function oa(sa){return String.fromCharCode(sa>>24&255,sa>>16&255,sa>>8&255,sa&255)}u=u.substring(u.indexOf(\",\")+1);u=window.atob?atob(u):Base64.decode(u,!0);var va=0;if(P(u,8)!=String.fromCharCode(137)+\"PNG\"+String.fromCharCode(13,10,26,10))null!=S&&S();else if(P(u,4),\"IHDR\"!=P(u,4))null!=S&&S();else{P(u,17);S=u.substring(0,va);do{var Aa=Z(u);if(\"IDAT\"==", "label_name": "CWE-79", "label": 79} -{"code": "mxEvent.getClientX(za);I.popupMenuHandler.hideMenu();mxEvent.consume(za)});mxEvent.addGestureListeners(document.body,null,function(za){var wa=!1;null!=Ma&&(U.diagramContainer.style.width=Math.max(20,Qa+mxEvent.getClientX(za)-Ma)+\"px\",wa=!0);null!=Oa&&(U.diagramContainer.style.height=Math.max(20,Ta+mxEvent.getClientY(za)-Oa)+\"px\",wa=!0);wa&&((window.opener||window.parent).postMessage(JSON.stringify({event:\"resize\",fullscreen:Editor.inlineFullscreen,rect:U.diagramContainer.getBoundingClientRect()}),\n\"*\"),Z(),U.refresh())},function(za){null==Ma&&null==Oa||mxEvent.consume(za);Oa=Ma=null});this.diagramContainer.style.borderRadius=\"4px\";document.body.style.backgroundColor=\"transparent\";U.bottomResizer.style.visibility=\"hidden\";U.rightResizer.style.visibility=\"hidden\";P.style.visibility=\"hidden\";W.style.visibility=\"hidden\";S.style.display=\"none\"}\"1\"==urlParams.prefetchFonts&&U.editor.loadFonts()}}};", "label_name": "CWE-79", "label": 79} -{"code": "function pa(){mxEllipse.call(this)}function ua(){mxEllipse.call(this)}function ya(){mxRhombus.call(this)}function Fa(){mxEllipse.call(this)}function Ma(){mxEllipse.call(this)}function Oa(){mxEllipse.call(this)}function Qa(){mxEllipse.call(this)}function Ta(){mxActor.call(this)}function za(){mxActor.call(this)}function wa(){mxActor.call(this)}function Ea(c,l,x,p){mxShape.call(this);this.bounds=c;this.fill=l;this.stroke=x;this.strokewidth=null!=p?p:1;this.rectStyle=\"square\";this.size=10;this.absoluteCornerSize=", "label_name": "CWE-79", "label": 79} -{"code": "S&&S(La)}};za.onerror=function(wa){null!=S&&S(wa)};za.src=ua}else L()}catch(wa){null!=S&&S(wa)}});Za.onerror=function(L){null!=S&&S(L)};Aa&&this.graph.addSvgShadow(Pa);this.graph.mathEnabled&&this.addMathCss(Pa);var z=mxUtils.bind(this,function(){try{null!=this.resolvedFontCss&&this.addFontCss(Pa,this.resolvedFontCss),Za.src=Editor.createSvgDataUri(mxUtils.getXml(Pa))}catch(L){null!=S&&S(L)}});this.embedExtFonts(mxUtils.bind(this,function(L){try{null!=L&&this.addFontCss(Pa,L),this.loadFonts(z)}catch(M){null!=", "label_name": "CWE-79", "label": 79} -{"code": "eb);this.updateSvgLinks(Da,ua,!0);this.addForeignObjectWarning(eb,Da);return Da}finally{Qa&&(this.useCssTransforms=!0,this.view.revalidate(),this.sizeDidChange())}};Graph.prototype.addForeignObjectWarning=function(z,L){if(\"0\"!=urlParams[\"svg-warning\"]&&0y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=u&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=", "label_name": "CWE-79", "label": 79} -{"code": "fa,la,ra){R.addItem(la,null,mxUtils.bind(this,function(){var u=new CreateGraphDialog(O,la,ra);O.showDialog(u.container,620,420,!0,!1);u.init()}),fa)};this.put(\"insertLayout\",new Menu(mxUtils.bind(this,function(R,fa){for(var la=0;lathis.opacity?\"alpha(opacity=\"+this.opacity+\")\":\"\";this.node.style.filter=b;this.flipH&&this.flipV?b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)\":this.flipH?b+=\"progid:DXImageTransform.Microsoft.BasicImage(mirror=1)\":this.flipV&&(b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)\");a.style.filter!=b&&(a.style.filter=b);\"image\"==\na.nodeName?a.style.rotation=this.rotation:0!=this.rotation?mxUtils.setPrefixedStyle(a.style,\"transform\",\"rotate(\"+this.rotation+\"deg)\"):mxUtils.setPrefixedStyle(a.style,\"transform\",\"\");a.style.width=this.node.style.width;a.style.height=this.node.style.height;this.node.style.backgroundImage=\"\";this.node.appendChild(a)}else this.setTransparentBackgroundImage(this.node)};function mxLabel(a,b,c,d){mxRectangleShape.call(this,a,b,c,d)}mxUtils.extend(mxLabel,mxRectangleShape);", "label_name": "CWE-94", "label": 94} -{"code": "f.setCellStyles(mxConstants.STYLE_ROTATION,Number(L.value),[e[M]])}}finally{f.getModel().endUpdate()}});O.className=\"geBtn gePrimaryBtn\";mxEvent.addListener(m,\"keypress\",function(M){13==M.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(C){for(C=document.elementFromPoint(C.clientX,\nC.clientY);null!=C&&C.parentNode!=x;)C=C.parentNode;var G=null;if(null!=C){var N=x.firstChild;for(G=0;null!=N&&N!=C;)N=N.nextSibling,G++}return G}function d(C,G,N,I,F,H,R,W,J){try{if(b.spinner.stop(),null==G||\"image/\"==G.substring(0,6))if(null==C&&null!=R||null==z[C]){var V=function(){Q.innerHTML=\"\";Q.style.cursor=\"pointer\";Q.style.whiteSpace=\"nowrap\";Q.style.textOverflow=\"ellipsis\";mxUtils.write(Q,null!=S.title&&0
    \");a=this.replaceLinefeeds?a.replace(/\\n/g,\"
    \"):a;var b=null!=this.background&&this.background!=mxConstants.NONE?this.background:null,c=null!=this.border&&this.border!=mxConstants.NONE?this.border:null;if(\"fill\"==this.overflow||\n\"width\"==this.overflow)null!=b&&(this.node.style.backgroundColor=b),null!=c&&(this.node.style.border=\"1px solid \"+c);else{var d=\"\";null!=b&&(d+=\"background-color:\"+mxUtils.htmlEntities(b)+\";\");null!=c&&(d+=\"border:1px solid \"+mxUtils.htmlEntities(c)+\";\");a='
    '+a+\"
    \"}this.node.innerHTML=\na;a=this.node.getElementsByTagName(\"div\");0'],{type:\"text/html\"})});navigator.clipboard.write([d])[\"catch\"](l)};EditorUi.prototype.copyCells=function(d,g){var k=this.editor.graph;if(k.isSelectionEmpty())d.innerHTML=\"\";else{var l=\nmxUtils.sortCells(k.model.getTopmostCells(k.getSelectionCells())),p=mxUtils.getXml(k.encodeCells(l));mxUtils.setTextContent(d,encodeURIComponent(p));g?(k.removeCells(l,!1),k.lastPasteXml=null):(k.lastPasteXml=p,k.pasteCounter=0);d.focus();document.execCommand(\"selectAll\",!1,null)}};EditorUi.prototype.copyXml=function(){var d=null;if(Editor.enableNativeCipboard){var g=this.editor.graph;g.isSelectionEmpty()||(d=mxUtils.sortCells(g.getExportableCells(g.model.getTopmostCells(g.getSelectionCells()))),", "label_name": "CWE-94", "label": 94} -{"code": "null!=na){ca=ia.getAttribute(\"section\");aa=ia.getAttribute(\"subsection\");if(null==ca&&(la=na.indexOf(\"/\"),ca=na.substring(0,la),null==aa)){var qa=na.indexOf(\"/\",la+1);-1 0) ?\n\t\t\t\t\t\t\tentry.title : mxResources.get('untitled'));\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (entry.title == null || entry.title.length == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlabel.style.color = '#d0d0d0';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlabel.style.color = '';\n\t\t\t\t\t\t}\n\t\t\t\t\t};", "label_name": "CWE-94", "label": 94} -{"code": "\t\t\tfunction toggleResolve(evt)\n\t\t\t{\n\t\t\t\tfunction doToggle()\n\t\t\t\t{\n\t\t\t\t\tvar resolveActionLnk = evt.target;\n\t\t\t\t\tresolveActionLnk.innerHTML = '';\n\n\t\t\t\t\tcomment.isResolved = !comment.isResolved;\n\t\t\t\t\tmxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));\n\t\t\t\t\tvar actionsDisplay = comment.isResolved? 'none' : '';\n\t\t\t\t\tvar replies = collectReplies(comment).replies;\n\t\t\t\t\tvar color = (Editor.isDarkMode()) ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');\n\t\t\t\t\t\n\t\t\t\t\tfor (var i = 0; i < replies.length; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\treplies[i].style.backgroundColor = color;\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar forOpenActions = replies[i].querySelectorAll('.geCommentAction');\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (var j = 0; j < forOpenActions.length; j ++) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (forOpenActions[j] == resolveActionLnk.parentNode) continue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tforOpenActions[j].style.display = actionsDisplay;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!resolvedChecked)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treplies[i].style.display = 'none';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tupdateNoComments();\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tif (comment.isResolved)\n\t\t\t\t{\n\t\t\t\t\taddReply(mxResources.get('reOpened') + ': ', true, doToggle, false, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\taddReply(mxResources.get('markedAsResolved'), false, doToggle, true);\n\t\t\t\t}\n\t\t\t};", "label_name": "CWE-79", "label": 79} -{"code": "\t\t\t\t\t\t\tfunction fillUsersSelect()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tusersSelect.innerHTML = '';\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor (var i = 0; i < driveUsers.length; i++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar option = document.createElement('option');\n\t\t\t\t\t\t\t\t\tmxUtils.write(option, driveUsers[i].displayName);\n\t\t\t\t\t\t\t\t\toption.value = i;\n\t\t\t\t\t\t\t\t\tusersSelect.appendChild(option);\n\t\t\t\t\t\t\t\t\t//More info (email) about the user in a disabled option\n\t\t\t\t\t\t\t\t\toption = document.createElement('option');\n\t\t\t\t\t\t\t\t\toption.innerHTML = '   ';\n\t\t\t\t\t\t\t\t\tmxUtils.write(option, '<' + driveUsers[i].email + '>');\n\t\t\t\t\t\t\t\t\toption.setAttribute('disabled', 'disabled');\n\t\t\t\t\t\t\t\t\tusersSelect.appendChild(option);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//Add account option\n\t\t\t\t\t\t\t\tvar option = document.createElement('option');\n\t\t\t\t\t\t\t\tmxUtils.write(option, mxResources.get('addAccount'));\n\t\t\t\t\t\t\t\toption.value = driveUsers.length;\n\t\t\t\t\t\t\t\tusersSelect.appendChild(option);\n\t\t\t\t\t\t\t}", "label_name": "CWE-94", "label": 94} -{"code": "GraphViewer.processElements = function(classname)\n{\n\tmxUtils.forEach(GraphViewer.getElementsByClassName(classname || 'mxgraph'), function(div)\n\t{\n\t\ttry\n\t\t{\n\t\t\tdiv.innerHTML = '';\n\t\t\tGraphViewer.createViewerForElement(div);\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\tdiv.innerHTML = e.message;\n\t\t\t\n\t\t\tif (window.console != null)\n\t\t\t{\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t});\n};", "label_name": "CWE-79", "label": 79} -{"code": "Format.prototype.clear = function()\n{\n\tthis.container.innerHTML = '';\n\t\n\t// Destroy existing panels\n\tif (this.panels != null)\n\t{\n\t\tfor (var i = 0; i < this.panels.length; i++)\n\t\t{\n\t\t\tthis.panels[i].destroy();\n\t\t}\n\t}\n\t\n\tthis.panels = [];\n};", "label_name": "CWE-94", "label": 94} -{"code": "Graph.prototype.getTooltipForCell = function(cell)\n{\n\tvar tip = '';\n\t\n\tif (mxUtils.isNode(cell.value))\n\t{\n\t\tvar tmp = null;\n\n\t\tif (Graph.translateDiagram && Graph.diagramLanguage != null)\n\t\t{\n\t\t\ttmp = cell.value.getAttribute('tooltip_' + Graph.diagramLanguage);\n\t\t}\n\t\t\n\t\tif (tmp == null)\n\t\t{\n\t\t\ttmp = cell.value.getAttribute('tooltip');\n\t\t}\n\t\t\n\t\tif (tmp != null)\n\t\t{\n\t\t\tif (tmp != null && this.isReplacePlaceholders(cell))\n\t\t\t{\n\t\t\t\ttmp = this.replacePlaceholders(cell, tmp);\n\t\t\t}\n\t\t\t\n\t\t\ttip = this.sanitizeHtml(tmp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar ignored = this.builtInProperties;\n\t\t\tvar attrs = cell.value.attributes;\n\t\t\tvar temp = [];\n\n\t\t\t// Hides links in edit mode\n\t\t\tif (this.isEnabled())\n\t\t\t{\n\t\t\t\tignored.push('linkTarget');\n\t\t\t\tignored.push('link');\n\t\t\t}\n\t\t\t\n\t\t\tfor (var i = 0; i < attrs.length; i++)\n\t\t\t{\n\t\t\t\tif (mxUtils.indexOf(ignored, attrs[i].nodeName) < 0 && attrs[i].nodeValue.length > 0)\n\t\t\t\t{\n\t\t\t\t\ttemp.push({name: attrs[i].nodeName, value: attrs[i].nodeValue});\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// Sorts by name\n\t\t\ttemp.sort(function(a, b)\n\t\t\t{\n\t\t\t\tif (a.name < b.name)\n\t\t\t\t{\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\telse if (a.name > b.name)\n\t\t\t\t{\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tfor (var i = 0; i < temp.length; i++)\n\t\t\t{\n\t\t\t\tif (temp[i].name != 'link' || !this.isCustomLink(temp[i].value))\n\t\t\t\t{\n\t\t\t\t\ttip += ((temp[i].name != 'link') ? '' + temp[i].name + ': ' : '') +\n\t\t\t\t\t\tmxUtils.htmlEntities(temp[i].value) + '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (tip.length > 0)\n\t\t\t{\n\t\t\t\ttip = tip.substring(0, tip.length - 1);\n\t\t\t\t\n\t\t\t\tif (mxClient.IS_SVG)\n\t\t\t\t{\n\t\t\t\t\ttip = '
    ' +\n\t\t\t\t\t\ttip + '
    ';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn tip;\n};", "label_name": "CWE-94", "label": 94} -{"code": "Toolbar.prototype.setFontSize = function(value)\n{\n\tif (this.sizeMenu != null)\n\t{\n\t\tthis.sizeMenu.innerHTML = '';\n\t\tvar div = document.createElement('div');\n\t\tdiv.style.display = 'inline-block';\n\t\tdiv.style.overflow = 'hidden';\n\t\tdiv.style.textOverflow = 'ellipsis';\n\t\tdiv.style.maxWidth = '24px';\n\t\tmxUtils.write(div, value);\n\t\tthis.sizeMenu.appendChild(div);\n\t\t\n\t\tthis.appendDropDownImageHtml(this.sizeMenu);\n\t}\n};", "label_name": "CWE-79", "label": 79} -{"code": "var S=document.createElement(\"tbody\"),Q=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(p=f.length-1;0<=p;p--){var P=function(T){var X=new Date(T.modifiedDate),ba=null;if(0<=X.getTime()){var ja=function(ka){v.stop();E.innerHTML=\"\";var da=mxUtils.parseXml(ka),fa=b.editor.extractGraphModel(da.documentElement,!0);if(null!=fa){var ma=function(Ba){null!=Ba&&(Ba=ya(Editor.parseDiagramNode(Ba)));return Ba},ya=function(Ba){var Ha=Ba.getAttribute(\"background\");", "label_name": "CWE-94", "label": 94} -{"code": "var S=document.createElement(\"tbody\"),Q=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(p=f.length-1;0<=p;p--){var P=function(T){var X=new Date(T.modifiedDate),ba=null;if(0<=X.getTime()){var ja=function(ka){v.stop();E.innerHTML=\"\";var da=mxUtils.parseXml(ka),fa=b.editor.extractGraphModel(da.documentElement,!0);if(null!=fa){var ma=function(Ba){null!=Ba&&(Ba=ya(Editor.parseDiagramNode(Ba)));return Ba},ya=function(Ba){var Ha=Ba.getAttribute(\"background\");", "label_name": "CWE-79", "label": 79} -{"code": "\"top center\";da.style.backgroundRepeat=\"no-repeat\";da.setAttribute(\"title\",\"Minimize\");var fa=!1,ma=mxUtils.bind(this,function(){S.innerHTML=\"\";if(!fa){var aa=function(la,oa,ra){la=B(\"\",la.funct,null,oa,la,ra);la.style.width=\"40px\";la.style.opacity=\"0.7\";return ca(la,null,\"pointer\")},ca=function(la,oa,ra){null!=oa&&la.setAttribute(\"title\",oa);la.style.cursor=null!=ra?ra:\"default\";la.style.margin=\"2px 0px\";S.appendChild(la);mxUtils.br(S);return la};ca(F.sidebar.createVertexTemplate(\"text;strokeColor=none;fillColor=none;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\",", "label_name": "CWE-94", "label": 94} -{"code": "!0,0,mxUtils.bind(this,function(b){this.hsplitPosition=b;this.refresh()})))};EditorUi.prototype.createStatusContainer=function(){var a=document.createElement(\"a\");a.className=\"geItem geStatus\";return a};EditorUi.prototype.setStatusText=function(a){this.statusContainer.innerHTML=a;0==this.statusContainer.getElementsByTagName(\"div\").length&&(this.statusContainer.innerHTML=\"\",a=this.createStatusDiv(a),this.statusContainer.appendChild(a))};", "label_name": "CWE-79", "label": 79} -{"code": "this.sidebar.showEntries(\"search\")):(this.sidebar.showPalette(\"search\",mxSettings.settings.search),this.editor.chromeless&&!this.editor.editable||!(mxSettings.settings.isNew||8>=parseInt(mxSettings.settings.version||0))||(this.toggleScratchpad(),mxSettings.save())));this.addListener(\"formatWidthChanged\",function(){mxSettings.setFormatWidth(this.formatWidth);mxSettings.save()})}};EditorUi.prototype.copyImage=function(c,e,g){try{null!=navigator.clipboard&&this.spinner.spin(document.body,mxResources.get(\"exporting\"))&&\nthis.editor.exportToCanvas(mxUtils.bind(this,function(k,m){try{this.spinner.stop();var p=this.createImageDataUri(k,e,\"png\"),v=parseInt(m.getAttribute(\"width\")),x=parseInt(m.getAttribute(\"height\"));this.writeImageToClipboard(p,v,x,mxUtils.bind(this,function(z){this.handleError(z)}))}catch(z){this.handleError(z)}}),null,null,null,mxUtils.bind(this,function(k){this.spinner.stop();this.handleError(k)}),null,null,null!=g?g:4,null==this.editor.graph.background||this.editor.graph.background==mxConstants.NONE,\nnull,null,null,10,null,null,!1,null,0'],{type:\"text/html\"})});navigator.clipboard.write([c])[\"catch\"](k)};EditorUi.prototype.copyCells=function(c,e){var g=this.editor.graph;if(g.isSelectionEmpty())c.innerHTML=\"\";else{var k=", "label_name": "CWE-79", "label": 79} -{"code": "function(b,c){b=typeof c;\"function\"==b?c=mxStyleRegistry.getName(c):\"object\"==b&&(c=null);return c};a.decode=function(b,c,d){d=d||new this.template.constructor;var e=c.getAttribute(\"id\");null!=e&&(b.objects[e]=d);for(c=c.firstChild;null!=c;){if(!this.processInclude(b,c,d)&&\"add\"==c.nodeName&&(e=c.getAttribute(\"as\"),null!=e)){var f=c.getAttribute(\"extend\"),g=null!=f?mxUtils.clone(d.styles[f]):null;null==g&&(null!=f&&mxLog.warn(\"mxStylesheetCodec.decode: stylesheet \"+f+\" not found to extend\"),g={});\nfor(f=c.firstChild;null!=f;){if(f.nodeType==mxConstants.NODETYPE_ELEMENT){var k=f.getAttribute(\"as\");if(\"add\"==f.nodeName){var l=mxUtils.getTextContent(f);null!=l&&0';this.appendDropDownImageHtml(a);b=a.getElementsByTagName(\"div\")[0];b.style.marginLeft=g+\"px\";b.style.marginTop=e+\"px\";EditorUi.compactUi&&(a.getElementsByTagName(\"img\")[0].style.left=\"24px\",a.getElementsByTagName(\"img\")[0].style.top=\"5px\",a.style.width=\nf-10+\"px\")};Toolbar.prototype.setFontName=function(a){if(null!=this.fontMenu){this.fontMenu.innerHTML=\"\";var b=document.createElement(\"div\");b.style.display=\"inline-block\";b.style.overflow=\"hidden\";b.style.textOverflow=\"ellipsis\";b.style.maxWidth=\"66px\";mxUtils.write(b,a);this.fontMenu.appendChild(b);this.appendDropDownImageHtml(this.fontMenu)}};", "label_name": "CWE-79", "label": 79} -{"code": "for(ca=la=0;ca
    < '+mxResources.get(\"back\")+'
    '+", "label_name": "CWE-94", "label": 94} -{"code": "null,null,null,10,null,null,!1,null,0'],{type:\"text/html\"})});navigator.clipboard.write([c])[\"catch\"](k)};EditorUi.prototype.copyCells=function(c,e){var g=this.editor.graph;if(g.isSelectionEmpty())c.innerHTML=\"\";else{var k=\nmxUtils.sortCells(g.model.getTopmostCells(g.getSelectionCells())),m=mxUtils.getXml(g.encodeCells(k));mxUtils.setTextContent(c,encodeURIComponent(m));e?(g.removeCells(k,!1),g.lastPasteXml=null):(g.lastPasteXml=m,g.pasteCounter=0);c.focus();document.execCommand(\"selectAll\",!1,null)}};EditorUi.prototype.copyXml=function(){var c=null;if(Editor.enableNativeCipboard){var e=this.editor.graph;e.isSelectionEmpty()||(c=mxUtils.sortCells(e.getExportableCells(e.model.getTopmostCells(e.getSelectionCells()))),", "label_name": "CWE-94", "label": 94} -{"code": "mxCellEditor.prototype.installListeners=function(a){mxEvent.addListener(a,\"dragstart\",mxUtils.bind(this,function(d){this.graph.stopEditing(!1);mxEvent.consume(d)}));mxEvent.addListener(a,\"blur\",mxUtils.bind(this,function(d){this.blurEnabled&&this.focusLost(d)}));mxEvent.addListener(a,\"keydown\",mxUtils.bind(this,function(d){mxEvent.isConsumed(d)||(this.isStopEditingEvent(d)?(this.graph.stopEditing(!1),mxEvent.consume(d)):27==d.keyCode&&(this.graph.stopEditing(this.isCancelEditingKeyEvent(d)),mxEvent.consume(d)))}));\nvar b=mxUtils.bind(this,function(d){null!=this.editingCell&&this.clearOnChange&&a.innerHTML==this.getEmptyLabelText()&&(!mxClient.IS_FF||8!=d.keyCode&&46!=d.keyCode)&&(this.clearOnChange=!1,a.innerHTML=\"\")});mxEvent.addListener(a,\"keypress\",b);mxEvent.addListener(a,\"paste\",b);b=mxUtils.bind(this,function(d){null!=this.editingCell&&(0==this.textarea.innerHTML.length||\"
    \"==this.textarea.innerHTML?(this.textarea.innerHTML=this.getEmptyLabelText(),this.clearOnChange=0\nmxUtils.indexOf(k,b[D].nodeName)&&0E.name?1:0});for(D=0;D\"+n[D].name+\": \":\"\")+mxUtils.htmlEntities(n[D].value)+\"\\n\");0'+e+\"
    \"))}}return e};", "label_name": "CWE-79", "label": 79} -{"code": "this.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label_name": "CWE-94", "label": 94} -{"code": "this.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label_name": "CWE-94", "label": 94} -{"code": "c.value&&c.value.nodeType==mxConstants.NODETYPE_ELEMENT){var e=d;d=mxUtils.importNode(b.document,c.value,!0);d.appendChild(e);b=e.getAttribute(\"id\");d.setAttribute(\"id\",b);e.removeAttribute(\"id\")}return d};a.beforeDecode=function(b,c,d){var e=c.cloneNode(!0),f=this.getName();c.nodeName!=f?(e=c.getElementsByTagName(f)[0],null!=e&&e.parentNode==c?(mxUtils.removeWhitespace(e,!0),mxUtils.removeWhitespace(e,!1),e.parentNode.removeChild(e)):e=null,d.value=c.cloneNode(!0),c=d.value.getAttribute(\"id\"),null!=\nc&&(d.setId(c),d.value.removeAttribute(\"id\"))):d.setId(c.getAttribute(\"id\"));if(null!=e)for(c=0;c\");this.div.style.visibility=\"\";mxUtils.fit(this.div)}};", "label_name": "CWE-94", "label": 94} -{"code": "mxShape.prototype.clear=function(){if(null!=this.node.ownerSVGElement)for(;null!=this.node.lastChild;)this.node.removeChild(this.node.lastChild);else this.node.style.cssText=\"position:absolute;\"+(null!=this.cursor?\"cursor:\"+this.cursor+\";\":\"\"),this.node.innerHTML=\"\"};", "label_name": "CWE-94", "label": 94} -{"code": "X){null!=X.shortcut&&900>n&&!mxClient.IS_IOS?O.firstChild.nextSibling.setAttribute(\"title\",X.shortcut):m.apply(this,arguments)};var q=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){q.apply(this,arguments);if(null!=this.userElement){var O=this.userElement;O.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+O.style.display;O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=\"url(\"+Editor.userImage+\")\";O.style.backgroundPosition=\"center center\";\nO.style.backgroundRepeat=\"no-repeat\";O.style.backgroundSize=\"24px 24px\";O.style.height=\"24px\";O.style.width=\"24px\";O.style.cssFloat=\"right\";O.setAttribute(\"title\",mxResources.get(\"changeUser\"));if(\"none\"!=O.style.display){O.style.display=\"inline-block\";var X=this.getCurrentFile();if(null!=X&&X.isRealtimeEnabled()&&X.isRealtimeSupported()){var ea=document.createElement(\"img\");ea.setAttribute(\"border\",\"0\");ea.style.position=\"absolute\";ea.style.left=\"18px\";ea.style.top=\"2px\";ea.style.width=\"12px\";ea.style.height=\n\"12px\";var ka=X.getRealtimeError();X=X.getRealtimeState();var ja=mxResources.get(\"realtimeCollaboration\");1==X?(ea.src=Editor.syncImage,ja+=\" (\"+mxResources.get(\"online\")+\")\"):(ea.src=Editor.syncProblemImage,ja=null!=ka&&null!=ka.message?ja+(\" (\"+ka.message+\")\"):ja+(\" (\"+mxResources.get(\"disconnected\")+\")\"));ea.setAttribute(\"title\",ja);O.style.paddingRight=\"4px\";O.appendChild(ea)}}}};var y=App.prototype.updateButtonContainer;App.prototype.updateButtonContainer=function(){y.apply(this,arguments);if(null!=", "label_name": "CWE-94", "label": 94} -{"code": "Ra,\"geMenuItem\");null!=Na?(Ra.style.backgroundImage=\"url(\"+Na+\")\",Ra.style.backgroundPosition=\"center center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.backgroundSize=\"24px 24px\",Ra.style.width=\"34px\",Ra.innerHTML=\"\"):ya||(Ra.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",Ra.style.backgroundPosition=\"right 6px center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.paddingRight=\"22px\");return Ra}function X(ua,ya,Na,Fa,Ra,db){var Va=document.createElement(\"a\");Va.className=\n\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Va.style.display=\"inline-block\";Va.style.boxSizing=\"border-box\";Va.style.height=\"30px\";Va.style.padding=\"6px\";Va.style.position=\"relative\";Va.style.verticalAlign=\"top\";Va.style.top=\"0px\";\"1\"==urlParams.sketch&&(Va.style.borderStyle=\"none\",Va.style.boxShadow=\"none\",Va.style.padding=\"6px\",Va.style.margin=\"0px\");null!=U.statusContainer?V.insertBefore(Va,U.statusContainer):V.appendChild(Va);null!=db?(Va.style.backgroundImage=\"url(\"+db+\")\",Va.style.backgroundPosition=\n\"center center\",Va.style.backgroundRepeat=\"no-repeat\",Va.style.backgroundSize=\"24px 24px\",Va.style.width=\"34px\"):mxUtils.write(Va,ua);mxEvent.addListener(Va,mxClient.IS_POINTER?\"pointerdown\":\"mousedown\",mxUtils.bind(this,function(fb){fb.preventDefault()}));mxEvent.addListener(Va,\"click\",function(fb){\"disabled\"!=Va.getAttribute(\"disabled\")&&ya(fb);mxEvent.consume(fb)});null==Na&&(Va.style.marginRight=\"4px\");null!=Fa&&Va.setAttribute(\"title\",Fa);null!=Ra&&(ua=function(){Ra.isEnabled()?(Va.removeAttribute(\"disabled\"),\nVa.style.cursor=\"pointer\"):(Va.setAttribute(\"disabled\",\"disabled\"),Va.style.cursor=\"default\")},Ra.addListener(\"stateChanged\",ua),J.addListener(\"enabledChanged\",ua),ua());return Va}function ea(ua,ya,Na){Na=document.createElement(\"div\");Na.className=\"geMenuItem\";Na.style.display=\"inline-block\";Na.style.verticalAlign=\"top\";Na.style.marginRight=\"6px\";Na.style.padding=\"0 4px 0 4px\";Na.style.height=\"30px\";Na.style.position=\"relative\";Na.style.top=\"0px\";\"1\"==urlParams.sketch&&(Na.style.boxShadow=\"none\");", "label_name": "CWE-79", "label": 79} -{"code": "mxEvent.consume(ua))},Za=U.actions.get(\"zoomIn\"),cb=U.actions.get(\"zoomOut\"),Ja=U.actions.get(\"resetView\");Q=U.actions.get(\"fullscreen\");var Ua=U.actions.get(\"undo\"),$a=U.actions.get(\"redo\"),z=X(\"\",Ua.funct,null,mxResources.get(\"undo\")+\" (\"+Ua.shortcut+\")\",Ua,Editor.undoImage),L=X(\"\",$a.funct,null,mxResources.get(\"redo\")+\" (\"+$a.shortcut+\")\",$a,Editor.redoImage),M=X(\"\",Q.funct,null,mxResources.get(\"fullscreen\"),Q,Editor.fullscreenImage);if(null!=N){Ja=function(){ra.style.display=null!=U.pages&&(\"0\"!=\nurlParams.pages||1document.documentMode)?mxUtils.importNodeImplementation(a,b,c):a.importNode(b,c)},importNodeImplementation:function(a,b,c){switch(b.nodeType){case 1:var d=a.createElement(b.nodeName);if(b.attributes&&0 task._id),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n })\n })\n }\n }\n })", "label_name": "CWE-79", "label": 79} -{"code": " labels: templateInstance.topTasks.get().map((task) => task._id),", "label_name": "CWE-79", "label": 79} -{"code": " labels: templateInstance.topTasks.get().map((task) => task._id),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n }\n })\n })\n }\n }\n })", "label_name": "CWE-79", "label": 79} -{"code": " labels: templateInstance.topTasks.get().map((task) => task._id),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n }\n })\n })\n }\n }\n })", "label_name": "CWE-79", "label": 79} -{"code": " async function doIt() {\n await test.server.serverCertificateManager.trustCertificate(certificate);\n const issuerCertificateFile = m(\"CA/public/cacert.pem\");\n const issuerCertificateRevocationListFile = m(\"CA/crl/revocation_list.der\");\n const issuerCertificate = readCertificate(issuerCertificateFile);\n const issuerCrl = await readCertificateRevocationList(issuerCertificateRevocationListFile);\n await test.server.serverCertificateManager.addIssuer(issuerCertificate);\n await test.server.serverCertificateManager.addRevocationList(issuerCrl);\n callback();\n }", "label_name": "CWE-770", "label": 770} -{"code": "PostgreSQL.prototype.buildExpression = function(columnName, operator,\n operatorValue, propertyDefinition) {\n switch (operator) {\n case 'like':\n return new ParameterizedSQL(columnName + \"::TEXT LIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'ilike':\n return new ParameterizedSQL(columnName + \"::TEXT ILIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'nlike':\n return new ParameterizedSQL(columnName + \"::TEXT NOT LIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'nilike':\n return new ParameterizedSQL(columnName + \"::TEXT NOT ILIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'regexp':\n if (operatorValue.global)\n g.warn('{{PostgreSQL}} regex syntax does not respect the {{`g`}} flag');\n\n if (operatorValue.multiline)\n g.warn('{{PostgreSQL}} regex syntax does not respect the {{`m`}} flag');\n\n const regexOperator = operatorValue.ignoreCase ? ' ~* ?' : ' ~ ?';\n return new ParameterizedSQL(columnName + regexOperator,\n [operatorValue.source]);\n case 'contains':\n return new ParameterizedSQL(columnName + ' @> array[' + operatorValue.map((v) => `'${v}'`) + ']::'\n + propertyDefinition.postgresql.dataType);\n case 'match':\n return new ParameterizedSQL(`to_tsvector(${columnName}) @@ to_tsquery('${operatorValue}')`);\n default:\n // invoke the base implementation of `buildExpression`\n return this.invokeSuper('buildExpression', columnName, operator,\n operatorValue, propertyDefinition);\n }\n};", "label_name": "CWE-89", "label": 89} -{"code": "spnego_gss_set_sec_context_option(\n\t\tOM_uint32 *minor_status,\n\t\tgss_ctx_id_t *context_handle,\n\t\tconst gss_OID desired_object,\n\t\tconst gss_buffer_t value)\n{\n\tOM_uint32 ret;\n\tret = gss_set_sec_context_option(minor_status,\n\t\t\t context_handle,\n\t\t\t desired_object,\n\t\t\t value);\n\treturn (ret);\n}", "label_name": "CWE-763", "label": 763} -{"code": "setv4key_principal_2_svc(setv4key_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n\n if (!(CHANGEPW_SERVICE(rqstp)) &&\n kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_SETKEY, arg->princ, NULL)) {\n ret.code = kadm5_setv4key_principal((void *)handle, arg->princ,\n arg->keyblock);\n } else {\n log_unauth(\"kadm5_setv4key_principal\", prime_arg,\n &client_name, &service_name, rqstp);\n ret.code = KADM5_AUTH_SETKEY;\n }\n\n if(ret.code != KADM5_AUTH_SETKEY) {\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_setv4key_principal\", prime_arg, errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n\n free(prime_arg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n}", "label_name": "CWE-772", "label": 772} -{"code": "xfs_acl_from_disk(struct xfs_acl *aclp)\n{\n\tstruct posix_acl_entry *acl_e;\n\tstruct posix_acl *acl;\n\tstruct xfs_acl_entry *ace;\n\tint count, i;\n\n\tcount = be32_to_cpu(aclp->acl_cnt);\n\tif (count > XFS_ACL_MAX_ENTRIES)\n\t\treturn ERR_PTR(-EFSCORRUPTED);\n\n\tacl = posix_acl_alloc(count, GFP_KERNEL);\n\tif (!acl)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tfor (i = 0; i < count; i++) {\n\t\tacl_e = &acl->a_entries[i];\n\t\tace = &aclp->acl_entry[i];\n\n\t\t/*\n\t\t * The tag is 32 bits on disk and 16 bits in core.\n\t\t *\n\t\t * Because every access to it goes through the core\n\t\t * format first this is not a problem.\n\t\t */\n\t\tacl_e->e_tag = be32_to_cpu(ace->ae_tag);\n\t\tacl_e->e_perm = be16_to_cpu(ace->ae_perm);\n\n\t\tswitch (acl_e->e_tag) {\n\t\tcase ACL_USER:\n\t\tcase ACL_GROUP:\n\t\t\tacl_e->e_id = be32_to_cpu(ace->ae_id);\n\t\t\tbreak;\n\t\tcase ACL_USER_OBJ:\n\t\tcase ACL_GROUP_OBJ:\n\t\tcase ACL_MASK:\n\t\tcase ACL_OTHER:\n\t\t\tacl_e->e_id = ACL_UNDEFINED_ID;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto fail;\n\t\t}\n\t}\n\treturn acl;\n\nfail:\n\tposix_acl_release(acl);\n\treturn ERR_PTR(-EINVAL);\n}", "label_name": "CWE-190", "label": 190} -{"code": "static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,\n\tstruct cftype *cft, struct eventfd_ctx *eventfd)\n{\n\tstruct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);\n\tstruct mem_cgroup_thresholds *thresholds;\n\tstruct mem_cgroup_threshold_ary *new;\n\tint type = MEMFILE_TYPE(cft->private);\n\tu64 usage;\n\tint i, j, size;\n\n\tmutex_lock(&memcg->thresholds_lock);\n\tif (type == _MEM)\n\t\tthresholds = &memcg->thresholds;\n\telse if (type == _MEMSWAP)\n\t\tthresholds = &memcg->memsw_thresholds;\n\telse\n\t\tBUG();\n\n\t/*\n\t * Something went wrong if we trying to unregister a threshold\n\t * if we don't have thresholds\n\t */\n\tBUG_ON(!thresholds);\n\n\tusage = mem_cgroup_usage(memcg, type == _MEMSWAP);\n\n\t/* Check if a threshold crossed before removing */\n\t__mem_cgroup_threshold(memcg, type == _MEMSWAP);\n\n\t/* Calculate new number of threshold */\n\tsize = 0;\n\tfor (i = 0; i < thresholds->primary->size; i++) {\n\t\tif (thresholds->primary->entries[i].eventfd != eventfd)\n\t\t\tsize++;\n\t}\n\n\tnew = thresholds->spare;\n\n\t/* Set thresholds array to NULL if we don't have thresholds */\n\tif (!size) {\n\t\tkfree(new);\n\t\tnew = NULL;\n\t\tgoto swap_buffers;\n\t}\n\n\tnew->size = size;\n\n\t/* Copy thresholds and find current threshold */\n\tnew->current_threshold = -1;\n\tfor (i = 0, j = 0; i < thresholds->primary->size; i++) {\n\t\tif (thresholds->primary->entries[i].eventfd == eventfd)\n\t\t\tcontinue;\n\n\t\tnew->entries[j] = thresholds->primary->entries[i];\n\t\tif (new->entries[j].threshold < usage) {\n\t\t\t/*\n\t\t\t * new->current_threshold will not be used\n\t\t\t * until rcu_assign_pointer(), so it's safe to increment\n\t\t\t * it here.\n\t\t\t */\n\t\t\t++new->current_threshold;\n\t\t}\n\t\tj++;\n\t}\n\nswap_buffers:\n\t/* Swap primary and spare array */\n\tthresholds->spare = thresholds->primary;\n\trcu_assign_pointer(thresholds->primary, new);\n\n\t/* To be sure that nobody uses thresholds */\n\tsynchronize_rcu();\n\n\tmutex_unlock(&memcg->thresholds_lock);\n}", "label_name": "CWE-476", "label": 476} -{"code": "static int __init big_key_init(void)\n{\n\treturn register_key_type(&key_type_big_key);\n}", "label_name": "CWE-476", "label": 476} -{"code": "static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)\n{\n\tioapic->rtc_status.pending_eoi = 0;\n\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);\n}", "label_name": "CWE-125", "label": 125} -{"code": "int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user)\n{\n\tstruct net_device *dev = skb->dev;\n\tint fhoff, nhoff, ret;\n\tstruct frag_hdr *fhdr;\n\tstruct frag_queue *fq;\n\tstruct ipv6hdr *hdr;\n\tu8 prevhdr;\n\n\t/* Jumbo payload inhibits frag. header */\n\tif (ipv6_hdr(skb)->payload_len == 0) {\n\t\tpr_debug(\"payload len = 0\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0)\n\t\treturn -EINVAL;\n\n\tif (!pskb_may_pull(skb, fhoff + sizeof(*fhdr)))\n\t\treturn -ENOMEM;\n\n\tskb_set_transport_header(skb, fhoff);\n\thdr = ipv6_hdr(skb);\n\tfhdr = (struct frag_hdr *)skb_transport_header(skb);\n\n\tfq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr,\n\t\t skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr));\n\tif (fq == NULL) {\n\t\tpr_debug(\"Can't find and can't create new queue\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tspin_lock_bh(&fq->q.lock);\n\n\tif (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) {\n\t\tret = -EINVAL;\n\t\tgoto out_unlock;\n\t}\n\n\t/* after queue has assumed skb ownership, only 0 or -EINPROGRESS\n\t * must be returned.\n\t */\n\tret = -EINPROGRESS;\n\tif (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&\n\t fq->q.meat == fq->q.len &&\n\t nf_ct_frag6_reasm(fq, skb, dev))\n\t\tret = 0;\n\nout_unlock:\n\tspin_unlock_bh(&fq->q.lock);\n\tinet_frag_put(&fq->q, &nf_frags);\n\treturn ret;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static inline void mcryptd_check_internal(struct rtattr **tb, u32 *type,\n\t\t\t\t\t u32 *mask)\n{\n\tstruct crypto_attr_type *algt;\n\n\talgt = crypto_get_attr_type(tb);\n\tif (IS_ERR(algt))\n\t\treturn;\n\tif ((algt->type & CRYPTO_ALG_INTERNAL))\n\t\t*type |= CRYPTO_ALG_INTERNAL;\n\tif ((algt->mask & CRYPTO_ALG_INTERNAL))\n\t\t*mask |= CRYPTO_ALG_INTERNAL;\n}", "label_name": "CWE-476", "label": 476} -{"code": "int fscrypt_get_encryption_info(struct inode *inode)\n{\n\tstruct fscrypt_info *ci = inode->i_crypt_info;\n\n\tif (!ci ||\n\t\t(ci->ci_keyring_key &&\n\t\t (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) |\n\t\t\t\t\t (1 << KEY_FLAG_REVOKED) |\n\t\t\t\t\t (1 << KEY_FLAG_DEAD)))))\n\t\treturn fscrypt_get_crypt_info(inode);\n\treturn 0;\n}", "label_name": "CWE-476", "label": 476} -{"code": "\nvoid skb_complete_tx_timestamp(struct sk_buff *skb,\n\t\t\t struct skb_shared_hwtstamps *hwtstamps)\n{\n\tstruct sock *sk = skb->sk;\n\n\tif (!skb_may_tx_timestamp(sk, false))\n\t\treturn;\n\n\t/* Take a reference to prevent skb_orphan() from freeing the socket,\n\t * but only if the socket refcount is not zero.\n\t */\n\tif (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {\n\t\t*skb_hwtstamps(skb) = *hwtstamps;\n\t\t__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);\n\t\tsock_put(sk);\n\t}", "label_name": "CWE-125", "label": 125} -{"code": "void snd_msndmidi_input_read(void *mpuv)\n{\n\tunsigned long flags;\n\tstruct snd_msndmidi *mpu = mpuv;\n\tvoid *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF;\n\n\tspin_lock_irqsave(&mpu->input_lock, flags);\n\twhile (readw(mpu->dev->MIDQ + JQS_wTail) !=\n\t readw(mpu->dev->MIDQ + JQS_wHead)) {\n\t\tu16 wTmp, val;\n\t\tval = readw(pwMIDQData + 2 * readw(mpu->dev->MIDQ + JQS_wHead));\n\n\t\t\tif (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER,\n\t\t\t\t &mpu->mode))\n\t\t\t\tsnd_rawmidi_receive(mpu->substream_input,\n\t\t\t\t\t\t (unsigned char *)&val, 1);\n\n\t\twTmp = readw(mpu->dev->MIDQ + JQS_wHead) + 1;\n\t\tif (wTmp > readw(mpu->dev->MIDQ + JQS_wSize))\n\t\t\twritew(0, mpu->dev->MIDQ + JQS_wHead);\n\t\telse\n\t\t\twritew(wTmp, mpu->dev->MIDQ + JQS_wHead);\n\t}\n\tspin_unlock_irqrestore(&mpu->input_lock, flags);\n}", "label_name": "CWE-125", "label": 125} -{"code": "static int uas_switch_interface(struct usb_device *udev,\n\t\t\t\tstruct usb_interface *intf)\n{\n\tint alt;\n\n\talt = uas_find_uas_alt_setting(intf);\n\tif (alt < 0)\n\t\treturn alt;\n\n\treturn usb_set_interface(udev,\n\t\t\tintf->altsetting[0].desc.bInterfaceNumber, alt);\n}", "label_name": "CWE-125", "label": 125} -{"code": "static ssize_t o2nm_node_ipv4_address_store(struct config_item *item,\n\t\t\t\t\t const char *page,\n\t\t\t\t\t size_t count)\n{\n\tstruct o2nm_node *node = to_o2nm_node(item);\n\tstruct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);\n\tint ret, i;\n\tstruct rb_node **p, *parent;\n\tunsigned int octets[4];\n\t__be32 ipv4_addr = 0;\n\n\tret = sscanf(page, \"%3u.%3u.%3u.%3u\", &octets[3], &octets[2],\n\t\t &octets[1], &octets[0]);\n\tif (ret != 4)\n\t\treturn -EINVAL;\n\n\tfor (i = 0; i < ARRAY_SIZE(octets); i++) {\n\t\tif (octets[i] > 255)\n\t\t\treturn -ERANGE;\n\t\tbe32_add_cpu(&ipv4_addr, octets[i] << (i * 8));\n\t}\n\n\tret = 0;\n\twrite_lock(&cluster->cl_nodes_lock);\n\tif (o2nm_node_ip_tree_lookup(cluster, ipv4_addr, &p, &parent))\n\t\tret = -EEXIST;\n\telse if (test_and_set_bit(O2NM_NODE_ATTR_ADDRESS,\n\t\t\t&node->nd_set_attributes))\n\t\tret = -EBUSY;\n\telse {\n\t\trb_link_node(&node->nd_ip_node, parent, p);\n\t\trb_insert_color(&node->nd_ip_node, &cluster->cl_node_ip_tree);\n\t}\n\twrite_unlock(&cluster->cl_nodes_lock);\n\tif (ret)\n\t\treturn ret;\n\n\tmemcpy(&node->nd_ipv4_address, &ipv4_addr, sizeof(ipv4_addr));\n\n\treturn count;\n}", "label_name": "CWE-476", "label": 476} -{"code": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu->flags & PPMU_P10_DD1) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "label_name": "CWE-476", "label": 476} -{"code": "static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret)\n{\n\tstruct trace_array *tr = data;\n\tstruct ftrace_event_file *ftrace_file;\n\tstruct syscall_trace_exit *entry;\n\tstruct syscall_metadata *sys_data;\n\tstruct ring_buffer_event *event;\n\tstruct ring_buffer *buffer;\n\tunsigned long irq_flags;\n\tint pc;\n\tint syscall_nr;\n\n\tsyscall_nr = trace_get_syscall_nr(current, regs);\n\tif (syscall_nr < 0)\n\t\treturn;\n\n\t/* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE()) */\n\tftrace_file = rcu_dereference_sched(tr->exit_syscall_files[syscall_nr]);\n\tif (!ftrace_file)\n\t\treturn;\n\n\tif (ftrace_trigger_soft_disabled(ftrace_file))\n\t\treturn;\n\n\tsys_data = syscall_nr_to_meta(syscall_nr);\n\tif (!sys_data)\n\t\treturn;\n\n\tlocal_save_flags(irq_flags);\n\tpc = preempt_count();\n\n\tbuffer = tr->trace_buffer.buffer;\n\tevent = trace_buffer_lock_reserve(buffer,\n\t\t\tsys_data->exit_event->event.type, sizeof(*entry),\n\t\t\tirq_flags, pc);\n\tif (!event)\n\t\treturn;\n\n\tentry = ring_buffer_event_data(event);\n\tentry->nr = syscall_nr;\n\tentry->ret = syscall_get_return_value(current, regs);\n\n\tevent_trigger_unlock_commit(ftrace_file, buffer, event, entry,\n\t\t\t\t irq_flags, pc);\n}", "label_name": "CWE-476", "label": 476} -{"code": "static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,\n\t\t u8 *dst, unsigned int dlen)\n{\n\treturn crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen);\n}", "label_name": "CWE-476", "label": 476} -{"code": "static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tstruct ahash_request *req = &ctx->req;\n\tchar state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];\n\tstruct sock *sk2;\n\tstruct alg_sock *ask2;\n\tstruct hash_ctx *ctx2;\n\tint err;\n\n\terr = crypto_ahash_export(req, state);\n\tif (err)\n\t\treturn err;\n\n\terr = af_alg_accept(ask->parent, newsock);\n\tif (err)\n\t\treturn err;\n\n\tsk2 = newsock->sk;\n\task2 = alg_sk(sk2);\n\tctx2 = ask2->private;\n\tctx2->more = 1;\n\n\terr = crypto_ahash_import(&ctx2->req, state);\n\tif (err) {\n\t\tsock_orphan(sk2);\n\t\tsock_put(sk2);\n\t}\n\n\treturn err;\n}", "label_name": "CWE-476", "label": 476} -{"code": "struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,\n\t\t\t\t const struct bpf_insn *patch, u32 len)\n{\n\tu32 insn_adj_cnt, insn_rest, insn_delta = len - 1;\n\tstruct bpf_prog *prog_adj;\n\n\t/* Since our patchlet doesn't expand the image, we're done. */\n\tif (insn_delta == 0) {\n\t\tmemcpy(prog->insnsi + off, patch, sizeof(*patch));\n\t\treturn prog;\n\t}\n\n\tinsn_adj_cnt = prog->len + insn_delta;\n\n\t/* Several new instructions need to be inserted. Make room\n\t * for them. Likely, there's no need for a new allocation as\n\t * last page could have large enough tailroom.\n\t */\n\tprog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),\n\t\t\t\t GFP_USER);\n\tif (!prog_adj)\n\t\treturn NULL;\n\n\tprog_adj->len = insn_adj_cnt;\n\n\t/* Patching happens in 3 steps:\n\t *\n\t * 1) Move over tail of insnsi from next instruction onwards,\n\t * so we can patch the single target insn with one or more\n\t * new ones (patching is always from 1 to n insns, n > 0).\n\t * 2) Inject new instructions at the target location.\n\t * 3) Adjust branch offsets if necessary.\n\t */\n\tinsn_rest = insn_adj_cnt - off - len;\n\n\tmemmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,\n\t\tsizeof(*patch) * insn_rest);\n\tmemcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);\n\n\tbpf_adj_branches(prog_adj, off, insn_delta);\n\n\treturn prog_adj;\n}", "label_name": "CWE-120", "label": 120} -{"code": "static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)\n{\n\tif (cfs_rq->load.weight)\n\t\treturn false;\n\n\tif (cfs_rq->avg.load_sum)\n\t\treturn false;\n\n\tif (cfs_rq->avg.util_sum)\n\t\treturn false;\n\n\tif (cfs_rq->avg.runnable_load_sum)\n\t\treturn false;\n\n\treturn true;\n}", "label_name": "CWE-835", "label": 835} -{"code": "struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,\n\t\t\t\t u64 devid, u8 *uuid, u8 *fsid)\n{\n\tstruct btrfs_device *device;\n\n\twhile (fs_devices) {\n\t\tif (!fsid ||\n\t\t !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {\n\t\t\tdevice = find_device(fs_devices, devid, uuid);\n\t\t\tif (device)\n\t\t\t\treturn device;\n\t\t}\n\t\tfs_devices = fs_devices->seed;\n\t}\n\treturn NULL;\n}", "label_name": "CWE-476", "label": 476} -{"code": "int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,\n size_t size)\n{\n GetBitContext gb;\n AC3HeaderInfo *hdr;\n int err;\n\n if (!*phdr)\n *phdr = av_mallocz(sizeof(AC3HeaderInfo));\n if (!*phdr)\n return AVERROR(ENOMEM);\n hdr = *phdr;\n\n init_get_bits8(&gb, buf, size);\n err = ff_ac3_parse_header(&gb, hdr);\n if (err < 0)\n return AVERROR_INVALIDDATA;\n\n return get_bits_count(&gb);\n}", "label_name": "CWE-476", "label": 476} -{"code": "static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)\n{\n /* MPEG-4 Studio Profile only, not supported by hardware */\n if (avctx->bits_per_raw_sample > 8) {\n av_assert1(avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);\n return avctx->pix_fmt;\n }\n\n if (avctx->codec->id == AV_CODEC_ID_MSS2)\n return AV_PIX_FMT_YUV420P;\n\n if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {\n if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)\n avctx->color_range = AVCOL_RANGE_MPEG;\n return AV_PIX_FMT_GRAY8;\n }\n\n return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);\n}", "label_name": "CWE-617", "label": 617} -{"code": "atol8(const char *p, size_t char_cnt)\n{\n\tint64_t l;\n\tint digit;\n \n\tl = 0;\n\twhile (char_cnt-- > 0) {\n\t\tif (*p >= '0' && *p <= '7')\n\t\t\tdigit = *p - '0';\n\t\telse\n\t\t\tbreak;\n\t\tp++;\n\t\tl <<= 3;\n\t\tl |= digit;\n\t}\n\treturn (l);\n}", "label_name": "CWE-125", "label": 125} -{"code": "archive_write_disk_set_acls(struct archive *a, int fd, const char *name,\n struct archive_acl *abstract_acl, __LA_MODE_T mode)\n{\n\tint\t\tret = ARCHIVE_OK;\n\n#if !ARCHIVE_ACL_LIBRICHACL\n\t(void)mode;\t/* UNUSED */\n#endif\n\n#if ARCHIVE_ACL_LIBRICHACL\n\tif ((archive_acl_types(abstract_acl)\n\t & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {\n\t\tret = set_richacl(a, fd, name, abstract_acl, mode,\n\t\t ARCHIVE_ENTRY_ACL_TYPE_NFS4, \"nfs4\");\n\t}\n#if ARCHIVE_ACL_LIBACL\n\telse\n#endif\n#endif\t/* ARCHIVE_ACL_LIBRICHACL */\n#if ARCHIVE_ACL_LIBACL\n\tif ((archive_acl_types(abstract_acl)\n\t & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {\n\t\tif ((archive_acl_types(abstract_acl)\n\t\t & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {\n\t\t\tret = set_acl(a, fd, name, abstract_acl,\n\t\t\t ARCHIVE_ENTRY_ACL_TYPE_ACCESS, \"access\");\n\t\t\tif (ret != ARCHIVE_OK)\n\t\t\t\treturn (ret);\n\t\t}\n\t\tif ((archive_acl_types(abstract_acl)\n\t\t & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)\n\t\t\tret = set_acl(a, fd, name, abstract_acl,\n\t\t\t ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, \"default\");\n\t}\n#endif\t/* ARCHIVE_ACL_LIBACL */\n\treturn (ret);\n}", "label_name": "CWE-59", "label": 59} -{"code": "static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */\n{\n\tva_list va;\n\tchar *message = NULL;\n\n\tva_start(va, format);\n\tzend_vspprintf(&message, 0, format, va);\n\n\tif (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {\n\t\tzend_throw_error(exception_ce, message);\n\t} else {\n\t\tzend_error(E_ERROR, \"%s\", message);\n\t}\n\n\tefree(message);\n\tva_end(va);\n}", "label_name": "CWE-134", "label": 134} -{"code": "PHP_FUNCTION(locale_get_all_variants)\n{\n\tconst char* \tloc_name = NULL;\n\tint \t\tloc_name_len = 0;\n\n\tint\tresult\t\t= 0;\n\tchar*\ttoken\t\t= NULL;\n\tchar*\tvariant\t\t= NULL;\n\tchar*\tsaved_ptr\t= NULL;\n\n\tintl_error_reset( NULL TSRMLS_CC );\n\t\n\tif(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t&loc_name, &loc_name_len ) == FAILURE)\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t \"locale_parse: unable to parse input params\", 0 TSRMLS_CC );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tif(loc_name_len == 0) {\n\t\tloc_name = intl_locale_get_default(TSRMLS_C);\n\t}\n\n\n\tarray_init( return_value );\n\n\t/* If the locale is grandfathered, stop, no variants */\n\tif( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){ \n\t\t/* (\"Grandfathered Tag. No variants.\"); */\n\t}\n\telse {\t\n\t/* Call ICU variant */\n\t\tvariant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0);\n\t\tif( result > 0 && variant){\n\t\t\t/* Tokenize on the \"_\" or \"-\" */\n\t\t\ttoken = php_strtok_r( variant , DELIMITER , &saved_ptr);\t\n\t\t\tadd_next_index_stringl( return_value, token , strlen(token) ,TRUE );\n\t\t\t/* tokenize on the \"_\" or \"-\" and stop at singleton if any\t*/\n\t\t\twhile( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){\n \t\t\t\tadd_next_index_stringl( return_value, token , strlen(token) ,TRUE );\n\t\t\t}\n\t\t}\n\t\tif( variant ){\n\t\t\tefree( variant );\n\t\t}\n\t}\n\t\t\t\n\n}", "label_name": "CWE-125", "label": 125} -{"code": "static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)\n{\n\tzval**\tele_value\t= NULL;\n\n\tif(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {\n\t\tif(Z_TYPE_PP(ele_value)!= IS_STRING ){\n\t\t\t/* element value is not a string */\n\t\t\treturn FAILURE;\n\t\t}\n\t\tif(strcmp(key_name, LOC_LANG_TAG) != 0 && \n\t\t strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {\n\t\t\t/* not lang or grandfathered tag */\n\t\t\tsmart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);\n\t\t}\n\t\tsmart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));\n\t\treturn SUCCESS;\n\t}\n\n\treturn LOC_NOT_FOUND;\n}", "label_name": "CWE-125", "label": 125} -{"code": "SPL_METHOD(SplFileObject, getCsvControl)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar delimiter[2], enclosure[2];\n\n\tarray_init(return_value);\n\t\n\tdelimiter[0] = intern->u.file.delimiter;\n\tdelimiter[1] = '\\0';\n\tenclosure[0] = intern->u.file.enclosure;\n\tenclosure[1] = '\\0';\n\n\tadd_next_index_string(return_value, delimiter, 1);\n\tadd_next_index_string(return_value, enclosure, 1);\n}", "label_name": "CWE-190", "label": 190} -{"code": "SPL_METHOD(SplFileInfo, getLinkTarget)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tint ret;\n\tchar buff[MAXPATHLEN];\n\tzend_error_handling error_handling;\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tzend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\n\n#if defined(PHP_WIN32) || HAVE_SYMLINK\n\tif (intern->file_name == NULL) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Empty filename\");\n\t\tRETURN_FALSE;\n\t} else if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) {\n\t\tchar expanded_path[MAXPATHLEN];\n\t\tif (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"No such file or directory\");\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1);\n\t} else {\n\t\tret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1);\n\t}\n#else\n\tret = -1; /* always fail if not implemented */\n#endif\n\n\tif (ret == -1) {\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Unable to read link %s, error: %s\", intern->file_name, strerror(errno));\n\t\tRETVAL_FALSE;\n\t} else {\n\t\t/* Append NULL to the end of the string */\n\t\tbuff[ret] = '\\0';\n\n\t\tRETVAL_STRINGL(buff, ret, 1);\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n}", "label_name": "CWE-190", "label": 190} -{"code": "SPL_METHOD(SplFileObject, next)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tspl_filesystem_file_free_line(intern TSRMLS_CC);\n\tif (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {\n\t\tspl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);\n\t}\n\tintern->u.file.current_line_num++;\n} /* }}} */", "label_name": "CWE-190", "label": 190} -{"code": "static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */\n{\n\tint ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);\n\n\twhile (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) {\n\t\tspl_filesystem_file_free_line(intern TSRMLS_CC);\n\t\tret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);\n\t}\n\t\n\treturn ret;\n}", "label_name": "CWE-190", "label": 190} -{"code": "SPL_METHOD(SplFileObject, current)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!intern->u.file.current_line && !intern->u.file.current_zval) {\n\t\tspl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);\n\t}\n\tif (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) {\n\t\tRETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);\n\t} else if (intern->u.file.current_zval) {\n\t\tRETURN_ZVAL(intern->u.file.current_zval, 1, 0);\n\t}\n\tRETURN_FALSE;\n} /* }}} */", "label_name": "CWE-190", "label": 190} -{"code": "SPL_METHOD(SplFileObject, hasChildren)\n{\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tRETURN_FALSE;\n} /* }}} */", "label_name": "CWE-190", "label": 190} -{"code": "SPL_METHOD(FilesystemIterator, getFlags)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tRETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));\n} /* }}} */", "label_name": "CWE-190", "label": 190} -{"code": "static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)\n{\n\tspl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;\n\tspl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);\n\t\n\tobject->u.dir.index++;\n\tdo {\n\t\tspl_filesystem_dir_read(object TSRMLS_CC);\n\t} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));\n\tif (object->file_name) {\n\t\tefree(object->file_name);\n\t\tobject->file_name = NULL;\n\t}\n\tif (iterator->current) {\n\t\tzval_ptr_dtor(&iterator->current);\n\t\titerator->current = NULL;\n\t}\n}", "label_name": "CWE-190", "label": 190} -{"code": "SPL_METHOD(SplFileObject, fgetcsv)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape;\n\tchar *delim = NULL, *enclo = NULL, *esc = NULL;\n\tint d_len = 0, e_len = 0, esc_len = 0;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|sss\", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {\n\t\tswitch(ZEND_NUM_ARGS())\n\t\t{\n\t\tcase 3:\n\t\t\tif (esc_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"escape must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tescape = esc[0];\n\t\t\t/* no break */\n\t\tcase 2:\n\t\t\tif (e_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"enclosure must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tenclosure = enclo[0];\n\t\t\t/* no break */\n\t\tcase 1:\n\t\t\tif (d_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"delimiter must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tdelimiter = delim[0];\n\t\t\t/* no break */\n\t\tcase 0:\n\t\t\tbreak;\n\t\t}\n\t\tspl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC);\n\t}\n}", "label_name": "CWE-190", "label": 190} -{"code": "zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */\n{\n\tspl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC);\n\t\n\tif (fsobj->u.dir.entry.d_name[0] == '\\0' && fsobj->orig_path == NULL) {\n\t\tmethod = \"_bad_state_ex\";\n\t\tmethod_len = sizeof(\"_bad_state_ex\") - 1;\n\t\tkey = NULL;\n\t}\n\t\n\treturn zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC);\n}", "label_name": "CWE-190", "label": 190} -{"code": "static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)\n{\n\tlong elements;\n\n\telements = parse_iv2((*p) + 2, p);\n\n\t(*p) += 2;\n\n\tif (ce->serialize == NULL) {\n\t\tobject_init_ex(*rval, ce);\n\t} else {\n\t\t/* If this class implements Serializable, it should not land here but in object_custom(). The passed string\n\t\tobviously doesn't descend from the regular serializer. */\n\t\tzend_error(E_WARNING, \"Erroneous data format for unserializing '%s'\", ce->name);\n\t\treturn 0;\n\t}\n\n\treturn elements;\n}", "label_name": "CWE-125", "label": 125} -{"code": "ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)\n{\n\tGC_REFCOUNT(ht) = 1;\n\tGC_TYPE_INFO(ht) = IS_ARRAY;\n\tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n\tht->nTableSize = zend_hash_check_size(nSize);\n\tht->nTableMask = HT_MIN_MASK;\n\tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n\tht->nNumUsed = 0;\n\tht->nNumOfElements = 0;\n\tht->nInternalPointer = HT_INVALID_IDX;\n\tht->nNextFreeElement = 0;\n\tht->pDestructor = pDestructor;\n}", "label_name": "CWE-190", "label": 190} -{"code": "static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\tDWORD nbWritten = 0;\n\n\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;\n\n\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */\n\t/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored\n\t * assert(Offset == 0);\n\t *\n\t * Using a serial printer, noticed though this field could be\n\t * set.\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"writing %\" PRIu32 \" bytes to %s\", Length,\n\t serial->device.name);\n\n\t/* FIXME: CommWriteFile to be replaced by WriteFile */\n\tif (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL))\n\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"write failure to %s, nbWritten=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbWritten, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}\n\n\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes written to %s\", nbWritten,\n\t serial->device.name);\n\tStream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "label_name": "CWE-125", "label": 125} -{"code": "BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)\n{\n\trdpGlyph* prevGlyph;\n\n\tif (id > 9)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache id: %\" PRIu32 \"\", id);\n\t\treturn FALSE;\n\t}\n\n\tif (index > glyphCache->glyphCache[id].number)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache index: %\" PRIu32 \" in cache id: %\" PRIu32 \"\", index, id);\n\t\treturn FALSE;\n\t}\n\n\tWLog_Print(glyphCache->log, WLOG_DEBUG, \"GlyphCachePut: id: %\" PRIu32 \" index: %\" PRIu32 \"\", id,\n\t index);\n\tprevGlyph = glyphCache->glyphCache[id].entries[index];\n\n\tif (prevGlyph)\n\t\tprevGlyph->Free(glyphCache->context, prevGlyph);\n\n\tglyphCache->glyphCache[id].entries[index] = glyph;\n\treturn TRUE;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision),\n trio_class_t* self, TRIO_CONST char* string,\n trio_flags_t flags, int width, int precision)\n{\n\tint length;\n\tint ch;\n\n\tassert(VALID(self));\n\tassert(VALID(self->OutStream));\n\n\tif (string == NULL)\n\t{\n\t\tstring = internalNullString;\n\t\tlength = sizeof(internalNullString) - 1;\n#if TRIO_FEATURE_QUOTE\n\t\t/* Disable quoting for the null pointer */\n\t\tflags &= (~FLAGS_QUOTE);\n#endif\n\t\twidth = 0;\n\t}\n\telse\n\t{\n\t\tif (precision == 0)\n\t\t{\n\t\t\tlength = trio_length(string);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlength = trio_length_max(string, precision);\n\t\t}\n\t}\n\tif ((NO_PRECISION != precision) && (precision < length))\n\t{\n\t\tlength = precision;\n\t}\n\twidth -= length;\n\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n\n\tif (!(flags & FLAGS_LEFTADJUST))\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n\n\twhile (length-- > 0)\n\t{\n\t\t/* The ctype parameters must be an unsigned char (or EOF) */\n\t\tch = (int)((unsigned char)(*string++));\n\t\tTrioWriteStringCharacter(self, ch, flags);\n\t}\n\n\tif (flags & FLAGS_LEFTADJUST)\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n}", "label_name": "CWE-190", "label": 190} -{"code": "TRIO_PUBLIC_STRING size_t trio_length TRIO_ARGS1((string), TRIO_CONST char* string)\n{\n\treturn strlen(string);\n}", "label_name": "CWE-190", "label": 190} -{"code": "int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (fields->Len > 0)\n\t{\n\t\tif ((fields->BufferOffset + fields->Len) > Stream_Length(s))\n\t\t\treturn -1;\n\n\t\tfields->Buffer = (PBYTE) malloc(fields->Len);\n\n\t\tif (!fields->Buffer)\n\t\t\treturn -1;\n\n\t\tStream_SetPosition(s, fields->BufferOffset);\n\t\tStream_Read(s, fields->Buffer, fields->Len);\n\t}\n\n\treturn 1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,\n UINT32 width, UINT32 height,\n const BYTE* data, UINT32 length,\n BYTE* pDstData, UINT32 DstFormat,\n UINT32 nDstStride,\n UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,\n UINT32 nHeight, UINT32 flip)\n{\n\twStream* s;\n\tBOOL ret;\n\ts = Stream_New((BYTE*)data, length);\n\n\tif (!s)\n\t\treturn FALSE;\n\n\tif (nDstStride == 0)\n\t\tnDstStride = nWidth * GetBytesPerPixel(DstFormat);\n\n\tswitch (bpp)\n\t{\n\t\tcase 32:\n\t\t\tcontext->format = PIXEL_FORMAT_BGRA32;\n\t\t\tbreak;\n\n\t\tcase 24:\n\t\t\tcontext->format = PIXEL_FORMAT_BGR24;\n\t\t\tbreak;\n\n\t\tcase 16:\n\t\t\tcontext->format = PIXEL_FORMAT_BGR16;\n\t\t\tbreak;\n\n\t\tcase 8:\n\t\t\tcontext->format = PIXEL_FORMAT_RGB8;\n\t\t\tbreak;\n\n\t\tcase 4:\n\t\t\tcontext->format = PIXEL_FORMAT_A4;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tStream_Free(s, TRUE);\n\t\t\treturn FALSE;\n\t}\n\n\tcontext->width = width;\n\tcontext->height = height;\n\tret = nsc_context_initialize(context, s);\n\tStream_Free(s, FALSE);\n\n\tif (!ret)\n\t\treturn FALSE;\n\n\t/* RLE decode */\n\tPROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)\n\tnsc_rle_decompress_data(context);\n\tPROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)\n\t/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */\n\tPROFILER_ENTER(context->priv->prof_nsc_decode)\n\tcontext->decode(context);\n\tPROFILER_EXIT(context->priv->prof_nsc_decode)\n\n\tif (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,\n\t width, height, context->BitmapData,\n\t PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static int mount_entry_on_relative_rootfs(struct mntent *mntent,\n\t\t\t\t\t const char *rootfs)\n{\n\tchar path[MAXPATHLEN];\n\tint ret;\n\n\t/* relative to root mount point */\n\tret = snprintf(path, sizeof(path), \"%s/%s\", rootfs, mntent->mnt_dir);\n\tif (ret >= sizeof(path)) {\n\t\tERROR(\"path name too long\");\n\t\treturn -1;\n\t}\n\n\treturn mount_entry_on_generic(mntent, path);\n}", "label_name": "CWE-59", "label": 59} -{"code": "GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)\n{\n\tint r;\n\n\tstatic const char resp[] =\n\t\t\"\"\n\t\t\"%d\"\n\t\t\"\";\n\n\tchar body[512];\n\tint bodylen;\n\tstruct NameValueParserData data;\n\tchar * int_ip, * int_port, * rem_host, * rem_port, * protocol;\n\tint opt=0;\n\t/*int proto=0;*/\n\tunsigned short iport, rport;\n\n\tif (GETFLAG(IPV6FCFWDISABLEDMASK))\n\t{\n\t\tSoapError(h, 702, \"FirewallDisabled\");\n\t\treturn;\n\t}\n\n\tParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);\n\tint_ip = GetValueFromNameValueList(&data, \"InternalClient\");\n\tint_port = GetValueFromNameValueList(&data, \"InternalPort\");\n\trem_host = GetValueFromNameValueList(&data, \"RemoteHost\");\n\trem_port = GetValueFromNameValueList(&data, \"RemotePort\");\n\tprotocol = GetValueFromNameValueList(&data, \"Protocol\");\n\n\tif (!int_port || !ext_port || !protocol)\n\t{\n\t\tClearNameValueList(&data);\n\t\tSoapError(h, 402, \"Invalid Args\");\n\t\treturn;\n\t}\n\n\trport = (unsigned short)atoi(rem_port);\n\tiport = (unsigned short)atoi(int_port);\n\t/*proto = atoi(protocol);*/\n\n\tsyslog(LOG_INFO, \"%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s\", action, int_ip, iport,rem_host, rport, protocol);\n\n\t/* TODO */\n\tr = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/\n\n\tswitch(r)\n\t{\n\t\tcase 1:\t/* success */\n\t\t\tbodylen = snprintf(body, sizeof(body), resp,\n\t\t\t action, ns/*\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\"*/,\n\t\t\t opt, action);\n\t\t\tBuildSendAndCloseSoapResp(h, body, bodylen);\n\t\t\tbreak;\n\t\tcase -5:\t/* Protocol not supported */\n\t\t\tSoapError(h, 705, \"ProtocolNotSupported\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSoapError(h, 501, \"ActionFailed\");\n\t}\n\tClearNameValueList(&data);\n}", "label_name": "CWE-476", "label": 476} -{"code": "rs_filter_graph(RSFilter *filter)\n{\n\tg_return_if_fail(RS_IS_FILTER(filter));\n\tGString *str = g_string_new(\"digraph G {\\n\");\n\n\trs_filter_graph_helper(str, filter);\n\n\tg_string_append_printf(str, \"}\\n\");\n\tg_file_set_contents(\"/tmp/rs-filter-graph\", str->str, str->len, NULL);\n\n\tif (0 != system(\"dot -Tpng >/tmp/rs-filter-graph.png = '0' && *ptr <= '9')\n ptr++;\n /* 'lu' must follow here */\n if (*ptr++ != 'l')\n return 1;\n if (*ptr == 'u')\n ptr++;\n else\n return 1;\n n++;\n }\n }\n\n return (n != 3);\n}", "label_name": "CWE-134", "label": 134} -{"code": "juniper_atm2_print(netdissect_options *ndo,\n const struct pcap_pkthdr *h, register const u_char *p)\n{\n int llc_hdrlen;\n\n struct juniper_l2info_t l2info;\n\n l2info.pictype = DLT_JUNIPER_ATM2;\n if (juniper_parse_header(ndo, p, h, &l2info) == 0)\n return l2info.header_len;\n\n p+=l2info.header_len;\n\n if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */\n oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);\n return l2info.header_len;\n }\n\n if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n\n llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);\n if (llc_hdrlen > 0)\n return l2info.header_len;\n }\n\n if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */\n (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {\n ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);\n return l2info.header_len;\n }\n\n if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */\n isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);\n /* FIXME check if frame was recognized */\n return l2info.header_len;\n }\n\n if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */\n return l2info.header_len;\n\n if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */\n return l2info.header_len;\n\n\treturn l2info.header_len;\n}", "label_name": "CWE-125", "label": 125} -{"code": "handle_ppp(netdissect_options *ndo,\n u_int proto, const u_char *p, int length)\n{\n\tif ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */\n\t\tppp_hdlc(ndo, p - 1, length);\n\t\treturn;\n\t}\n\n\tswitch (proto) {\n\tcase PPP_LCP: /* fall through */\n\tcase PPP_IPCP:\n\tcase PPP_OSICP:\n\tcase PPP_MPLSCP:\n\tcase PPP_IPV6CP:\n\tcase PPP_CCP:\n\tcase PPP_BACP:\n\t\thandle_ctrl_proto(ndo, proto, p, length);\n\t\tbreak;\n\tcase PPP_ML:\n\t\thandle_mlppp(ndo, p, length);\n\t\tbreak;\n\tcase PPP_CHAP:\n\t\thandle_chap(ndo, p, length);\n\t\tbreak;\n\tcase PPP_PAP:\n\t\thandle_pap(ndo, p, length);\n\t\tbreak;\n\tcase PPP_BAP:\t\t/* XXX: not yet completed */\n\t\thandle_bap(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IP:\t/*XXX*/\n case PPP_VJNC:\n\tcase PPP_IP:\n\t\tip_print(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IPV6:\t/*XXX*/\n\tcase PPP_IPV6:\n\t\tip6_print(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IPX:\t/*XXX*/\n\tcase PPP_IPX:\n\t\tipx_print(ndo, p, length);\n\t\tbreak;\n\tcase PPP_OSI:\n\t\tisoclns_print(ndo, p, length, length);\n\t\tbreak;\n\tcase PPP_MPLS_UCAST:\n\tcase PPP_MPLS_MCAST:\n\t\tmpls_print(ndo, p, length);\n\t\tbreak;\n\tcase PPP_COMP:\n\t\tND_PRINT((ndo, \"compressed PPP data\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"%s \", tok2str(ppptype2str, \"unknown PPP protocol (0x%04x)\", proto)));\n\t\tprint_unknown_data(ndo, p, \"\\n\\t\", length);\n\t\tbreak;\n\t}\n}", "label_name": "CWE-125", "label": 125} -{"code": "parserep(netdissect_options *ndo,\n register const struct sunrpc_msg *rp, register u_int length)\n{\n\tregister const uint32_t *dp;\n\tu_int len;\n\tenum sunrpc_accept_stat astat;\n\n\t/*\n\t * Portability note:\n\t * Here we find the address of the ar_verf credentials.\n\t * Originally, this calculation was\n\t *\tdp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf\n\t * On the wire, the rp_acpt field starts immediately after\n\t * the (32 bit) rp_stat field. However, rp_acpt (which is a\n\t * \"struct accepted_reply\") contains a \"struct opaque_auth\",\n\t * whose internal representation contains a pointer, so on a\n\t * 64-bit machine the compiler inserts 32 bits of padding\n\t * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use\n\t * the internal representation to parse the on-the-wire\n\t * representation. Instead, we skip past the rp_stat field,\n\t * which is an \"enum\" and so occupies one 32-bit word.\n\t */\n\tdp = ((const uint32_t *)&rp->rm_reply) + 1;\n\tND_TCHECK(dp[1]);\n\tlen = EXTRACT_32BITS(&dp[1]);\n\tif (len >= length)\n\t\treturn (NULL);\n\t/*\n\t * skip past the ar_verf credentials.\n\t */\n\tdp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);\n\tND_TCHECK2(dp[0], 0);\n\n\t/*\n\t * now we can check the ar_stat field\n\t */\n\tastat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);\n\tif (astat != SUNRPC_SUCCESS) {\n\t\tND_PRINT((ndo, \" %s\", tok2str(sunrpc_str, \"ar_stat %d\", astat)));\n\t\tnfserr = 1;\t\t/* suppress trunc string */\n\t\treturn (NULL);\n\t}\n\t/* successful return */\n\tND_TCHECK2(*dp, sizeof(astat));\n\treturn ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));\ntrunc:\n\treturn (0);\n}", "label_name": "CWE-125", "label": 125} -{"code": "le64addr_string(netdissect_options *ndo, const u_char *ep)\n{\n\tconst unsigned int len = 8;\n\tregister u_int i;\n\tregister char *cp;\n\tregister struct enamemem *tp;\n\tchar buf[BUFSIZE];\n\n\ttp = lookup_bytestring(ndo, ep, len);\n\tif (tp->e_name)\n\t\treturn (tp->e_name);\n\n\tcp = buf;\n\tfor (i = len; i > 0 ; --i) {\n\t\t*cp++ = hex[*(ep + i - 1) >> 4];\n\t\t*cp++ = hex[*(ep + i - 1) & 0xf];\n\t\t*cp++ = ':';\n\t}\n\tcp --;\n\n\t*cp = '\\0';\n\n\ttp->e_name = strdup(buf);\n\tif (tp->e_name == NULL)\n\t\t(*ndo->ndo_error)(ndo, \"le64addr_string: strdup(buf)\");\n\n\treturn (tp->e_name);\n}", "label_name": "CWE-125", "label": 125} -{"code": "ip_optprint(netdissect_options *ndo,\n register const u_char *cp, u_int length)\n{\n\tregister u_int option_len;\n\tconst char *sep = \"\";\n\n\tfor (; length > 0; cp += option_len, length -= option_len) {\n\t\tu_int option_code;\n\n\t\tND_PRINT((ndo, \"%s\", sep));\n\t\tsep = \",\";\n\n\t\tND_TCHECK(*cp);\n\t\toption_code = *cp;\n\n\t\tND_PRINT((ndo, \"%s\",\n\t\t tok2str(ip_option_values,\"unknown %u\",option_code)));\n\n\t\tif (option_code == IPOPT_NOP ||\n option_code == IPOPT_EOL)\n\t\t\toption_len = 1;\n\n\t\telse {\n\t\t\tND_TCHECK(cp[1]);\n\t\t\toption_len = cp[1];\n\t\t\tif (option_len < 2) {\n\t\t\t\tND_PRINT((ndo, \" [bad length %u]\", option_len));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (option_len > length) {\n\t\t\tND_PRINT((ndo, \" [bad length %u]\", option_len));\n\t\t\treturn;\n\t\t}\n\n\t\tND_TCHECK2(*cp, option_len);\n\n\t\tswitch (option_code) {\n\t\tcase IPOPT_EOL:\n\t\t\treturn;\n\n\t\tcase IPOPT_TS:\n\t\t\tip_printts(ndo, cp, option_len);\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR: /* fall through */\n\t\tcase IPOPT_SSRR:\n\t\tcase IPOPT_LSRR:\n\t\t\tip_printroute(ndo, cp, option_len);\n\t\t\tbreak;\n\n\t\tcase IPOPT_RA:\n\t\t\tif (option_len < 4) {\n\t\t\t\tND_PRINT((ndo, \" [bad length %u]\", option_len));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tND_TCHECK(cp[3]);\n\t\t\tif (EXTRACT_16BITS(&cp[2]) != 0)\n\t\t\t\tND_PRINT((ndo, \" value %u\", EXTRACT_16BITS(&cp[2])));\n\t\t\tbreak;\n\n\t\tcase IPOPT_NOP: /* nothing to print - fall through */\n\t\tcase IPOPT_SECURITY:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"%s\", tstr));\n}", "label_name": "CWE-125", "label": 125} -{"code": "pimv2_addr_print(netdissect_options *ndo,\n const u_char *bp, enum pimv2_addrtype at, int silent)\n{\n\tint af;\n\tint len, hdrlen;\n\n\tND_TCHECK(bp[0]);\n\n\tif (pimv2_addr_len == 0) {\n\t\tND_TCHECK(bp[1]);\n\t\tswitch (bp[0]) {\n\t\tcase 1:\n\t\t\taf = AF_INET;\n\t\t\tlen = sizeof(struct in_addr);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\taf = AF_INET6;\n\t\t\tlen = sizeof(struct in6_addr);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t}\n\t\tif (bp[1] != 0)\n\t\t\treturn -1;\n\t\thdrlen = 2;\n\t} else {\n\t\tswitch (pimv2_addr_len) {\n\t\tcase sizeof(struct in_addr):\n\t\t\taf = AF_INET;\n\t\t\tbreak;\n\t\tcase sizeof(struct in6_addr):\n\t\t\taf = AF_INET6;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t\t}\n\t\tlen = pimv2_addr_len;\n\t\thdrlen = 0;\n\t}\n\n\tbp += hdrlen;\n\tswitch (at) {\n\tcase pimv2_unicast:\n\t\tND_TCHECK2(bp[0], len);\n\t\tif (af == AF_INET) {\n\t\t\tif (!silent)\n\t\t\t\tND_PRINT((ndo, \"%s\", ipaddr_string(ndo, bp)));\n\t\t}\n\t\telse if (af == AF_INET6) {\n\t\t\tif (!silent)\n\t\t\t\tND_PRINT((ndo, \"%s\", ip6addr_string(ndo, bp)));\n\t\t}\n\t\treturn hdrlen + len;\n\tcase pimv2_group:\n\tcase pimv2_source:\n\t\tND_TCHECK2(bp[0], len + 2);\n\t\tif (af == AF_INET) {\n\t\t\tif (!silent) {\n\t\t\t\tND_PRINT((ndo, \"%s\", ipaddr_string(ndo, bp + 2)));\n\t\t\t\tif (bp[1] != 32)\n\t\t\t\t\tND_PRINT((ndo, \"/%u\", bp[1]));\n\t\t\t}\n\t\t}\n\t\telse if (af == AF_INET6) {\n\t\t\tif (!silent) {\n\t\t\t\tND_PRINT((ndo, \"%s\", ip6addr_string(ndo, bp + 2)));\n\t\t\t\tif (bp[1] != 128)\n\t\t\t\t\tND_PRINT((ndo, \"/%u\", bp[1]));\n\t\t\t}\n\t\t}\n\t\tif (bp[0] && !silent) {\n\t\t\tif (at == pimv2_group) {\n\t\t\t\tND_PRINT((ndo, \"(0x%02x)\", bp[0]));\n\t\t\t} else {\n\t\t\t\tND_PRINT((ndo, \"(%s%s%s\",\n\t\t\t\t\tbp[0] & 0x04 ? \"S\" : \"\",\n\t\t\t\t\tbp[0] & 0x02 ? \"W\" : \"\",\n\t\t\t\t\tbp[0] & 0x01 ? \"R\" : \"\"));\n\t\t\t\tif (bp[0] & 0xf8) {\n\t\t\t\t\tND_PRINT((ndo, \"+0x%02x\", bp[0] & 0xf8));\n\t\t\t\t}\n\t\t\t\tND_PRINT((ndo, \")\"));\n\t\t\t}\n\t\t}\n\t\treturn hdrlen + 2 + len;\n\tdefault:\n\t\treturn -1;\n\t}\ntrunc:\n\treturn -1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "cisco_autorp_print(netdissect_options *ndo,\n register const u_char *bp, register u_int len)\n{\n\tint type;\n\tint numrps;\n\tint hold;\n\n\tND_TCHECK(bp[0]);\n\tND_PRINT((ndo, \" auto-rp \"));\n\ttype = bp[0];\n\tswitch (type) {\n\tcase 0x11:\n\t\tND_PRINT((ndo, \"candidate-advert\"));\n\t\tbreak;\n\tcase 0x12:\n\t\tND_PRINT((ndo, \"mapping\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"type-0x%02x\", type));\n\t\tbreak;\n\t}\n\n\tND_TCHECK(bp[1]);\n\tnumrps = bp[1];\n\n\tND_TCHECK2(bp[2], 2);\n\tND_PRINT((ndo, \" Hold \"));\n\thold = EXTRACT_16BITS(&bp[2]);\n\tif (hold)\n\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));\n\telse\n\t\tND_PRINT((ndo, \"FOREVER\"));\n\n\t/* Next 4 bytes are reserved. */\n\n\tbp += 8; len -= 8;\n\n\t/*XXX skip unless -v? */\n\n\t/*\n\t * Rest of packet:\n\t * numrps entries of the form:\n\t * 32 bits: RP\n\t * 6 bits: reserved\n\t * 2 bits: PIM version supported, bit 0 is \"supports v1\", 1 is \"v2\".\n\t * 8 bits: # of entries for this RP\n\t * each entry: 7 bits: reserved, 1 bit: negative,\n\t *\t 8 bits: mask 32 bits: source\n\t * lather, rinse, repeat.\n\t */\n\twhile (numrps--) {\n\t\tint nentries;\n\t\tchar s;\n\n\t\tND_TCHECK2(bp[0], 4);\n\t\tND_PRINT((ndo, \" RP %s\", ipaddr_string(ndo, bp)));\n\t\tND_TCHECK(bp[4]);\n\t\tswitch (bp[4] & 0x3) {\n\t\tcase 0: ND_PRINT((ndo, \" PIMv?\"));\n\t\t\tbreak;\n\t\tcase 1:\tND_PRINT((ndo, \" PIMv1\"));\n\t\t\tbreak;\n\t\tcase 2:\tND_PRINT((ndo, \" PIMv2\"));\n\t\t\tbreak;\n\t\tcase 3:\tND_PRINT((ndo, \" PIMv1+2\"));\n\t\t\tbreak;\n\t\t}\n\t\tif (bp[4] & 0xfc)\n\t\t\tND_PRINT((ndo, \" [rsvd=0x%02x]\", bp[4] & 0xfc));\n\t\tND_TCHECK(bp[5]);\n\t\tnentries = bp[5];\n\t\tbp += 6; len -= 6;\n\t\ts = ' ';\n\t\tfor (; nentries; nentries--) {\n\t\t\tND_TCHECK2(bp[0], 6);\n\t\t\tND_PRINT((ndo, \"%c%s%s/%d\", s, bp[0] & 1 ? \"!\" : \"\",\n\t\t\t ipaddr_string(ndo, &bp[2]), bp[1]));\n\t\t\tif (bp[0] & 0x02) {\n\t\t\t\tND_PRINT((ndo, \" bidir\"));\n\t\t\t}\n\t\t\tif (bp[0] & 0xfc) {\n\t\t\t\tND_PRINT((ndo, \"[rsvd=0x%02x]\", bp[0] & 0xfc));\n\t\t\t}\n\t\t\ts = ',';\n\t\t\tbp += 6; len -= 6;\n\t\t}\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"[|autorp]\"));\n\treturn;\n}", "label_name": "CWE-125", "label": 125} -{"code": "mp_capable_print(netdissect_options *ndo,\n const u_char *opt, u_int opt_len, u_char flags)\n{\n const struct mp_capable *mpc = (const struct mp_capable *) opt;\n\n if (!(opt_len == 12 && flags & TH_SYN) &&\n !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK))\n return 0;\n\n if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) {\n ND_PRINT((ndo, \" Unknown Version (%d)\", MP_CAPABLE_OPT_VERSION(mpc->sub_ver)));\n return 1;\n }\n\n if (mpc->flags & MP_CAPABLE_C)\n ND_PRINT((ndo, \" csum\"));\n ND_PRINT((ndo, \" {0x%\" PRIx64, EXTRACT_64BITS(mpc->sender_key)));\n if (opt_len == 20) /* ACK */\n ND_PRINT((ndo, \",0x%\" PRIx64, EXTRACT_64BITS(mpc->receiver_key)));\n ND_PRINT((ndo, \"}\"));\n return 1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)\n{\n u_int tlen, pdu_type, pdu_len;\n const u_char *tptr;\n const rpki_rtr_pdu *pdu_header;\n\n tptr = pptr;\n tlen = len;\n\n if (!ndo->ndo_vflag) {\n\tND_PRINT((ndo, \", RPKI-RTR\"));\n\treturn;\n }\n\n while (tlen >= sizeof(rpki_rtr_pdu)) {\n\n ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));\n\n\tpdu_header = (const rpki_rtr_pdu *)tptr;\n pdu_type = pdu_header->pdu_type;\n pdu_len = EXTRACT_32BITS(pdu_header->length);\n ND_TCHECK2(*tptr, pdu_len);\n\n /* infinite loop check */\n if (!pdu_type || !pdu_len) {\n break;\n }\n\n if (tlen < pdu_len) {\n goto trunc;\n }\n\n\t/*\n\t * Print the PDU.\n\t */\n\tif (rpki_rtr_pdu_print(ndo, tptr, 8))\n\t\tgoto trunc;\n\n tlen -= pdu_len;\n tptr += pdu_len;\n }\n return;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t%s\", tstr));\n}", "label_name": "CWE-125", "label": 125} -{"code": "static int parse_report(transport_smart *transport, git_push *push)\n{\n\tgit_pkt *pkt = NULL;\n\tconst char *line_end = NULL;\n\tgitno_buffer *buf = &transport->buffer;\n\tint error, recvd;\n\tgit_buf data_pkt_buf = GIT_BUF_INIT;\n\n\tfor (;;) {\n\t\tif (buf->offset > 0)\n\t\t\terror = git_pkt_parse_line(&pkt, buf->data,\n\t\t\t\t\t\t &line_end, buf->offset);\n\t\telse\n\t\t\terror = GIT_EBUFS;\n\n\t\tif (error < 0 && error != GIT_EBUFS) {\n\t\t\terror = -1;\n\t\t\tgoto done;\n\t\t}\n\n\t\tif (error == GIT_EBUFS) {\n\t\t\tif ((recvd = gitno_recv(buf)) < 0) {\n\t\t\t\terror = recvd;\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\tif (recvd == 0) {\n\t\t\t\tgiterr_set(GITERR_NET, \"early EOF\");\n\t\t\t\terror = GIT_EEOF;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tgitno_consume(buf, line_end);\n\n\t\terror = 0;\n\n\t\tif (pkt == NULL)\n\t\t\tcontinue;\n\n\t\tswitch (pkt->type) {\n\t\t\tcase GIT_PKT_DATA:\n\t\t\t\t/* This is a sideband packet which contains other packets */\n\t\t\t\terror = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf);\n\t\t\t\tbreak;\n\t\t\tcase GIT_PKT_ERR:\n\t\t\t\tgiterr_set(GITERR_NET, \"report-status: Error reported: %s\",\n\t\t\t\t\t((git_pkt_err *)pkt)->error);\n\t\t\t\terror = -1;\n\t\t\t\tbreak;\n\t\t\tcase GIT_PKT_PROGRESS:\n\t\t\t\tif (transport->progress_cb) {\n\t\t\t\t\tgit_pkt_progress *p = (git_pkt_progress *) pkt;\n\t\t\t\t\terror = transport->progress_cb(p->data, p->len, transport->message_cb_payload);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\terror = add_push_report_pkt(push, pkt);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tgit_pkt_free(pkt);\n\n\t\t/* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */\n\t\tif (error == GIT_ITEROVER) {\n\t\t\terror = 0;\n\t\t\tif (data_pkt_buf.size > 0) {\n\t\t\t\t/* If there was data remaining in the pack data buffer,\n\t\t\t\t * then the server sent a partial pkt-line */\n\t\t\t\tgiterr_set(GITERR_NET, \"Incomplete pack data pkt-line\");\n\t\t\t\terror = GIT_ERROR;\n\t\t\t}\n\t\t\tgoto done;\n\t\t}\n\n\t\tif (error < 0) {\n\t\t\tgoto done;\n\t\t}\n\t}\ndone:\n\tgit_buf_free(&data_pkt_buf);\n\treturn error;\n}", "label_name": "CWE-476", "label": 476} -{"code": "static inline Quantum GetPixelChannel(const Image *magick_restrict image,\n const PixelChannel channel,const Quantum *magick_restrict pixel)\n{\n if (image->channel_map[image->channel_map[channel].offset].traits == UndefinedPixelTrait)\n return((Quantum) 0);\n return(pixel[image->channel_map[channel].offset]);\n}", "label_name": "CWE-787", "label": 787} -{"code": "static int dbConnect(char *host, char *user, char *passwd)\n{\n DBUG_ENTER(\"dbConnect\");\n if (verbose)\n {\n fprintf(stderr, \"# Connecting to %s...\\n\", host ? host : \"localhost\");\n }\n mysql_init(&mysql_connection);\n if (opt_compress)\n mysql_options(&mysql_connection, MYSQL_OPT_COMPRESS, NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n {\n mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\t\t opt_ssl_capath, opt_ssl_cipher);\n mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n }\n#endif\n if (opt_protocol)\n mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n if (opt_bind_addr)\n mysql_options(&mysql_connection, MYSQL_OPT_BIND, opt_bind_addr);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n if (shared_memory_base_name)\n mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);\n mysql_options(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqlcheck\");\n if (!(sock = mysql_real_connect(&mysql_connection, host, user, passwd,\n NULL, opt_mysql_port, opt_mysql_unix_port, 0)))\n {\n DBerror(&mysql_connection, \"when trying to connect\");\n DBUG_RETURN(1);\n }\n mysql_connection.reconnect= 1;\n DBUG_RETURN(0);\n} /* dbConnect */", "label_name": "CWE-295", "label": 295} -{"code": "static unsigned char *read_chunk(struct mschm_decompressor_p *self,\n\t\t\t\t struct mschmd_header *chm,\n\t\t\t\t struct mspack_file *fh,\n\t\t\t\t unsigned int chunk_num)\n{\n struct mspack_system *sys = self->system;\n unsigned char *buf;\n\n /* check arguments - most are already checked by chmd_fast_find */\n if (chunk_num > chm->num_chunks) return NULL;\n \n /* ensure chunk cache is available */\n if (!chm->chunk_cache) {\n\tsize_t size = sizeof(unsigned char *) * chm->num_chunks;\n\tif (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) {\n\t self->error = MSPACK_ERR_NOMEMORY;\n\t return NULL;\n\t}\n\tmemset(chm->chunk_cache, 0, size);\n }\n\n /* try to answer out of chunk cache */\n if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num];\n\n /* need to read chunk - allocate memory for it */\n if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) {\n\tself->error = MSPACK_ERR_NOMEMORY;\n\treturn NULL;\n }\n\n /* seek to block and read it */\n if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)),\n\t\t MSPACK_SYS_SEEK_START))\n {\n\tself->error = MSPACK_ERR_SEEK;\n\tsys->free(buf);\n\treturn NULL;\n }\n if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) {\n\tself->error = MSPACK_ERR_READ;\n\tsys->free(buf);\n\treturn NULL;\n }\n\n /* check the signature. Is is PMGL or PMGI? */\n if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) &&\n\t ((buf[3] == 0x4C) || (buf[3] == 0x49))))\n {\n\tself->error = MSPACK_ERR_SEEK;\n\tsys->free(buf);\n\treturn NULL;\n }\n\n /* all OK. Store chunk in cache and return it */\n return chm->chunk_cache[chunk_num] = buf;\n}", "label_name": "CWE-193", "label": 193} -{"code": "static int bmp_getint32(jas_stream_t *in, int_fast32_t *val)\n{\n\tint n;\n\tuint_fast32_t v;\n\tint c;\n\tfor (n = 4, v = 0;;) {\n\t\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t\tv |= (c << 24);\n\t\tif (--n <= 0) {\n\t\t\tbreak;\n\t\t}\n\t\tv >>= 8;\n\t}\n\tif (val) {\n\t\t*val = v;\n\t}\n\treturn 0;\n}", "label_name": "CWE-476", "label": 476} -{"code": "static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 4, &tmp))\n\t\treturn -1;\n\t*val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) &\n\t 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp);\n\treturn 0;\n}", "label_name": "CWE-190", "label": 190} -{"code": "static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 4, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n}", "label_name": "CWE-190", "label": 190} -{"code": "static void sycc444_to_rgb(opj_image_t *img)\n{\n\tint *d0, *d1, *d2, *r, *g, *b;\n\tconst int *y, *cb, *cr;\n\tunsigned int maxw, maxh, max, i;\n\tint offset, upb;\n\n\tupb = (int)img->comps[0].prec;\n\toffset = 1<<(upb - 1); upb = (1<comps[0].w; maxh = (unsigned int)img->comps[0].h;\n\tmax = maxw * maxh;\n\n\ty = img->comps[0].data;\n\tcb = img->comps[1].data;\n\tcr = img->comps[2].data;\n\n\td0 = r = (int*)malloc(sizeof(int) * (size_t)max);\n\td1 = g = (int*)malloc(sizeof(int) * (size_t)max);\n\td2 = b = (int*)malloc(sizeof(int) * (size_t)max);\n\n\tif(r == NULL || g == NULL || b == NULL) goto fails;\n\n\tfor(i = 0U; i < max; ++i)\n\t{\n\t\tsycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);\n\t\t++y; ++cb; ++cr; ++r; ++g; ++b;\n\t}\n\tfree(img->comps[0].data); img->comps[0].data = d0;\n\tfree(img->comps[1].data); img->comps[1].data = d1;\n\tfree(img->comps[2].data); img->comps[2].data = d2;\n\treturn;\n\nfails:\n\tif(r) free(r);\n\tif(g) free(g);\n\tif(b) free(b);\n\n}/* sycc444_to_rgb() */", "label_name": "CWE-125", "label": 125} -{"code": "parse_range(char *str, size_t file_sz, int *nranges)\n{\n\tstatic struct range\t ranges[MAX_RANGES];\n\tint\t\t\t i = 0;\n\tchar\t\t\t*p, *q;\n\n\t/* Extract range unit */\n\tif ((p = strchr(str, '=')) == NULL)\n\t\treturn (NULL);\n\n\t*p++ = '\\0';\n\t/* Check if it's a bytes range spec */\n\tif (strcmp(str, \"bytes\") != 0)\n\t\treturn (NULL);\n\n\twhile ((q = strchr(p, ',')) != NULL) {\n\t\t*q++ = '\\0';\n\n\t\t/* Extract start and end positions */\n\t\tif (parse_range_spec(p, file_sz, &ranges[i]) == 0)\n\t\t\tcontinue;\n\n\t\ti++;\n\t\tif (i == MAX_RANGES)\n\t\t\treturn (NULL);\n\n\t\tp = q;\n\t}\n\n\tif (parse_range_spec(p, file_sz, &ranges[i]) != 0)\n\t\ti++;\n\n\t*nranges = i;\n\treturn (i ? ranges : NULL);\n}", "label_name": "CWE-770", "label": 770} -{"code": "name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {\n\tint name_end = -1;\n\tint j = *idx;\n\tint ptr_count = 0;\n#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)\n#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)\n#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)\n\n\tchar *cp = name_out;\n\tconst char *const end = name_out + name_out_len;\n\n\t/* Normally, names are a series of length prefixed strings terminated */\n\t/* with a length of 0 (the lengths are u8's < 63). */\n\t/* However, the length can start with a pair of 1 bits and that */\n\t/* means that the next 14 bits are a pointer within the current */\n\t/* packet. */\n\n\tfor (;;) {\n\t\tu8 label_len;\n\t\tif (j >= length) return -1;\n\t\tGET8(label_len);\n\t\tif (!label_len) break;\n\t\tif (label_len & 0xc0) {\n\t\t\tu8 ptr_low;\n\t\t\tGET8(ptr_low);\n\t\t\tif (name_end < 0) name_end = j;\n\t\t\tj = (((int)label_len & 0x3f) << 8) + ptr_low;\n\t\t\t/* Make sure that the target offset is in-bounds. */\n\t\t\tif (j < 0 || j >= length) return -1;\n\t\t\t/* If we've jumped more times than there are characters in the\n\t\t\t * message, we must have a loop. */\n\t\t\tif (++ptr_count > length) return -1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (label_len > 63) return -1;\n\t\tif (cp != name_out) {\n\t\t\tif (cp + 1 >= end) return -1;\n\t\t\t*cp++ = '.';\n\t\t}\n\t\tif (cp + label_len >= end) return -1;\n\t\tmemcpy(cp, packet + j, label_len);\n\t\tcp += label_len;\n\t\tj += label_len;\n\t}\n\tif (cp >= end) return -1;\n\t*cp = '\\0';\n\tif (name_end < 0)\n\t\t*idx = j;\n\telse\n\t\t*idx = name_end;\n\treturn 0;\n err:\n\treturn -1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)\n{\n cJSON *current_element = NULL;\n\n if ((object == NULL) || (name == NULL))\n {\n return NULL;\n }\n\n current_element = object->child;\n if (case_sensitive)\n {\n while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))\n {\n current_element = current_element->next;\n }\n }\n else\n {\n while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))\n {\n current_element = current_element->next;\n }\n }\n\n return current_element;\n}", "label_name": "CWE-476", "label": 476} -{"code": "fname_match(\n regmatch_T\t*rmp,\n char_u\t*name,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match = NULL;\n char_u\t*p;\n\n if (name != NULL)\n {\n\t// Ignore case when 'fileignorecase' or the argument is set.\n\trmp->rm_ic = p_fic || ignore_case;\n\tif (vim_regexec(rmp, name, (colnr_T)0))\n\t match = name;\n\telse\n\t{\n\t // Replace $(HOME) with '~' and try matching again.\n\t p = home_replace_save(NULL, name);\n\t if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))\n\t\tmatch = name;\n\t vim_free(p);\n\t}\n }\n\n return match;\n}", "label_name": "CWE-476", "label": 476} -{"code": "buflist_match(\n regmatch_T\t*rmp,\n buf_T\t*buf,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match;\n\n // First try the short file name, then the long file name.\n match = fname_match(rmp, buf->b_sfname, ignore_case);\n if (match == NULL)\n\tmatch = fname_match(rmp, buf->b_ffname, ignore_case);\n\n return match;\n}", "label_name": "CWE-476", "label": 476} -{"code": "static VTermScreen *screen_new(VTerm *vt)\n{\n VTermState *state = vterm_obtain_state(vt);\n VTermScreen *screen;\n int rows, cols;\n\n if(!state)\n return NULL;\n\n screen = vterm_allocator_malloc(vt, sizeof(VTermScreen));\n\n vterm_get_size(vt, &rows, &cols);\n\n screen->vt = vt;\n screen->state = state;\n\n screen->damage_merge = VTERM_DAMAGE_CELL;\n screen->damaged.start_row = -1;\n screen->pending_scrollrect.start_row = -1;\n\n screen->rows = rows;\n screen->cols = cols;\n\n screen->callbacks = NULL;\n screen->cbdata = NULL;\n\n screen->buffers[0] = realloc_buffer(screen, NULL, rows, cols);\n\n screen->buffer = screen->buffers[0];\n\n screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * cols);\n\n vterm_state_set_callbacks(screen->state, &state_cbs, screen);\n\n return screen;\n}", "label_name": "CWE-476", "label": 476} -{"code": "cJSON *cJSON_CreateFloatArray( double *numbers, int count )\n{\n\tint i;\n\tcJSON *n = 0, *p = 0, *a = cJSON_CreateArray();\n\tfor ( i = 0; a && i < count; ++i ) {\n\t\tn = cJSON_CreateFloat( numbers[i] );\n\t\tif ( ! i )\n\t\t\ta->child = n;\n\t\telse\n\t\t\tsuffix_object( p, n );\n\t\tp = n;\n\t}\n\treturn a;\n}", "label_name": "CWE-120", "label": 120} -{"code": "void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )\n{\n\tcJSON_AddItemToArray( array, create_reference( item ) );\n}", "label_name": "CWE-120", "label": 120} -{"code": "cJSON *cJSON_CreateArray( void )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item )\n\t\titem->type = cJSON_Array;\n\treturn item;\n}", "label_name": "CWE-120", "label": 120} -{"code": "static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}", "label_name": "CWE-125", "label": 125} -{"code": "int ZEXPORT deflatePrime (strm, bits, value)\n z_streamp strm;\n int bits;\n int value;\n{\n deflate_state *s;\n int put;\n\n if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n s = strm->state;\n if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))\n return Z_BUF_ERROR;\n do {\n put = Buf_size - s->bi_valid;\n if (put > bits)\n put = bits;\n s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);\n s->bi_valid += put;\n _tr_flush_bits(s);\n value >>= put;\n bits -= put;\n } while (bits);\n return Z_OK;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {\n\tconst int nb10sz = 16;\n\tmemcpy (res, dbg_data, nb10sz);\n\tres->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);\n}", "label_name": "CWE-125", "label": 125} -{"code": "static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,\n const unsigned char *end )\n{\n int ret = 0;\n size_t n;\n\n if( ssl->conf->f_psk == NULL &&\n ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no pre-shared key\" ) );\n return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n }\n\n /*\n * Receive client pre-shared key identity name\n */\n if( *p + 2 > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n n = ( (*p)[0] << 8 ) | (*p)[1];\n *p += 2;\n\n if( n < 1 || n > 65535 || *p + n > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->conf->f_psk != NULL )\n {\n if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n else\n {\n /* Identity is not a big secret since clients send it in the clear,\n * but treat it carefully anyway, just in case */\n if( n != ssl->conf->psk_identity_len ||\n mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )\n {\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n }\n\n if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )\n {\n MBEDTLS_SSL_DEBUG_BUF( 3, \"Unknown PSK identity\", *p, n );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );\n return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );\n }\n\n *p += n;\n\n return( 0 );\n}", "label_name": "CWE-190", "label": 190} -{"code": "build_config(char *prefix, struct server *server)\n{\n char *path = NULL;\n int path_size = strlen(prefix) + strlen(server->port) + 20;\n\n path = ss_malloc(path_size);\n snprintf(path, path_size, \"%s/.shadowsocks_%s.conf\", prefix, server->port);\n FILE *f = fopen(path, \"w+\");\n if (f == NULL) {\n if (verbose) {\n LOGE(\"unable to open config file\");\n }\n ss_free(path);\n return;\n }\n fprintf(f, \"{\\n\");\n fprintf(f, \"\\\"server_port\\\":%d,\\n\", atoi(server->port));\n fprintf(f, \"\\\"password\\\":\\\"%s\\\"\", server->password);\n if (server->fast_open[0]) fprintf(f, \",\\n\\\"fast_open\\\": %s\", server->fast_open);\n if (server->mode) fprintf(f, \",\\n\\\"mode\\\":\\\"%s\\\"\", server->mode);\n if (server->method) fprintf(f, \",\\n\\\"method\\\":\\\"%s\\\"\", server->method);\n if (server->plugin) fprintf(f, \",\\n\\\"plugin\\\":\\\"%s\\\"\", server->plugin);\n if (server->plugin_opts) fprintf(f, \",\\n\\\"plugin_opts\\\":\\\"%s\\\"\", server->plugin_opts);\n fprintf(f, \"\\n}\\n\");\n fclose(f);\n ss_free(path);\n}", "label_name": "CWE-78", "label": 78} -{"code": "char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n /*\n rfbLog(\"rfbProcessFileTransferReadBuffer(%dlen)\\n\", length);\n */\n if (length>0) {\n buffer=malloc((uint64_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n}", "label_name": "CWE-787", "label": 787} -{"code": "get_html_data (MAPI_Attr *a)\n{\n VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);\n\n int j;\n for (j = 0; j < a->num_values; j++)\n {\n\tbody[j] = XMALLOC(VarLenData, 1);\n\tbody[j]->len = a->values[j].len;\n\tbody[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);\n\tmemmove (body[j]->data, a->values[j].data.buf, body[j]->len);\n }\n return body;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static char *r_socket_http_answer (RSocket *s, int *code, int *rlen) {\n\tr_return_val_if_fail (s, NULL);\n\tconst char *p;\n\tint ret, len = 0, bufsz = 32768, delta = 0;\n\tchar *dn, *buf = calloc (1, bufsz + 32); // XXX: use r_buffer here\n\tif (!buf) {\n\t\treturn NULL;\n\t}\n\tchar *res = NULL;\n\tint olen = __socket_slurp (s, (ut8*)buf, bufsz);\n\tif ((dn = (char*)r_str_casestr (buf, \"\\n\\n\"))) {\n\t\tdelta += 2;\n\t} else if ((dn = (char*)r_str_casestr (buf, \"\\r\\n\\r\\n\"))) {\n\t\tdelta += 4;\n\t} else {\n\t\tgoto fail;\n\t}\n\n\tolen -= delta;\n\t*dn = 0; // chop headers\n\t/* Parse Len */\n\tp = r_str_casestr (buf, \"Content-Length: \");\n\tif (p) {\n\t\tlen = atoi (p + 16);\n\t} else {\n\t\tlen = olen - (dn - buf);\n\t}\n\tif (len > 0) {\n\t\tif (len > olen) {\n\t\t\tres = malloc (len + 2);\n\t\t\tmemcpy (res, dn + delta, olen);\n\t\t\tdo {\n\t\t\t\tret = r_socket_read_block (s, (ut8*) res + olen, len - olen);\n\t\t\t\tif (ret < 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tolen += ret;\n\t\t\t} while (olen < len);\n\t\t\tres[len] = 0;\n\t\t} else {\n\t\t\tres = malloc (len + 1);\n\t\t\tif (res) {\n\t\t\t\tmemcpy (res, dn + delta, len);\n\t\t\t\tres[len] = 0;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tres = NULL;\n\t}\nfail:\n\tfree (buf);\n// is 's' free'd? isn't this going to cause a double free?\n\tr_socket_close (s);\n\tif (rlen) {\n\t\t*rlen = len;\n\t}\n\treturn res;\n}", "label_name": "CWE-78", "label": 78} -{"code": "static pyc_object *get_list_object(RBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n = 0;\n\n\tn = get_ut32 (buffer, &error);\n\tif (n > ST32_MAX) {\n\t\teprintf (\"bad marshal data (list size out of range)\\n\");\n\t\treturn NULL;\n\t}\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tret = get_array_object_generic (buffer, n);\n\tif (ret) {\n\t\tret->type = TYPE_LIST;\n\t\treturn ret;\n\t}\n\treturn NULL;\n}", "label_name": "CWE-825", "label": 825} -{"code": "static cache_accel_t *read_cache_accel(RBuffer *cache_buf, cache_hdr_t *hdr, cache_map_t *maps) {\n\tif (!cache_buf || !hdr || !hdr->accelerateInfoSize || !hdr->accelerateInfoAddr) {\n\t\treturn NULL;\n\t}\n\n\tut64 offset = va2pa (hdr->accelerateInfoAddr, hdr->mappingCount, maps, cache_buf, 0, NULL, NULL);\n\tif (!offset) {\n\t\treturn NULL;\n\t}\n\n\tut64 size = sizeof (cache_accel_t);\n\tcache_accel_t *accel = R_NEW0 (cache_accel_t);\n\tif (!accel) {\n\t\treturn NULL;\n\t}\n\n\tif (r_buf_fread_at (cache_buf, offset, (ut8*) accel, \"16il\", 1) != size) {\n\t\tR_FREE (accel);\n\t\treturn NULL;\n\t}\n\n\taccel->imagesExtrasOffset += offset;\n\taccel->bottomUpListOffset += offset;\n\taccel->dylibTrieOffset += offset;\n\taccel->initializersOffset += offset;\n\taccel->dofSectionsOffset += offset;\n\taccel->reExportListOffset += offset;\n\taccel->depListOffset += offset;\n\taccel->rangeTableOffset += offset;\n\n\treturn accel;\n}", "label_name": "CWE-787", "label": 787} -{"code": "R_API RCmdAliasVal *r_cmd_alias_get(RCmd *cmd, const char *k) {\n\tr_return_val_if_fail (cmd && cmd->aliases && k, NULL);\n\treturn ht_pp_find(cmd->aliases, k, NULL);\n}", "label_name": "CWE-125", "label": 125} -{"code": "RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n\tif (!bin->entry_table) {\n\t\treturn NULL;\n\t}\n\tRList *entries = r_list_newf (free);\n\tif (!entries) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_bin_ne_get_segments (bin);\n\tif (!segments) {\n\t\tr_list_free (entries);\n\t\treturn NULL;\n\t}\n\tif (bin->ne_header->csEntryPoint) {\n\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\tif (!entry) {\n\t\t\tr_list_free (entries);\n\t\t\treturn NULL;\n\t\t}\n\t\tentry->bits = 16;\n\t\tut32 entry_cs = bin->ne_header->csEntryPoint;\n\t\tRBinSection *s = r_list_get_n (segments, entry_cs - 1);\n\t\tentry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);\n\n\t\tr_list_append (entries, entry);\n\t}\n\tint off = 0;\n\tsize_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset;\n\twhile (off < bin->ne_header->EntryTableLength) {\n\t\tif (tableat + off >= r_buf_size (bin->buf)) {\n\t\t\tbreak;\n\t\t}\n\t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n\t\tif (!bundle_length) {\n\t\t\tbreak;\n\t\t}\n\t\toff++;\n\t\tut8 bundle_type = *(ut8 *)(bin->entry_table + off);\n\t\toff++;\n\t\tint i;\n\t\tfor (i = 0; i < bundle_length; i++) {\n\t\t\tif (tableat + off + 4 >= r_buf_size (bin->buf)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\t\tif (!entry) {\n\t\t\t\tr_list_free (entries);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\toff++;\n\t\t\tif (!bundle_type) { // Skip\n\t\t\t\toff--;\n\t\t\t\tfree (entry);\n\t\t\t\tbreak;\n\t\t\t} else if (bundle_type == 0xff) { // moveable\n\t\t\t\toff += 2;\n\t\t\t\tut8 segnum = *(bin->entry_table + off);\n\t\t\t\toff++;\n\t\t\t\tut16 segoff = *(ut16 *)(bin->entry_table + off);\n\t\t\t\tif (segnum > 0) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n\t\t\t\t}\n\t\t\t} else { // Fixed\n\t\t\t\tif (bundle_type < bin->ne_header->SegCount) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset\n\t\t\t\t\t\t* bin->alignment + *(ut16 *)(bin->entry_table + off);\n\t\t\t\t}\n\t\t\t}\n\t\t\toff += 2;\n\t\t\tr_list_append (entries, entry);\n\t\t}\n\t}\n\tr_list_free (segments);\n\tbin->entries = entries;\n\treturn entries;\n}", "label_name": "CWE-125", "label": 125} -{"code": "static bool vtable_is_value_in_text_section(RVTableContext *context, ut64 curAddress, ut64 *value) {\n\t//value at the current address\n\tut64 curAddressValue;\n\tif (!context->read_addr (context->anal, curAddress, &curAddressValue)) {\n\t\treturn false;\n\t}\n\t//if the value is in text section\n\tbool ret = vtable_addr_in_text_section (context, curAddressValue);\n\tif (value) {\n\t\t*value = curAddressValue;\n\t}\n\treturn ret;\n}", "label_name": "CWE-824", "label": 824} -{"code": "BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content,\n int content_len)\n{\n Packet *p = NULL;\n int hlen = 20;\n int ttl = 64;\n uint8_t *pcontent;\n IPV4Hdr ip4h;\n\n p = SCCalloc(1, sizeof(*p) + default_packet_size);\n if (unlikely(p == NULL))\n return NULL;\n\n PACKET_INITIALIZE(p);\n\n gettimeofday(&p->ts, NULL);\n //p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p);\n ip4h.ip_verhl = 4 << 4;\n ip4h.ip_verhl |= hlen >> 2;\n ip4h.ip_len = htons(hlen + content_len);\n ip4h.ip_id = htons(id);\n ip4h.ip_off = htons(off);\n if (mf)\n ip4h.ip_off = htons(IP_MF | off);\n else\n ip4h.ip_off = htons(off);\n ip4h.ip_ttl = ttl;\n ip4h.ip_proto = IPPROTO_ICMP;\n\n ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */\n ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */\n\n /* copy content_len crap, we need full length */\n PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h));\n p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p);\n SET_IPV4_SRC_ADDR(p, &p->src);\n SET_IPV4_DST_ADDR(p, &p->dst);\n\n pcontent = SCCalloc(1, content_len);\n if (unlikely(pcontent == NULL))\n return NULL;\n memset(pcontent, content, content_len);\n PacketCopyDataOffset(p, hlen, pcontent, content_len);\n SET_PKT_LEN(p, hlen + content_len);\n SCFree(pcontent);\n\n p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen);\n\n /* Self test. */\n if (IPV4_GET_VER(p) != 4)\n goto error;\n if (IPV4_GET_HLEN(p) != hlen)\n goto error;\n if (IPV4_GET_IPLEN(p) != hlen + content_len)\n goto error;\n if (IPV4_GET_IPID(p) != id)\n goto error;\n if (IPV4_GET_IPOFFSET(p) != off)\n goto error;\n if (IPV4_GET_MF(p) != mf)\n goto error;\n if (IPV4_GET_IPTTL(p) != ttl)\n goto error;\n if (IPV4_GET_IPPROTO(p) != IPPROTO_ICMP)\n goto error;\n\n return p;\nerror:\n if (p != NULL)\n SCFree(p);\n return NULL;\n}", "label_name": "CWE-358", "label": 358} -{"code": "static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,\n\tunsigned int *pv)\n{\n\tunsigned int field_type;\n\tunsigned int value_count;\n\n\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n\n\tif(value_count!=1) return 0;\n\n\tif(field_type==3) { // SHORT (uint16)\n\t\t*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);\n\t\treturn 1;\n\t}\n\telse if(field_type==4) { // LONG (uint32)\n\t\t*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-125", "label": 125} -{"code": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n\t\tconst iw_byte *d, size_t d_len)\n{\n\tstruct iw_exif_state e;\n\tiw_uint32 ifd;\n\n\tif(d_len<8) return;\n\n\tiw_zeromem(&e,sizeof(struct iw_exif_state));\n\te.d = d;\n\te.d_len = d_len;\n\n\te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n\n\tifd = iw_get_ui32_e(&d[4],e.endian);\n\n\tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n}", "label_name": "CWE-125", "label": 125} -{"code": "static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n\tdouble *pv)\n{\n\tunsigned int field_type;\n\tunsigned int value_count;\n\tunsigned int value_pos;\n\tunsigned int numer, denom;\n\n\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n\n\tif(value_count!=1) return 0;\n\n\tif(field_type!=5) return 0; // 5=Rational (two uint32's)\n\n\t// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read\n\t// the location where it is stored.\n\n\tvalue_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n\tif(value_pos > e->d_len-8) return 0;\n\n\t// Read the actual value.\n\tnumer = iw_get_ui32_e(&e->d[value_pos ],e->endian);\n\tdenom = iw_get_ui32_e(&e->d[value_pos+4],e->endian);\n\tif(denom==0) return 0;\n\n\t*pv = ((double)numer)/denom;\n\treturn 1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "IW_IMPL(int) iw_get_input_density(struct iw_context *ctx,\n double *px, double *py, int *pcode)\n{\n\t*px = 1.0;\n\t*py = 1.0;\n\t*pcode = ctx->img1.density_code;\n\tif(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) {\n\t\t*px = ctx->img1.density_x;\n\t\t*py = ctx->img1.density_y;\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-369", "label": 369} -{"code": "get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n/* This version is for reading raw-word-format PPM files with any maxval */\n{\n ppm_source_ptr source = (ppm_source_ptr)sinfo;\n register JSAMPROW ptr;\n register U_CHAR *bufferptr;\n register JSAMPLE *rescale = source->rescale;\n JDIMENSION col;\n unsigned int maxval = source->maxval;\n\n if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n ptr = source->pub.buffer[0];\n bufferptr = source->iobuffer;\n for (col = cinfo->image_width; col > 0; col--) {\n register unsigned int temp;\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n }\n return 1;\n}", "label_name": "CWE-787", "label": 787} -{"code": "void imap_quote_string (char *dest, size_t dlen, const char *src)\n{\n static const char quote[] = \"\\\"\\\\\";\n char *pt;\n const char *s;\n\n pt = dest;\n s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr (quote, *s))\n {\n dlen -= 2;\n if (!dlen)\n\tbreak;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = 0;\n}", "label_name": "CWE-78", "label": 78} -{"code": "static void _imap_quote_string (char *dest, size_t dlen, const char *src,\n const char *to_quote)\n{\n char *pt;\n const char *s;\n\n pt = dest;\n s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr (to_quote, *s))\n {\n dlen -= 2;\n if (!dlen)\n\tbreak;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = 0;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static int pop_sync_mailbox(struct Context *ctx, int *index_hint)\n{\n int i, j, ret = 0;\n char buf[LONG_STRING];\n struct PopData *pop_data = (struct PopData *) ctx->data;\n struct Progress progress;\n#ifdef USE_HCACHE\n header_cache_t *hc = NULL;\n#endif\n\n pop_data->check_time = 0;\n\n while (true)\n {\n if (pop_reconnect(ctx) < 0)\n return -1;\n\n mutt_progress_init(&progress, _(\"Marking messages deleted...\"),\n MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);\n\n#ifdef USE_HCACHE\n hc = pop_hcache_open(pop_data, ctx->path);\n#endif\n\n for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)\n {\n if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)\n {\n j++;\n if (!ctx->quiet)\n mutt_progress_update(&progress, j, -1);\n snprintf(buf, sizeof(buf), \"DELE %d\\r\\n\", ctx->hdrs[i]->refno);\n ret = pop_query(pop_data, buf, sizeof(buf));\n if (ret == 0)\n {\n mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data);\n#ifdef USE_HCACHE\n mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));\n#endif\n }\n }\n\n#ifdef USE_HCACHE\n if (ctx->hdrs[i]->changed)\n {\n mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),\n ctx->hdrs[i], 0);\n }\n#endif\n }\n\n#ifdef USE_HCACHE\n mutt_hcache_close(hc);\n#endif\n\n if (ret == 0)\n {\n mutt_str_strfcpy(buf, \"QUIT\\r\\n\", sizeof(buf));\n ret = pop_query(pop_data, buf, sizeof(buf));\n }\n\n if (ret == 0)\n {\n pop_data->clear_cache = true;\n pop_clear_cache(pop_data);\n pop_data->status = POP_DISCONNECTED;\n return 0;\n }\n\n if (ret == -2)\n {\n mutt_error(\"%s\", pop_data->err_msg);\n return -1;\n }\n }\n}", "label_name": "CWE-22", "label": 22} -{"code": "int imap_subscribe(char *path, bool subscribe)\n{\n struct ImapData *idata = NULL;\n char buf[LONG_STRING];\n char mbox[LONG_STRING];\n char errstr[STRING];\n struct Buffer err, token;\n struct ImapMbox mx;\n\n if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox)\n {\n mutt_error(_(\"Bad mailbox name\"));\n return -1;\n }\n idata = imap_conn_find(&(mx.account), 0);\n if (!idata)\n goto fail;\n\n imap_fix_path(idata, mx.mbox, buf, sizeof(buf));\n if (!*buf)\n mutt_str_strfcpy(buf, \"INBOX\", sizeof(buf));\n\n if (ImapCheckSubscribed)\n {\n mutt_buffer_init(&token);\n mutt_buffer_init(&err);\n err.data = errstr;\n err.dsize = sizeof(errstr);\n snprintf(mbox, sizeof(mbox), \"%smailboxes \\\"%s\\\"\", subscribe ? \"\" : \"un\", path);\n if (mutt_parse_rc_line(mbox, &token, &err))\n mutt_debug(1, \"Error adding subscribed mailbox: %s\\n\", errstr);\n FREE(&token.data);\n }\n\n if (subscribe)\n mutt_message(_(\"Subscribing to %s...\"), buf);\n else\n mutt_message(_(\"Unsubscribing from %s...\"), buf);\n imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);\n\n snprintf(buf, sizeof(buf), \"%sSUBSCRIBE %s\", subscribe ? \"\" : \"UN\", mbox);\n\n if (imap_exec(idata, buf, 0) < 0)\n goto fail;\n\n imap_unmunge_mbox_name(idata, mx.mbox);\n if (subscribe)\n mutt_message(_(\"Subscribed to %s\"), mx.mbox);\n else\n mutt_message(_(\"Unsubscribed from %s\"), mx.mbox);\n FREE(&mx.mbox);\n return 0;\n\nfail:\n FREE(&mx.mbox);\n return -1;\n}", "label_name": "CWE-78", "label": 78} -{"code": "ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return true;\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return true;\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}", "label_name": "CWE-476", "label": 476} -{"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-787", "label": 787} -{"code": "process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n{\n\tUNUSED(size);\n\tint indexw;\n\tint indexh;\n\tint code;\n\tint collen;\n\tint replen;\n\tint color;\n\tint x;\n\tint revcode;\n\tuint8 * last_line;\n\tuint8 * this_line;\n\tuint8 * org_in;\n\tuint8 * org_out;\n\n\torg_in = in;\n\torg_out = out;\n\tlast_line = 0;\n\tindexh = 0;\n\twhile (indexh < height)\n\t{\n\t\tout = (org_out + width * height * 4) - ((indexh + 1) * width * 4);\n\t\tcolor = 0;\n\t\tthis_line = out;\n\t\tindexw = 0;\n\t\tif (last_line == 0)\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor = CVAL(in);\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = CVAL(in);\n\t\t\t\t\tif (x & 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\tcolor = -x;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tcolor = x;\n\t\t\t\t\t}\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tindexh++;\n\t\tlast_line = this_line;\n\t}\n\treturn (int) (in - org_in);\n}", "label_name": "CWE-787", "label": 787} -{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-191", "label": 191} -{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-191", "label": 191} -{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-787", "label": 787} -{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-125", "label": 125} -{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-787", "label": 787} -{"code": "process_bitmap_updates(STREAM s)\n{\n\tuint16 num_updates;\n\tuint16 left, top, right, bottom, width, height;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tuint8 *data, *bmpdata;\n\tint i;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\n\tin_uint16_le(s, num_updates);\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t{\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n\t\txfree(bmpdata);\n\t}\n}", "label_name": "CWE-190", "label": 190} -{"code": "_PyMemoTable_ResizeTable(PyMemoTable *self, Py_ssize_t min_size)\n{\n PyMemoEntry *oldtable = NULL;\n PyMemoEntry *oldentry, *newentry;\n Py_ssize_t new_size = MT_MINSIZE;\n Py_ssize_t to_process;\n\n assert(min_size > 0);\n\n /* Find the smallest valid table size >= min_size. */\n while (new_size < min_size && new_size > 0)\n new_size <<= 1;\n if (new_size <= 0) {\n PyErr_NoMemory();\n return -1;\n }\n /* new_size needs to be a power of two. */\n assert((new_size & (new_size - 1)) == 0);\n\n /* Allocate new table. */\n oldtable = self->mt_table;\n self->mt_table = PyMem_NEW(PyMemoEntry, new_size);\n if (self->mt_table == NULL) {\n self->mt_table = oldtable;\n PyErr_NoMemory();\n return -1;\n }\n self->mt_allocated = new_size;\n self->mt_mask = new_size - 1;\n memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size);\n\n /* Copy entries from the old table. */\n to_process = self->mt_used;\n for (oldentry = oldtable; to_process > 0; oldentry++) {\n if (oldentry->me_key != NULL) {\n to_process--;\n /* newentry is a pointer to a chunk of the new\n mt_table, so we're setting the key:value pair\n in-place. */\n newentry = _PyMemoTable_Lookup(self, oldentry->me_key);\n newentry->me_key = oldentry->me_key;\n newentry->me_value = oldentry->me_value;\n }\n }\n\n /* Deallocate the old table. */\n PyMem_FREE(oldtable);\n return 0;\n}", "label_name": "CWE-190", "label": 190} -{"code": "PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value)\n{\n PyMemoEntry *entry;\n\n assert(key != NULL);\n\n entry = _PyMemoTable_Lookup(self, key);\n if (entry->me_key != NULL) {\n entry->me_value = value;\n return 0;\n }\n Py_INCREF(key);\n entry->me_key = key;\n entry->me_value = value;\n self->mt_used++;\n\n /* If we added a key, we can safely resize. Otherwise just return!\n * If used >= 2/3 size, adjust size. Normally, this quaduples the size.\n *\n * Quadrupling the size improves average table sparseness\n * (reducing collisions) at the cost of some memory. It also halves\n * the number of expensive resize operations in a growing memo table.\n *\n * Very large memo tables (over 50K items) use doubling instead.\n * This may help applications with severe memory constraints.\n */\n if (!(self->mt_used * 3 >= (self->mt_mask + 1) * 2))\n return 0;\n return _PyMemoTable_ResizeTable(self,\n (self->mt_used > 50000 ? 2 : 4) * self->mt_used);\n}", "label_name": "CWE-190", "label": 190} -{"code": "Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, int\n end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!value) {\n PyErr_SetString(PyExc_ValueError,\n \"field value is required for Assign\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = Assign_kind;\n p->v.Assign.targets = targets;\n p->v.Assign.value = value;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label_name": "CWE-125", "label": 125} -{"code": "AsyncFunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq\n * decorator_list, expr_ty returns, int lineno, int col_offset,\n int end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!name) {\n PyErr_SetString(PyExc_ValueError,\n \"field name is required for AsyncFunctionDef\");\n return NULL;\n }\n if (!args) {\n PyErr_SetString(PyExc_ValueError,\n \"field args is required for AsyncFunctionDef\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = AsyncFunctionDef_kind;\n p->v.AsyncFunctionDef.name = name;\n p->v.AsyncFunctionDef.args = args;\n p->v.AsyncFunctionDef.body = body;\n p->v.AsyncFunctionDef.decorator_list = decorator_list;\n p->v.AsyncFunctionDef.returns = returns;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label_name": "CWE-125", "label": 125} -{"code": "validate_commit_metadata (GVariant *commit_data,\n const char *ref,\n const char *required_metadata,\n gboolean require_xa_metadata,\n GError **error)\n{\n g_autoptr(GVariant) commit_metadata = NULL;\n const char *xa_metadata = NULL;\n\n commit_metadata = g_variant_get_child_value (commit_data, 0);\n\n if (commit_metadata != NULL)\n g_variant_lookup (commit_metadata, \"xa.metadata\", \"&s\", &xa_metadata);\n\n if ((xa_metadata == NULL && require_xa_metadata) ||\n (xa_metadata != NULL && g_strcmp0 (required_metadata, xa_metadata) != 0))\n {\n g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,\n _(\"Commit metadata for %s not matching expected metadata\"), ref);\n return FALSE;\n }\n\n return TRUE;\n}", "label_name": "CWE-276", "label": 276} -{"code": "mark_op_resolved (FlatpakTransactionOperation *op,\n const char *commit,\n GFile *sideload_path,\n GBytes *metadata,\n GBytes *old_metadata)\n{\n g_debug (\"marking op %s:%s resolved to %s\", kind_to_str (op->kind), flatpak_decomposed_get_ref (op->ref), commit ? commit : \"-\");\n\n g_assert (op != NULL);\n\n g_assert (commit != NULL);\n\n op->resolved = TRUE;\n\n if (op->resolved_commit != commit)\n {\n g_free (op->resolved_commit); /* This is already set if we retry resolving to get a token, so free first */\n op->resolved_commit = g_strdup (commit);\n }\n\n if (sideload_path)\n op->resolved_sideload_path = g_object_ref (sideload_path);\n\n if (metadata)\n {\n g_autoptr(GKeyFile) metakey = g_key_file_new ();\n if (g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))\n {\n op->resolved_metadata = g_bytes_ref (metadata);\n op->resolved_metakey = g_steal_pointer (&metakey);\n }\n else\n g_message (\"Warning: Failed to parse metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n }\n if (old_metadata)\n {\n g_autoptr(GKeyFile) metakey = g_key_file_new ();\n if (g_key_file_load_from_bytes (metakey, old_metadata, G_KEY_FILE_NONE, NULL))\n {\n op->resolved_old_metadata = g_bytes_ref (old_metadata);\n op->resolved_old_metakey = g_steal_pointer (&metakey);\n }\n else\n g_message (\"Warning: Failed to parse old metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n }\n}", "label_name": "CWE-276", "label": 276} -{"code": "TEE_Result syscall_cryp_obj_populate(unsigned long obj,\n\t\t\tstruct utee_attribute *usr_attrs,\n\t\t\tunsigned long attr_count)\n{\n\tTEE_Result res;\n\tstruct tee_ta_session *sess;\n\tstruct tee_obj *o;\n\tconst struct tee_cryp_obj_type_props *type_props;\n\tTEE_Attribute *attrs = NULL;\n\n\tres = tee_ta_get_current_session(&sess);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_obj_get(to_user_ta_ctx(sess->ctx),\n\t\t\t tee_svc_uref_to_vaddr(obj), &o);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\t/* Must be a transient object */\n\tif ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\t/* Must not be initialized already */\n\tif ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\ttype_props = tee_svc_find_type_props(o->info.objectType);\n\tif (!type_props)\n\t\treturn TEE_ERROR_NOT_IMPLEMENTED;\n\n\tattrs = malloc(sizeof(TEE_Attribute) * attr_count);\n\tif (!attrs)\n\t\treturn TEE_ERROR_OUT_OF_MEMORY;\n\tres = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,\n\t\t\t attrs);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;\n\n\tres = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,\n\t\t\t\t attrs, attr_count);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;\n\n\tres = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);\n\tif (res == TEE_SUCCESS)\n\t\to->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;\n\nout:\n\tfree(attrs);\n\treturn res;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static int do_i2c_mw(struct cmd_tbl *cmdtp, int flag, int argc,\n\t\t char *const argv[])\n{\n\tuint\tchip;\n\tulong\taddr;\n\tint\talen;\n\tuchar\tbyte;\n\tint\tcount;\n\tint ret;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tstruct udevice *dev;\n#endif\n\n\tif ((argc < 4) || (argc > 5))\n\t\treturn CMD_RET_USAGE;\n\n\t/*\n\t * Chip is always specified.\n\t */\n\tchip = hextoul(argv[1], NULL);\n\n\t/*\n\t * Address is always specified.\n\t */\n\taddr = hextoul(argv[2], NULL);\n\talen = get_alen(argv[2], DEFAULT_ADDR_LEN);\n\tif (alen > 3)\n\t\treturn CMD_RET_USAGE;\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tret = i2c_get_cur_bus_chip(chip, &dev);\n\tif (!ret && alen != -1)\n\t\tret = i2c_set_chip_offset_len(dev, alen);\n\tif (ret)\n\t\treturn i2c_report_err(ret, I2C_ERR_WRITE);\n#endif\n\t/*\n\t * Value to write is always specified.\n\t */\n\tbyte = hextoul(argv[3], NULL);\n\n\t/*\n\t * Optional count\n\t */\n\tif (argc == 5)\n\t\tcount = hextoul(argv[4], NULL);\n\telse\n\t\tcount = 1;\n\n\twhile (count-- > 0) {\n#if CONFIG_IS_ENABLED(DM_I2C)\n\t\tret = dm_i2c_write(dev, addr++, &byte, 1);\n#else\n\t\tret = i2c_write(chip, addr++, alen, &byte, 1);\n#endif\n\t\tif (ret)\n\t\t\treturn i2c_report_err(ret, I2C_ERR_WRITE);\n\t\t/*\n\t\t * Wait for the write to complete. The write can take\n\t\t * up to 10mSec (we allow a little more time).\n\t\t */\n/*\n * No write delay with FRAM devices.\n */\n#if !defined(CONFIG_SYS_I2C_FRAM)\n\t\tudelay(11000);\n#endif\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-787", "label": 787} -{"code": "SWFInput_readSBits(SWFInput input, int number)\n{\n\tint num = SWFInput_readBits(input, number);\n\n\tif ( num & (1<<(number-1)) )\n\t\treturn num - (1<metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1;\n\n\t*in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn 0;\n}", "label_name": "CWE-125", "label": 125} -{"code": "uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0;\n\n\tif (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1;\n\n\t*in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn 0;\n}", "label_name": "CWE-787", "label": 787} -{"code": "uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return NULL;\n\n\tuint32_t *MP4buffer = NULL;\n\tif (index < mp4->indexcount && mp4->mediafp)\n\t{\n\t\tMP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]);\n\n\t\tif (MP4buffer)\n\t\t{\n\t\t\tLONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);\n\t\t\tfread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp);\n\t\t\treturn MP4buffer;\n\t\t}\n\t}\n\treturn NULL;\n}", "label_name": "CWE-787", "label": 787} -{"code": "processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {\n const char *textStart, *textEnd;\n const char *next;\n enum XML_Error result;\n OPEN_INTERNAL_ENTITY *openEntity;\n\n if (parser->m_freeInternalEntities) {\n openEntity = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity->next;\n } else {\n openEntity\n = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));\n if (! openEntity)\n return XML_ERROR_NO_MEMORY;\n }\n entity->open = XML_TRUE;\n entity->processed = 0;\n openEntity->next = parser->m_openInternalEntities;\n parser->m_openInternalEntities = openEntity;\n openEntity->entity = entity;\n openEntity->startTagLevel = parser->m_tagLevel;\n openEntity->betweenDecl = betweenDecl;\n openEntity->internalEventPtr = NULL;\n openEntity->internalEventEndPtr = NULL;\n textStart = (char *)entity->textPtr;\n textEnd = (char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n next = textStart;\n\n#ifdef XML_DTD\n if (entity->is_param) {\n int tok\n = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);\n result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,\n tok, next, &next, XML_FALSE);\n } else\n#endif /* XML_DTD */\n result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,\n textStart, textEnd, &next, XML_FALSE);\n\n if (result == XML_ERROR_NONE) {\n if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {\n entity->processed = (int)(next - textStart);\n parser->m_processor = internalEntityProcessor;\n } else {\n entity->open = XML_FALSE;\n parser->m_openInternalEntities = openEntity->next;\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n }\n }\n return result;\n}", "label_name": "CWE-125", "label": 125} -{"code": "processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {\n const char *textStart, *textEnd;\n const char *next;\n enum XML_Error result;\n OPEN_INTERNAL_ENTITY *openEntity;\n\n if (parser->m_freeInternalEntities) {\n openEntity = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity->next;\n } else {\n openEntity\n = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));\n if (! openEntity)\n return XML_ERROR_NO_MEMORY;\n }\n entity->open = XML_TRUE;\n entity->processed = 0;\n openEntity->next = parser->m_openInternalEntities;\n parser->m_openInternalEntities = openEntity;\n openEntity->entity = entity;\n openEntity->startTagLevel = parser->m_tagLevel;\n openEntity->betweenDecl = betweenDecl;\n openEntity->internalEventPtr = NULL;\n openEntity->internalEventEndPtr = NULL;\n textStart = (char *)entity->textPtr;\n textEnd = (char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n next = textStart;\n\n#ifdef XML_DTD\n if (entity->is_param) {\n int tok\n = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);\n result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,\n tok, next, &next, XML_FALSE);\n } else\n#endif /* XML_DTD */\n result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,\n textStart, textEnd, &next, XML_FALSE);\n\n if (result == XML_ERROR_NONE) {\n if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {\n entity->processed = (int)(next - textStart);\n parser->m_processor = internalEntityProcessor;\n } else {\n entity->open = XML_FALSE;\n parser->m_openInternalEntities = openEntity->next;\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n }\n }\n return result;\n}", "label_name": "CWE-776", "label": 776} -{"code": "vips_tracked_malloc( size_t size )\n{\n void *buf;\n\n\tvips_tracked_init(); \n\n\t/* Need an extra sizeof(size_t) bytes to track \n\t * size of this block. Ask for an extra 16 to make sure we don't break\n\t * alignment rules.\n\t */\n\tsize += 16;\n\n if( !(buf = g_try_malloc( size )) ) {\n#ifdef DEBUG\n\t\tg_assert_not_reached();\n#endif /*DEBUG*/\n\n\t\tvips_error( \"vips_tracked\", \n\t\t\t_( \"out of memory --- size == %dMB\" ), \n\t\t\t(int) (size / (1024.0 * 1024.0)) );\n\t\tg_warning( _( \"out of memory --- size == %dMB\" ), \n\t\t\t(int) (size / (1024.0 * 1024.0)) );\n\n return( NULL );\n\t}\n\n\tg_mutex_lock( vips_tracked_mutex );\n\n\t*((size_t *)buf) = size;\n\tbuf = (void *) ((char *)buf + 16);\n\n\tvips_tracked_mem += size;\n\tif( vips_tracked_mem > vips_tracked_mem_highwater ) \n\t\tvips_tracked_mem_highwater = vips_tracked_mem;\n\tvips_tracked_allocs += 1;\n\n#ifdef DEBUG_VERBOSE\n\tprintf( \"vips_tracked_malloc: %p, %zd bytes\\n\", buf, size ); \n#endif /*DEBUG_VERBOSE*/\n\n\tg_mutex_unlock( vips_tracked_mutex );\n\n\tVIPS_GATE_MALLOC( size ); \n\n return( buf );\n}", "label_name": "CWE-908", "label": 908} -{"code": "completion_glob_pattern (string)\n char *string;\n{\n register int c;\n char *send;\n int open;\n\n DECLARE_MBSTATE;\n\n open = 0;\n send = string + strlen (string);\n\n while (c = *string++)\n {\n switch (c)\n\t{\n\tcase '?':\n\tcase '*':\n\t return (1);\n\n\tcase '[':\n\t open++;\n\t continue;\n\n\tcase ']':\n\t if (open)\n\t return (1);\n\t continue;\n\n\tcase '+':\n\tcase '@':\n\tcase '!':\n\t if (*string == '(')\t/*)*/\n\t return (1);\n\t continue;\n\n\tcase '\\\\':\n\t if (*string++ == 0)\n\t return (0);\n\t}\n\n /* Advance one fewer byte than an entire multibyte character to\n\t account for the auto-increment in the loop above. */\n#ifdef HANDLE_MULTIBYTE\n string--;\n ADVANCE_CHAR_P (string, send - string);\n string++;\n#else\n ADVANCE_CHAR_P (string, send - string);\n#endif\n }\n return (0);\n}", "label_name": "CWE-273", "label": 273} -{"code": "unquoted_glob_pattern_p (string)\n register char *string;\n{\n register int c;\n char *send;\n int open, bsquote;\n\n DECLARE_MBSTATE;\n\n open = bsquote = 0;\n send = string + strlen (string);\n\n while (c = *string++)\n {\n switch (c)\n\t{\n\tcase '?':\n\tcase '*':\n\t return (1);\n\n\tcase '[':\n\t open++;\n\t continue;\n\n\tcase ']':\n\t if (open)\n\t return (1);\n\t continue;\n\n\tcase '+':\n\tcase '@':\n\tcase '!':\n\t if (*string == '(')\t/*)*/\n\t return (1);\n\t continue;\n\n\t/* A pattern can't end with a backslash, but a backslash in the pattern\n\t can be removed by the matching engine, so we have to run it through\n\t globbing. */\n\tcase '\\\\':\n\t if (*string != '\\0' && *string != '/')\n\t {\n\t bsquote = 1;\n\t string++;\n\t continue;\n\t }\n\t else if (*string == 0)\n\t return (0);\n\t \t \n\tcase CTLESC:\n\t if (*string++ == '\\0')\n\t return (0);\n\t}\n\n /* Advance one fewer byte than an entire multibyte character to\n\t account for the auto-increment in the loop above. */\n#ifdef HANDLE_MULTIBYTE\n string--;\n ADVANCE_CHAR_P (string, send - string);\n string++;\n#else\n ADVANCE_CHAR_P (string, send - string);\n#endif\n }\n\n return ((bsquote && posix_glob_backslash) ? 2 : 0);\n}", "label_name": "CWE-273", "label": 273} -{"code": "pci_emul_add_capability(struct pci_vdev *dev, u_char *capdata, int caplen)\n{\n\tint i, capoff, reallen;\n\tuint16_t sts;\n\n\tassert(caplen > 0);\n\n\treallen = roundup2(caplen, 4);\t\t/* dword aligned */\n\n\tsts = pci_get_cfgdata16(dev, PCIR_STATUS);\n\tif ((sts & PCIM_STATUS_CAPPRESENT) == 0)\n\t\tcapoff = CAP_START_OFFSET;\n\telse\n\t\tcapoff = dev->capend + 1;\n\n\t/* Check if we have enough space */\n\tif (capoff + reallen > PCI_REGMAX + 1)\n\t\treturn -1;\n\n\t/* Set the previous capability pointer */\n\tif ((sts & PCIM_STATUS_CAPPRESENT) == 0) {\n\t\tpci_set_cfgdata8(dev, PCIR_CAP_PTR, capoff);\n\t\tpci_set_cfgdata16(dev, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT);\n\t} else\n\t\tpci_set_cfgdata8(dev, dev->prevcap + 1, capoff);\n\n\t/* Copy the capability */\n\tfor (i = 0; i < caplen; i++)\n\t\tpci_set_cfgdata8(dev, capoff + i, capdata[i]);\n\n\t/* Set the next capability pointer */\n\tpci_set_cfgdata8(dev, capoff + 1, 0);\n\n\tdev->prevcap = capoff;\n\tdev->capend = capoff + reallen - 1;\n\treturn 0;\n}", "label_name": "CWE-617", "label": 617} -{"code": "modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n{\n\tint error;\n\tstruct inout_port iop;\n\tstruct mem_range mr;\n\n\tif (is_pci_gvt(dev)) {\n\t\t/* GVT device is the only one who traps the pci bar access and\n\t\t * intercepts the corresponding contents in kernel. It needs\n\t\t * register pci resource only, but no need to register the\n\t\t * region.\n\t\t *\n\t\t * FIXME: This is a short term solution. This patch will be\n\t\t * obsoleted with the migration of using OVMF to do bar\n\t\t * addressing and generate ACPI PCI resource from using\n\t\t * acrn-dm.\n\t\t */\n\t\tprintf(\"modify_bar_registration: bypass for pci-gvt\\n\");\n\t\treturn;\n\t}\n\tswitch (dev->bar[idx].type) {\n\tcase PCIBAR_IO:\n\t\tbzero(&iop, sizeof(struct inout_port));\n\t\tiop.name = dev->name;\n\t\tiop.port = dev->bar[idx].addr;\n\t\tiop.size = dev->bar[idx].size;\n\t\tif (registration) {\n\t\t\tiop.flags = IOPORT_F_INOUT;\n\t\t\tiop.handler = pci_emul_io_handler;\n\t\t\tiop.arg = dev;\n\t\t\terror = register_inout(&iop);\n\t\t} else\n\t\t\terror = unregister_inout(&iop);\n\t\tbreak;\n\tcase PCIBAR_MEM32:\n\tcase PCIBAR_MEM64:\n\t\tbzero(&mr, sizeof(struct mem_range));\n\t\tmr.name = dev->name;\n\t\tmr.base = dev->bar[idx].addr;\n\t\tmr.size = dev->bar[idx].size;\n\t\tif (registration) {\n\t\t\tmr.flags = MEM_F_RW;\n\t\t\tmr.handler = pci_emul_mem_handler;\n\t\t\tmr.arg1 = dev;\n\t\t\tmr.arg2 = idx;\n\t\t\terror = register_mem(&mr);\n\t\t} else\n\t\t\terror = unregister_mem(&mr);\n\t\tbreak;\n\tdefault:\n\t\terror = EINVAL;\n\t\tbreak;\n\t}\n\tassert(error == 0);\n}", "label_name": "CWE-617", "label": 617} -{"code": "pci_emul_add_msicap(struct pci_vdev *dev, int msgnum)\n{\n\tstruct msicap msicap;\n\n\tpci_populate_msicap(&msicap, msgnum, 0);\n\n\treturn pci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n}", "label_name": "CWE-617", "label": 617} -{"code": "pci_get_cfgdata32(struct pci_vdev *dev, int offset)\n{\n\tassert(offset <= (PCI_REGMAX - 3) && (offset & 3) == 0);\n\treturn (*(uint32_t *)(dev->cfgdata + offset));\n}", "label_name": "CWE-617", "label": 617} -{"code": "string_object_to_c_ast(const char *s, PyObject *filename, int start,\n PyCompilerFlags *flags, int feature_version,\n PyArena *arena)\n{\n mod_ty mod;\n PyCompilerFlags localflags;\n perrdetail err;\n int iflags = PARSER_FLAGS(flags);\n\n node *n = Ta3Parser_ParseStringObject(s, filename,\n &_Ta3Parser_Grammar, start, &err,\n &iflags);\n if (flags == NULL) {\n localflags.cf_flags = 0;\n flags = &localflags;\n }\n if (n) {\n flags->cf_flags |= iflags & PyCF_MASK;\n mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena);\n Ta3Node_Free(n);\n }\n else {\n err_input(&err);\n mod = NULL;\n }\n err_free(&err);\n return mod;\n}", "label_name": "CWE-125", "label": 125} -{"code": "tok_new(void)\n{\n struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(\n sizeof(struct tok_state));\n if (tok == NULL)\n return NULL;\n tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;\n tok->done = E_OK;\n tok->fp = NULL;\n tok->input = NULL;\n tok->tabsize = TABSIZE;\n tok->indent = 0;\n tok->indstack[0] = 0;\n\n tok->atbol = 1;\n tok->pendin = 0;\n tok->prompt = tok->nextprompt = NULL;\n tok->lineno = 0;\n tok->level = 0;\n tok->altwarning = 1;\n tok->alterror = 1;\n tok->alttabsize = 1;\n tok->altindstack[0] = 0;\n tok->decoding_state = STATE_INIT;\n tok->decoding_erred = 0;\n tok->read_coding_spec = 0;\n tok->enc = NULL;\n tok->encoding = NULL;\n tok->cont_line = 0;\n#ifndef PGEN\n tok->filename = NULL;\n tok->decoding_readline = NULL;\n tok->decoding_buffer = NULL;\n#endif\n\n tok->async_def = 0;\n tok->async_def_indent = 0;\n tok->async_def_nl = 0;\n\n return tok;\n}", "label_name": "CWE-125", "label": 125} -{"code": "fp_setreadl(struct tok_state *tok, const char* enc)\n{\n PyObject *readline, *io, *stream;\n _Py_IDENTIFIER(open);\n _Py_IDENTIFIER(readline);\n int fd;\n long pos;\n\n fd = fileno(tok->fp);\n /* Due to buffering the file offset for fd can be different from the file\n * position of tok->fp. If tok->fp was opened in text mode on Windows,\n * its file position counts CRLF as one char and can't be directly mapped\n * to the file offset for fd. Instead we step back one byte and read to\n * the end of line.*/\n pos = ftell(tok->fp);\n if (pos == -1 ||\n lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) {\n PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL);\n return 0;\n }\n\n io = PyImport_ImportModuleNoBlock(\"io\");\n if (io == NULL)\n return 0;\n\n stream = _PyObject_CallMethodId(io, &PyId_open, \"isisOOO\",\n fd, \"r\", -1, enc, Py_None, Py_None, Py_False);\n Py_DECREF(io);\n if (stream == NULL)\n return 0;\n\n readline = _PyObject_GetAttrId(stream, &PyId_readline);\n Py_DECREF(stream);\n if (readline == NULL)\n return 0;\n Py_XSETREF(tok->decoding_readline, readline);\n\n if (pos > 0) {\n PyObject *bufobj = PyObject_CallObject(readline, NULL);\n if (bufobj == NULL)\n return 0;\n Py_DECREF(bufobj);\n }\n\n return 1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "indenterror(struct tok_state *tok)\n{\n if (tok->alterror) {\n tok->done = E_TABSPACE;\n tok->cur = tok->inp;\n return 1;\n }\n if (tok->altwarning) {\n#ifdef PGEN\n PySys_WriteStderr(\"inconsistent use of tabs and spaces \"\n \"in indentation\\n\");\n#else\n PySys_FormatStderr(\"%U: inconsistent use of tabs and spaces \"\n \"in indentation\\n\", tok->filename);\n#endif\n tok->altwarning = 0;\n }\n return 0;\n}", "label_name": "CWE-125", "label": 125} -{"code": "static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)\n{\n PyObject *fnames, *result;\n int i;\n fnames = PyTuple_New(num_fields);\n if (!fnames) return NULL;\n for (i = 0; i < num_fields; i++) {\n PyObject *field = PyUnicode_FromString(fields[i]);\n if (!field) {\n Py_DECREF(fnames);\n return NULL;\n }\n PyTuple_SET_ITEM(fnames, i, field);\n }\n result = PyObject_CallFunction((PyObject*)&PyType_Type, \"s(O){sOss}\",\n type, base, \"_fields\", fnames, \"__module__\", \"_ast3\");\n Py_DECREF(fnames);\n return (PyTypeObject*)result;\n}", "label_name": "CWE-125", "label": 125} -{"code": "ast2obj_keyword(void* _o)\n{\n keyword_ty o = (keyword_ty)_o;\n PyObject *result = NULL, *value = NULL;\n if (!o) {\n Py_INCREF(Py_None);\n return Py_None;\n }\n\n result = PyType_GenericNew(keyword_type, NULL, NULL);\n if (!result) return NULL;\n value = ast2obj_identifier(o->arg);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_arg, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->value);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_value, value) == -1)\n goto failed;\n Py_DECREF(value);\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label_name": "CWE-125", "label": 125} -{"code": "obj2ast_keyword(PyObject* obj, keyword_ty* out, PyArena* arena)\n{\n PyObject* tmp = NULL;\n identifier arg;\n expr_ty value;\n\n if (exists_not_none(obj, &PyId_arg)) {\n int res;\n tmp = _PyObject_GetAttrId(obj, &PyId_arg);\n if (tmp == NULL) goto failed;\n res = obj2ast_identifier(tmp, &arg, arena);\n if (res != 0) goto failed;\n Py_CLEAR(tmp);\n } else {\n arg = NULL;\n }\n if (_PyObject_HasAttrId(obj, &PyId_value)) {\n int res;\n tmp = _PyObject_GetAttrId(obj, &PyId_value);\n if (tmp == NULL) goto failed;\n res = obj2ast_expr(tmp, &value, arena);\n if (res != 0) goto failed;\n Py_CLEAR(tmp);\n } else {\n PyErr_SetString(PyExc_TypeError, \"required field \\\"value\\\" missing from keyword\");\n return 1;\n }\n *out = keyword(arg, value, arena);\n return 0;\nfailed:\n Py_XDECREF(tmp);\n return 1;\n}", "label_name": "CWE-125", "label": 125} -{"code": "static int exists_not_none(PyObject *obj, _Py_Identifier *id)\n{\n int isnone;\n PyObject *attr = _PyObject_GetAttrId(obj, id);\n if (!attr) {\n PyErr_Clear();\n return 0;\n }\n isnone = attr == Py_None;\n Py_DECREF(attr);\n return !isnone;\n}", "label_name": "CWE-125", "label": 125} -{"code": "ast2obj_slice(void* _o)\n{\n slice_ty o = (slice_ty)_o;\n PyObject *result = NULL, *value = NULL;\n if (!o) {\n Py_INCREF(Py_None);\n return Py_None;\n }\n\n switch (o->kind) {\n case Slice_kind:\n result = PyType_GenericNew(Slice_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_expr(o->v.Slice.lower);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_lower, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->v.Slice.upper);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_upper, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->v.Slice.step);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_step, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n case ExtSlice_kind:\n result = PyType_GenericNew(ExtSlice_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_list(o->v.ExtSlice.dims, ast2obj_slice);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_dims, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n case Index_kind:\n result = PyType_GenericNew(Index_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_expr(o->v.Index.value);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_value, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n }\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label_name": "CWE-125", "label": 125} -{"code": "ast_for_decorator(struct compiling *c, const node *n)\n{\n /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */\n expr_ty d = NULL;\n expr_ty name_expr;\n\n REQ(n, decorator);\n REQ(CHILD(n, 0), AT);\n REQ(RCHILD(n, -1), NEWLINE);\n\n name_expr = ast_for_dotted_name(c, CHILD(n, 1));\n if (!name_expr)\n return NULL;\n\n if (NCH(n) == 3) { /* No arguments */\n d = name_expr;\n name_expr = NULL;\n }\n else if (NCH(n) == 5) { /* Call with no arguments */\n d = Call(name_expr, NULL, NULL, LINENO(n),\n n->n_col_offset, c->c_arena);\n if (!d)\n return NULL;\n name_expr = NULL;\n }\n else {\n d = ast_for_call(c, CHILD(n, 3), name_expr);\n if (!d)\n return NULL;\n name_expr = NULL;\n }\n\n return d;\n}", "label_name": "CWE-125", "label": 125} -{"code": "FstringParser_Finish(FstringParser *state, struct compiling *c,\n const node *n)\n{\n asdl_seq *seq;\n\n FstringParser_check_invariants(state);\n\n /* If we're just a constant string with no expressions, return\n that. */\n if(state->expr_list.size == 0) {\n if (!state->last_str) {\n /* Create a zero length string. */\n state->last_str = PyUnicode_FromStringAndSize(NULL, 0);\n if (!state->last_str)\n goto error;\n }\n return make_str_node_and_del(&state->last_str, c, n);\n }\n\n /* Create a Str node out of last_str, if needed. It will be the\n last node in our expression list. */\n if (state->last_str) {\n expr_ty str = make_str_node_and_del(&state->last_str, c, n);\n if (!str || ExprList_Append(&state->expr_list, str) < 0)\n goto error;\n }\n /* This has already been freed. */\n assert(state->last_str == NULL);\n\n seq = ExprList_Finish(&state->expr_list, c->c_arena);\n if (!seq)\n goto error;\n\n /* If there's only one expression, return it. Otherwise, we need\n to join them together. */\n if (seq->size == 1)\n return seq->elements[0];\n\n return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena);\n\nerror:\n FstringParser_Dealloc(state);\n return NULL;\n}", "label_name": "CWE-125", "label": 125} -{"code": "decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s,\n size_t len)\n{\n return PyBytes_DecodeEscape(s, len, NULL, 0, NULL);\n}", "label_name": "CWE-125", "label": 125} -{"code": "add_mibfile(const char* tmpstr, const char* d_name, FILE *ip )\n{\n FILE *fp;\n char token[MAXTOKEN], token2[MAXTOKEN];\n\n /*\n * which module is this \n */\n if ((fp = fopen(tmpstr, \"r\")) == NULL) {\n snmp_log_perror(tmpstr);\n return 1;\n }\n DEBUGMSGTL((\"parse-mibs\", \"Checking file: %s...\\n\",\n tmpstr));\n mibLine = 1;\n File = tmpstr;\n if (get_token(fp, token, MAXTOKEN) != LABEL) {\n\t fclose(fp);\n\t return 1;\n }\n /*\n * simple test for this being a MIB \n */\n if (get_token(fp, token2, MAXTOKEN) == DEFINITIONS) {\n new_module(token, tmpstr);\n if (ip)\n fprintf(ip, \"%s %s\\n\", token, d_name);\n fclose(fp);\n return 0;\n } else {\n fclose(fp);\n return 1;\n }\n}", "label_name": "CWE-59", "label": 59} -{"code": "pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)\n{\n\tInitializeCriticalSection(mutex);\n\treturn 0;\n}", "label_name": "CWE-125", "label": 125} -{"code": "static inline void init_keys(at91_aes_key_size_t *key_size,\n\t\t\t unsigned int *cipher_key,\n\t\t\t unsigned int *cmac_key,\n\t\t\t unsigned int *iv)\n{\n#if defined(CONFIG_AES_KEY_SIZE_128)\n\t*key_size = AT91_AES_KEY_SIZE_128;\n#elif defined(CONFIG_AES_KEY_SIZE_192)\n\t*key_size = AT91_AES_KEY_SIZE_192;\n#elif defined(CONFIG_AES_KEY_SIZE_256)\n\t*key_size = AT91_AES_KEY_SIZE_256;\n#else\n#error \"bad AES key size\"\n#endif\n\n\tiv[0]\t\t= CONFIG_AES_IV_WORD0;\n\tiv[1]\t\t= CONFIG_AES_IV_WORD1;\n\tiv[2]\t\t= CONFIG_AES_IV_WORD2;\n\tiv[3]\t\t= CONFIG_AES_IV_WORD3;\n\n\tcipher_key[0]\t= CONFIG_AES_CIPHER_KEY_WORD0;\n\tcmac_key[0]\t= CONFIG_AES_CMAC_KEY_WORD0;\n\tcipher_key[1]\t= CONFIG_AES_CIPHER_KEY_WORD1;\n\tcmac_key[1]\t= CONFIG_AES_CMAC_KEY_WORD1;\n\tcipher_key[2]\t= CONFIG_AES_CIPHER_KEY_WORD2;\n\tcmac_key[2]\t= CONFIG_AES_CMAC_KEY_WORD2;\n\tcipher_key[3]\t= CONFIG_AES_CIPHER_KEY_WORD3;\n\tcmac_key[3]\t= CONFIG_AES_CMAC_KEY_WORD3;\n\n#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)\n\tcipher_key[4]\t= CONFIG_AES_CIPHER_KEY_WORD4;\n\tcmac_key[4]\t= CONFIG_AES_CMAC_KEY_WORD4;\n\tcipher_key[5]\t= CONFIG_AES_CIPHER_KEY_WORD5;\n\tcmac_key[5]\t= CONFIG_AES_CMAC_KEY_WORD5;\n#endif\n\n#if defined(CONFIG_AES_KEY_SIZE_256)\n\tcipher_key[6]\t= CONFIG_AES_CIPHER_KEY_WORD6;\n\tcmac_key[6]\t= CONFIG_AES_CMAC_KEY_WORD6;\n\tcipher_key[7]\t= CONFIG_AES_CIPHER_KEY_WORD7;\n\tcmac_key[7]\t= CONFIG_AES_CMAC_KEY_WORD7;\n#endif\n}", "label_name": "CWE-212", "label": 212} -{"code": "sysLocation_handler(snmp_varbind_t *varbind, uint32_t *oid)\n{\n snmp_api_set_string(varbind, oid, \"\");\n}", "label_name": "CWE-125", "label": 125} -{"code": "snmp_api_set_oid(snmp_varbind_t *varbind, uint32_t *oid, uint32_t *ret_oid)\n{\n\n snmp_api_replace_oid(varbind, oid);\n varbind->value_type = BER_DATA_TYPE_OID;\n varbind->value.oid = ret_oid;\n}", "label_name": "CWE-125", "label": 125} -{"code": "snmp_ber_decode_string_len_buffer(unsigned char *buf, uint32_t *buff_len, const char **str, uint32_t *length)\n{\n uint8_t type, i, length_bytes;\n\n buf = snmp_ber_decode_type(buf, buff_len, &type);\n\n if(buf == NULL || type != BER_DATA_TYPE_OCTET_STRING) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return NULL;\n }\n\n if((*buf & 0x80) == 0) {\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n } else {\n\n length_bytes = (uint8_t)(*buf++ & 0x7F);\n (*buff_len)--;\n if(length_bytes > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return NULL;\n }\n\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n for(i = 1; i < length_bytes; ++i) {\n *length <<= 8;\n *length |= *buf++;\n (*buff_len)--;\n }\n }\n\n *str = (const char *)buf;\n *buff_len -= *length;\n\n return buf + *length;\n}", "label_name": "CWE-125", "label": 125} -{"code": "snmp_ber_encode_unsigned_integer(unsigned char *out, uint32_t *out_len, uint8_t type, uint32_t number)\n{\n uint32_t original_out_len;\n\n original_out_len = *out_len;\n do {\n (*out_len)++;\n *out-- = (uint8_t)(number & 0xFF);\n number >>= 8;\n } while(number);\n\n out = snmp_ber_encode_length(out, out_len, ((*out_len - original_out_len) & 0xFF));\n out = snmp_ber_encode_type(out, out_len, type);\n\n return out;\n}", "label_name": "CWE-125", "label": 125} -{"code": "snmp_ber_decode_type(unsigned char *buff, uint32_t *buff_len, uint8_t *type)\n{\n if(*buff_len == 0) {\n return NULL;\n }\n\n *type = *buff++;\n (*buff_len)--;\n\n return buff;\n}", "label_name": "CWE-125", "label": 125} -{"code": "snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)\n{\n static snmp_header_t header;\n static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];\n static uint32_t varbind_length = SNMP_MAX_NR_VALUES;\n\n buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);\n if(buff == NULL) {\n return NULL;\n }\n\n if(header.version != SNMP_VERSION_1) {\n if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) {\n LOG_ERR(\"Request with invalid community\\n\");\n return NULL;\n }\n }\n\n /*\n * Now handle the SNMP requests depending on their type\n */\n switch(header.pdu_type) {\n case SNMP_DATA_TYPE_PDU_GET_REQUEST:\n if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {\n return NULL;\n }\n break;\n\n case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:\n if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {\n return NULL;\n }\n break;\n\n case SNMP_DATA_TYPE_PDU_GET_BULK:\n if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {\n return NULL;\n }\n break;\n\n default:\n LOG_ERR(\"Invalid request type\");\n return NULL;\n }\n\n header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;\n out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);\n\n return ++out;\n}", "label_name": "CWE-125", "label": 125} -{"code": "snmp_mib_add(snmp_mib_resource_t *new_resource)\n{\n snmp_mib_resource_t *resource;\n\n for(resource = list_head(snmp_mib);\n resource; resource = resource->next) {\n\n if(snmp_oid_cmp_oid(resource->oid, new_resource->oid) > 0) {\n break;\n }\n }\n if(resource == NULL) {\n list_add(snmp_mib, new_resource);\n } else {\n list_insert(snmp_mib, new_resource, resource);\n }\n\n#if LOG_LEVEL == LOG_LEVEL_DBG\n /*\n * We print the entire resource table\n */\n LOG_DBG(\"Table after insert.\\n\");\n for(resource = list_head(snmp_mib);\n resource; resource = resource->next) {\n\n snmp_oid_print(resource->oid);\n }\n#endif /* LOG_LEVEL == LOG_LEVEL_DBG */\n}", "label_name": "CWE-125", "label": 125} -{"code": "static pj_status_t pjsip_auth_verify( const pjsip_authorization_hdr *hdr,\n\t\t\t\t const pj_str_t *method,\n\t\t\t\t const pjsip_cred_info *cred_info )\n{\n if (pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR) == 0) {\n\tchar digest_buf[PJSIP_MD5STRLEN];\n\tpj_str_t digest;\n\tconst pjsip_digest_credential *dig = &hdr->credential.digest;\n\n\t/* Check that username and realm match. \n\t * These checks should have been performed before entering this\n\t * function.\n\t */\n\tPJ_ASSERT_RETURN(pj_strcmp(&dig->username, &cred_info->username) == 0,\n\t\t\t PJ_EINVALIDOP);\n\tPJ_ASSERT_RETURN(pj_strcmp(&dig->realm, &cred_info->realm) == 0,\n\t\t\t PJ_EINVALIDOP);\n\n\t/* Prepare for our digest calculation. */\n\tdigest.ptr = digest_buf;\n\tdigest.slen = PJSIP_MD5STRLEN;\n\n\t/* Create digest for comparison. */\n\tpjsip_auth_create_digest(&digest, \n\t\t\t\t &hdr->credential.digest.nonce,\n\t\t\t\t &hdr->credential.digest.nc, \n\t\t\t\t &hdr->credential.digest.cnonce,\n\t\t\t\t &hdr->credential.digest.qop,\n\t\t\t\t &hdr->credential.digest.uri,\n\t\t\t\t &cred_info->realm,\n\t\t\t\t cred_info, \n\t\t\t\t method );\n\n\t/* Compare digest. */\n\treturn (pj_stricmp(&digest, &hdr->credential.digest.response) == 0) ?\n\t PJ_SUCCESS : PJSIP_EAUTHINVALIDDIGEST;\n\n } else {\n\tpj_assert(!\"Unsupported authentication scheme\");\n\treturn PJSIP_EINVALIDAUTHSCHEME;\n }\n}", "label_name": "CWE-120", "label": 120} -{"code": "static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len)\n{\n char *p = buf;\n char *end = buf+len;\n unsigned i;\n int printed;\n\n /* check length for the \"m=\" line. */\n if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) {\n\treturn -1;\n }\n *p++ = 'm';\t /* m= */\n *p++ = '=';\n pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen);\n p += m->desc.media.slen;\n *p++ = ' ';\n printed = pj_utoa(m->desc.port, p);\n p += printed;\n if (m->desc.port_count > 1) {\n\t*p++ = '/';\n\tprinted = pj_utoa(m->desc.port_count, p);\n\tp += printed;\n }\n *p++ = ' ';\n pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen);\n p += m->desc.transport.slen;\n for (i=0; idesc.fmt_count; ++i) {\n\t*p++ = ' ';\n\tpj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen);\n\tp += m->desc.fmt[i].slen;\n }\n *p++ = '\\r';\n *p++ = '\\n';\n\n /* print connection info, if present. */\n if (m->conn) {\n\tprinted = print_connection_info(m->conn, p, (int)(end-p));\n\tif (printed < 0) {\n\t return -1;\n\t}\n\tp += printed;\n }\n \n /* print optional bandwidth info. */\n for (i=0; ibandw_count; ++i) {\n\tprinted = (int)print_bandw(m->bandw[i], p, end-p);\n\tif (printed < 0) {\n\t return -1;\n\t}\n\tp += printed;\n }\n\n /* print attributes. */\n for (i=0; iattr_count; ++i) {\n\tprinted = (int)print_attr(m->attr[i], p, end-p);\n\tif (printed < 0) {\n\t return -1;\n\t}\n\tp += printed;\n }\n\n return (int)(p-buf);\n}", "label_name": "CWE-120", "label": 120} -{"code": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_pli(\n\t\t\t\t\tpjmedia_rtcp_session *session, \n\t\t\t\t\tvoid *buf,\n\t\t\t\t\tpj_size_t *length)\n{\n pjmedia_rtcp_common *hdr;\n unsigned len;\n\n PJ_ASSERT_RETURN(session && buf && length, PJ_EINVAL);\n\n len = 12;\n if (len > *length)\n\treturn PJ_ETOOSMALL;\n\n /* Build RTCP-FB PLI header */\n hdr = (pjmedia_rtcp_common*)buf;\n pj_memcpy(hdr, &session->rtcp_rr_pkt.common, sizeof(*hdr));\n hdr->pt = RTCP_PSFB;\n hdr->count = 1; /* FMT = 1 */\n hdr->length = pj_htons((pj_uint16_t)(len/4 - 1));\n\n /* Finally */\n *length = len;\n\n return PJ_SUCCESS;\n}", "label_name": "CWE-125", "label": 125} -{"code": "char *compose_path(ctrl_t *ctrl, char *path)\n{\n\tstruct stat st;\n\tstatic char rpath[PATH_MAX];\n\tchar *name, *ptr;\n\tchar dir[PATH_MAX] = { 0 };\n\n\tstrlcpy(dir, ctrl->cwd, sizeof(dir));\n\tDBG(\"Compose path from cwd: %s, arg: %s\", ctrl->cwd, path ?: \"\");\n\tif (!path || !strlen(path))\n\t\tgoto check;\n\n\tif (path) {\n\t\tif (path[0] != '/') {\n\t\t\tif (dir[strlen(dir) - 1] != '/')\n\t\t\t\tstrlcat(dir, \"/\", sizeof(dir));\n\t\t}\n\t\tstrlcat(dir, path, sizeof(dir));\n\t}\n\ncheck:\n\twhile ((ptr = strstr(dir, \"//\")))\n\t\tmemmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);\n\n\tif (!chrooted) {\n\t\tsize_t len = strlen(home);\n\n\t\tDBG(\"Server path from CWD: %s\", dir);\n\t\tif (len > 0 && home[len - 1] == '/')\n\t\t\tlen--;\n\t\tmemmove(dir + len, dir, strlen(dir) + 1);\n\t\tmemcpy(dir, home, len);\n\t\tDBG(\"Resulting non-chroot path: %s\", dir);\n\t}\n\n\t/*\n\t * Handle directories slightly differently, since dirname() on a\n\t * directory returns the parent directory. So, just squash ..\n\t */\n\tif (!stat(dir, &st) && S_ISDIR(st.st_mode)) {\n\t\tif (!realpath(dir, rpath))\n\t\t\treturn NULL;\n\t} else {\n\t\t/*\n\t\t * Check realpath() of directory containing the file, a\n\t\t * STOR may want to save a new file. Then append the\n\t\t * file and return it.\n\t\t */\n\t\tname = basename(path);\n\t\tptr = dirname(dir);\n\n\t\tmemset(rpath, 0, sizeof(rpath));\n\t\tif (!realpath(ptr, rpath)) {\n\t\t\tINFO(\"Failed realpath(%s): %m\", ptr);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (rpath[1] != 0)\n\t\t\tstrlcat(rpath, \"/\", sizeof(rpath));\n\t\tstrlcat(rpath, name, sizeof(rpath));\n\t}\n\n\tif (!chrooted && strncmp(dir, home, strlen(home))) {\n\t\tDBG(\"Failed non-chroot dir:%s vs home:%s\", dir, home);\n\t\treturn NULL;\n\t}\n\n\treturn rpath;\n}", "label_name": "CWE-22", "label": 22} -{"code": "static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,\n Jsi_Value **ret, Jsi_Func *funcPtr)\n{\n if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj))\n return Jsi_LogError(\"expected array object\");\n const char *jstr = \"\";\n int argc, curlen;\n Jsi_DString dStr = {};\n\n curlen = Jsi_ObjGetLength(interp, _this->d.obj);\n if (curlen == 0) {\n goto bail;\n }\n\n if (Jsi_ValueGetLength(interp, args) >= 1) {\n Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0);\n if (sc != NULL)\n jstr = Jsi_ValueToString(interp, sc, NULL);\n }\n \n if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {\n goto bail;\n }\n int i;\n for (i = 0; i < argc; ++i) {\n const char *cp;\n Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i);\n if (!ov) {\n /* TODO: are NULL args ok? */ \n continue;\n cp = \"\";\n } else\n cp = Jsi_ValueToString(interp, ov, NULL);\n if (i && jstr[0])\n Jsi_DSAppend(&dStr, jstr, NULL);\n Jsi_DSAppend(&dStr, cp, NULL);\n }\n \n Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr));\n Jsi_DSFree(&dStr);\n return JSI_OK;\nbail:\n Jsi_ValueMakeStringDup(interp, ret, \"\");\n return JSI_OK; \n}", "label_name": "CWE-190", "label": 190} -{"code": "const char *jsi_GetHomeDir(Jsi_Interp *interp) {\n const char *str = NULL;\n if (interp->homeDir)\n return interp->homeDir;\n#ifdef __WIN32\n str = getenv(\"USERPROFILE\"); /* TODO: windows home dir. */\n#else\n \n if ((str = getenv(\"HOME\")) == NULL) {\n struct passwd pwd, *pw;\n char buf[20000];\n if (getpwuid_r(getuid(), &pwd, buf, sizeof(buf), &pw) == 0 && pw->pw_dir) \n str = pw->pw_dir;\n }\n#endif\n if (!str) {\n Jsi_LogBug(\"no home dir\");\n str = \"/\";\n }\n#ifdef JSI_LITE_ONLY\n return str;\n#else\n return (interp->homeDir = Jsi_KeyAdd(interp, str));\n#endif\n}", "label_name": "CWE-120", "label": 120} -{"code": "static void mdbEvalSetColumn(MyDbEvalContext *p, int iCol, Jsi_DString *dStr) {\n //Jsi_Interp *interp = p->jdb->interp;\n char nbuf[200];\n MysqlPrep *prep = p->prep;\n SqlFieldResults *field = prep->fieldResult+iCol;\n Jsi_Interp *interp = p->jdb->interp;\n if (field->isnull)\n return;\n \n switch(field->jsiTypeMap) {\n case JSI_OPTION_STRING: {\n int bytes = field->len;\n const char *zBlob = field->buffer.vstring;\n \n if( !zBlob ) {\n const char *nv = p->jdb->optPtr->nullvalue;\n Jsi_DSAppend(dStr, nv?nv:\"null\", NULL);\n return;\n }\n Jsi_DSAppendLen(dStr, zBlob, bytes);\n return;\n }\n case JSI_OPTION_BOOL: {\n snprintf(nbuf, sizeof(nbuf), \"%s\", field->buffer.vchar?\"true\":\"false\");\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case JSI_OPTION_INT64: {\n snprintf(nbuf, sizeof(nbuf), \"%lld\", field->buffer.vlonglong);\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n //case JSI_OPTION_TIME_T:\n case JSI_OPTION_TIME_D:\n case JSI_OPTION_TIME_W: {\n Jsi_Number jtime = mdbMyTimeToJS(&field->buffer.timestamp);\n Jsi_NumberToString(interp, jtime, nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case JSI_OPTION_DOUBLE: {\n Jsi_NumberToString(interp, field->buffer.vdouble, nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n default:\n Jsi_LogWarn(\"unknown type: %d\", field->jsiTypeMap);\n \n }\n}", "label_name": "CWE-120", "label": 120} -{"code": "static void dbEvalSetColumn(DbEvalContext *p, int iCol, Jsi_DString *dStr) {\n Jsi_Interp *interp = p->jdb->interp;\n char nbuf[200];\n\n sqlite3_stmt *pStmt = p->pPreStmt->pStmt;\n\n switch( sqlite3_column_type(pStmt, iCol) ) {\n case SQLITE_BLOB: {\n int bytes = sqlite3_column_bytes(pStmt, iCol);\n const char *zBlob = (char*)sqlite3_column_blob(pStmt, iCol);\n if( !zBlob ) {\n return;\n }\n Jsi_DSAppendLen(dStr, zBlob, bytes);\n return;\n }\n case SQLITE_INTEGER: {\n sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);\n if (v==0 || v==1) {\n const char *dectyp = sqlite3_column_decltype(pStmt, iCol);\n if (dectyp && !Jsi_Strncasecmp(dectyp,\"bool\", 4)) {\n Jsi_DSAppend(dStr, (v?\"true\":\"false\"), NULL);\n return;\n }\n }\n#ifdef __WIN32\n snprintf(nbuf, sizeof(nbuf), \"%\" PRId64, (Jsi_Wide)v);\n#else\n snprintf(nbuf, sizeof(nbuf), \"%lld\", v);\n#endif\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case SQLITE_FLOAT: {\n Jsi_NumberToString(interp, sqlite3_column_double(pStmt, iCol), nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case SQLITE_NULL: {\n return;\n }\n }\n const char *str = (char*)sqlite3_column_text(pStmt, iCol );\n if (!str)\n str = p->jdb->optPtr->nullvalue;\n Jsi_DSAppend(dStr, str?str:\"\", NULL);\n}", "label_name": "CWE-120", "label": 120} -{"code": "jsi_wsGetHeaders(jsi_wsPss *pss, struct lws *wsi, Jsi_DString* dStr, int lens[], int hmax)\n{\n int n = 0, i = 0, nlen;\n char buf[1000];\n const char *cp;\n while ((cp = (char*)lws_token_to_string((enum lws_token_indexes)n))) {\n int len = lws_hdr_copy(wsi, buf, sizeof(buf), ( enum lws_token_indexes)n);\n n++;\n if (i>=(n*2+2)) break;\n if (len<=0) continue;\n buf[sizeof(buf)-1] = 0;\n if (!buf[0]) continue;\n nlen = Jsi_Strlen(cp);\n if (nlen>0 && cp[nlen-1]==' ') nlen--;\n if (nlen>0 && cp[nlen-1]==':') nlen--;\n Jsi_DSAppendLen(dStr, cp, nlen);\n Jsi_DSAppend(dStr, \"=\", buf, \"\\n\", NULL);\n if (lens) {\n lens[i++] = nlen;\n lens[i++] = Jsi_Strlen(buf);\n }\n }\n //printf(\"HEE: %d = %s\\n\", pss->wid, Jsi_DSValue(dStr) );\n return i;\n}", "label_name": "CWE-120", "label": 120} -{"code": "static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {\n __Pyx_RefNannyDeclarations\n __Pyx_RefNannySetupContext(\"__Pyx_InitCachedConstants\", 0);\n\n /* \"clickhouse_driver/varint.pyx\":4\n * \n * \n * def write_varint(Py_ssize_t number, buf): # <<<<<<<<<<<<<<\n * \"\"\"\n * Writes integer of variable length using LEB128.\n */\n __pyx_tuple_ = PyTuple_Pack(5, __pyx_n_s_number, __pyx_n_s_buf, __pyx_n_s_i, __pyx_n_s_towrite, __pyx_n_s_num_buf); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 4, __pyx_L1_error)\n __Pyx_GOTREF(__pyx_tuple_);\n __Pyx_GIVEREF(__pyx_tuple_);\n __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_clickhouse_driver_varint_pyx, __pyx_n_s_write_varint, 4, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 4, __pyx_L1_error)\n\n /* \"clickhouse_driver/varint.pyx\":29\n * \n * \n * def read_varint(f): # <<<<<<<<<<<<<<\n * \"\"\"\n * Reads integer of variable length using LEB128.\n */\n __pyx_tuple__3 = PyTuple_Pack(5, __pyx_n_s_f, __pyx_n_s_shift, __pyx_n_s_result, __pyx_n_s_i, __pyx_n_s_read_one); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 29, __pyx_L1_error)\n __Pyx_GOTREF(__pyx_tuple__3);\n __Pyx_GIVEREF(__pyx_tuple__3);\n __pyx_codeobj__4 = (PyObject*)__Pyx_PyCode_New(1, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__3, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_clickhouse_driver_varint_pyx, __pyx_n_s_read_varint, 29, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__4)) __PYX_ERR(0, 29, __pyx_L1_error)\n __Pyx_RefNannyFinishContext();\n return 0;\n __pyx_L1_error:;\n __Pyx_RefNannyFinishContext();\n return -1;\n}", "label_name": "CWE-120", "label": 120} -{"code": "setup_secureChannel(void) {\n TestingPolicy(&dummyPolicy, dummyCertificate, &fCalled, &keySizes);\n UA_SecureChannel_init(&testChannel, &UA_ConnectionConfig_default);\n UA_SecureChannel_setSecurityPolicy(&testChannel, &dummyPolicy, &dummyCertificate);\n\n testingConnection = createDummyConnection(65535, &sentData);\n UA_Connection_attachSecureChannel(&testingConnection, &testChannel);\n testChannel.connection = &testingConnection;\n\n testChannel.state = UA_SECURECHANNELSTATE_OPEN;\n}", "label_name": "CWE-770", "label": 770} -{"code": "NOEXPORT int parse_socket_error(CLI *c, const char *text) {\n switch(get_last_socket_error()) {\n /* http://tangentsoft.net/wskfaq/articles/bsd-compatibility.html */\n case 0: /* close on read, or close on write on WIN32 */\n#ifndef USE_WIN32\n case EPIPE: /* close on write on Unix */\n#endif\n case S_ECONNABORTED:\n s_log(LOG_INFO, \"%s: Socket is closed\", text);\n return 0;\n case S_EINTR:\n s_log(LOG_DEBUG, \"%s: Interrupted by a signal: retrying\", text);\n return 1;\n case S_EWOULDBLOCK:\n s_log(LOG_NOTICE, \"%s: Would block: retrying\", text);\n s_poll_sleep(1, 0); /* Microsoft bug KB177346 */\n return 1;\n#if S_EAGAIN!=S_EWOULDBLOCK\n case S_EAGAIN:\n s_log(LOG_DEBUG,\n \"%s: Temporary lack of resources: retrying\", text);\n return 1;\n#endif\n#ifdef USE_WIN32\n case S_ECONNRESET:\n /* dying \"exec\" processes on Win32 cause reset instead of close */\n if(c->opt->exec_name) {\n s_log(LOG_INFO, \"%s: Socket is closed (exec)\", text);\n return 0;\n }\n /* fall through */\n#endif\n default:\n sockerror(text);\n throw_exception(c, 1);\n return -1; /* some C compilers require a return value */\n }\n}", "label_name": "CWE-295", "label": 295} -{"code": "int options_parse(CONF_TYPE type) {\n SERVICE_OPTIONS *section;\n\n options_defaults();\n section=&new_service_options;\n if(options_file(configuration_file, type, §ion))\n return 1;\n if(init_section(1, §ion))\n return 1;\n\n s_log(LOG_NOTICE, \"Configuration successful\");\n return 0;\n}", "label_name": "CWE-295", "label": 295} -{"code": "void main_init() { /* one-time initialization */\n#ifdef USE_SYSTEMD\n int i;\n\n systemd_fds=sd_listen_fds(1);\n if(systemd_fds<0)\n fatal(\"systemd initialization failed\");\n listen_fds_start=SD_LISTEN_FDS_START;\n /* set non-blocking mode on systemd file descriptors */\n for(i=0; i0)\n s_log(LOG_INFO, \"Systemd socket activation: %d descriptors received\",\n systemd_fds);\n}", "label_name": "CWE-295", "label": 295} -{"code": "NOEXPORT unsigned __stdcall daemon_thread(void *arg) {\n (void)arg; /* squash the unused parameter warning */\n\n tls_alloc(NULL, NULL, \"main\"); /* new thread-local storage */\n main_init();\n SetEvent(main_initialized); /* unlock the GUI thread */\n /* get a valid configuration */\n while(main_configure(cmdline.config_file, NULL)) {\n if(cmdline.config_file && *cmdline.config_file=='-')\n cmdline.config_file=NULL; /* don't retry commandline switches */\n unbind_ports(); /* in case initialization failed after bind_ports() */\n log_flush(LOG_MODE_ERROR); /* otherwise logs are buffered */\n PostMessage(hwnd, WM_INVALID_CONFIG, 0, 0); /* display error */\n WaitForSingleObject(config_ready, INFINITE);\n }\n PostMessage(hwnd, WM_VALID_CONFIG, 0, 0);\n\n /* start the main loop */\n daemon_loop();\n main_cleanup();\n _endthreadex(0); /* SIGNAL_TERMINATE received */\n return 0;\n}", "label_name": "CWE-295", "label": 295} -{"code": "NOEXPORT void tray_update(const int num) {\n NOTIFYICONDATA nid;\n static ICON_TYPE previous_icon=ICON_NONE;\n ICON_TYPE current_icon;\n LPTSTR tip;\n\n if(!global_options.option.taskbar) { /* currently disabled */\n tray_delete(); /* remove the taskbark icon if exists */\n return;\n }\n if(!tray_menu_handle) /* initialize taskbar */\n tray_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_TRAYMENU));\n if(!tray_menu_handle) {\n ioerror(\"LoadMenu\");\n return;\n }\n if(cmdline.service)\n EnableMenuItem(tray_menu_handle, IDM_EDIT_CONFIG, MF_GRAYED);\n\n ZeroMemory(&nid, sizeof nid);\n nid.cbSize=sizeof nid;\n nid.uID=1; /* application-defined icon ID */\n nid.uFlags=NIF_MESSAGE|NIF_TIP;\n nid.uCallbackMessage=WM_SYSTRAY; /* notification message */\n nid.hWnd=hwnd; /* window to receive notifications */\n if(num<0) {\n tip=str_tprintf(TEXT(\"Server is down\"));\n current_icon=ICON_ERROR;\n } else if(num>0) {\n tip=str_tprintf(TEXT(\"%d active session(s)\"), num);\n current_icon=ICON_ACTIVE;\n } else {\n tip=str_tprintf(TEXT(\"Server is idle\"));\n current_icon=ICON_IDLE;\n }\n _tcsncpy(nid.szTip, tip, 63);\n nid.szTip[63]=TEXT('\\0');\n str_free(tip);\n nid.hIcon=global_options.icon[current_icon];\n if(current_icon!=previous_icon) {\n nid.uFlags|=NIF_ICON;\n previous_icon=current_icon;\n }\n if(Shell_NotifyIcon(NIM_MODIFY, &nid)) /* modify tooltip */\n return; /* OK: taskbar icon exists */\n /* tooltip update failed - try to create the icon */\n nid.uFlags|=NIF_ICON;\n Shell_NotifyIcon(NIM_ADD, &nid);\n}", "label_name": "CWE-295", "label": 295} -{"code": "jpeg_error_handler(j_common_ptr)\n{\n return;\n}", "label_name": "CWE-476", "label": 476} -{"code": "void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,\n\ti64 pos)\n{\n\ti64 pixmap_version;\n\ti64 pack_size;\n\ti64 plane_bytes;\n\ti64 n;\n\n\tde_dbg(c, \"additional PixMap header fields, at %d\", (int)pos);\n\tde_dbg_indent(c, 1);\n\n\tpixmap_version = dbuf_getu16be(f, pos+0);\n\tde_dbg(c, \"pixmap version: %d\", (int)pixmap_version);\n\n\tbi->packing_type = dbuf_getu16be(f, pos+2);\n\tde_dbg(c, \"packing type: %d\", (int)bi->packing_type);\n\n\tpack_size = dbuf_getu32be(f, pos+4);\n\tde_dbg(c, \"pixel data length: %d\", (int)pack_size);\n\n\tbi->hdpi = pict_read_fixed(f, pos+8);\n\tbi->vdpi = pict_read_fixed(f, pos+12);\n\tde_dbg(c, \"dpi: %.2f\"DE_CHAR_TIMES\"%.2f\", bi->hdpi, bi->vdpi);\n\n\tbi->pixeltype = dbuf_getu16be(f, pos+16);\n\tbi->pixelsize = dbuf_getu16be(f, pos+18);\n\tbi->cmpcount = dbuf_getu16be(f, pos+20);\n\tbi->cmpsize = dbuf_getu16be(f, pos+22);\n\tde_dbg(c, \"pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d\",\n\t\t(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);\n\n\tbi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;\n\tif(bi->pdwidth < bi->npwidth) {\n\t\tbi->pdwidth = bi->npwidth;\n\t}\n\n\tplane_bytes = dbuf_getu32be(f, pos+24);\n\tde_dbg(c, \"plane bytes: %d\", (int)plane_bytes);\n\n\tbi->pmTable = (u32)dbuf_getu32be(f, pos+28);\n\tde_dbg(c, \"pmTable: 0x%08x\", (unsigned int)bi->pmTable);\n\n\tn = dbuf_getu32be(f, pos+32);\n\tde_dbg(c, \"pmReserved: 0x%08x\", (unsigned int)n);\n\n\tde_dbg_indent(c, -1);\n}", "label_name": "CWE-369", "label": 369} -{"code": "void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint32_t enc_len,\n char *public_shares,\n unsigned _t, unsigned _n) {\n LOG_INFO(__FUNCTION__);\n\n INIT_ERROR_STATE\n\n CHECK_STATE(encrypted_dkg_secret);\n CHECK_STATE(public_shares);\n CHECK_STATE(_t <= _n && _n > 0)\n\n SAFE_CHAR_BUF(decrypted_dkg_secret, DKG_MAX_SEALED_LEN);\n\n int status = AES_decrypt(encrypted_dkg_secret, enc_len, decrypted_dkg_secret,\n DKG_MAX_SEALED_LEN);\n\n CHECK_STATUS2(\"aes decrypt data - encrypted_dkg_secret failed with status %d\");\n\n status = calc_public_shares(decrypted_dkg_secret, public_shares, _t) != 0;\n CHECK_STATUS(\"t does not match polynomial in db\");\n\n SET_SUCCESS\n\n clean:\n ;\n LOG_INFO(\"SGX call completed\");\n}", "label_name": "CWE-787", "label": 787} -{"code": "void mobi_buffer_move(MOBIBuffer *buf, const int offset, const size_t len) {\n size_t aoffset = (size_t) abs(offset);\n unsigned char *source = buf->data + buf->offset;\n if (offset >= 0) {\n if (buf->offset + aoffset + len > buf->maxlen) {\n debug_print(\"%s\", \"End of buffer\\n\");\n buf->error = MOBI_BUFFER_END;\n return;\n }\n source += aoffset;\n } else {\n if (buf->offset < aoffset) {\n debug_print(\"%s\", \"End of buffer\\n\");\n buf->error = MOBI_BUFFER_END;\n return;\n }\n source -= aoffset;\n }\n memmove(buf->data + buf->offset, source, len);\n buf->offset += len;\n}", "label_name": "CWE-787", "label": 787} -{"code": "int audio_level_json(struct list *levell,\n\t\t const char *userid_self, const char *clientid_self,\n\t\t char **json_str, char **anon_str)\n{\n\tstruct json_object *jobj;\n\tstruct json_object *jarr;\n\tchar uid_anon[ANON_ID_LEN];\n\tchar cid_anon[ANON_CLIENT_LEN];\n\tstruct mbuf *pmb = NULL;\n\tint err = 0;\n\tstruct le *le;\n\n\tif (!levell || !json_str)\n\t\treturn EINVAL;\n\t\n\tjobj = jzon_alloc_object();\n\tif (!jobj)\n\t\treturn ENOMEM;\n\n\tjarr = jzon_alloc_array();\n\tif (!jarr) {\n\t\terr = ENOMEM;\n\t\tgoto out;\n\t}\n\n\tif (anon_str) {\n\t\tpmb = mbuf_alloc(512);\n\t\tmbuf_printf(pmb, \"%zu levels: \", list_count(levell));\n\t}\n\t\n\tLIST_FOREACH(levell, le) {\n\t\tstruct audio_level *a = le->data;\n\t\tstruct json_object *ja;\n\t\tconst char *userid = a->userid;\n\t\tconst char *clientid = a->clientid;\n\n\t\tif (a->is_self) {\n\t\t\tif (userid_self)\n\t\t\t\tuserid = userid_self;\n\t\t\tif (clientid_self)\n\t\t\t\tclientid = clientid_self;\n\t\t}\n\n\t\tja = jzon_alloc_object();\n\t\tif (ja) {\n\t\t\tjzon_add_str(ja, \"userid\", userid);\n\t\t\tjzon_add_str(ja, \"clientid\", clientid);\n\t\t\tjzon_add_int(ja, \"audio_level\",\n\t\t\t\t (int32_t)a->aulevel_smooth);\n\t\t\tjzon_add_int(ja, \"audio_level_now\",\n\t\t\t\t (int32_t)a->aulevel);\n\t\t}\n\t\tjson_object_array_add(jarr, ja);\n\n\t\t/* add to info string */\n\t\tif (pmb) {\n\t\t\tanon_id(uid_anon, userid);\n\t\t\tanon_client(cid_anon, clientid);\n\t\t\tmbuf_printf(pmb, \"{[%s.%s] audio_level: %d/%d}\",\n\t\t\t\t uid_anon, cid_anon,\n\t\t\t\t a->aulevel_smooth, a->aulevel);\n\t\t\tif (le != levell->tail)\n\t\t\t\tmbuf_printf(pmb, \",\");\n\t\t}\t\t\n\t}\n\tjson_object_object_add(jobj, \"audio_levels\", jarr);\n\n\tif (pmb) {\n\t\tpmb->pos = 0;\n\t\tmbuf_strdup(pmb, anon_str, pmb->end);\n\t\tmem_deref(pmb);\n\t}\n\n\tjzon_encode(json_str, jobj);\n out:\t\n\tmem_deref(jobj);\n\n\treturn err;\n}", "label_name": "CWE-134", "label": 134} -{"code": "def _inject_file_into_fs(fs, path, contents):\n absolute_path = os.path.join(fs, path.lstrip('/'))\n parent_dir = os.path.dirname(absolute_path)\n utils.execute('mkdir', '-p', parent_dir, run_as_root=True)\n utils.execute('tee', absolute_path, process_input=contents,\n run_as_root=True)", "label_name": "CWE-22", "label": 22} -{"code": " def set(self, key, value, serialize=True, timeout=0):\n \"\"\"\n Set a key/value pair in memcache\n\n :param key: key\n :param value: value\n :param serialize: if True, value is pickled before sending to memcache\n :param timeout: ttl in memcache\n \"\"\"\n key = md5hash(key)\n if timeout > 0:\n timeout += time.time()\n flags = 0\n if serialize:\n value = pickle.dumps(value, PICKLE_PROTOCOL)\n flags |= PICKLE_FLAG\n for (server, fp, sock) in self._get_conns(key):\n try:\n sock.sendall('set %s %d %d %s noreply\\r\\n%s\\r\\n' % \\\n (key, flags, timeout, len(value), value))\n self._return_conn(server, fp, sock)\n return\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 94} -{"code": " def get_multi(self, keys, server_key):\n \"\"\"\n Gets multiple values from memcache for the given keys.\n\n :param keys: keys for values to be retrieved from memcache\n :param servery_key: key to use in determining which server in the ring\n is used\n :returns: list of values\n \"\"\"\n server_key = md5hash(server_key)\n keys = [md5hash(key) for key in keys]\n for (server, fp, sock) in self._get_conns(server_key):\n try:\n sock.sendall('get %s\\r\\n' % ' '.join(keys))\n line = fp.readline().strip().split()\n responses = {}\n while line[0].upper() != 'END':\n if line[0].upper() == 'VALUE':\n size = int(line[3])\n value = fp.read(size)\n if int(line[2]) & PICKLE_FLAG:\n value = pickle.loads(value)\n responses[line[1]] = value\n fp.readline()\n line = fp.readline().strip().split()\n values = []\n for key in keys:\n if key in responses:\n values.append(responses[key])\n else:\n values.append(None)\n self._return_conn(server, fp, sock)\n return values\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 94} -{"code": " def get(self, key):\n \"\"\"\n Gets the object specified by key. It will also unpickle the object\n before returning if it is pickled in memcache.\n\n :param key: key\n :returns: value of the key in memcache\n \"\"\"\n key = md5hash(key)\n value = None\n for (server, fp, sock) in self._get_conns(key):\n try:\n sock.sendall('get %s\\r\\n' % key)\n line = fp.readline().strip().split()\n while line[0].upper() != 'END':\n if line[0].upper() == 'VALUE' and line[1] == key:\n size = int(line[3])\n value = fp.read(size)\n if int(line[2]) & PICKLE_FLAG:\n value = pickle.loads(value)\n fp.readline()\n line = fp.readline().strip().split()\n self._return_conn(server, fp, sock)\n return value\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 94} -{"code": " def set_multi(self, mapping, server_key, serialize=True, timeout=0):\n \"\"\"\n Sets multiple key/value pairs in memcache.\n\n :param mapping: dictonary of keys and values to be set in memcache\n :param servery_key: key to use in determining which server in the ring\n is used\n :param serialize: if True, value is pickled before sending to memcache\n :param timeout: ttl for memcache\n \"\"\"\n server_key = md5hash(server_key)\n if timeout > 0:\n timeout += time.time()\n msg = ''\n for key, value in mapping.iteritems():\n key = md5hash(key)\n flags = 0\n if serialize:\n value = pickle.dumps(value, PICKLE_PROTOCOL)\n flags |= PICKLE_FLAG\n msg += ('set %s %d %d %s noreply\\r\\n%s\\r\\n' %\n (key, flags, timeout, len(value), value))\n for (server, fp, sock) in self._get_conns(server_key):\n try:\n sock.sendall(msg)\n self._return_conn(server, fp, sock)\n return\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 94} -{"code": "def is_safe_url(url, host=None):\n \"\"\"\n Return ``True`` if the url is a safe redirection (i.e. it doesn't point to\n a different host and uses a safe scheme).\n\n Always returns ``False`` on an empty url.\n \"\"\"\n if url is not None:\n url = url.strip()\n if not url:\n return False\n # Chrome treats \\ completely as /\n url = url.replace('\\\\', '/')\n # Chrome considers any URL with more than two slashes to be absolute, but\n # urlparse is not so flexible. Treat any url with three slashes as unsafe.\n if url.startswith('///'):\n return False\n url_info = urlparse(url)\n # Forbid URLs like http:///example.com - with a scheme, but without a hostname.\n # In that URL, example.com is not the hostname but, a path component. However,\n # Chrome will still consider example.com to be the hostname, so we must not\n # allow this syntax.\n if not url_info.netloc and url_info.scheme:\n return False\n # Forbid URLs that start with control characters. Some browsers (like\n # Chrome) ignore quite a few control characters at the start of a\n # URL and might consider the URL as scheme relative.\n if unicodedata.category(url[0])[0] == 'C':\n return False\n return ((not url_info.netloc or url_info.netloc == host) and\n (not url_info.scheme or url_info.scheme in ['http', 'https']))", "label_name": "CWE-79", "label": 79} -{"code": " def load(self):\n\n if len(self.tile) != 1 or self.tile[0][0] != \"iptc\":\n return ImageFile.ImageFile.load(self)\n\n type, tile, box = self.tile[0]\n\n encoding, offset = tile\n\n self.fp.seek(offset)\n\n # Copy image data to temporary file\n outfile = tempfile.mktemp()\n o = open(outfile, \"wb\")\n if encoding == \"raw\":\n # To simplify access to the extracted file,\n # prepend a PPM header\n o.write(\"P5\\n%d %d\\n255\\n\" % self.size)\n while True:\n type, size = self.field()\n if type != (8, 10):\n break\n while size > 0:\n s = self.fp.read(min(size, 8192))\n if not s:\n break\n o.write(s)\n size = size - len(s)\n o.close()\n\n try:\n try:\n # fast\n self.im = Image.core.open_ppm(outfile)\n except:\n # slightly slower\n im = Image.open(outfile)\n im.load()\n self.im = im.im\n finally:\n try: os.unlink(outfile)\n except: pass", "label_name": "CWE-59", "label": 59} -{"code": "def subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (undo).'\n ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())", "label_name": "CWE-79", "label": 79} -{"code": " def fetch_file(self, in_path, out_path):\n ''' fetch a file from chroot to local '''\n\n in_path = self._normalize_path(in_path, self.get_jail_path())\n vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.jail)\n\n self._copy_file(in_path, out_path)", "label_name": "CWE-59", "label": 59} -{"code": " def _normalize_path(self, path, prefix):\n if not path.startswith(os.path.sep):\n path = os.path.join(os.path.sep, path)\n normpath = os.path.normpath(path)\n return os.path.join(prefix, normpath[1:])", "label_name": "CWE-59", "label": 59} -{"code": " def put_file(self, in_path, out_path):\n ''' transfer a file from local to zone '''\n\n out_path = self._normalize_path(out_path, self.get_zone_path())\n vvv(\"PUT %s TO %s\" % (in_path, out_path), host=self.zone)\n\n self._copy_file(in_path, out_path)", "label_name": "CWE-59", "label": 59} -{"code": " def fetch_file(self, in_path, out_path):\n ''' fetch a file from zone to local '''\n\n in_path = self._normalize_path(in_path, self.get_zone_path())\n vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.zone)\n\n self._copy_file(in_path, out_path)", "label_name": "CWE-59", "label": 59} -{"code": "def _websocket_mask_python(mask, data):\n \"\"\"Websocket masking function.\n\n `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n Returns a `bytes` object of the same length as `data` with the mask applied\n as specified in section 5.3 of RFC 6455.\n\n This pure-python implementation may be replaced by an optimized version when available.\n \"\"\"\n mask = array.array(\"B\", mask)\n unmasked = array.array(\"B\", data)\n for i in xrange(len(data)):\n unmasked[i] = unmasked[i] ^ mask[i % 4]\n if hasattr(unmasked, 'tobytes'):\n # tostring was deprecated in py32. It hasn't been removed,\n # but since we turn on deprecation warnings in our tests\n # we need to use the right one.\n return unmasked.tobytes()\n else:\n return unmasked.tostring()", "label_name": "CWE-203", "label": 203} -{"code": " def GET(self, path, queries=()):\n return self._request('GET', path, queries)", "label_name": "CWE-295", "label": 295} -{"code": "def checkin(pickledata):\n config = pickle.loads(bz2.decompress(base64.urlsafe_b64decode(pickledata)))\n r, message = read_host_config(SESSION, config)\n if r is not None:\n return message + 'checked in successful'\n else:\n return message + 'error checking in'", "label_name": "CWE-94", "label": 94} -{"code": "def class_instances_from_soap_enveloped_saml_thingies(text, modules):\n \"\"\"Parses a SOAP enveloped header and body SAML thing and returns the\n thing as a dictionary class instance.\n\n :param text: The SOAP object as XML\n :param modules: modules representing xsd schemas\n :return: The body and headers as class instances\n \"\"\"\n try:\n envelope = ElementTree.fromstring(text)\n except Exception as exc:\n raise XmlParseError(\"%s\" % exc)\n\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n env = {\"header\": [], \"body\": None}\n\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n env[\"body\"] = instanciate_class(part[0], modules)\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n env[\"header\"].append(instanciate_class(item, modules))\n\n return env", "label_name": "CWE-611", "label": 611} -{"code": " def prop_sentences_stats(self, type, vId = None):\n return {\n 'get_data' : \"SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC\",\n 'all_networks' : \"SELECT networks.* FROM networks ORDER BY id\",\n 'get_preview' : \"SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = '%s'\" % (vId),\n 'id_networks' : \"SELECT networks.* FROM networks WHERE id = '%s'\" % (vId),\n 'get_requests' : \"SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id \",\n 'get_sessions' : \"SELECT COUNT(*) AS Total FROM networks\",\n 'get_clicks' : \"SELECT COUNT(*) AS Total FROM clicks\",\n 'get_online' : \"SELECT COUNT(*) AS Total FROM victims WHERE status = '%s'\" % ('online')\n }.get(type, False)", "label_name": "CWE-89", "label": 89} -{"code": " def prop_sentences_stats(self, type, vId = None):\n return {\n 'get_data' : \"SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC\",\n 'all_networks' : \"SELECT networks.* FROM networks ORDER BY id\",\n 'get_preview' : \"SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = '%s'\" % (vId),\n 'id_networks' : \"SELECT networks.* FROM networks WHERE id = '%s'\" % (vId),\n 'get_requests' : \"SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id \",\n 'get_sessions' : \"SELECT COUNT(*) AS Total FROM networks\",\n 'get_clicks' : \"SELECT COUNT(*) AS Total FROM clicks\",\n 'get_online' : \"SELECT COUNT(*) AS Total FROM victims WHERE status = '%s'\" % ('online')\n }.get(type, False)", "label_name": "CWE-79", "label": 79} -{"code": "def home_get_preview():\n vId = request.form['vId']\n d = db.sentences_stats('get_preview', vId)\n n = db.sentences_stats('id_networks', vId)\n return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});", "label_name": "CWE-89", "label": 89} -{"code": " def load(self, stream):\n '''read vault steam and return python object'''\n return yaml.load(self.vault.decrypt(stream))", "label_name": "CWE-94", "label": 94} -{"code": " def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\n http_client=None, homeserver_to_use=GenericWorkerServer\n )\n return hs", "label_name": "CWE-601", "label": 601} -{"code": " def make_homeserver(self, reactor, clock):\n # we mock out the keyring so as to skip the authentication check on the\n # federation API call.\n mock_keyring = Mock(spec=[\"verify_json_for_server\"])\n mock_keyring.verify_json_for_server.return_value = defer.succeed(True)\n\n # we mock out the federation client too\n mock_federation_client = Mock(spec=[\"put_json\"])\n mock_federation_client.put_json.return_value = defer.succeed((200, \"OK\"))\n\n # the tests assume that we are starting at unix time 1000\n reactor.pump((1000,))\n\n hs = self.setup_test_homeserver(\n notifier=Mock(),\n http_client=mock_federation_client,\n keyring=mock_keyring,\n replication_streams={},\n )\n\n return hs", "label_name": "CWE-601", "label": 601} -{"code": " def prepare(self, reactor, clock, homeserver):\n # make a second homeserver, configured to use the first one as a key notary\n self.http_client2 = Mock()\n config = default_config(name=\"keyclient\")\n config[\"trusted_key_servers\"] = [\n {\n \"server_name\": self.hs.hostname,\n \"verify_keys\": {\n \"ed25519:%s\"\n % (\n self.hs_signing_key.version,\n ): signedjson.key.encode_verify_key_base64(\n self.hs_signing_key.verify_key\n )\n },\n }\n ]\n self.hs2 = self.setup_test_homeserver(\n http_client=self.http_client2, config=config\n )\n\n # wire up outbound POST /key/v2/query requests from hs2 so that they\n # will be forwarded to hs1\n async def post_json(destination, path, data):\n self.assertEqual(destination, self.hs.hostname)\n self.assertEqual(\n path, \"/_matrix/key/v2/query\",\n )\n\n channel = FakeChannel(self.site, self.reactor)\n req = SynapseRequest(channel)\n req.content = BytesIO(encode_canonical_json(data))\n\n req.requestReceived(\n b\"POST\", path.encode(\"utf-8\"), b\"1.1\",\n )\n channel.await_result()\n self.assertEqual(channel.code, 200)\n resp = channel.json_body\n return resp\n\n self.http_client2.post_json.side_effect = post_json", "label_name": "CWE-601", "label": 601} -{"code": " def testInputPreProcessFormats(self):\n input_str = 'input1=/path/file.txt[ab3];input2=file2'\n input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'\n input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)\n input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(\n input_expr_str)\n self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3'))\n self.assertTrue(input_dict['input2'] == ('file2', None))\n print(input_expr_dict['input3'])\n self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2]))\n self.assertAllClose(input_expr_dict['input4'], [4, 5])\n self.assertTrue(len(input_dict) == 2)\n self.assertTrue(len(input_expr_dict) == 2)", "label_name": "CWE-94", "label": 94} -{"code": " def testRunCommandInvalidInputKeyError(self, use_tfrt):\n self.parser = saved_model_cli.create_parser()\n base_path = test.test_src_dir_path(SAVED_MODEL_PATH)\n args = self.parser.parse_args([\n 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def',\n 'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))'\n ] + (['--use_tfrt'] if use_tfrt else []))\n with self.assertRaises(ValueError):\n saved_model_cli.run(args)", "label_name": "CWE-94", "label": 94} -{"code": " def test_str(self):\n code = LoginCode(user=self.user, code='foo', timestamp=datetime(2018, 7, 1))\n self.assertEqual(str(code), 'test_user - 2018-07-01 00:00:00')", "label_name": "CWE-312", "label": 312} -{"code": " def test_request_login_code(self):\n response = self.client.post('/accounts/login/', {\n 'username': self.user.username,\n 'next': '/private/',\n })\n\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response['Location'], '/accounts/login/code/')\n\n login_code = LoginCode.objects.filter(user=self.user).first()\n\n self.assertIsNotNone(login_code)\n self.assertEqual(login_code.next, '/private/')\n self.assertEqual(len(mail.outbox), 1)\n self.assertIn(\n 'http://testserver/accounts/login/code/?code={}'.format(login_code.code),\n mail.outbox[0].body,\n )", "label_name": "CWE-312", "label": 312} -{"code": " def test_received_preq_completed_connection_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = True\n preq.connection_close = True\n inst.received(b\"GET / HTTP/1.1\\n\\n\" + b\"a\" * 50000)\n self.assertEqual(inst.request, None)\n self.assertEqual(inst.server.tasks, [])", "label_name": "CWE-444", "label": 444} -{"code": " def test_bad_host_header(self):\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n to_send = \"GET / HTTP/1.0\\n\" \" Host: 0\\n\\n\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))", "label_name": "CWE-444", "label": 444} -{"code": " def test_before_start_response_http_11(self):\n to_send = \"GET /before_start_response HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()), [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"]\n )\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label_name": "CWE-444", "label": 444} -{"code": " def test_filelike_shortcl_http11(self):\n to_send = \"GET /filelike_shortcl HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)", "label_name": "CWE-444", "label": 444} -{"code": " def test_request_body_too_large_with_no_cl_http11_connclose(self):\n body = \"a\" * self.toobig\n to_send = \"GET / HTTP/1.1\\nConnection: close\\n\\n\"\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed 0)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label_name": "CWE-444", "label": 444} -{"code": " def test_keepalive_http11_explicit(self):\n # Explicitly set keep-alive\n data = \"Default: Keep me alive\"\n s = tobytes(\n \"GET / HTTP/1.1\\n\"\n \"Connection: keep-alive\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"\n \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertTrue(response.getheader(\"connection\") != \"close\")", "label_name": "CWE-444", "label": 444} -{"code": " def testSimpleGET(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nFirstName: mickey\nlastname: Mouse\ncontent-length: 7\n\nHello.\n\"\"\"\n parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,\n {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"7\",},\n )\n self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")\n self.assertEqual(parser.proxy_scheme, \"\")\n self.assertEqual(parser.proxy_netloc, \"\")\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\\n\")", "label_name": "CWE-444", "label": 444} -{"code": " def test_parse_header_connection_close(self):\n data = b\"GET /foobar HTTP/1.1\\nConnection: close\\n\\n\"\n self.parser.parse_header(data)\n self.assertEqual(self.parser.connection_close, True)", "label_name": "CWE-444", "label": 444} -{"code": " def test_received_bad_host_header(self):\n from waitress.utilities import BadRequest\n\n data = b\"\"\"\\\nHTTP/1.0 GET /foobar\n Host: foo\n\n\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 33)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.error.__class__, BadRequest)", "label_name": "CWE-444", "label": 444} -{"code": " def test_received_no_doublecr(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 21)\n self.assertFalse(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", "label_name": "CWE-444", "label": 444} -{"code": " def testSpoofedHeadersDropped(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nx-auth_user: bob\ncontent-length: 7\n\nHello.\n\"\"\"\n self.feed(data)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {\"CONTENT_LENGTH\": \"7\",})", "label_name": "CWE-444", "label": 444} -{"code": " def test_parse_header_gardenpath(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nfoo: bar\"\"\"\n self.parser.parse_header(data)\n self.assertEqual(self.parser.first_line, b\"GET /foobar HTTP/8.4\")\n self.assertEqual(self.parser.headers[\"FOO\"], \"bar\")", "label_name": "CWE-444", "label": 444} -{"code": " def test_received_control_line_finished_all_chunks_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n result = inst.received(b\"0;discard\\n\")\n self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.all_chunks_received, True)\n self.assertEqual(result, 10)\n self.assertEqual(inst.completed, False)", "label_name": "CWE-444", "label": 444} -{"code": " def rpn(self, irc, msg, args):\n \"\"\"\n\n Returns the value of an RPN expression.\n \"\"\"\n stack = []\n for arg in args:\n try:\n x = complex(arg)\n if x == abs(x):\n x = abs(x)\n stack.append(x)\n except ValueError: # Not a float.\n if arg in self._mathSafeEnv:\n f = self._mathSafeEnv[arg]\n if callable(f):\n called = False\n arguments = []\n while not called and stack:\n arguments.append(stack.pop())\n try:\n stack.append(f(*arguments))\n called = True\n except TypeError:\n pass\n if not called:\n irc.error(_('Not enough arguments for %s') % arg)\n return\n else:\n stack.append(f)\n elif arg in self._rpnEnv:\n self._rpnEnv[arg](stack)\n else:\n arg2 = stack.pop()\n arg1 = stack.pop()\n s = '%s%s%s' % (arg1, arg, arg2)\n try:\n stack.append(eval(s, self._mathSafeEnv, self._mathSafeEnv))\n except SyntaxError:\n irc.error(format(_('%q is not a defined function.'),\n arg))\n return\n if len(stack) == 1:\n irc.reply(str(self._complexToString(complex(stack[0]))))\n else:\n s = ', '.join(map(self._complexToString, list(map(complex, stack))))\n irc.reply(_('Stack: [%s]') % s)", "label_name": "CWE-94", "label": 94} -{"code": " def _sqrt(x):\n if isinstance(x, complex) or x < 0:\n return cmath.sqrt(x)\n else:\n return math.sqrt(x)", "label_name": "CWE-94", "label": 94} -{"code": " def icalc(self, irc, msg, args, text):\n \"\"\"\n\n This is the same as the calc command except that it allows integer\n math, and can thus cause the bot to suck up CPU. Hence it requires\n the 'trusted' capability to use.\n \"\"\"\n if self._calc_match_forbidden_chars.match(text):\n # Note: this is important to keep this to forbid usage of\n # __builtins__\n irc.error(_('There\\'s really no reason why you should have '\n 'underscores or brackets in your mathematical '\n 'expression. Please remove them.'))\n return\n # This removes spaces, too, but we'll leave the removal of _[] for\n # safety's sake.\n text = self._calc_remover(text)\n if 'lambda' in text:\n irc.error(_('You can\\'t use lambda in this command.'))\n return\n text = text.replace('lambda', '')\n try:\n self.log.info('evaluating %q from %s', text, msg.prefix)\n irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))\n except OverflowError:\n maxFloat = math.ldexp(0.9999999999999999, 1024)\n irc.error(_('The answer exceeded %s or so.') % maxFloat)\n except TypeError:\n irc.error(_('Something in there wasn\\'t a valid number.'))\n except NameError as e:\n irc.error(_('%s is not a defined function.') % str(e).split()[1])\n except Exception as e:\n irc.error(utils.exnToString(e))", "label_name": "CWE-94", "label": 94} -{"code": "def insensitive_exact(field: Term, value: str) -> Criterion:\n return Upper(field).eq(Upper(f\"{value}\"))", "label_name": "CWE-89", "label": 89} -{"code": "def insensitive_ends_with(field: Term, value: str) -> Criterion:\n return Upper(field).like(Upper(f\"%{value}\"))", "label_name": "CWE-89", "label": 89} -{"code": "def google_remote_app():\n if \"google\" not in oauth.remote_apps:\n oauth.remote_app(\n \"google\",\n base_url=\"https://www.google.com/accounts/\",\n authorize_url=\"https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent\",\n request_token_url=None,\n request_token_params={\n \"scope\": \"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile\"\n },\n access_token_url=\"https://accounts.google.com/o/oauth2/token\",\n access_token_method=\"POST\",\n consumer_key=settings.GOOGLE_CLIENT_ID,\n consumer_secret=settings.GOOGLE_CLIENT_SECRET,\n )\n\n return oauth.google", "label_name": "CWE-601", "label": 601} -{"code": "def login():\n callback = url_for(\".callback\", _external=True)\n next_path = request.args.get(\n \"next\", url_for(\"redash.index\", org_slug=session.get(\"org_slug\"))\n )\n logger.debug(\"Callback url: %s\", callback)\n logger.debug(\"Next is: %s\", next_path)\n return google_remote_app().authorize(callback=callback, state=next_path)", "label_name": "CWE-601", "label": 601} -{"code": "def is_private_address(url):\n hostname = urlparse(url).hostname\n ip_address = socket.gethostbyname(hostname)\n return ipaddress.ip_address(text_type(ip_address)).is_private", "label_name": "CWE-918", "label": 918} -{"code": "def env() -> Environment:\n from openapi_python_client import utils\n\n TEMPLATE_FILTERS = {\"snakecase\": utils.snake_case, \"spinalcase\": utils.spinal_case}\n env = Environment(loader=PackageLoader(\"openapi_python_client\"), trim_blocks=True, lstrip_blocks=True)\n env.filters.update(TEMPLATE_FILTERS)\n return env", "label_name": "CWE-22", "label": 22} -{"code": " def get_type_string(self) -> str:\n \"\"\" Get a string representation of type that should be used when declaring this property \"\"\"\n if self.required:\n return self._type_string\n return f\"Optional[{self._type_string}]\"", "label_name": "CWE-94", "label": 94} -{"code": "def group_title(value: str) -> str:\n value = re.sub(r\"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)\", lambda m: m.group(1).title() + m.group(2), value.strip())\n value = re.sub(r\"(^|[ _-])([A-Z])\", lambda m: m.group(1) + m.group(2).lower(), value)\n return value", "label_name": "CWE-94", "label": 94} -{"code": "def escape_text(text: EscapableEntity) -> str:\n \"\"\"Escape HTML text\n\n We only strip some tags and allow some simple tags\n such as

    , or to be part of the string.\n This is useful for messages where we want to keep formatting\n options. (Formerly known as 'permissive_attrencode')\n\n Args:\n text:\n\n Examples:\n\n >>> escape_text(\"Hello this is dog!\")\n 'Hello this is dog!'\n\n This is lame.\n\n >>> escape_text(\"Hello this is dog!\")\n 'Hello this <a href=>is dog!'\n\n Returns:\n\n \"\"\"\n if isinstance(text, HTML):\n return text.__html__()\n\n text = escape_attribute(text)\n text = _UNESCAPER_TEXT.sub(r'<\\1\\2>', text)\n for a_href in _A_HREF.finditer(text):\n text = text.replace(a_href.group(0), u\"\" % _QUOTE.sub(u\"\\\"\", a_href.group(1)))\n return text.replace(u\"&nbsp;\", u\" \")", "label_name": "CWE-79", "label": 79} -{"code": "def task_remove(request, task_id):\n \"\"\"\n remove task by task_id\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n try:\n # delete job from DjangoJob\n task = Task.objects.get(id=task_id)\n clients = clients_of_task(task)\n for client in clients:\n job_id = get_job_id(client, task)\n DjangoJob.objects.filter(name=job_id).delete()\n # delete task\n Task.objects.filter(id=task_id).delete()\n return JsonResponse({'result': '1'})\n except:\n return JsonResponse({'result': '0'})", "label_name": "CWE-78", "label": 78} -{"code": "def load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs):\n \"\"\"\n This is the image 'Preview' tab for the right-hand panel.\n \"\"\"\n context = {}\n\n # the index of a field within a well\n index = getIntOrDefault(request, \"index\", 0)\n\n manager = BaseContainer(conn, **{str(c_type): long(c_id)})\n if share_id:\n context[\"share\"] = BaseShare(conn, share_id)\n if c_type == \"well\":\n manager.image = manager.well.getImage(index)\n\n allRdefs = manager.image.getAllRenderingDefs()\n rdefs = {}\n rdefId = manager.image.getRenderingDefId()\n # remove duplicates per user\n for r in allRdefs:\n ownerId = r[\"owner\"][\"id\"]\n r[\"current\"] = r[\"id\"] == rdefId\n # if duplicate rdefs for user, pick one with highest ID\n if ownerId not in rdefs or rdefs[ownerId][\"id\"] < r[\"id\"]:\n rdefs[ownerId] = r\n rdefs = rdefs.values()\n # format into rdef strings,\n # E.g. {c: '1|3118:35825$FF0000,2|2086:18975$FFFF00', m: 'c'}\n rdefQueries = []\n for r in rdefs:\n chs = []\n for i, c in enumerate(r[\"c\"]):\n act = \"-\"\n if c[\"active\"]:\n act = \"\"\n color = c[\"lut\"] if \"lut\" in c else c[\"color\"]\n reverse = \"r\" if c[\"inverted\"] else \"-r\"\n chs.append(\n \"%s%s|%s:%s%s$%s\" % (act, i + 1, c[\"start\"], c[\"end\"], reverse, color)\n )\n rdefQueries.append(\n {\n \"id\": r[\"id\"],\n \"owner\": r[\"owner\"],\n \"c\": \",\".join(chs),\n \"m\": r[\"model\"] == \"greyscale\" and \"g\" or \"c\",\n }\n )\n max_w, max_h = conn.getMaxPlaneSize()\n size_x = manager.image.getSizeX()\n size_y = manager.image.getSizeY()\n\n context[\"tiledImage\"] = (size_x * size_y) > (max_w * max_h)\n context[\"manager\"] = manager\n context[\"rdefsJson\"] = json.dumps(rdefQueries)\n context[\"rdefs\"] = rdefs\n context[\"template\"] = \"webclient/annotations/metadata_preview.html\"\n return context", "label_name": "CWE-79", "label": 79} -{"code": "\tdef decompile(self):\n\t\tself.writeln(\"** Decompiling APK...\", clr.OKBLUE)\n\t\twith ZipFile(self.file) as zipped:\n\t\t\ttry:\n\t\t\t\tdex = self.tempdir + \"/\" + self.apk.package + \".dex\"\n\t\t\t\twith open(dex, \"wb\") as classes:\n\t\t\t\t\tclasses.write(zipped.read(\"classes.dex\"))\n\t\t\texcept Exception as e:\n\t\t\t\tsys.exit(self.writeln(str(e), clr.WARNING))\n\t\tdec = \"%s %s -d %s --deobf\" % (self.jadx, dex, self.tempdir)\n\t\tos.system(dec)\n\t\treturn self.tempdir", "label_name": "CWE-78", "label": 78} -{"code": " def test_it_works_with_explicit_external_host(self, app, monkeypatch):\n with app.test_request_context():\n monkeypatch.setattr('flask.request.host_url', 'http://example.com')\n result = _validate_redirect_url('http://works.com',\n _external_host='works.com')\n assert result is True\n monkeypatch.undo()", "label_name": "CWE-601", "label": 601} -{"code": " def __init__(self, sourceName: str):\n self.sourceName = sourceName\n self.type = \"file\"\n self.content = None", "label_name": "CWE-78", "label": 78} -{"code": " def relative(self, relativePath) -> FileInputSource:\n return FileInputSource(os.path.join(self.directory(), relativePath))", "label_name": "CWE-22", "label": 22} -{"code": "def command_dispatch(request):\n \"\"\"\n Xtheme command dispatch view.\n\n :param request: A request\n :type request: django.http.HttpRequest\n :return: A response\n :rtype: django.http.HttpResponse\n \"\"\"\n command = request.POST.get(\"command\")\n if command:\n response = handle_command(request, command)\n if response:\n return response\n raise Problem(\"Error! Unknown command: `%r`\" % command)", "label_name": "CWE-79", "label": 79} -{"code": "def view_configuration():\n read_column = calibre_db.session.query(db.Custom_Columns)\\\n .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all()\n restrict_columns = calibre_db.session.query(db.Custom_Columns)\\\n .filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all()\n languages = calibre_db.speaking_language()\n translations = [LC('en')] + babel.list_translations()\n return render_title_template(\"config_view_edit.html\", conf=config, readColumns=read_column,\n restrictColumns=restrict_columns,\n languages=languages,\n translations=translations,\n title=_(u\"UI Configuration\"), page=\"uiconfig\")", "label_name": "CWE-918", "label": 918} -{"code": "def edit_user(user_id):\n content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User\n if not content or (not config.config_anonbrowse and content.name == \"Guest\"):\n flash(_(u\"User not found\"), category=\"error\")\n return redirect(url_for('admin.admin'))\n languages = calibre_db.speaking_language(return_all_languages=True)\n translations = babel.list_translations() + [LC('en')]\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n if request.method == \"POST\":\n to_save = request.form.to_dict()\n resp = _handle_edit_user(to_save, content, languages, translations, kobo_support)\n if resp:\n return resp\n return render_title_template(\"user_edit.html\",\n translations=translations,\n languages=languages,\n new_user=0,\n content=content,\n config=config,\n registered_oauth=oauth_check,\n mail_configured=config.get_mail_server_configured(),\n kobo_support=kobo_support,\n title=_(u\"Edit User %(nick)s\", nick=content.name),\n page=\"edituser\")", "label_name": "CWE-918", "label": 918} -{"code": " def get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False,\n config_read_column=False, *join):", "label_name": "CWE-918", "label": 918} -{"code": " def setup_db(cls, config_calibre_dir, app_db_path):\n cls.dispose()\n\n if not config_calibre_dir:\n cls.config.invalidate()\n return False\n\n dbpath = os.path.join(config_calibre_dir, \"metadata.db\")\n if not os.path.exists(dbpath):\n cls.config.invalidate()\n return False\n\n try:\n cls.engine = create_engine('sqlite://',\n echo=False,\n isolation_level=\"SERIALIZABLE\",\n connect_args={'check_same_thread': False},\n poolclass=StaticPool)\n with cls.engine.begin() as connection:\n connection.execute(text(\"attach database '{}' as calibre;\".format(dbpath)))\n connection.execute(text(\"attach database '{}' as app_settings;\".format(app_db_path)))\n\n conn = cls.engine.connect()\n # conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302\n except Exception as ex:\n cls.config.invalidate(ex)\n return False\n\n cls.config.db_configured = True\n\n if not cc_classes:\n try:\n cc = conn.execute(text(\"SELECT id, datatype FROM custom_columns\"))\n cls.setup_db_cc_classes(cc)\n except OperationalError as e:\n log.error_or_exception(e)\n\n cls.session_factory = scoped_session(sessionmaker(autocommit=False,\n autoflush=True,\n bind=cls.engine))\n for inst in cls.instances:\n inst.initSession()\n\n cls._init = True\n return True", "label_name": "CWE-918", "label": 918} -{"code": "def edit_book_series_index(series_index, book):\n # Add default series_index to book\n modif_date = False\n series_index = series_index or '1'\n if not series_index.replace('.', '', 1).isdigit():\n flash(_(\"%(seriesindex)s is not a valid number, skipping\", seriesindex=series_index), category=\"warning\")\n return False\n if str(book.series_index) != series_index:\n book.series_index = series_index\n modif_date = True\n return modif_date", "label_name": "CWE-918", "label": 918} -{"code": "def table_xchange_author_title():\n vals = request.get_json().get('xchange')\n if vals:\n for val in vals:\n modif_date = False\n book = calibre_db.get_book(val)\n authors = book.title\n book.authors = calibre_db.order_authors([book])\n author_names = []\n for authr in book.authors:\n author_names.append(authr.name.replace('|', ','))\n\n title_change = handle_title_on_edit(book, \" \".join(author_names))\n input_authors, authorchange, renamed = handle_author_on_edit(book, authors)\n if authorchange or title_change:\n edited_books_id = book.id\n modif_date = True\n\n if config.config_use_google_drive:\n gdriveutils.updateGdriveCalibreFromLocal()\n\n if edited_books_id:\n helper.update_dir_structure(edited_books_id, config.config_calibre_dir, input_authors[0],\n renamed_author=renamed)\n if modif_date:\n book.last_modified = datetime.utcnow()\n try:\n calibre_db.session.commit()\n except (OperationalError, IntegrityError) as e:\n calibre_db.session.rollback()\n log.error_or_exception(\"Database error: %s\", e)\n return json.dumps({'success': False})\n\n if config.config_use_google_drive:\n gdriveutils.updateGdriveCalibreFromLocal()\n return json.dumps({'success': True})\n return \"\"", "label_name": "CWE-918", "label": 918} -{"code": "def merge_list_book():\n vals = request.get_json().get('Merge_books')\n to_file = list()\n if vals:\n # load all formats from target book\n to_book = calibre_db.get_book(vals[0])\n vals.pop(0)\n if to_book:\n for file in to_book.data:\n to_file.append(file.format)\n to_name = helper.get_valid_filename(to_book.title, chars=96) + ' - ' + \\\n helper.get_valid_filename(to_book.authors[0].name, chars=96)\n for book_id in vals:\n from_book = calibre_db.get_book(book_id)\n if from_book:\n for element in from_book.data:\n if element.format not in to_file:\n # create new data entry with: book_id, book_format, uncompressed_size, name\n filepath_new = os.path.normpath(os.path.join(config.config_calibre_dir,\n to_book.path,\n to_name + \".\" + element.format.lower()))\n filepath_old = os.path.normpath(os.path.join(config.config_calibre_dir,\n from_book.path,\n element.name + \".\" + element.format.lower()))\n copyfile(filepath_old, filepath_new)\n to_book.data.append(db.Data(to_book.id,\n element.format,\n element.uncompressed_size,\n to_name))\n delete_book_from_table(from_book.id,\"\", True)\n return json.dumps({'success': True})\n return \"\"", "label_name": "CWE-918", "label": 918} -{"code": "def table_get_custom_enum(c_id):\n ret = list()\n cc = (calibre_db.session.query(db.Custom_Columns)\n .filter(db.Custom_Columns.id == c_id)\n .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none())\n ret.append({'value': \"\", 'text': \"\"})\n for idx, en in enumerate(cc.get_display_dict()['enum_values']):\n ret.append({'value': en, 'text': en})\n return json.dumps(ret)", "label_name": "CWE-918", "label": 918} -{"code": "def render_edit_book(book_id):\n cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()\n book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)\n if not book:\n flash(_(u\"Oops! Selected book title is unavailable. File does not exist or is not accessible\"), category=\"error\")\n return redirect(url_for(\"web.index\"))\n\n for lang in book.languages:\n lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code)\n\n book.authors = calibre_db.order_authors([book])\n\n author_names = []\n for authr in book.authors:\n author_names.append(authr.name.replace('|', ','))\n\n # Option for showing convertbook button\n valid_source_formats=list()\n allowed_conversion_formats = list()\n kepub_possible=None\n if config.config_converterpath:\n for file in book.data:\n if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM:\n valid_source_formats.append(file.format.lower())\n if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]:\n kepub_possible = True\n if not config.config_converterpath:\n valid_source_formats.append('epub')\n\n # Determine what formats don't already exist\n if config.config_converterpath:\n allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:]\n for file in book.data:\n if file.format.lower() in allowed_conversion_formats:\n allowed_conversion_formats.remove(file.format.lower())\n if kepub_possible:\n allowed_conversion_formats.append('kepub')\n return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc,\n title=_(u\"edit metadata\"), page=\"editbook\",\n conversion_formats=allowed_conversion_formats,\n config=config,\n source_formats=valid_source_formats)", "label_name": "CWE-918", "label": 918} -{"code": "def update_dir_structure_gdrive(book_id, first_author, renamed_author):\n book = calibre_db.get_book(book_id)\n\n authordir = book.path.split('/')[0]\n titledir = book.path.split('/')[1]\n new_authordir = rename_all_authors(first_author, renamed_author, gdrive=True)\n new_titledir = get_valid_filename(book.title, chars=96) + u\" (\" + str(book_id) + u\")\"\n\n if titledir != new_titledir:\n gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), titledir)\n if gFile:\n gd.moveGdriveFileRemote(gFile, new_titledir)\n book.path = book.path.split('/')[0] + u'/' + new_titledir\n gd.updateDatabaseOnEdit(gFile['id'], book.path) # only child folder affected\n else:\n return _(u'File %(file)s not found on Google Drive', file=book.path) # file not found\n\n if authordir != new_authordir and authordir not in renamed_author:\n gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), new_titledir)\n if gFile:\n gd.moveGdriveFolderRemote(gFile, new_authordir)\n book.path = new_authordir + u'/' + book.path.split('/')[1]\n gd.updateDatabaseOnEdit(gFile['id'], book.path)\n else:\n return _(u'File %(file)s not found on Google Drive', file=authordir) # file not found\n\n # change location in database to new author/title path\n book.path = os.path.join(new_authordir, new_titledir).replace('\\\\', '/')\n return rename_files_on_change(first_author, renamed_author, book, gdrive=True)", "label_name": "CWE-918", "label": 918} -{"code": "def uniq(inpt):\n output = []\n inpt = [ \" \".join(inp.split()) for inp in inpt]\n for x in inpt:\n if x not in output:\n output.append(x)\n return output", "label_name": "CWE-918", "label": 918} -{"code": "def check_unrar(unrarLocation):\n if not unrarLocation:\n return\n\n if not os.path.exists(unrarLocation):\n return _('Unrar binary file not found')\n\n try:\n unrarLocation = [unrarLocation]\n value = process_wait(unrarLocation, pattern='UNRAR (.*) freeware')\n if value:\n version = value.group(1)\n log.debug(\"unrar version %s\", version)\n\n except (OSError, UnicodeDecodeError) as err:\n log.error_or_exception(err)\n return _('Error excecuting UnRar')", "label_name": "CWE-918", "label": 918} -{"code": "def rename_all_authors(first_author, renamed_author, calibre_path=\"\", localbook=None, gdrive=False):\n # Create new_author_dir from parameter or from database\n # Create new title_dir from database and add id\n if first_author:\n new_authordir = get_valid_filename(first_author, chars=96)\n for r in renamed_author:\n new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()\n old_author_dir = get_valid_filename(r, chars=96)\n new_author_rename_dir = get_valid_filename(new_author.name, chars=96)\n if gdrive:\n gFile = gd.getFileFromEbooksFolder(None, old_author_dir)\n if gFile:\n gd.moveGdriveFolderRemote(gFile, new_author_rename_dir)\n else:\n if os.path.isdir(os.path.join(calibre_path, old_author_dir)):\n try:\n old_author_path = os.path.join(calibre_path, old_author_dir)\n new_author_path = os.path.join(calibre_path, new_author_rename_dir)\n shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path))\n except (OSError) as ex:\n log.error(\"Rename author from: %s to %s: %s\", old_author_path, new_author_path, ex)\n log.debug(ex, exc_info=True)\n return _(\"Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s\",\n src=old_author_path, dest=new_author_path, error=str(ex))\n else:\n new_authordir = get_valid_filename(localbook.authors[0].name, chars=96)\n return new_authordir", "label_name": "CWE-918", "label": 918} -{"code": "def feed_category(book_id):\n off = request.args.get(\"offset\") or 0\n entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,\n db.Books,\n db.Books.tags.any(db.Tags.id == book_id),\n [db.Books.timestamp.desc()])\n return render_xml_template('feed.xml', entries=entries, pagination=pagination)", "label_name": "CWE-918", "label": 918} -{"code": "def feed_unread_books():\n off = request.args.get(\"offset\") or 0\n result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True)\n return render_xml_template('feed.xml', entries=result, pagination=pagination)", "label_name": "CWE-918", "label": 918} -{"code": "def render_hot_books(page, order):\n if current_user.check_visibility(constants.SIDEBAR_HOT):\n if order[1] not in ['hotasc', 'hotdesc']:\n # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+\n #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or\n # order[0][0].compare(func.count(ub.Downloads.book_id).asc())):\n order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc'\n if current_user.show_detail_random():\n random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \\\n .order_by(func.random()).limit(config.config_random_books)\n else:\n random = false()\n off = int(int(config.config_books_per_page) * (page - 1))\n all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\\\n .order_by(*order[0]).group_by(ub.Downloads.book_id)\n hot_books = all_books.offset(off).limit(config.config_books_per_page)\n entries = list()\n for book in hot_books:\n downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter(\n db.Books.id == book.Downloads.book_id).first()\n if downloadBook:\n entries.append(downloadBook)\n else:\n ub.delete_download(book.Downloads.book_id)\n numBooks = entries.__len__()\n pagination = Pagination(page, config.config_books_per_page, numBooks)\n return render_title_template('index.html', random=random, entries=entries, pagination=pagination,\n title=_(u\"Hot Books (Most Downloaded)\"), page=\"hot\", order=order[1])\n else:\n abort(404)", "label_name": "CWE-918", "label": 918} -{"code": "def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs):\n for extension in include_extension_inputs:\n q = q.filter(db.Books.data.any(db.Data.format == extension))\n for extension in exclude_extension_inputs:\n q = q.filter(not_(db.Books.data.any(db.Data.format == extension)))\n return q", "label_name": "CWE-918", "label": 918} -{"code": "def logout():\n if current_user is not None and current_user.is_authenticated:\n ub.delete_user_session(current_user.id, flask_session.get('_id',\"\"))\n logout_user()\n if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):\n logout_oauth_user()\n log.debug(u\"User logged out\")\n return redirect(url_for('web.login'))", "label_name": "CWE-918", "label": 918} -{"code": "def profile():\n languages = calibre_db.speaking_language()\n translations = babel.list_translations() + [LC('en')]\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n if feature_support['oauth'] and config.config_login_type == 2:\n oauth_status = get_oauth_status()\n local_oauth_check = oauth_check\n else:\n oauth_status = None\n local_oauth_check = {}\n\n if request.method == \"POST\":\n change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)\n return render_title_template(\"user_edit.html\",\n translations=translations,\n profile=1,\n languages=languages,\n content=current_user,\n kobo_support=kobo_support,\n title=_(u\"%(name)s's profile\", name=current_user.name),\n page=\"me\",\n registered_oauth=local_oauth_check,\n oauth_status=oauth_status)", "label_name": "CWE-918", "label": 918} -{"code": "def set_bookmark(book_id, book_format):\n bookmark_key = request.form[\"bookmark\"]\n ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id),\n ub.Bookmark.book_id == book_id,\n ub.Bookmark.format == book_format)).delete()\n if not bookmark_key:\n ub.session_commit()\n return \"\", 204\n\n lbookmark = ub.Bookmark(user_id=current_user.id,\n book_id=book_id,\n format=book_format,\n bookmark_key=bookmark_key)\n ub.session.merge(lbookmark)\n ub.session_commit(\"Bookmark for user {} in book {} created\".format(current_user.id, book_id))\n return \"\", 201", "label_name": "CWE-918", "label": 918} -{"code": " def test_more_custom_templates(self):\n \"\"\"\n Test custom templates and metadata\n Template is relative to collection-specific dir\n Add custom metadata and test its presence in custom search page\n \"\"\"\n custom_search = os.path.join(self.root_dir, COLLECTIONS, 'test',\n 'templates', 'search.html')\n\n # add metadata\n main(['metadata', 'test', '--set', 'some=value'])\n\n with open(custom_search, 'w+b') as fh:\n fh.write(b'overriden search page: ')\n fh.write(b'{{ metadata | tojson }}\\n')\n\n # force clear of jinja env cache to reload\n self.app.rewriterapp.jinja_env.jinja_env.cache = {}\n\n resp = self.testapp.get('/test/')\n resp.charset = 'utf-8'\n assert resp.status_int == 200\n assert resp.content_type == 'text/html'\n assert 'overriden search page: ' in resp.text\n print(resp.text)\n assert '\"some\":\"value\"' in resp.text, resp.text", "label_name": "CWE-79", "label": 79} -{"code": "def test_unicorn_render_kwarg():\n token = Token(\n TokenType.TEXT,\n \"unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'\",\n )\n unicorn_node = unicorn(None, token)\n context = {}\n actual = unicorn_node.render(context)\n\n assert \"->tested!<-\" in actual", "label_name": "CWE-79", "label": 79} -{"code": "def create(request, topic_id):\n topic = get_object_or_404(\n Topic.objects.for_access(request.user),\n pk=topic_id)\n form = NotificationCreationForm(\n user=request.user,\n topic=topic,\n data=request.POST)\n\n if form.is_valid():\n form.save()\n else:\n messages.error(request, utils.render_form_errors(form))\n\n return redirect(request.POST.get('next', topic.get_absolute_url()))", "label_name": "CWE-601", "label": 601} -{"code": "def custom_logout(request, **kwargs):\n if not request.user.is_authenticated:\n return redirect(request.GET.get('next', reverse(settings.LOGIN_URL)))\n\n if request.method == 'POST':\n return _logout_view(request, **kwargs)\n\n return render(request, 'spirit/user/auth/logout.html')", "label_name": "CWE-601", "label": 601} -{"code": "def test_remote_static(app):\n \"\"\"Test endpoint that serves files as a logged user\"\"\"\n # GIVEN a file on disk\n file = \"../demo/ACC5963A1_lanes_1234_star_sorted_sj_filtered_sorted.bed.gz\"\n\n # GIVEN a running demo app\n with app.test_client() as client:\n # GIVEN that user is logged in\n client.get(url_for(\"auto_login\"))\n with client.session_transaction() as session:\n # GIVEN that resource file exists in user session\n session[\"igv_tracks\"] = [file]\n\n # THEN the resource should be available to the user\n resp = client.get(\n url_for(\n \"alignviewers.remote_static\",\n file=file,\n )\n )\n assert resp.status_code == 200", "label_name": "CWE-918", "label": 918} -{"code": "def validate_and_sanitize_search_inputs(fn, instance, args, kwargs):\n\tkwargs.update(dict(zip(fn.__code__.co_varnames, args)))\n\tsanitize_searchfield(kwargs['searchfield'])\n\tkwargs['start'] = cint(kwargs['start'])\n\tkwargs['page_len'] = cint(kwargs['page_len'])\n\n\tif kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']):\n\t\treturn []\n\n\treturn fn(**kwargs)", "label_name": "CWE-79", "label": 79} -{"code": "def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:\n if isinstance(typ, new.BoolDefinition):\n return old.BaseType(\"bool\")\n if isinstance(typ, new.AddressDefinition):\n return old.BaseType(\"address\")\n if isinstance(typ, new.InterfaceDefinition):\n return old.InterfaceType(typ._id)\n if isinstance(typ, new.BytesMDefinition):\n m = typ._length # type: ignore\n return old.BaseType(f\"bytes{m}\")\n if isinstance(typ, new.BytesArrayDefinition):\n return old.ByteArrayType(typ.length)\n if isinstance(typ, new.StringDefinition):\n return old.StringType(typ.length)\n if isinstance(typ, new.DecimalDefinition):\n return old.BaseType(\"decimal\")\n if isinstance(typ, new.SignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"int\" + str(bits))\n if isinstance(typ, new.UnsignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"uint\" + str(bits))\n if isinstance(typ, new.ArrayDefinition):\n return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.DynamicArrayDefinition):\n return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.TupleDefinition):\n return old.TupleType(typ.value_type)\n if isinstance(typ, new.StructDefinition):\n return old.StructType(\n {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id\n )\n raise InvalidType(f\"unknown type {typ}\")", "label_name": "CWE-190", "label": 190} -{"code": " def __call__(self, request):\n file_fields = request.POST.getlist(\"s3file\")\n for field_name in file_fields:\n paths = request.POST.getlist(field_name)\n request.FILES.setlist(field_name, list(self.get_files_from_storage(paths)))\n\n if local_dev and request.path == \"/__s3_mock__/\":\n return views.S3MockView.as_view()(request)\n\n return self.get_response(request)", "label_name": "CWE-22", "label": 22} -{"code": " def test_process_request(self, rf):\n uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"\n\n storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"", "label_name": "CWE-22", "label": 22} -{"code": " public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {\n \n Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);\n String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);\n Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);\n \n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n if (err != null) {\n err.printStackTrace(pw);\n } else {\n pw.println(\"(none)\");\n }\n pw.flush();\n \n // If we are here there was no error servlet, so show the default error page\n String output = Launcher.RESOURCES.getString(\"WinstoneResponse.ErrorPage\",\n new String[] { sc + \"\", (msg == null ? \"\" : msg), sw.toString(),\n Launcher.RESOURCES.getString(\"ServerVersion\"),\n \"\" + new Date() });\n response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);\n Writer out = response.getWriter();\n out.write(output);\n out.flush();\n }", "label_name": "CWE-79", "label": 79} -{"code": " private boolean exractAndLoad(ArrayList errors, String version, String customPath, String resourcePath) {\n URL resource = classLoader.getResource(resourcePath);\n if( resource !=null ) {\n \n String libName = name + \"-\" + getBitModel();\n if( version !=null) {\n libName += \"-\" + version;\n }\n \n if( customPath!=null ) {\n // Try to extract it to the custom path...\n File target = file(customPath, map(libName));\n if( extract(errors, resource, target) ) {\n if( load(errors, target) ) {\n return true;\n }\n }\n }\n \n // Fall back to extracting to the tmp dir\n customPath = System.getProperty(\"java.io.tmpdir\");\n File target = file(customPath, map(libName));\n if( extract(errors, resource, target) ) {\n if( load(errors, target) ) {\n return true;\n }\n }\n }\n return false;\n }", "label_name": "CWE-94", "label": 94} -{"code": " private String getMimeType(ParsedUri pParsedUri) {\n if (pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()) != null) {\n return \"text/javascript\";\n } else {\n String mimeType = pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue());\n if (mimeType != null) {\n return mimeType;\n }\n mimeType = configuration.get(ConfigKey.MIME_TYPE);\n return mimeType != null ? mimeType : ConfigKey.MIME_TYPE.getDefaultValue();\n }\n }", "label_name": "CWE-79", "label": 79} -{"code": " public void testCallbackPost() throws URISyntaxException, IOException, java.text.ParseException {\n HttpExchange exchange = prepareExchange(\"http://localhost:8080/jolokia?callback=data\",\n \"Content-Type\",\"text/plain; charset=UTF-8\",\n \"Origin\",null\n );\n\n // Simple GET method\n prepareMemoryPostReadRequest(exchange);\n Headers header = new Headers();\n ByteArrayOutputStream out = prepareResponse(handler, exchange, header);\n\n handler.doHandle(exchange);\n\n assertEquals(header.getFirst(\"content-type\"),\"text/javascript; charset=utf-8\");\n String result = out.toString(\"utf-8\");\n assertTrue(result.endsWith(\"});\"));\n assertTrue(result.startsWith(\"data({\"));\n assertTrue(result.contains(\"\\\"used\\\"\"));\n\n assertEquals(header.getFirst(\"Cache-Control\"),\"no-cache\");\n assertEquals(header.getFirst(\"Pragma\"),\"no-cache\");\n SimpleDateFormat rfc1123Format = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss zzz\", Locale.US);\n rfc1123Format.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n String expires = header.getFirst(\"Expires\");\n String date = header.getFirst(\"Date\");\n\n Date parsedExpires = rfc1123Format.parse(expires);\n Date parsedDate = rfc1123Format.parse(date);\n assertTrue(parsedExpires.before(parsedDate) || parsedExpires.equals(parsedDate));\n Date now = new Date();\n assertTrue(parsedExpires.before(now) || parsedExpires.equals(now));\n }", "label_name": "CWE-79", "label": 79} -{"code": " private File tempFile() throws IOException {\n String newpostfix;\n String diskFilename = getDiskFilename();\n if (diskFilename != null) {\n newpostfix = '_' + diskFilename;\n } else {\n newpostfix = getPostfix();\n }\n File tmpFile;\n if (getBaseDirectory() == null) {\n // create a temporary file\n tmpFile = File.createTempFile(getPrefix(), newpostfix);\n } else {\n tmpFile = File.createTempFile(getPrefix(), newpostfix, new File(\n getBaseDirectory()));\n }\n if (deleteOnExit()) {\n // See https://github.com/netty/netty/issues/10351\n DeleteFileOnExitHook.add(tmpFile.getPath());\n }\n return tmpFile;\n }", "label_name": "CWE-379", "label": 379} -{"code": " public void testRenameTo() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n tmpFile.deleteOnExit();\n final int totalByteCount = 4096;\n byte[] bytes = new byte[totalByteCount];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n ByteBuf content = Unpooled.wrappedBuffer(bytes);\n test.setContent(content);\n boolean succ = test.renameTo(tmpFile);\n assertTrue(succ);\n FileInputStream fis = new FileInputStream(tmpFile);\n try {\n byte[] buf = new byte[totalByteCount];\n int count = 0;\n int offset = 0;\n int size = totalByteCount;\n while ((count = fis.read(buf, offset, size)) > 0) {\n offset += count;\n size -= count;\n if (offset >= totalByteCount || size <= 0) {\n break;\n }\n }\n assertArrayEquals(bytes, buf);\n assertEquals(0, fis.available());\n } finally {\n fis.close();\n }\n } finally {\n //release the ByteBuf in AbstractMemoryHttpData\n test.delete();\n }\n }", "label_name": "CWE-378", "label": 378} -{"code": " public static void beforeClass() throws IOException {\n final Random r = new Random();\n for (int i = 0; i < BYTES.length; i++) {\n BYTES[i] = (byte) r.nextInt(255);\n }\n\n tmp = File.createTempFile(\"netty-traffic\", \".tmp\");\n tmp.deleteOnExit();\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(tmp);\n out.write(BYTES);\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n // ignore\n }\n }\n }\n }", "label_name": "CWE-379", "label": 379} -{"code": " public static File createTempFile(String prefix, String suffix, File directory) throws IOException {\n if (javaVersion() >= 7) {\n if (directory == null) {\n return Files.createTempFile(prefix, suffix).toFile();\n }\n return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();\n }\n if (directory == null) {\n return File.createTempFile(prefix, suffix);\n }\n File file = File.createTempFile(prefix, suffix, directory);\n // Try to adjust the perms, if this fails there is not much else we can do...\n file.setReadable(false, false);\n file.setReadable(true, true);\n return file;\n }", "label_name": "CWE-378", "label": 378} -{"code": " protected boolean evaluate(InputSource inputSource)\n {\n try\n {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n DocumentBuilder dbuilder = factory.newDocumentBuilder();\n Document doc = dbuilder.parse(inputSource);\n\n //An XPath expression could return a true or false value instead of a node.\n //eval() is a better way to determine the boolean value of the exp.\n //For compliance with legacy behavior where selecting an empty node returns true,\n //selectNodeIterator is attempted in case of a failure.\n\n CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();\n XObject result = cachedXPathAPI.eval(doc, xpath);\n if (result.bool())\n return true;\n else\n {\n NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);\n return (iterator.nextNode() != null);\n }\n\n }\n catch (Throwable e)\n {\n return false;\n }\n }", "label_name": "CWE-611", "label": 611} -{"code": " public byte[] toByteArray()\n {\n\t\t/* index || secretKeySeed || secretKeyPRF || publicSeed || root */\n int n = params.getDigestSize();\n int indexSize = (params.getHeight() + 7) / 8;\n int secretKeySize = n;\n int secretKeyPRFSize = n;\n int publicSeedSize = n;\n int rootSize = n;\n int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;\n byte[] out = new byte[totalSize];\n int position = 0;\n\t\t/* copy index */\n byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);\n XMSSUtil.copyBytesAtOffset(out, indexBytes, position);\n position += indexSize;\n\t\t/* copy secretKeySeed */\n XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);\n position += secretKeySize;\n\t\t/* copy secretKeyPRF */\n XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);\n position += secretKeyPRFSize;\n\t\t/* copy publicSeed */\n XMSSUtil.copyBytesAtOffset(out, publicSeed, position);\n position += publicSeedSize;\n\t\t/* copy root */\n XMSSUtil.copyBytesAtOffset(out, root, position);\n\t\t/* concatenate bdsState */\n byte[] bdsStateOut = null;\n try\n {\n bdsStateOut = XMSSUtil.serialize(bdsState);\n }\n catch (IOException e)\n {\n e.printStackTrace();\n throw new RuntimeException(\"error serializing bds state\");\n }\n return Arrays.concatenate(out, bdsStateOut);\n }", "label_name": "CWE-502", "label": 502} -{"code": " public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters\n .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssPrivateKey.getIndex())\n .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssPrivateKey.getPublicSeed())\n .withRoot(xmssPrivateKey.getRoot());\n\n if (xmssPrivateKey.getBdsState() != null)\n {\n keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }", "label_name": "CWE-470", "label": 470} -{"code": " protected BigInteger[] derDecode(\n byte[] encoding)\n throws IOException\n {\n ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);\n ASN1InputStream aIn = new ASN1InputStream(bIn);\n ASN1Sequence s = (ASN1Sequence)aIn.readObject();\n\n BigInteger[] sig = new BigInteger[2];\n\n sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();\n sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();\n\n return sig;\n }", "label_name": "CWE-347", "label": 347} -{"code": " protected String getExecutionPreamble()\n {\n if ( getWorkingDirectoryAsString() == null )\n {\n return null;\n }\n\n String dir = getWorkingDirectoryAsString();\n StringBuilder sb = new StringBuilder();\n sb.append( \"cd \" );\n\n sb.append( unifyQuotes( dir ) );\n sb.append( \" && \" );\n\n return sb.toString();\n }", "label_name": "CWE-78", "label": 78} -{"code": " public void testPreserveSingleQuotesOnArgument()\n {\n Shell sh = newShell();\n\n sh.setWorkingDirectory( \"/usr/bin\" );\n sh.setExecutable( \"chmod\" );\n\n String[] args = { \"\\'some arg with spaces\\'\" };\n\n List shellCommandLine = sh.getShellCommandLine( args );\n\n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n assertTrue( cli.endsWith( args[0] ) );\n }", "label_name": "CWE-78", "label": 78} -{"code": "\tpublic byte[] decrypt(final JWEHeader header,\n\t\t\t final Base64URL encryptedKey,\n\t\t\t final Base64URL iv,\n\t\t\t final Base64URL cipherText,\n\t\t\t final Base64URL authTag)\n\t\tthrows JOSEException {\n\n\t\tfinal JWEAlgorithm alg = header.getAlgorithm();\n\t\tfinal ECDH.AlgorithmMode algMode = ECDH.resolveAlgorithmMode(alg);\n\n\t\tcritPolicy.ensureHeaderPasses(header);\n\n\t\t// Get ephemeral EC key\n\t\tECKey ephemeralKey = header.getEphemeralPublicKey();\n\n\t\tif (ephemeralKey == null) {\n\t\t\tthrow new JOSEException(\"Missing ephemeral public EC key \\\"epk\\\" JWE header parameter\");\n\t\t}\n\n\t\tECPublicKey ephemeralPublicKey = ephemeralKey.toECPublicKey();\n\t\t\n\t\t// Curve check\n\t\tECDH.ensurePointOnCurve(ephemeralPublicKey, getPrivateKey());\n\n\t\t// Derive 'Z'\n\t\tSecretKey Z = ECDH.deriveSharedSecret(\n\t\t\tephemeralPublicKey,\n\t\t\tprivateKey,\n\t\t\tgetJCAContext().getKeyEncryptionProvider());\n\n\t\t// Derive shared key via concat KDF\n\t\tgetConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat\n\t\tSecretKey sharedKey = ECDH.deriveSharedKey(header, Z, getConcatKDF());\n\n\t\tfinal SecretKey cek;\n\n\t\tif (algMode.equals(ECDH.AlgorithmMode.DIRECT)) {\n\t\t\tcek = sharedKey;\n\t\t} else if (algMode.equals(ECDH.AlgorithmMode.KW)) {\n\t\t\tif (encryptedKey == null) {\n\t\t\t\tthrow new JOSEException(\"Missing JWE encrypted key\");\n\t\t\t}\n\t\t\tcek = AESKW.unwrapCEK(sharedKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());\n\t\t} else {\n\t\t\tthrow new JOSEException(\"Unexpected JWE ECDH algorithm mode: \" + algMode);\n\t\t}\n\n\t\treturn ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext());\n\t}", "label_name": "CWE-347", "label": 347} -{"code": "\tpublic static byte[] decryptWithConcatKDF(final JWEHeader header,\n\t\t\t\t\t\t final SecretKey secretKey,\n\t\t\t\t\t\t final Base64URL encryptedKey,\n\t\t\t\t\t\t final Base64URL iv,\n\t\t\t\t\t\t final Base64URL cipherText,\n\t\t\t\t\t\t final Base64URL authTag,\n\t\t\t\t\t\t final Provider ceProvider,\n\t\t\t\t\t\t final Provider macProvider)\n\t\tthrows JOSEException {\n\n\t\tbyte[] epu = null;\n\n\t\tif (header.getCustomParam(\"epu\") instanceof String) {\n\n\t\t\tepu = new Base64URL((String)header.getCustomParam(\"epu\")).decode();\n\t\t}\n\n\t\tbyte[] epv = null;\n\n\t\tif (header.getCustomParam(\"epv\") instanceof String) {\n\n\t\t\tepv = new Base64URL((String)header.getCustomParam(\"epv\")).decode();\n\t\t}\n\n\t\tSecretKey cekAlt = LegacyConcatKDF.generateCEK(secretKey, header.getEncryptionMethod(), epu, epv);\n\n\t\tfinal byte[] plainText = AESCBC.decrypt(cekAlt, iv.decode(), cipherText.decode(), ceProvider);\n\n\t\tSecretKey cik = LegacyConcatKDF.generateCIK(secretKey, header.getEncryptionMethod(), epu, epv);\n\n\t\tString macInput = header.toBase64URL().toString() + \".\" +\n\t\t\tencryptedKey.toString() + \".\" +\n\t\t\tiv.toString() + \".\" +\n\t\t\tcipherText.toString();\n\n\t\tbyte[] mac = HMAC.compute(cik, macInput.getBytes(), macProvider);\n\n\t\tif (! ConstantTimeUtils.areEqual(authTag.decode(), mac)) {\n\n\t\t\tthrow new JOSEException(\"HMAC integrity check failed\");\n\t\t}\n\n\t\treturn plainText;\n\t}", "label_name": "CWE-354", "label": 354} -{"code": " protected DispatchHandler getDispatchHandler() {\n if (dispatchHandler == null) {\n dispatchHandler = new DispatchHandler();\n }\n\n return dispatchHandler;\n }", "label_name": "CWE-611", "label": 611} -{"code": " public void setFeature(String name, boolean value) throws SAXException {\n getXMLReader().setFeature(name, value);\n }", "label_name": "CWE-611", "label": 611} -{"code": " public void removeHandler(String path) {\n getDispatchHandler().removeHandler(path);\n }", "label_name": "CWE-611", "label": 611} -{"code": " public Document read(InputStream in, String systemId)\n throws DocumentException {\n InputSource source = new InputSource(in);\n source.setSystemId(systemId);\n if (this.encoding != null) {\n source.setEncoding(this.encoding);\n }\n\n return read(source);\n }", "label_name": "CWE-611", "label": 611} -{"code": " public void setIncludeExternalDTDDeclarations(boolean include) {\n this.includeExternalDTDDeclarations = include;\n }", "label_name": "CWE-611", "label": 611} -{"code": " public EntityResolver getEntityResolver() {\n return entityResolver;\n }", "label_name": "CWE-611", "label": 611} -{"code": " public SAXReader(boolean validating) {\n this.validating = validating;\n }", "label_name": "CWE-611", "label": 611} -{"code": " public void setXMLReaderClassName(String xmlReaderClassName)\n throws SAXException {\n setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName));\n }", "label_name": "CWE-611", "label": 611} -{"code": " private String getLocalePrefix(FacesContext context) {\n\n String localePrefix = null;\n \n localePrefix = context.getExternalContext().getRequestParameterMap().get(\"loc\");\n \n if(localePrefix != null){\n return localePrefix;\n }\n \n String appBundleName = context.getApplication().getMessageBundle();\n if (null != appBundleName) {\n \t\n Locale locale = null;\n if (context.getViewRoot() != null) {\n locale = context.getViewRoot().getLocale();\n } else {\n locale = context.getApplication().getViewHandler().calculateLocale(context);\n }\n \n try {\n ResourceBundle appBundle =\n ResourceBundle.getBundle(appBundleName,\n locale,\n Util.getCurrentLoader(ResourceManager.class));\n localePrefix =\n appBundle\n .getString(ResourceHandler.LOCALE_PREFIX);\n } catch (MissingResourceException mre) { \n if (LOGGER.isLoggable(Level.FINEST)) {\n LOGGER.log(Level.FINEST, \"Ignoring missing resource\", mre);\n }\n }\n }\n return localePrefix;\n\n }", "label_name": "CWE-22", "label": 22} -{"code": " public static void main(String[] args) {\n\n // Will serve all static file are under \"/public\" in classpath if the route isn't consumed by others routes.\n staticFileLocation(\"/public\");\n\n get(\"/hello\", (request, response) -> {\n return \"Hello World!\";\n });\n }", "label_name": "CWE-22", "label": 22} -{"code": " void rawUnicode() {\n // 2- and 3-byte UTF-8\n final PathAndQuery res1 = PathAndQuery.parse(\"/\\u00A2?\\u20AC\"); // \u00a2 and \u20ac\n assertThat(res1).isNotNull();\n assertThat(res1.path()).isEqualTo(\"/%C2%A2\");\n assertThat(res1.query()).isEqualTo(\"%E2%82%AC\");\n\n // 4-byte UTF-8\n final PathAndQuery res2 = PathAndQuery.parse(\"/\\uD800\\uDF48\"); // \ud800\udf48\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/%F0%90%8D%88\");\n assertThat(res2.query()).isNull();\n\n // 5- and 6-byte forms are only theoretically possible, so we won't test them here.\n }", "label_name": "CWE-22", "label": 22} -{"code": " void doubleDots() {\n assertThat(PathAndQuery.parse(\"/..\")).isNull();\n assertThat(PathAndQuery.parse(\"/../\")).isNull();\n assertThat(PathAndQuery.parse(\"/../foo\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/..\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/../\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/../bar\")).isNull();\n\n // Escaped\n assertThat(PathAndQuery.parse(\"/.%2e\")).isNull();\n assertThat(PathAndQuery.parse(\"/%2E./\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/.%2e\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/%2E./\")).isNull();\n\n // Not the double dots we are looking for.\n final PathAndQuery res = PathAndQuery.parse(\"/..a\");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/..a\");\n final PathAndQuery res2 = PathAndQuery.parse(\"/a..\");\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/a..\");\n }", "label_name": "CWE-22", "label": 22} -{"code": " void controlChars() {\n assertThat(PathAndQuery.parse(\"/\\0\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\nb\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\u007fb\")).isNull();\n\n // Escaped\n assertThat(PathAndQuery.parse(\"/%00\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%09b\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%0ab\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%0db\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%7fb\")).isNull();\n\n // With query string\n assertThat(PathAndQuery.parse(\"/\\0?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\tb?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\nb?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\rb?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\u007fb?c\")).isNull();\n\n // With query string with control chars\n assertThat(PathAndQuery.parse(\"/?\\0\")).isNull();\n assertThat(PathAndQuery.parse(\"/?%00\")).isNull();\n assertThat(PathAndQuery.parse(\"/?a\\u007fb\")).isNull();\n assertThat(PathAndQuery.parse(\"/?a%7Fb\")).isNull();\n // However, 0x0A, 0x0D, 0x09 should be accepted in a query string.\n assertThat(PathAndQuery.parse(\"/?a\\tb\").query()).isEqualTo(\"a%09b\");\n assertThat(PathAndQuery.parse(\"/?a\\nb\").query()).isEqualTo(\"a%0Ab\");\n assertThat(PathAndQuery.parse(\"/?a\\rb\").query()).isEqualTo(\"a%0Db\");\n assertThat(PathAndQuery.parse(\"/?a%09b\").query()).isEqualTo(\"a%09b\");\n assertThat(PathAndQuery.parse(\"/?a%0Ab\").query()).isEqualTo(\"a%0Ab\");\n assertThat(PathAndQuery.parse(\"/?a%0Db\").query()).isEqualTo(\"a%0Db\");\n }", "label_name": "CWE-22", "label": 22} -{"code": " void space() {\n final PathAndQuery res = PathAndQuery.parse(\"/ ? \");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/%20\");\n assertThat(res.query()).isEqualTo(\"+\");\n\n final PathAndQuery res2 = PathAndQuery.parse(\"/%20?%20\");\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/%20\");\n assertThat(res2.query()).isEqualTo(\"+\");\n }", "label_name": "CWE-22", "label": 22} -{"code": "\t public String getHeader(String name) {\n\t //logger.info(\"Ineader .. parameter .......\");\n\t String value = super.getHeader(name);\n\t if (value == null)\n\t return null;\n\t //logger.info(\"Ineader RequestWrapper ........... value ....\");\n\t return cleanXSS(value);\n\t }", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {\n\t\t\n\t\t\n\t\t\n\t\treturn this.displayCategory(friendlyUrl,ref,model,request,response,locale);\n\t}", "label_name": "CWE-79", "label": 79} -{"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tencryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label_name": "CWE-125", "label": 125} -{"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tencryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label_name": "CWE-787", "label": 787} -{"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t\tint result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);\n\t\t\tcipher.doFinal(ciphertext, ciphertextOffset + result);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label_name": "CWE-125", "label": 125} -{"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the ciphertext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, dataLen);\n\t\tghash.pad(ad != null ? ad.length : 0, dataLen);\n\t\tghash.finish(iv, 0, 16);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\ttry {\n\t\t\tint result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);\n\t\t\tcipher.doFinal(plaintext, plaintextOffset + result);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\treturn dataLen;\n\t}", "label_name": "CWE-125", "label": 125} -{"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the ciphertext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tpoly.update(ciphertext, ciphertextOffset, dataLen);\n\t\tfinish(ad, dataLen);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\tencrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);\n\t\treturn dataLen;\n\t}", "label_name": "CWE-787", "label": 787} -{"code": " static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) {\n Ruby runtime = context.getRuntime();\n XmlSchema xmlSchema = (XmlSchema) NokogiriService.XML_SCHEMA_ALLOCATOR.allocate(runtime, klazz);\n xmlSchema.setInstanceVariable(\"@errors\", runtime.newEmptyArray());\n\n try {\n SchemaErrorHandler error_handler = new SchemaErrorHandler(context.getRuntime(), (RubyArray)xmlSchema.getInstanceVariable(\"@errors\"));\n Schema schema = xmlSchema.getSchema(source, context.getRuntime().getCurrentDirectory(), context.getRuntime().getInstanceConfig().getScriptFileName(), error_handler);\n xmlSchema.setValidator(schema.newValidator());\n return xmlSchema;\n } catch (SAXException ex) {\n throw context.getRuntime().newRuntimeError(\"Could not parse document: \" + ex.getMessage());\n }\n }", "label_name": "CWE-611", "label": 611} -{"code": " public DefaultFileSystemResourceLoader() {\n this.baseDirPath = Optional.empty();\n }", "label_name": "CWE-22", "label": 22} -{"code": " protected List readPropertySourceListFromFiles(String files) {\n List propertySources = new ArrayList<>();\n Collection propertySourceLoaders = getPropertySourceLoaders();\n Optional> filePathList = Optional.ofNullable(files)\n .filter(value -> !value.isEmpty())\n .map(value -> value.split(FILE_SEPARATOR))\n .map(Arrays::asList)\n .map(Collections::unmodifiableList);\n\n filePathList.ifPresent(list -> {\n if (!list.isEmpty()) {\n int order = AbstractPropertySourceLoader.DEFAULT_POSITION + 50;\n for (String filePath: list) {\n if (!propertySourceLoaders.isEmpty()) {\n String extension = NameUtils.extension(filePath);\n String fileName = NameUtils.filename(filePath);\n Optional propertySourceLoader = Optional.ofNullable(loaderByFormatMap.get(extension));\n if (propertySourceLoader.isPresent()) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Reading property sources from loader: {}\", propertySourceLoader);\n }\n Optional> properties = readPropertiesFromLoader(fileName, filePath, propertySourceLoader.get());\n if (properties.isPresent()) {\n propertySources.add(PropertySource.of(filePath, properties.get(), order));\n }\n order++;\n } else {\n throw new ConfigurationException(\"Unsupported properties file format: \" + fileName);\n }\n }\n }\n }\n });\n return propertySources;\n }", "label_name": "CWE-22", "label": 22} -{"code": "\tpublic ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, \n\t\t\tGitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, \n\t\t\tWicketServlet wicketServlet, WebSocketManager webSocketManager, \n\t\t\tAttachmentUploadServlet attachmentUploadServlet, ServletContainer jerseyServlet) {\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.shiroFilter = shiroFilter;\n this.gitFilter = gitFilter;\n\t\tthis.preReceiveServlet = preReceiveServlet;\n\t\tthis.postReceiveServlet = postReceiveServlet;\n\t\tthis.wicketServlet = wicketServlet;\n\t\tthis.webSocketManager = webSocketManager;\n\t\tthis.jerseyServlet = jerseyServlet;\n\t\tthis.attachmentUploadServlet = attachmentUploadServlet;\n\t}", "label_name": "CWE-502", "label": 502} -{"code": " public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n Bytes shiftAmount = frame.popStackItem();\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.popStackItem();\n frame.pushStackItem(UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n final Bytes value = leftPad(frame.popStackItem());\n\n if (shiftAmountInt >= 256) {\n frame.pushStackItem(UInt256.ZERO);\n } else {\n frame.pushStackItem(value.shiftLeft(shiftAmountInt));\n }\n }\n return successResponse;\n }", "label_name": "CWE-681", "label": 681} -{"code": " public HtmlElement content(String body) {\n return content(new TextElement(body));\n }", "label_name": "CWE-79", "label": 79} -{"code": " private String attributeToString(Object attribute) {\n if (attribute == null) {\n return null;\n }\n\n if (attribute instanceof Number) {\n return attribute.toString();\n } else if (attribute instanceof String) {\n return (String) attribute;\n } else if (attribute instanceof Element) {\n return ((Element) attribute).getTextContent();\n } else {\n logger.warn(\"This library currently doesn't handle attributes of type [\" + attribute.getClass() + \"]\");\n }\n\n return null;\n }", "label_name": "CWE-611", "label": 611} -{"code": " protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {\n String secret = getSecret();\n Key key = new SecretKeySpec(Decoders.BASE64.decode(secret), getSignatureAlgorithm().getJcaName());\n \n Jwt jwt = Jwts.parser().\n setSigningKey(key).\n parse((String) token.getPrincipal());\n Map principal = getPrincipal(jwt);\n return new SimpleAuthenticationInfo(principal, ((String) token.getCredentials()).toCharArray(), getName());\n }", "label_name": "CWE-347", "label": 347} -{"code": " private String getSkinResourcePath(String resource)\n {\n String skinFolder = getSkinFolder();\n String resourcePath = skinFolder + resource;\n\n // Prevent inclusion of templates from other directories\n Path normalizedResource = Paths.get(resourcePath).normalize();\n // Protect against directory attacks.\n if (!normalizedResource.startsWith(skinFolder)) {\n LOGGER.warn(\"Direct access to skin file [{}] refused. Possible break-in attempt!\", normalizedResource);\n return null;\n }\n\n return resourcePath;\n }", "label_name": "CWE-22", "label": 22} -{"code": " public int addWorkUnit(WorkUnit workUnit, long fileModificationTimeInMillis, long fileSize) {\n workUnitList.add(workUnit);\n if (fileModificationTimeInMillis < oldestFileModificationTime) {\n oldestFileModificationTime = fileModificationTimeInMillis;\n }\n if (fileModificationTimeInMillis > youngestFileModificationTime) {\n youngestFileModificationTime = fileModificationTimeInMillis;\n }\n totalFileSize += fileSize;\n return size();\n }", "label_name": "CWE-502", "label": 502} -{"code": " void setPaths(final String s) {\n try {\n final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes(\"8859_1\")));\n this.paths = (WorkBundle) ois.readObject();\n } catch (Exception e) {\n logger.error(\"Cannot deserialize WorkBundle using {} bytes\", s.length(), e);\n throw new IllegalArgumentException(\"Cannot deserialize WorkBundle\");\n }\n }", "label_name": "CWE-502", "label": 502} -{"code": " public static Object deserialize(final String s) {\n ObjectInputStream ois = null;\n try {\n ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes(\"8859_1\")));\n return ois.readObject();\n } catch (Exception e) {\n logger.error(\"Cannot deserialize payload using \" + (s == null ? -1 : s.length()) + \" bytes\", e);\n throw new IllegalArgumentException(\"Cannot deserialize payload\");\n } finally {\n if (ois != null) {\n try {\n ois.close();\n } catch (IOException ignore) {\n // empty catch block\n }\n }\n }\n }", "label_name": "CWE-502", "label": 502} -{"code": " private static void writeBaloFile(HttpURLConnection conn, Path baloPath, String fullModuleName,\n long resContentLength) {\n try (InputStream inputStream = conn.getInputStream();\n FileOutputStream outputStream = new FileOutputStream(baloPath.toString())) {\n writeAndHandleProgress(inputStream, outputStream, resContentLength / 1024, fullModuleName);\n } catch (IOException e) {\n createError(\"error occurred copying the balo file: \" + e.getMessage());\n }\n }", "label_name": "CWE-306", "label": 306} -{"code": "\tprotected List findEfficiencyStatements(IdentityRef identity) {\n\t\tList efficiencyStatements = new ArrayList<>();\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"select statement from effstatement as statement\")\n\t\t .append(\" where statement.identity.key=:identityKey\");\n\n\t\tList statements = dbInstance.getCurrentEntityManager()\n\t\t\t\t.createQuery(sb.toString(), UserEfficiencyStatementImpl.class)\n\t\t\t\t.setParameter(\"identityKey\", identity.getKey())\n\t\t\t\t.getResultList();\n\t\tfor(UserEfficiencyStatementImpl statement:statements) {\n\t\t\tif(StringHelper.containsNonWhitespace(statement.getStatementXml())) {\n\t\t\t\tEfficiencyStatement s = (EfficiencyStatement)xstream.fromXML(statement.getStatementXml());\n\t\t\t\tefficiencyStatements.add(s);\n\t\t\t}\n\t\t}\n\t\treturn efficiencyStatements;\n\t}", "label_name": "CWE-91", "label": 91} -{"code": "\tpublic Controller getMediaController(UserRequest ureq, WindowControl wControl, Media media, MediaRenderingHints hints) {\n\t\tString statementXml = media.getContent();\n\t\tEfficiencyStatement statement = null;\n\t\tif(StringHelper.containsNonWhitespace(statementXml)) {\n\t\t\ttry {\n\t\t\t\tstatement = (EfficiencyStatement)myXStream.fromXML(statementXml);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"Cannot load efficiency statement from artefact\", e);\n\t\t\t}\n\t\t}\n\t\tCertificateAndEfficiencyStatementController ctrl = new CertificateAndEfficiencyStatementController(wControl, ureq, statement);\n\t\tctrl.disableMediaCollector();\n\t\treturn ctrl;\n\t}", "label_name": "CWE-91", "label": 91} -{"code": "\tpublic void testUpdateMapper_serializade() {\n\t\t//create a mapper\n\t\tString mapperId = UUID.randomUUID().toString();\n\t\tString sessionId = UUID.randomUUID().toString().substring(0, 32);\n\t\tPersistentMapper sMapper = new PersistentMapper(\"mapper-to-persist-bis\");\n\t\tPersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1);\n\t\tAssert.assertNotNull(pMapper);\n\t\tdbInstance.commitAndCloseSession();\n\t\t\n\t\t//load the mapper\n\t\tPersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);\n\t\tAssert.assertNotNull(loadedMapper);\n\t\tObject objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;\n\t\tAssert.assertEquals(\"mapper-to-persist-bis\", sMapperReloaded.getKey());\n\t\t\n\t\t//update\n\t\tPersistentMapper sMapper2 = new PersistentMapper(\"mapper-to-update\");\n\t\tboolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, -1);\n\t\tAssert.assertTrue(updated);\n\t\tdbInstance.commitAndCloseSession();\n\t\t\n\t\t//load the updated mapper\n\t\tPersistedMapper loadedMapper2 = mapperDao.loadByMapperId(mapperId);\n\t\tAssert.assertNotNull(loadedMapper2);\n\t\tObject objReloaded2 = XStreamHelper.createXStreamInstance().fromXML(loadedMapper2.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded2 instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2;\n\t\tAssert.assertEquals(\"mapper-to-update\", sMapperReloaded2.getKey());\n\t}", "label_name": "CWE-91", "label": 91} -{"code": "\tprotected static RootSearcher searchRootDirectory(Path fPath)\n\tthrows IOException {\n\t\tRootSearcher rootSearcher = new RootSearcher();\n\t\tFiles.walkFileTree(fPath, rootSearcher);\n\t\treturn rootSearcher;\n\t}", "label_name": "CWE-22", "label": 22} -{"code": "\tpublic static ResourceEvaluation evaluate(File file, String filename) {\n\t\tResourceEvaluation eval = new ResourceEvaluation();\n\t\ttry {\n\t\t\tImsManifestFileFilter visitor = new ImsManifestFileFilter();\n\t\t\tPath fPath = PathUtils.visit(file, filename, visitor);\n\t\t\tif(visitor.isValid()) {\n\t\t\t\tPath realManifestPath = visitor.getManifestPath();\n\t\t\t\tPath manifestPath = fPath.resolve(realManifestPath);\n\t\t\t\t\n\t\t\t\tRootSearcher rootSearcher = new RootSearcher();\n\t\t\t\tFiles.walkFileTree(fPath, rootSearcher);\n\t\t\t\tif(rootSearcher.foundRoot()) {\n\t\t\t\t\tmanifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);\n\t\t\t\t} else {\n\t\t\t\t\tmanifestPath = fPath.resolve(IMS_MANIFEST);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDocument doc = IMSLoader.loadIMSDocument(manifestPath);\n\t\t\t\tif(validateImsManifest(doc)) {\n\t\t\t\t\teval.setValid(true);\n\t\t\t\t} else {\n\t\t\t\t\teval.setValid(false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\teval.setValid(false);\n\t\t\t}\n\t\t\tPathUtils.closeSubsequentFS(fPath);\n\t\t} catch (IOException | IllegalArgumentException e) {\n\t\t\tlog.error(\"\", e);\n\t\t\teval.setValid(false);\n\t\t}\n\t\treturn eval;\n\t}", "label_name": "CWE-22", "label": 22} -{"code": "\tprotected Response attachToPost(Message mess, String filename, InputStream file, HttpServletRequest request) {\n\t\tIdentity identity = getIdentity(request);\n\t\tif(identity == null) {\n\t\t\treturn Response.serverError().status(Status.UNAUTHORIZED).build();\n\t\t} else if (!identity.equalsByPersistableKey(mess.getCreator())) {\n\t\t\tif(mess.getModifier() == null || !identity.equalsByPersistableKey(mess.getModifier())) {\n\t\t\t\treturn Response.serverError().status(Status.UNAUTHORIZED).build();\n\t\t\t}\n\t\t}\n\n\t\tVFSContainer container = fom.getMessageContainer(mess.getForum().getKey(), mess.getKey());\n\t\tVFSItem item = container.resolve(filename);\n\t\tVFSLeaf attachment = null;\n\t\tif(item == null) {\n\t\t\tattachment = container.createChildLeaf(filename);\n\t\t} else {\n\t\t\tfilename = VFSManager.rename(container, filename);\n\t\t\tif(filename == null) {\n\t\t\t\treturn Response.serverError().status(Status.NOT_ACCEPTABLE).build();\n\t\t\t}\n\t\t\tattachment = container.createChildLeaf(filename);\n\t\t}\n\t\t\n\n\t\ttry(OutputStream out = attachment.getOutputStream(false)) {\n\t\t\tIOUtils.copy(file, out);\n\t\t} catch (IOException e) {\n\t\t\treturn Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();\n\t\t} finally {\n\t\t\tFileUtils.closeSafely(file);\n\t\t}\n\t\treturn Response.ok().build();\n\t}", "label_name": "CWE-22", "label": 22} -{"code": " private void ensureCorrectTheme(Intent data) {\n String oldListLayout = data.getStringExtra(SettingsActivity.SP_FEED_LIST_LAYOUT);\n String newListLayout = mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT,\"0\");\n\n if (ThemeChooser.themeRequiresRestartOfUI() || !newListLayout.equals(oldListLayout)) {\n NewsReaderListActivity.this.recreate();\n } else if (data.hasExtra(SettingsActivity.CACHE_CLEARED)) {\n resetUiAndStartSync();\n }\n }", "label_name": "CWE-829", "label": 829} -{"code": " public static DocumentBuilderFactory getNsAwareDocumentBuilderFactory() throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(true);\n setFeature(dbf, \"http://apache.org/xml/features/disallow-doctype-decl\");\n return dbf;\n }", "label_name": "CWE-611", "label": 611} -{"code": " public void testFormat() throws Exception {\n assertEquals(\" c\", format(\"c\", 1).replaceAll(\"[\\r\\n]\", \"\"));\n assertEquals(\" c\", format(\"c\", 3).replaceAll(\"[\\r\\n]\", \"\"));\n assertEquals(\"c\", format(\"c\", -21));\n\n assertThrows(IllegalArgumentException.class, () -> format(\"c\", 0));\n\n // check if the XXE protection is enabled\n String xxeAttack = \"\\n\" + \" \\n\" + \" ]>\" + \"&xxe;\";\n assertEquals(xxeAttack, format(xxeAttack, 1));\n\n // wrongly formatted XML\n assertEquals(\"c\", format(\"c\", 1));\n }", "label_name": "CWE-611", "label": 611} -{"code": "\tpublic CommandExecutionResult createBinary(String code, String full, boolean compact) {\n\t\tfinal Player player = new PlayerBinary(full, getSkinParam(), ruler, compactByDefault);\n\t\tplayers.put(code, player);\n\t\treturn CommandExecutionResult.ok();\n\t}", "label_name": "CWE-918", "label": 918} -{"code": "\tpublic static boolean isTransparent(HColor back) {\n\t\tif (back == TRANSPARENT) {\n\t\t\treturn true;\n\t\t}\n\t\tif (back instanceof HColorBackground && ((HColorBackground) back).getBack() == TRANSPARENT) {\n\t\t\treturn true;\n\t\t}\n\t\tif (back instanceof HColorSimple && ((HColorSimple) back).isTransparent()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "label_name": "CWE-918", "label": 918} -{"code": "\tprotected void doGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException\n\t{\n // GAE can't serve dot prefixed folders\n String uri = request.getRequestURI().replace(\"/.\", \"/\");\n\n if (uri.toLowerCase().contains(\".json\"))\n {\n \tresponse.setContentType(\"application/json\");\n }\n\n // Serve whatever was requested from .well-known\n try (InputStream in = getServletContext().getResourceAsStream(uri))\n {\n if (in == null)\n {\n \tresponse.sendError(404);\n return;\n }\n \n byte[] buffer = new byte[8192];\n int count;\n\n while ((count = in.read(buffer)) > 0)\n {\n \tresponse.getOutputStream().write(buffer, 0, count);\n }\n \n response.getOutputStream().flush();\n response.getOutputStream().close();\n }\n }", "label_name": "CWE-22", "label": 22} -{"code": " callback: (request: PublishRequest, response: PublishResponse) => void;", "label_name": "CWE-770", "label": 770} -{"code": "\tprivate void initializeVelocity() {\n\t\tif (velocityEngine == null) {\n\t\t\tvelocityEngine = new VelocityEngine();\n\t\t\t\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG, \"startup_wizard_vel.log\");\n\t\t\t// Linux requires setting logging properties to initialize Velocity Context.\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,\n\t\t\t \"org.apache.velocity.runtime.log.CommonsLogLogChute\");\n\t\t\tprops.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, \"initial_wizard_velocity\");\n\t\t\t\n\t\t\t// so the vm pages can import the header/footer\n\t\t\tprops.setProperty(RuntimeConstants.RESOURCE_LOADER, \"class\");\n\t\t\tprops.setProperty(\"class.resource.loader.description\", \"Velocity Classpath Resource Loader\");\n\t\t\tprops.setProperty(\"class.resource.loader.class\",\n\t\t\t \"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader\");\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvelocityEngine.init(props);\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tlog.error(\"velocity init failed, because: \" + e);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-22", "label": 22} -{"code": " public void getLogFile(@PathVariable(\"filename\") String fileName, HttpServletResponse response) throws Exception {\n InputStream inputStream = null;\n try {\n \t//Validate/Sanitize user input filename using a standard library, prevent from path traversal \n String logFileName = getFilePath() + File.separator + FilenameUtils.getName(fileName);\n File fileToDownload = new File(logFileName);\n inputStream = new FileInputStream(fileToDownload);\n response.setContentType(\"application/force-download\");\n response.setHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n IOUtils.copy(inputStream, response.getOutputStream());\n response.flushBuffer();\n } catch (Exception e) {\n logger.debug(\"Request could not be completed at this moment. Please try again.\");\n logger.debug(e.getStackTrace().toString());\n throw e;\n } finally {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException e) {\n logger.debug(e.getStackTrace().toString());\n throw e;\n }\n }\n }\n\n }", "label_name": "CWE-22", "label": 22} -{"code": "void CClient::EchoMessage(const CMessage& Message) {\n CMessage EchoedMessage = Message;\n for (CClient* pClient : GetClients()) {\n if (pClient->HasEchoMessage() ||\n (pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||\n pClient->HasSelfMessage()))) {\n EchoedMessage.SetNick(GetNickMask());\n pClient->PutClient(EchoedMessage);\n }\n }\n}", "label_name": "CWE-476", "label": 476} -{"code": "BOOL nego_read_request(rdpNego* nego, wStream* s)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;\n\n\tif (!tpkt_read_header(s, &length))\n\t\treturn FALSE;\n\n\tif (!tpdu_read_connection_request(s, &li, length))\n\t\treturn FALSE;\n\n\tif (li != Stream_GetRemainingLength(s) + 6)\n\t{\n\t\tWLog_ERR(TAG, \"Incorrect TPDU length indicator.\");\n\t\treturn FALSE;\n\t}\n\n\tif (!nego_read_request_token_or_cookie(nego, s))\n\t{\n\t\tWLog_ERR(TAG, \"Failed to parse routing token or cookie.\");\n\t\treturn FALSE;\n\t}\n\n\tif (Stream_GetRemainingLength(s) >= 8)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */\n\n\t\tif (type != TYPE_RDP_NEG_REQ)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Incorrect negotiation request type %\" PRIu8 \"\", type);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tnego_process_negotiation_request(nego, s);\n\t}\n\n\treturn tpkt_ensure_stream_consumed(s, length);\n}", "label_name": "CWE-125", "label": 125} -{"code": "NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId,\n size_t* pcbAvPairListRemaining)\n{\n\tsize_t cbAvPair = cbAvPairList;\n\tNTLM_AV_PAIR* pAvPair = pAvPairList;\n\n\tif (!ntlm_av_pair_check(pAvPair, cbAvPair))\n\t\tpAvPair = NULL;\n\n\twhile (pAvPair)\n\t{\n\t\tUINT16 id = ntlm_av_pair_get_id(pAvPair);\n\n\t\tif (id == AvId)\n\t\t\tbreak;\n\t\tif (id == MsvAvEOL)\n\t\t{\n\t\t\tpAvPair = NULL;\n\t\t\tbreak;\n\t\t}\n\n\t\tpAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);\n\t}\n\n\tif (!pAvPair)\n\t\tcbAvPair = 0;\n\tif (pcbAvPairListRemaining)\n\t\t*pcbAvPairListRemaining = cbAvPair;\n\n\treturn pAvPair;\n}", "label_name": "CWE-125", "label": 125} -{"code": "Variant HHVM_METHOD(XMLReader, expand,\n const Variant& basenode /* = null */) {\n auto* data = Native::data(this_);\n req::ptr doc;\n xmlDocPtr docp = nullptr;\n SYNC_VM_REGS_SCOPED();\n\n if (!basenode.isNull()) {\n auto dombasenode = Native::data(basenode.toObject());\n doc = dombasenode->doc();\n docp = doc->docp();\n if (docp == nullptr) {\n raise_warning(\"Invalid State Error\");\n return false;\n }\n }\n\n if (data->m_ptr) {\n xmlNodePtr node = xmlTextReaderExpand(data->m_ptr);\n if (node == nullptr) {\n raise_warning(\"An Error Occurred while expanding\");\n return false;\n } else {\n xmlNodePtr nodec = xmlDocCopyNode(node, docp, 1);\n if (nodec == nullptr) {\n raise_notice(\"Cannot expand this node type\");\n return false;\n } else {\n return php_dom_create_object(nodec, doc);\n }\n }\n }\n\n raise_warning(\"Load Data before trying to read\");\n return false;\n}", "label_name": "CWE-22", "label": 22} -{"code": "void do_change_user(int afdt_fd) {\n std::string uname;\n lwp_read(afdt_fd, uname);\n if (!uname.length()) return;\n\n auto buf = PasswdBuffer{};\n struct passwd *pw;\n if (getpwnam_r(uname.c_str(), &buf.ent, buf.data.get(), buf.size, &pw)) {\n // TODO(alexeyt) should we log something and/or fail to start?\n return;\n }\n if (!pw) {\n // TODO(alexeyt) should we log something and/or fail to start?\n return;\n }\n\n if (pw->pw_gid) {\n initgroups(pw->pw_name, pw->pw_gid);\n setgid(pw->pw_gid);\n }\n if (pw->pw_uid) {\n setuid(pw->pw_uid);\n }\n}", "label_name": "CWE-22", "label": 22} -{"code": "bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n assertx(m_len != -1);\n if (whence == SEEK_CUR) {\n if (offset > 0 && offset < bufferedLen()) {\n setReadPosition(getReadPosition() + offset);\n setPosition(getPosition() + offset);\n return true;\n }\n offset += getPosition();\n whence = SEEK_SET;\n }\n\n // invalidate the current buffer\n setWritePosition(0);\n setReadPosition(0);\n if (whence == SEEK_SET) {\n m_cursor = offset;\n } else {\n assertx(whence == SEEK_END);\n m_cursor = m_len + offset;\n }\n setPosition(m_cursor);\n return true;\n}", "label_name": "CWE-787", "label": 787} -{"code": " int size() const {\n return m_str ? m_str->size() : 0;\n }", "label_name": "CWE-787", "label": 787} -{"code": "Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n const String& key,\n const String& iv) {\n auto pm = get_valid_mcrypt_resource(td);\n if (!pm) {\n return false;\n }\n\n int max_key_size = mcrypt_enc_get_key_size(pm->m_td);\n int iv_size = mcrypt_enc_get_iv_size(pm->m_td);\n\n if (key.empty()) {\n raise_warning(\"Key size is 0\");\n }\n\n unsigned char *key_s = (unsigned char *)malloc(key.size());\n memset(key_s, 0, key.size());\n\n unsigned char *iv_s = (unsigned char *)malloc(iv_size + 1);\n memset(iv_s, 0, iv_size + 1);\n\n int key_size;\n if (key.size() > max_key_size) {\n raise_warning(\"Key size too large; supplied length: %d, max: %d\",\n key.size(), max_key_size);\n key_size = max_key_size;\n } else {\n key_size = key.size();\n }\n memcpy(key_s, key.data(), key.size());\n\n if (iv.size() != iv_size) {\n raise_warning(\"Iv size incorrect; supplied length: %d, needed: %d\",\n iv.size(), iv_size);\n }\n memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n\n mcrypt_generic_deinit(pm->m_td);\n int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);\n\n /* If this function fails, close the mcrypt module to prevent crashes\n * when further functions want to access this resource */\n if (result < 0) {\n pm->close();\n switch (result) {\n case -3:\n raise_warning(\"Key length incorrect\");\n break;\n case -4:\n raise_warning(\"Memory allocation error\");\n break;\n case -1:\n default:\n raise_warning(\"Unknown error\");\n break;\n }\n } else {\n pm->m_init = true;\n }\n\n free(iv_s);\n free(key_s);\n return result;\n}", "label_name": "CWE-787", "label": 787} -{"code": "TypedValue HHVM_FUNCTION(substr_compare,\n const String& main_str,\n const String& str,\n int offset,\n int length /* = INT_MAX */,\n bool case_insensitivity /* = false */) {\n int s1_len = main_str.size();\n int s2_len = str.size();\n\n if (length <= 0) {\n raise_warning(\"The length must be greater than zero\");\n return make_tv(false);\n }\n\n if (offset < 0) {\n offset = s1_len + offset;\n if (offset < 0) offset = 0;\n }\n\n if (offset >= s1_len) {\n raise_warning(\"The start position cannot exceed initial string length\");\n return make_tv(false);\n }\n\n int cmp_len = s1_len - offset;\n if (cmp_len < s2_len) cmp_len = s2_len;\n if (cmp_len > length) cmp_len = length;\n\n const char *s1 = main_str.data();\n if (case_insensitivity) {\n return tvReturn(bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len));\n }\n return tvReturn(string_ncmp(s1 + offset, str.data(), cmp_len));\n}", "label_name": "CWE-787", "label": 787} -{"code": "static bool extractFileTo(zip* zip, const std::string &file, std::string& to,\n char* buf, size_t len) {\n auto sep = file.rfind('/');\n if (sep != std::string::npos) {\n auto path = to + file.substr(0, sep);\n if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {\n return false;\n }\n\n if (sep == file.length() - 1) {\n return true;\n }\n }\n\n to.append(file);\n struct zip_stat zipStat;\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto zipFile = zip_fopen_index(zip, zipStat.index, 0);\n FAIL_IF_INVALID_PTR(zipFile);\n\n auto outFile = fopen(to.c_str(), \"wb\");\n if (outFile == nullptr) {\n zip_fclose(zipFile);\n return false;\n }\n\n for (auto n = zip_fread(zipFile, buf, len); n != 0;\n n = zip_fread(zipFile, buf, len)) {\n if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {\n zip_fclose(zipFile);\n fclose(outFile);\n remove(to.c_str());\n return false;\n }\n }\n\n zip_fclose(zipFile);\n if (fclose(outFile) != 0) {\n return false;\n }\n\n return true;\n}", "label_name": "CWE-22", "label": 22} -{"code": "static String HHVM_FUNCTION(bcadd, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n if (scale < 0) scale = BCG(bc_precision);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_add(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n return ret;\n}", "label_name": "CWE-190", "label": 190} -{"code": "static String HHVM_FUNCTION(bcmul, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n if (scale < 0) scale = BCG(bc_precision);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_multiply(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n return ret;\n}", "label_name": "CWE-190", "label": 190} -{"code": "jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend)\n{\n\tjas_matrix_t *matrix;\n\tassert(xstart <= xend && ystart <= yend);\n\tif (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {\n\t\treturn 0;\n\t}\n\tmatrix->xstart_ = xstart;\n\tmatrix->ystart_ = ystart;\n\tmatrix->xend_ = xend;\n\tmatrix->yend_ = yend;\n\treturn matrix;\n}", "label_name": "CWE-190", "label": 190} -{"code": "jas_matrix_t *jas_matrix_create(int numrows, int numcols)\n{\n\tjas_matrix_t *matrix;\n\tint i;\n\tsize_t size;\n\n\tmatrix = 0;\n\n\tif (numrows < 0 || numcols < 0) {\n\t\tgoto error;\n\t}\n\n\tif (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {\n\t\tgoto error;\n\t}\n\tmatrix->flags_ = 0;\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\tmatrix->rows_ = 0;\n\tmatrix->maxrows_ = numrows;\n\tmatrix->data_ = 0;\n\tmatrix->datasize_ = 0;\n\n\t// matrix->datasize_ = numrows * numcols;\n\tif (!jas_safe_size_mul(numrows, numcols, &size)) {\n\t\tgoto error;\n\t}\n\tmatrix->datasize_ = size;\n\n\tif (matrix->maxrows_ > 0) {\n\t\tif (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,\n\t\t sizeof(jas_seqent_t *)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (matrix->datasize_ > 0) {\n\t\tif (!(matrix->data_ = jas_alloc2(matrix->datasize_,\n\t\t sizeof(jas_seqent_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[i * matrix->numcols_];\n\t}\n\n\tfor (i = 0; i < matrix->datasize_; ++i) {\n\t\tmatrix->data_[i] = 0;\n\t}\n\n\tmatrix->xstart_ = 0;\n\tmatrix->ystart_ = 0;\n\tmatrix->xend_ = matrix->numcols_;\n\tmatrix->yend_ = matrix->numrows_;\n\n\treturn matrix;\n\nerror:\n\tif (matrix) {\n\t\tjas_matrix_destroy(matrix);\n\t}\n\treturn 0;\n}", "label_name": "CWE-190", "label": 190} -{"code": "check_owner_password_V4(std::string& user_password,\n std::string const& owner_password,\n QPDF::EncryptionData const& data)\n{\n // Algorithm 3.7 from the PDF 1.7 Reference Manual\n\n unsigned char key[OU_key_bytes_V4];\n compute_O_rc4_key(user_password, owner_password, data, key);\n unsigned char O_data[key_bytes];\n memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);\n iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, true);\n std::string new_user_password =\n std::string(reinterpret_cast(O_data), key_bytes);\n bool result = false;\n if (check_user_password(new_user_password, data))\n {\n result = true;\n user_password = new_user_password;\n }\n return result;\n}", "label_name": "CWE-125", "label": 125} -{"code": "Pl_Count::write(unsigned char* buf, size_t len)\n{\n if (len)\n {\n\tthis->m->count += QIntC::to_offset(len);\n\tgetNext()->write(buf, len);\n\tthis->m->last_char = buf[len - 1];\n }\n}", "label_name": "CWE-787", "label": 787} -{"code": "AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)\n{\n AP4_UI32 predefined;\n stream.ReadUI32(predefined);\n stream.ReadUI32(m_HandlerType);\n stream.ReadUI32(m_Reserved[0]);\n stream.ReadUI32(m_Reserved[1]);\n stream.ReadUI32(m_Reserved[2]);\n \n // read the name unless it is empty\n int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n if (name_size == 0) return;\n char* name = new char[name_size+1];\n stream.Read(name, name_size);\n name[name_size] = '\\0'; // force a null termination\n // handle a special case: the Quicktime files have a pascal\n // string here, but ISO MP4 files have a C string.\n // we try to detect a pascal encoding and correct it.\n if (name[0] == name_size-1) {\n m_HandlerName = name+1;\n } else {\n m_HandlerName = name;\n }\n delete[] name;\n}", "label_name": "CWE-476", "label": 476} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;\n\tattr->size = offset;\n\treturn attr;\n}", "label_name": "CWE-788", "label": 788} -{"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-805", "label": 805} -{"code": "static int lookup1_values(int entries, int dim)\n{\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n assert(pow((float) r+1, dim) > entries);\n assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above\n return r;\n}", "label_name": "CWE-908", "label": 908} -{"code": "static float *get_window(vorb *f, int len)\n{\n len <<= 1;\n if (len == f->blocksize_0) return f->window[0];\n if (len == f->blocksize_1) return f->window[1];\n assert(0);\n return NULL;\n}", "label_name": "CWE-787", "label": 787} -{"code": "static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)\n{\n int dy = y1 - y0;\n int adx = x1 - x0;\n int ady = abs(dy);\n int base;\n int x=x0,y=y0;\n int err = 0;\n int sy;\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {\n if (dy < 0) {\n base = -integer_divide_table[ady][adx];\n sy = base-1;\n } else {\n base = integer_divide_table[ady][adx];\n sy = base+1;\n }\n } else {\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n }\n#else\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n#endif\n ady -= abs(base) * adx;\n if (x1 > n) x1 = n;\n if (x < x1) {\n LINE_OP(output[x], inverse_db_table[y]);\n for (++x; x < x1; ++x) {\n err += ady;\n if (err >= adx) {\n err -= adx;\n y += sy;\n } else\n y += base;\n LINE_OP(output[x], inverse_db_table[y]);\n }\n }\n}", "label_name": "CWE-787", "label": 787} -{"code": "static NO_INLINE JsVar *jspGetNamedFieldInParents(JsVar *object, const char* name, bool returnName) {\n // Now look in prototypes\n JsVar * child = jspeiFindChildFromStringInParents(object, name);\n\n /* Check for builtins via separate function\n * This way we save on RAM for built-ins because everything comes out of program code */\n if (!child) {\n child = jswFindBuiltInFunction(object, name);\n }\n\n /* We didn't get here if we found a child in the object itself, so\n * if we're here then we probably have the wrong name - so for example\n * with `a.b = c;` could end up setting `a.prototype.b` (bug #360)\n *\n * Also we might have got a built-in, which wouldn't have a name on it\n * anyway - so in both cases, strip the name if it is there, and create\n * a new name that references the object we actually requested the\n * member from..\n */\n if (child && returnName) {\n // Get rid of existing name\n if (jsvIsName(child)) {\n JsVar *t = jsvGetValueOfName(child);\n jsvUnLock(child);\n child = t;\n }\n // create a new name\n JsVar *nameVar = jsvNewFromString(name);\n JsVar *newChild = jsvCreateNewChild(object, nameVar, child);\n jsvUnLock2(nameVar, child);\n child = newChild;\n }\n\n // If not found and is the prototype, create it\n if (!child) {\n if (jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) {\n // prototype is supposed to be an object\n JsVar *proto = jsvNewObject();\n // make sure it has a 'constructor' variable that points to the object it was part of\n jsvObjectSetChild(proto, JSPARSE_CONSTRUCTOR_VAR, object);\n child = jsvAddNamedChild(object, proto, JSPARSE_PROTOTYPE_VAR);\n jspEnsureIsPrototype(object, child);\n jsvUnLock(proto);\n } else if (strcmp(name, JSPARSE_INHERITS_VAR)==0) {\n const char *objName = jswGetBasicObjectName(object);\n if (objName) {\n child = jspNewPrototype(objName);\n }\n }\n }\n\n return child;\n}", "label_name": "CWE-787", "label": 787} -{"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-22", "label": 22} -{"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-22", "label": 22} -{"code": "void test_base64_decode(void)\n{\n char buffer[16];\n int len = mutt_b64_decode(buffer, encoded);\n if (!TEST_CHECK(len == sizeof(clear) - 1))\n {\n TEST_MSG(\"Expected: %zu\", sizeof(clear) - 1);\n TEST_MSG(\"Actual : %zu\", len);\n }\n buffer[len] = '\\0';\n if (!TEST_CHECK(strcmp(buffer, clear) == 0))\n {\n TEST_MSG(\"Expected: %s\", clear);\n TEST_MSG(\"Actual : %s\", buffer);\n }\n}", "label_name": "CWE-120", "label": 120} -{"code": "inline void AveragePool(const uint8* input_data, const Dims<4>& input_dims,\n int stride_width, int stride_height, int pad_width,\n int pad_height, int filter_width, int filter_height,\n int32 output_activation_min,\n int32 output_activation_max, uint8* output_data,\n const Dims<4>& output_dims) {\n tflite::PoolParams params;\n params.stride_height = stride_height;\n params.stride_width = stride_width;\n params.filter_height = filter_height;\n params.filter_width = filter_width;\n params.padding_values.height = pad_height;\n params.padding_values.width = pad_width;\n params.quantized_activation_min = output_activation_min;\n params.quantized_activation_max = output_activation_max;\n AveragePool(params, DimsToShape(input_dims), input_data,\n DimsToShape(output_dims), output_data);\n}", "label_name": "CWE-835", "label": 835} -{"code": "void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride,\n int pad_width, int pad_height, int filter_width,\n int filter_height, float* output_data,\n const Dims<4>& output_dims) {\n AveragePool(input_data, input_dims, stride, stride, pad_width, pad_height,\n filter_width, filter_height, output_data, output_dims);\n}", "label_name": "CWE-835", "label": 835} -{"code": " void AddBatchOffsets(Tensor* indices, const Tensor& params) {\n int64_t batch_size = 1; // The size of all batch dimensions.\n for (int idx = 0; idx < batch_dims_; ++idx) {\n batch_size *= params.dim_size(idx);\n }\n\n auto indices_flat = indices->flat();\n int64_t const index_inner_size = indices->NumElements() / batch_size;\n int64_t const batch_offset = params.dim_size(batch_dims_);\n for (int64_t batch_idx = 0, dest_idx = 0; batch_idx < batch_size;\n ++batch_idx) {\n for (int64_t idx = 0; idx < index_inner_size; ++idx) {\n indices_flat(dest_idx++) += batch_offset * batch_idx;\n }\n }\n }", "label_name": "CWE-369", "label": 369} -{"code": "StatusOr SpecializeType(const AttrSlice& attrs,\n const OpDef& op_def) {\n FullTypeDef ft;\n ft.set_type_id(TFT_PRODUCT);\n\n for (int i = 0; i < op_def.output_arg_size(); i++) {\n auto* t = ft.add_args();\n\n *t = op_def.output_arg(i).experimental_full_type();\n\n // Resolve dependent types. The convention for op registrations is to use\n // attributes as type variables.\n // See https://www.tensorflow.org/guide/create_op#type_polymorphism.\n // Once the op signature can be defined entirely in FullType, this\n // convention can be deprecated.\n //\n // Note: While this code performs some basic verifications, it generally\n // assumes consistent op defs and attributes. If more complete\n // verifications are needed, they should be done by separately, and in a\n // way that can be reused for type inference.\n for (int j = 0; j < t->args_size(); j++) {\n auto* arg = t->mutable_args(i);\n if (arg->type_id() == TFT_VAR) {\n const auto* attr = attrs.Find(arg->s());\n DCHECK(attr != nullptr);\n if (attr->value_case() == AttrValue::kList) {\n const auto& attr_list = attr->list();\n arg->set_type_id(TFT_PRODUCT);\n for (int i = 0; i < attr_list.type_size(); i++) {\n map_dtype_to_tensor(attr_list.type(i), arg->add_args());\n }\n\n } else if (attr->value_case() == AttrValue::kType) {\n map_dtype_to_tensor(attr->type(), arg);\n\n } else {\n return Status(error::UNIMPLEMENTED,\n absl::StrCat(\"unknown attribute type\",\n attrs.DebugString(), \" key=\", arg->s()));\n }\n\n arg->clear_s();\n }\n }\n }\n\n return ft;\n}", "label_name": "CWE-476", "label": 476} -{"code": "bool ConstantFolding::SimplifyReshape(const GraphProperties& properties,\n bool use_shape_info, NodeDef* node) {\n if (!use_shape_info || node->attr().count(\"T\") == 0 ||\n !IsSimplifiableReshape(*node, properties)) {\n return false;\n }\n DataType output_type = node->attr().at(\"T\").type();\n node->set_op(\"Identity\");\n EraseRegularNodeAttributes(node);\n (*node->mutable_attr())[\"T\"].set_type(output_type);\n *node->mutable_input(1) = AsControlDependency(node->input(1));\n return true;\n}", "label_name": "CWE-617", "label": 617} -{"code": "Status InferenceContext::Multiply(DimensionHandle first,\n DimensionOrConstant second,\n DimensionHandle* out) {\n const int64_t first_value = Value(first);\n const int64_t second_value = Value(second);\n // Special cases.\n if (first_value == 0) {\n *out = first;\n } else if (second_value == 0) {\n *out = MakeDim(second);\n } else if (first_value == 1) {\n *out = MakeDim(second);\n } else if (second_value == 1) {\n *out = first;\n } else if (first_value == kUnknownDim || second_value == kUnknownDim) {\n *out = UnknownDim();\n } else {\n // Invariant: Both values are known and greater than 1.\n const int64_t product = first_value * second_value;\n if (product < 0) {\n return errors::InvalidArgument(\n \"Negative dimension size caused by overflow when multiplying \",\n first_value, \" and \", second_value);\n }\n *out = MakeDim(product);\n }\n return Status::OK();\n}", "label_name": "CWE-190", "label": 190} -{"code": " friend bool operator==(const TensorKey& t1, const TensorKey& t2) {\n if (t1.dtype() != t2.dtype() || t1.shape() != t2.shape()) {\n return false;\n }\n if (DataTypeCanUseMemcpy(t1.dtype())) {\n return t1.tensor_data() == t2.tensor_data();\n }\n if (t1.dtype() == DT_STRING) {\n const auto s1 = t1.unaligned_flat();\n const auto s2 = t2.unaligned_flat();\n for (int64_t i = 0, n = t1.NumElements(); i < n; ++i) {\n if (TF_PREDICT_FALSE(s1(i) != s2(i))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }", "label_name": "CWE-120", "label": 120} -{"code": "__global__ void UnsortedSegmentCustomKernel(const Index input_outer_dim_size,\n const Index inner_dim_size,\n const Index output_outer_dim_size,\n const Index* segment_ids,\n const T* input, T* output) {\n const Index input_total_size = input_outer_dim_size * inner_dim_size;\n const Index output_total_size = output_outer_dim_size * inner_dim_size;\n for (int input_index : GpuGridRangeX(input_total_size)) {\n const Index input_segment_index = input_index / inner_dim_size;\n const Index segment_offset = input_index % inner_dim_size;\n const Index output_segment_index = segment_ids[input_segment_index];\n if (output_segment_index < 0 || output_segment_index >= output_total_size) {\n continue;\n }\n const Index output_index =\n output_segment_index * inner_dim_size + segment_offset;\n KernelReductionFunctor()(output + output_index, ldg(input + input_index));\n }\n}", "label_name": "CWE-681", "label": 681} -{"code": "TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n int max_index = -1;\n const int segment_id_size = segment_ids->dims->data[0];\n if (segment_id_size > 0) {\n max_index = segment_ids->data.i32[segment_id_size - 1];\n }\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;\n for (int i = 1; i < data_rank; ++i) {\n output_shape->data[i] = data->dims->data[i];\n }\n return context->ResizeTensor(context, output, output_shape);\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* data =\n reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 1);\n\n TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt16);\n output->type = kTfLiteInt32;\n if (data->out_float) {\n output->type = kTfLiteFloat32;\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(2);\n int num_frames = 0;\n if (input->dims->data[0] >= data->state->window.size) {\n num_frames = (input->dims->data[0] - data->state->window.size) /\n data->state->window.step / data->frame_stride +\n 1;\n }\n output_size->data[0] = num_frames;\n output_size->data[1] = data->state->filterbank.num_channels *\n (1 + data->left_context + data->right_context);\n\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 125} -{"code": " TfLiteRegistration CopyOpRegistration() {\n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // Set output size to input size\n const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n return context->ResizeTensor(context, tensor1, newSize);\n };\n\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n CallReporting* call_reporting =\n static_cast(node->builtin_data);\n // Copy input data to output data.\n const TfLiteTensor* a0 = GetInput(context, node, 0);\n TfLiteTensor* a1 = GetOutput(context, node, 0);\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n a1->data.f[i] = a0->data.f[i];\n }\n call_reporting->Record();\n return kTfLiteOk;\n };\n return reg;\n }", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus PrepareHashtableSize(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputResourceIdTensor);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);\n\n TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);\n TF_LITE_ENSURE(context, output_tensor != nullptr);\n TF_LITE_ENSURE_EQ(context, output_tensor->type, kTfLiteInt64);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n outputSize->data[0] = 1;\n return context->ResizeTensor(context, output_tensor, outputSize);\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,\n TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n\n // Make sure that the input is in uint8_t with at least 1 data entry.\n const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);\n if (input->type != kTfLiteUInt8) return kTfLiteError;\n if (NumElements(input->dims) == 0) return kTfLiteError;\n\n // Allocate a temporary buffer with the same size of input for sorting.\n TF_LITE_ENSURE_STATUS(context->RequestScratchBufferInArena(\n context, sizeof(uint8_t) * NumElements(input->dims),\n &data->sorting_buffer));\n // We can interleave scratch / persistent buffer allocation.\n data->invoke_count = reinterpret_cast(\n context->AllocatePersistentBuffer(context, sizeof(int)));\n *data->invoke_count = 0;\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus LogSoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) {\n LogSoftmaxOpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, output->params.scale, 16.0 / 256);\n static const double kBeta = 1.0;\n if (input->type == kTfLiteUInt8) {\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 255);\n data->params.table = data->f_table;\n optimized_ops::PopulateSoftmaxLookupTable(&data->params,\n input->params.scale, kBeta);\n data->params.zero_point = output->params.zero_point;\n data->params.scale = output->params.scale;\n }\n if (input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 127);\n static const int kScaledDiffIntegerBits = 5;\n tflite::PreprocessLogSoftmaxScalingExp(\n kBeta, input->params.scale, kScaledDiffIntegerBits,\n &data->input_multiplier, &data->input_left_shift,\n &data->reverse_scaling_divisor, &data->reverse_scaling_right_shift);\n data->reverse_scaling_right_shift *= -1;\n data->diff_min =\n -1.0 * tflite::CalculateInputRadius(kScaledDiffIntegerBits,\n data->input_left_shift);\n }\n }\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Relu6Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n size_t elements = input->bytes / sizeof(float);\n const float* in = GetTensorData(input);\n const float* in_end = in + elements;\n float* out = GetTensorData(output);\n for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f);\n return kTfLiteOk;\n } break;\n case kTfLiteUInt8:\n QuantizedReluX(0.0f, 6.0f, input, output, data);\n return kTfLiteOk;\n case kTfLiteInt8: {\n QuantizedReluX(0.0f, 6.0f, input, output, data);\n return kTfLiteOk;\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context,\n \"Only float32, uint8 and int8 are supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus ReluPrepare(TfLiteContext* context, TfLiteNode* node) {\n ReluOpData* data = reinterpret_cast(node->user_data);\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n if (input->type == kTfLiteInt8 || input->type == kTfLiteUInt8) {\n double real_multiplier = input->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Relu1Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n optimized_ops::Relu1(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output),\n GetTensorData(output));\n return kTfLiteOk;\n } break;\n case kTfLiteUInt8: {\n QuantizedReluX(-1.0f, 1.0f, input, output, data);\n return kTfLiteOk;\n } break;\n case kTfLiteInt8: {\n QuantizedReluX(-1, 1, input, output, data);\n return kTfLiteOk;\n } break;\n default:\n TF_LITE_KERNEL_LOG(context,\n \"Only float32, uint8, int8 supported \"\n \"currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus ReluEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n optimized_ops::Relu(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } break;\n // TODO(renjieliu): We may revisit the quantization calculation logic,\n // the unbounded upper limit is actually hard to quantize.\n case kTfLiteUInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n case kTfLiteInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context, \"Only float32 & int8/uint8 is supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) {\n EvalAdd(context, node, params, data, input1, input2, output);\n } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_OK(context,\n EvalAddQuantized(context, node, params, data,\n input1, input2, output));\n } else {\n TF_LITE_UNSUPPORTED_TYPE(context, output->type, \"Add\");\n }\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n // TODO(b/137042749): TFLite infrastructure (converter, delegate) doesn't\n // fully support 0-output ops yet. Currently it works if we manually crfat\n // a TFLite graph that contains variable ops. Note:\n // * The TFLite Converter need to be changed to be able to produce an op\n // with 0 output.\n // * The delegation code need to be changed to handle 0 output ops. However\n // everything still works fine when variable ops aren't used.\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n if (input->type != kTfLiteFloat32) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, \"Ceil\");\n }\n\n optimized_ops::Ceil(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n if (!is_supported_type(input->type)) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);\n }\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n if (!is_supported_type(input->type)) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);\n }\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);\n TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);\n\n const TfLiteTensor* value = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, NumDimensions(value) >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));\n\n outputSize->data[0] = SizeOfDimension(lookup, 0);\n outputSize->data[1] = SizeOfDimension(value, 1);\n for (int i = 2; i < NumDimensions(value); i++) {\n outputSize->data[i] = SizeOfDimension(value, i);\n }\n return context->ResizeTensor(context, output, outputSize);\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // Check for supported activation types.\n auto* params =\n reinterpret_cast(node->builtin_data);\n const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const bool is_quantized =\n ((filter->type == kTfLiteUInt8) || (filter->type == kTfLiteInt8));\n const bool is_hybrid = is_quantized && (input->type == kTfLiteFloat32);\n const bool is_pie = kernel_type == kLegacyPie;\n\n // Pie and hybrid path supports all kinds of fused activations, otherwise only\n // clipping activations are supported.\n if (!is_pie && !is_hybrid) {\n TF_LITE_ENSURE(context, params->activation == kTfLiteActNone ||\n params->activation == kTfLiteActRelu ||\n params->activation == kTfLiteActReluN1To1 ||\n params->activation == kTfLiteActRelu6);\n }\n return PrepareImpl(context, node);\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = input->dims->data[1];\n output_size->data[2] = input->dims->data[2];\n output_size->data[3] = input->dims->data[3];\n\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteIntArray* input_dims = input->dims;\n int input_dims_size = input_dims->size;\n TF_LITE_ENSURE(context, input_dims_size >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(input_dims_size);\n for (int i = 0; i < input_dims_size; i++) {\n output_shape->data[i] = input_dims->data[i];\n }\n\n // Resize the output tensor to the same size as the input tensor.\n output->type = input->type;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_shape));\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n\n const bool requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n double real_multiplier =\n input1->params.scale * input2->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n int batches = input->dims->data[0];\n int height = input->dims->data[1];\n int width = input->dims->data[2];\n int channels_out = input->dims->data[3];\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n params->filter_height, params->filter_width, padding, &out_height,\n &out_width);\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n if (pool_type == kAverage || pool_type == kMax) {\n TFLITE_DCHECK_LE(std::abs(input->params.scale - output->params.scale),\n 1.0e-6);\n TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point);\n }\n if (pool_type == kL2) {\n // We currently don't have a quantized implementation of L2Pool\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = batches;\n output_size->data[1] = out_height;\n output_size->data[2] = out_width;\n output_size->data[3] = channels_out;\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* start = GetInput(context, node, kStartTensor);\n const TfLiteTensor* limit = GetInput(context, node, kLimitTensor);\n const TfLiteTensor* delta = GetInput(context, node, kDeltaTensor);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeOutput(context, start, limit, delta, output));\n }\n\n switch (output->type) {\n case kTfLiteInt32: {\n EvalImpl(start, delta, output);\n break;\n }\n case kTfLiteFloat32: {\n EvalImpl(start, delta, output);\n break;\n }\n default: {\n context->ReportError(context, \"Unsupported data type: %d\", output->type);\n return kTfLiteError;\n }\n }\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n Subgraph* subgraph = reinterpret_cast(context->impl_);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n int resource_id = input_resource_id_tensor->data.i32[0];\n auto& resources = subgraph->resources();\n auto* variable = resource::GetResourceVariable(&resources, resource_id);\n TF_LITE_ENSURE(context, variable != nullptr);\n\n TfLiteTensor* variable_tensor = variable->GetTensor();\n TfLiteTensor* output = GetOutput(context, node, kOutputValue);\n\n TF_LITE_ENSURE_TYPES_EQ(context, variable_tensor->type, output->type);\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(\n context, output, TfLiteIntArrayCopy(variable_tensor->dims)));\n memcpy(output->data.raw, variable_tensor->data.raw, output->bytes);\n\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, node->inputs->size, 1);\n TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputValue);\n SetTensorToDynamic(output);\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus EvalLogic(TfLiteContext* context, TfLiteNode* node,\n OpContext* op_context, T init_value,\n T reducer(const T current, const T in)) {\n int64_t num_axis = NumElements(op_context->axis);\n TfLiteTensor* temp_index = GetTemporary(context, node, /*index=*/0);\n TfLiteTensor* resolved_axis = GetTemporary(context, node, /*index=*/1);\n // Resize the output tensor if the output tensor is dynamic.\n if (IsDynamicTensor(op_context->output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTempAxis(context, op_context, resolved_axis));\n TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, op_context));\n }\n if (op_context->input->type == kTfLiteUInt8 ||\n op_context->input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, op_context->input->params.scale,\n op_context->output->params.scale);\n TF_LITE_ENSURE_EQ(context, op_context->input->params.zero_point,\n op_context->output->params.zero_point);\n }\n TF_LITE_ENSURE(\n context,\n reference_ops::ReduceGeneric(\n GetTensorData(op_context->input), op_context->input->dims->data,\n op_context->input->dims->size, GetTensorData(op_context->output),\n op_context->output->dims->data, op_context->output->dims->size,\n GetTensorData(op_context->axis), num_axis,\n op_context->params->keep_dims, GetTensorData(temp_index),\n GetTensorData(resolved_axis), init_value, reducer));\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n TfLiteIntArray* output_shape = GetOutputShape(context, node);\n std::unique_ptr\n scoped_output_shape(output_shape, TfLiteIntArrayFree);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // Tensorflow's Reshape allows one of the shape components to have the\n // special -1 value, meaning it will be calculated automatically based on the\n // input. Here we calculate what that dimension should be so that the number\n // of output elements in the same as the number of input elements.\n int num_input_elements = NumElements(input);\n\n int num_output_elements = 1;\n int stretch_dim = -1;\n for (int i = 0; i < output_shape->size; ++i) {\n int value = output_shape->data[i];\n if (value == -1) {\n TF_LITE_ENSURE_EQ(context, stretch_dim, -1);\n stretch_dim = i;\n } else {\n num_output_elements *= value;\n }\n }\n if (stretch_dim != -1) {\n output_shape->data[stretch_dim] = num_input_elements / num_output_elements;\n num_output_elements *= output_shape->data[stretch_dim];\n }\n\n TF_LITE_ENSURE_EQ(context, num_input_elements, num_output_elements);\n return context->ResizeTensor(context, output, scoped_output_shape.release());\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus ReverseSequenceHelper(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* seq_lengths_tensor =\n GetInput(context, node, kSeqLengthsTensor);\n switch (seq_lengths_tensor->type) {\n case kTfLiteInt32: {\n return ReverseSequenceImpl(context, node);\n }\n case kTfLiteInt64: {\n return ReverseSequenceImpl(context, node);\n }\n default: {\n context->ReportError(\n context,\n \"Seq_lengths type '%s' is not supported by reverse_sequence.\",\n TfLiteTypeGetName(seq_lengths_tensor->type));\n return kTfLiteError;\n }\n }\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* fft_length = GetInput(context, node, kFftLengthTensor);\n const int32_t* fft_length_data = GetTensorData(fft_length);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type != kTfLiteComplex64) {\n context->ReportError(context,\n \"Type '%s' for output is not supported by rfft2d.\",\n TfLiteTypeGetName(output->type));\n return kTfLiteError;\n }\n\n // Resize the output tensor if the fft_length tensor is not constant.\n // Otherwise, check if the output shape is correct.\n if (!IsConstantTensor(fft_length)) {\n TF_LITE_ENSURE_STATUS(ResizeOutputandTemporaryTensors(context, node));\n } else {\n int num_dims_output = NumDimensions(output);\n const RuntimeShape output_shape = GetTensorShape(output);\n TF_LITE_ENSURE_EQ(context, num_dims_output, NumDimensions(input));\n TF_LITE_ENSURE(context, num_dims_output >= 2);\n TF_LITE_ENSURE_EQ(context, output_shape.Dims(num_dims_output - 2),\n fft_length_data[0]);\n TF_LITE_ENSURE_EQ(context, output_shape.Dims(num_dims_output - 1),\n fft_length_data[1] / 2 + 1);\n }\n\n return Rfft2dHelper(context, node);\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);\n const TfLiteTensor* segment_ids =\n GetInput(context, node, kInputSegmentIdsTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeOutputTensor(context, data, segment_ids, output));\n }\n\n#define TF_LITE_SEGMENT_SUM(dtype) \\\n reference_ops::SegmentSum( \\\n GetTensorShape(data), GetTensorData(data), \\\n GetTensorShape(segment_ids), GetTensorData(segment_ids), \\\n GetTensorShape(output), GetTensorData(output));\n switch (data->type) {\n case kTfLiteInt32:\n TF_LITE_SEGMENT_SUM(int32_t);\n break;\n case kTfLiteFloat32:\n TF_LITE_SEGMENT_SUM(float);\n break;\n default:\n context->ReportError(context,\n \"Currently SegmentSum doesn't support type: %s\",\n TfLiteTypeGetName(data->type));\n return kTfLiteError;\n }\n#undef TF_LITE_SEGMENT_SUM\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 125} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n TF_LITE_ENSURE_TYPES_EQ(context, GetInput(context, node, 0)->type,\n kTfLiteString);\n TF_LITE_ENSURE_TYPES_EQ(context, GetOutput(context, node, 0)->type,\n kTfLiteString);\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 787} -{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* cond_tensor =\n GetInput(context, node, kInputConditionTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (cond_tensor->type != kTfLiteBool) {\n context->ReportError(context,\n \"Condition tensor must be of type bool, but saw '%s'.\",\n TfLiteTypeGetName(cond_tensor->type));\n return kTfLiteError;\n }\n\n // As output will be a 2D tensor of indices, use int64 to be consistent with\n // tensorflow.\n output->type = kTfLiteInt64;\n\n // Exit early if cond is a non-const tensor. Set output tensor to dynamic so\n // output size can be determined in Eval.\n if (!IsConstantTensor(cond_tensor)) {\n SetTensorToDynamic(output);\n return kTfLiteOk;\n }\n return ResizeOutputTensor(context, cond_tensor, output);\n}", "label_name": "CWE-125", "label": 125} -{"code": " void CalculateOutputIndexRowSplit(\n const RowPartitionTensor& row_split,\n const vector& parent_output_index,\n INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size,\n vector* result) {\n INDEX_TYPE row_split_size = row_split.size();\n if (row_split_size > 0) {\n result->reserve(row_split(row_split_size - 1));\n }\n for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) {\n INDEX_TYPE row_length = row_split(i + 1) - row_split(i);\n INDEX_TYPE real_length = std::min(output_size, row_length);\n INDEX_TYPE parent_output_index_current = parent_output_index[i];\n\n if (parent_output_index_current == -1) {\n real_length = 0;\n }\n for (INDEX_TYPE j = 0; j < real_length; ++j) {\n result->push_back(parent_output_index_current);\n parent_output_index_current += output_index_multiplier;\n }\n for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) {\n result->push_back(-1);\n }\n }\n if (row_split_size > 0) {\n DCHECK_EQ(result->size(), row_split(row_split_size - 1));\n }\n }", "label_name": "CWE-131", "label": 131} -{"code": " void ValidateInputTensors(OpKernelContext* ctx, const Tensor& in0,\n const Tensor& in1) override {\n OP_REQUIRES(\n ctx, in0.dims() >= 2,\n errors::InvalidArgument(\"In[0] ndims must be >= 2: \", in0.dims()));\n\n OP_REQUIRES(\n ctx, in1.dims() >= 2,\n errors::InvalidArgument(\"In[0] ndims must be >= 2: \", in1.dims()));\n }", "label_name": "CWE-125", "label": 125} -{"code": "template void testFeatTable(const T & table, const char * testName)\n{\n FeatureMap testFeatureMap;\n dummyFace.replace_table(TtfUtil::Tag::Feat, &table, sizeof(T));\n gr_face * face = gr_make_face_with_ops(&dummyFace, &face_handle::ops, gr_face_dumbRendering);\n if (!face) throw std::runtime_error(\"failed to load font\");\n bool readStatus = testFeatureMap.readFeats(*face);\n testAssert(\"readFeats\", readStatus);\n fprintf(stderr, testName, NULL);\n testAssertEqual(\"test num features %hu,%hu\\n\", testFeatureMap.numFeats(), table.m_header.m_numFeat);\n\n for (size_t i = 0; i < sizeof(table.m_defs) / sizeof(FeatDefn); i++)\n {\n const FeatureRef * ref = testFeatureMap.findFeatureRef(table.m_defs[i].m_featId);\n testAssert(\"test feat\\n\", ref);\n testAssertEqual(\"test feat settings %hu %hu\\n\", ref->getNumSettings(), table.m_defs[i].m_numFeatSettings);\n testAssertEqual(\"test feat label %hu %hu\\n\", ref->getNameId(), table.m_defs[i].m_label);\n size_t settingsIndex = (table.m_defs[i].m_settingsOffset - sizeof(FeatHeader)\n - (sizeof(FeatDefn) * table.m_header.m_numFeat)) / sizeof(FeatSetting);\n for (size_t j = 0; j < table.m_defs[i].m_numFeatSettings; j++)\n {\n testAssertEqual(\"setting label %hu %hu\\n\", ref->getSettingName(j),\n table.m_settings[settingsIndex+j].m_label);\n }\n }\n gr_face_destroy(face);\n}", "label_name": "CWE-476", "label": 476} -{"code": "folly::Optional EncryptedReadRecordLayer::read(\n folly::IOBufQueue& buf) {\n auto decryptedBuf = getDecryptedBuf(buf);\n if (!decryptedBuf) {\n return folly::none;\n }\n\n TLSMessage msg;\n // Iterate over the buffers while trying to find\n // the first non-zero octet. This is much faster than\n // first iterating and then trimming.\n auto currentBuf = decryptedBuf->get();\n bool nonZeroFound = false;\n do {\n currentBuf = currentBuf->prev();\n size_t i = currentBuf->length();\n while (i > 0 && !nonZeroFound) {\n nonZeroFound = (currentBuf->data()[i - 1] != 0);\n i--;\n }\n if (nonZeroFound) {\n msg.type = static_cast(currentBuf->data()[i]);\n }\n currentBuf->trimEnd(currentBuf->length() - i);\n } while (!nonZeroFound && currentBuf != decryptedBuf->get());\n if (!nonZeroFound) {\n throw std::runtime_error(\"No content type found\");\n }\n msg.fragment = std::move(*decryptedBuf);\n\n switch (msg.type) {\n case ContentType::handshake:\n case ContentType::alert:\n case ContentType::application_data:\n break;\n default:\n throw std::runtime_error(folly::to(\n \"received encrypted content type \",\n static_cast(msg.type)));\n }\n\n if (!msg.fragment || msg.fragment->empty()) {\n if (msg.type == ContentType::application_data) {\n msg.fragment = folly::IOBuf::create(0);\n } else {\n throw std::runtime_error(\"received empty fragment\");\n }\n }\n\n return msg;\n}", "label_name": "CWE-770", "label": 770} -{"code": "Envoy::Ssl::ClientValidationStatus DefaultCertValidator::verifyCertificate(\n X509* cert, const std::vector& verify_san_list,\n const std::vector>&\n subject_alt_name_matchers) {\n Envoy::Ssl::ClientValidationStatus validated = Envoy::Ssl::ClientValidationStatus::NotValidated;\n\n if (!verify_san_list.empty()) {\n if (!verifySubjectAltName(cert, verify_san_list)) {\n stats_.fail_verify_san_.inc();\n return Envoy::Ssl::ClientValidationStatus::Failed;\n }\n validated = Envoy::Ssl::ClientValidationStatus::Validated;\n }\n\n if (!subject_alt_name_matchers.empty()) {\n if (!matchSubjectAltName(cert, subject_alt_name_matchers)) {\n stats_.fail_verify_san_.inc();\n return Envoy::Ssl::ClientValidationStatus::Failed;\n }\n validated = Envoy::Ssl::ClientValidationStatus::Validated;\n }\n\n if (!verify_certificate_hash_list_.empty() || !verify_certificate_spki_list_.empty()) {\n const bool valid_certificate_hash =\n !verify_certificate_hash_list_.empty() &&\n verifyCertificateHashList(cert, verify_certificate_hash_list_);\n const bool valid_certificate_spki =\n !verify_certificate_spki_list_.empty() &&\n verifyCertificateSpkiList(cert, verify_certificate_spki_list_);\n\n if (!valid_certificate_hash && !valid_certificate_spki) {\n stats_.fail_verify_cert_hash_.inc();\n return Envoy::Ssl::ClientValidationStatus::Failed;\n }\n\n validated = Envoy::Ssl::ClientValidationStatus::Validated;\n }\n\n return validated;\n}", "label_name": "CWE-295", "label": 295} -{"code": "bool SPIFFEValidator::matchSubjectAltName(X509& leaf_cert) {\n bssl::UniquePtr san_names(static_cast(\n X509_get_ext_d2i(&leaf_cert, NID_subject_alt_name, nullptr, nullptr)));\n // We must not have san_names == nullptr here because this function is called after the\n // SPIFFE cert validation algorithm succeeded, which requires exactly one URI SAN in the leaf\n // cert.\n ASSERT(san_names != nullptr,\n \"san_names should have at least one name after SPIFFE cert validation\");\n\n // Only match against URI SAN since SPIFFE specification does not restrict values in other SAN\n // types. See the discussion: https://github.com/envoyproxy/envoy/issues/15392\n for (const GENERAL_NAME* general_name : san_names.get()) {\n if (general_name->type == GEN_URI) {\n const std::string san = Utility::generalNameAsString(general_name);\n for (const auto& config_san_matcher : subject_alt_name_matchers_) {\n if (config_san_matcher.match(san)) {\n return true;\n }\n }\n }\n }\n return false;\n}", "label_name": "CWE-295", "label": 295} -{"code": "TEST_P(SslSocketTest, GetUriWithUriSan) {\n const std::string client_ctx_yaml = R\"EOF(\n common_tls_context:\n tls_certificates:\n certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem\"\n)EOF\";\n\n const std::string server_ctx_yaml = R\"EOF(\n common_tls_context:\n tls_certificates:\n certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/unittest_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/unittest_key.pem\"\n validation_context:\n trusted_ca:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem\"\n match_subject_alt_names:\n exact: \"spiffe://lyft.com/test-team\"\n)EOF\";\n\n TestUtilOptions test_options(client_ctx_yaml, server_ctx_yaml, true, GetParam());\n testUtil(test_options.setExpectedClientCertUri(\"spiffe://lyft.com/test-team\")\n .setExpectedSerialNumber(TEST_SAN_URI_CERT_SERIAL));\n}", "label_name": "CWE-295", "label": 295} -{"code": " inline int check(int itemSize, int nItems=1, bool wait=true)\n {\n if (ptr + itemSize * nItems > end) {\n if (ptr + itemSize > end)\n return overrun(itemSize, nItems, wait);\n\n nItems = (end - ptr) / itemSize;\n }\n return nItems;\n }", "label_name": "CWE-787", "label": 787} -{"code": " inline void skip(int bytes) {\n while (bytes > 0) {\n int n = check(1, bytes);\n ptr += n;\n bytes -= n;\n }\n }", "label_name": "CWE-787", "label": 787} -{"code": " int overrun(int itemSize, int nItems, bool wait) { throw EndOfStream(); }", "label_name": "CWE-787", "label": 787} -{"code": "int ZlibOutStream::length()\n{\n return offset + ptr - start;\n}", "label_name": "CWE-787", "label": 787} -{"code": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(CentralDirectoryRecord) - (sizeof(u8*) * 3);\n if (buffer.size() < fields_size)\n return false;\n if (memcmp(buffer.data(), central_directory_record_signature, sizeof(central_directory_record_signature)) != 0)\n return false;\n memcpy(reinterpret_cast(&made_by_version), buffer.data() + sizeof(central_directory_record_signature), fields_size);\n name = buffer.data() + sizeof(central_directory_record_signature) + fields_size;\n extra_data = name + name_length;\n comment = extra_data + extra_data_length;\n return true;\n }", "label_name": "CWE-120", "label": 120} -{"code": "bool PackLinuxElf32::calls_crt1(Elf32_Rel const *rel, int sz)\n{\n if (!dynsym || !dynstr) {\n return false;\n }\n for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf32_Rel)), ++rel, ++relnum) {\n unsigned const symnum = get_te32(&rel->r_info) >> 8;\n char const *const symnam = get_dynsym_name(symnum, relnum);\n if (0==strcmp(symnam, \"__libc_start_main\") // glibc\n || 0==strcmp(symnam, \"__libc_init\") // Android\n || 0==strcmp(symnam, \"__uClibc_main\")\n || 0==strcmp(symnam, \"__uClibc_start_main\"))\n return true;\n }\n return false;\n}", "label_name": "CWE-190", "label": 190} -{"code": "int64_t LineBasedFrameDecoder::findEndOfLine(IOBufQueue& buf) {\n Cursor c(buf.front());\n for (uint32_t i = 0; i < maxLength_ && i < buf.chainLength(); i++) {\n auto b = c.read();\n if (b == '\\n' && terminatorType_ != TerminatorType::CARRIAGENEWLINE) {\n return i;\n } else if (terminatorType_ != TerminatorType::NEWLINE &&\n b == '\\r' && !c.isAtEnd() && c.read() == '\\n') {\n return i;\n }\n }\n\n return -1;\n}", "label_name": "CWE-787", "label": 787} -{"code": "snmp_process_data(void)\n{\n static unsigned char packet[SNMP_MAX_PACKET_SIZE];\n unsigned char *packet_end;\n static uint32_t packet_len;\n\n packet_end = packet + sizeof(packet) - 1;\n packet_len = 0;\n\n LOG_DBG(\"receiving UDP datagram from [\");\n LOG_DBG_6ADDR(&UIP_IP_BUF->srcipaddr);\n LOG_DBG_(\"]:%u\", uip_ntohs(UIP_UDP_BUF->srcport));\n LOG_DBG_(\" Length: %u\\n\", uip_datalen());\n\n /*\n * Handle the request\n */\n if((packet_end = snmp_engine(uip_appdata, uip_datalen(), packet_end, &packet_len)) == NULL) {\n LOG_DBG(\"Error while handling the request\\n\");\n } else {\n LOG_DBG(\"Sending response\\n\");\n /*\n * Send the response\n */\n uip_udp_packet_sendto(snmp_udp_conn, packet_end, packet_len, &UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport);\n }\n}", "label_name": "CWE-125", "label": 125} -{"code": "int LibarchivePlugin::extractionFlags() const\n{\n int result = ARCHIVE_EXTRACT_TIME;\n result |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;\n\n // TODO: Don't use arksettings here\n /*if ( ArkSettings::preservePerms() )\n {\n result &= ARCHIVE_EXTRACT_PERM;\n }\n\n if ( !ArkSettings::extractOverwrite() )\n {\n result &= ARCHIVE_EXTRACT_NO_OVERWRITE;\n }*/\n\n return result;\n}", "label_name": "CWE-59", "label": 59} -{"code": "void MainWindow::showUpgradePrompt()\n{\n if (Settings.checkUpgradeAutomatic()) {\n showStatusMessage(\"Checking for upgrade...\");\n QNetworkRequest request(QUrl(\"https://check.shotcut.org/version.json\"));\n QSslConfiguration sslConfig = request.sslConfiguration();\n sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);\n request.setSslConfiguration(sslConfig);\n m_network.get(request);\n } else {\n m_network.setStrictTransportSecurityEnabled(false);\n QAction* action = new QAction(tr(\"Click here to check for a new version of Shotcut.\"), 0);\n connect(action, SIGNAL(triggered(bool)), SLOT(on_actionUpgrade_triggered()));\n showStatusMessage(action, 15 /* seconds */);\n }\n}", "label_name": "CWE-295", "label": 295} -{"code": "bool AES_GCM_EncryptContext::Encrypt(\n\tconst void *pPlaintextData, size_t cbPlaintextData,\n\tconst void *pIV,\n\tvoid *pEncryptedDataAndTag, uint32 *pcbEncryptedDataAndTag,\n\tconst void *pAdditionalAuthenticationData, size_t cbAuthenticationData\n) {\n unsigned long long pcbEncryptedDataAndTag_longlong = *pcbEncryptedDataAndTag;\n\n crypto_aead_aes256gcm_encrypt_afternm(\n\t\tstatic_cast( pEncryptedDataAndTag ), &pcbEncryptedDataAndTag_longlong,\n\t\tstatic_cast( pPlaintextData ), cbPlaintextData,\n\t\tstatic_cast(pAdditionalAuthenticationData), cbAuthenticationData,\n\t\tnullptr,\n\t\tstatic_cast( pIV ),\n\t\tstatic_cast( m_ctx )\n\t);\n\n *pcbEncryptedDataAndTag = pcbEncryptedDataAndTag_longlong;\n\n return true;\n}", "label_name": "CWE-787", "label": 787} -{"code": "Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)\r\n{\r\n auto* zei = entries.getUnchecked (index);\r\n\r\n #if JUCE_WINDOWS\r\n auto entryPath = zei->entry.filename;\r\n #else\r\n auto entryPath = zei->entry.filename.replaceCharacter ('\\\\', '/');\r\n #endif\r\n\r\n if (entryPath.isEmpty())\r\n return Result::ok();\r\n\r\n auto targetFile = targetDirectory.getChildFile (entryPath);\r\n\r\n if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\\\'))\r\n return targetFile.createDirectory(); // (entry is a directory, not a file)\r\n\r\n std::unique_ptr in (createStreamForEntry (index));\r\n\r\n if (in == nullptr)\r\n return Result::fail (\"Failed to open the zip file for reading\");\r\n\r\n if (targetFile.exists())\r\n {\r\n if (! shouldOverwriteFiles)\r\n return Result::ok();\r\n\r\n if (! targetFile.deleteFile())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n }\r\n\r\n if (! targetFile.getParentDirectory().createDirectory())\r\n return Result::fail (\"Failed to create target folder: \" + targetFile.getParentDirectory().getFullPathName());\r\n\r\n if (zei->entry.isSymbolicLink)\r\n {\r\n String originalFilePath (in->readEntireStreamAsString()\r\n .replaceCharacter (L'/', File::getSeparatorChar()));\r\n\r\n if (! File::createSymbolicLink (targetFile, originalFilePath, true))\r\n return Result::fail (\"Failed to create symbolic link: \" + originalFilePath);\r\n }\r\n else\r\n {\r\n FileOutputStream out (targetFile);\r\n\r\n if (out.failedToOpen())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n\r\n out << *in;\r\n }\r\n\r\n targetFile.setCreationTime (zei->entry.fileTime);\r\n targetFile.setLastModificationTime (zei->entry.fileTime);\r\n targetFile.setLastAccessTime (zei->entry.fileTime);\r\n\r\n return Result::ok();\r\n}\r", "label_name": "CWE-59", "label": 59} -{"code": "std::string RestAuthHandler::generateJwt(std::string const& username,\n std::string const& password) {\n AuthenticationFeature* af = AuthenticationFeature::instance();\n TRI_ASSERT(af != nullptr);\n return fuerte::jwt::generateUserToken(af->tokenCache().jwtSecret(), username, _validFor);\n}", "label_name": "CWE-613", "label": 613} -{"code": "RestAuthHandler::RestAuthHandler(application_features::ApplicationServer& server,\n GeneralRequest* request, GeneralResponse* response)\n : RestVocbaseBaseHandler(server, request, response),\n _validFor(60 * 60 * 24 * 30) {}", "label_name": "CWE-613", "label": 613} -{"code": "string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {\n CHECK_STATE(errStatus);\n CHECK_STATE(err_string);\n CHECK_STATE(_key);\n auto keyArray = make_shared>(BUF_LEN, 0);\n auto encryptedKey = make_shared>(BUF_LEN, 0);\n\n vector errMsg(BUF_LEN, 0);\n\n strncpy(keyArray->data(), _key, BUF_LEN);\n *errStatus = 0;\n unsigned int encryptedLen = 0;\n\n sgx_status_t status = trustedEncryptKeyAES(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(), &encryptedLen);\n\n HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());\n\n SAFE_CHAR_BUF(resultBuf, 2 * BUF_LEN + 1);\n\n carray2Hex(encryptedKey->data(), encryptedLen, resultBuf, 2 * BUF_LEN + 1);\n\n return string(resultBuf);\n}", "label_name": "CWE-787", "label": 787} -{"code": "shared_ptr > check_and_set_SEK(const string &SEK) {\n\n vector decr_key(BUF_LEN, 0);\n vector errMsg(BUF_LEN, 0);\n int err_status = 0;\n\n auto encrypted_SEK = make_shared < vector < uint8_t >> (BUF_LEN, 0);\n\n uint32_t l = 0;\n\n sgx_status_t status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l,\n SEK.c_str());\n\n encrypted_SEK->resize(l);\n\n HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());\n\n validate_SEK();\n\n return encrypted_SEK;\n}", "label_name": "CWE-787", "label": 787} -{"code": "TEST_CASE_METHOD(TestFixture, \"DKG AES encrypted secret shares test\", \"[dkg-aes-encr-sshares]\") {\n vector errMsg(BUF_LEN, 0);\n vector result(BUF_LEN, 0);\n\n int errStatus = 0;\n uint32_t encLen = 0;\n\n vector encryptedDKGSecret(BUF_LEN, 0);\n PRINT_SRC_LINE\n auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n\n uint64_t enc_len = encLen;\n\n PRINT_SRC_LINE\n status = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), enc_len);\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n\n vector encrPRDHKey(BUF_LEN, 0);\n\n string pub_keyB = SAMPLE_PUBLIC_KEY_B;\n\n vector s_shareG2(BUF_LEN, 0);\n PRINT_SRC_LINE\n status = trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &encLen,\n result.data(),\n s_shareG2.data(),\n (char *) pub_keyB.data(), 2, 2, 1);\n\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n}", "label_name": "CWE-787", "label": 787} -{"code": "RawTile KakaduImage::getRegion( int seq, int ang, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h )\n{\n // Scale up our output bit depth to the nearest factor of 8\n unsigned int obpc = bpc;\n if( bpc <= 16 && bpc > 8 ) obpc = 16;\n else if( bpc <= 8 ) obpc = 8;\n\n#ifdef DEBUG\n Timer timer;\n timer.start();\n#endif\n\n RawTile rawtile( 0, res, seq, ang, w, h, channels, obpc );\n\n if( obpc == 16 ) rawtile.data = new unsigned short[w*h*channels];\n else if( obpc == 8 ) rawtile.data = new unsigned char[w*h*channels];\n else throw file_error( \"Kakadu :: Unsupported number of bits\" );\n\n rawtile.dataLength = w*h*channels*(obpc/8);\n rawtile.filename = getImagePath();\n rawtile.timestamp = timestamp;\n\n process( res, layers, x, y, w, h, rawtile.data );\n\n#ifdef DEBUG\n logfile << \"Kakadu :: getRegion() :: \" << timer.getTime() << \" microseconds\" << endl;\n#endif\n\n return rawtile;\n\n}", "label_name": "CWE-190", "label": 190} -{"code": " bool CheckRegion(int nPos, int nSize)\n {\n return (nPos >= 0 && nPos + nSize >= nPos && nPos + nSize <= m_nLen);\n }", "label_name": "CWE-787", "label": 787} -{"code": "int32_t CxImage::GetSize()\r\n{\r\n\treturn head.biSize + head.biSizeImage + GetPaletteSize();\r\n}\r", "label_name": "CWE-770", "label": 770} -{"code": "void DCR_CLASS dcr_parse_riff(DCRAW* p)\r\n{\r\n\tunsigned i, size, end;\r\n\tchar tag[4], date[64], month[64];\r\n\tstatic const char mon[12][4] =\r\n\t{ \"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\" };\r\n\tstruct tm t;\r\n\r\n\tp->order = 0x4949;\r\n\tdcr_fread(p->obj_, tag, 4, 1);\r\n\tsize = dcr_get4(p);\r\n\tend = dcr_ftell(p->obj_) + size;\r\n\tif (!memcmp(tag,\"RIFF\",4) || !memcmp(tag,\"LIST\",4)) {\r\n\t\tdcr_get4(p);\r\n\t\twhile (dcr_ftell(p->obj_)+7 < (long)end)\r\n\t\t\tdcr_parse_riff(p);\r\n\t} else if (!memcmp(tag,\"nctg\",4)) {\r\n\t\twhile (dcr_ftell(p->obj_)+7 < (long)end) {\r\n\t\t\ti = dcr_get2(p);\r\n\t\t\tsize = dcr_get2(p);\r\n\t\t\tif ((i+1) >> 1 == 10 && size == 20)\r\n\t\t\t\tdcr_get_timestamp(p,0);\r\n\t\t\telse dcr_fseek(p->obj_, size, SEEK_CUR);\r\n\t\t}\r\n\t} else if (!memcmp(tag,\"IDIT\",4) && size < 64) {\r\n\t\tdcr_fread(p->obj_, date, 64, 1);\r\n\t\tdate[size] = 0;\r\n\t\tmemset (&t, 0, sizeof t);\r\n\t\tif (sscanf (date, \"%*s %s %d %d:%d:%d %d\", month, &t.tm_mday,\r\n\t\t\t&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {\r\n\t\t\tfor (i=0; i < 12 && strcasecmp(mon[i],month); i++);\r\n\t\t\tt.tm_mon = i;\r\n\t\t\tt.tm_year -= 1900;\r\n\t\t\tif (mktime(&t) > 0)\r\n\t\t\t\tp->timestamp = mktime(&t);\r\n\t\t}\r\n\t} else\r\n\t\tdcr_fseek(p->obj_, size, SEEK_CUR);\r\n}\r", "label_name": "CWE-770", "label": 770} -{"code": " def quote_column_name(name) #:nodoc:\n %Q(\"#{name}\")\n end", "label_name": "CWE-89", "label": 89} -{"code": " def _call(env)\n unless ALLOWED_VERBS.include? env[\"REQUEST_METHOD\"]\n return fail(405, \"Method Not Allowed\")\n end\n\n path_info = Utils.unescape(env[\"PATH_INFO\"])\n parts = path_info.split SEPS\n\n parts.inject(0) do |depth, part|\n case part\n when '', '.'\n depth\n when '..'\n return fail(404, \"Not Found\") if depth - 1 < 0\n depth - 1\n else\n depth + 1\n end\n end", "label_name": "CWE-22", "label": 22} -{"code": " it \"with Pathname command\" do\n cl = subject.build_command_line(Pathname.new(\"/usr/bin/ruby\"))\n expect(cl).to eq \"/usr/bin/ruby\"\n end", "label_name": "CWE-78", "label": 78} -{"code": " it \"without params\" do\n cl = subject.build_command_line(\"true\")\n expect(cl).to eq \"true\"\n end", "label_name": "CWE-78", "label": 78} -{"code": " it \"with params as empty Hash\" do\n cl = subject.build_command_line(\"true\", {})\n expect(cl).to eq \"true\"\n end", "label_name": "CWE-78", "label": 78} -{"code": " def media_type_mismatch?\n ! supplied_file_media_types.include?(calculated_media_type)\n end", "label_name": "CWE-79", "label": 79} -{"code": " def filename_extension\n File.extname(@name.to_s.downcase).sub(/^\\./, '').to_sym\n end", "label_name": "CWE-79", "label": 79} -{"code": " def show_tree\n Log.add_info(request, params.inspect)\n\n if !@login_user.nil? and @login_user.admin?(User::AUTH_FOLDER)\n\n @group_id = nil\n if !params[:thetisBoxSelKeeper].nil?\n @group_id = params[:thetisBoxSelKeeper].split(':').last\n elsif !params[:group_id].nil? and !params[:group_id].empty?\n @group_id = params[:group_id]\n end\n\n @folder_tree = Folder.get_tree_by_group_for_admin(@group_id || '0')\n else\n @folder_tree = Folder.get_tree_for(@login_user)\n end\n end", "label_name": "CWE-89", "label": 89} -{"code": " def wf_issue\n Log.add_info(request, params.inspect)\n\n begin\n @item = Item.find(params[:id])\n @workflow = @item.workflow\n rescue => evar\n Log.add_error(request, evar)\n end\n \n attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now})\n @workflow.update_attributes(attrs.permit(Workflow::PERMIT_BASE))\n\n @orders = @workflow.get_orders\n\n render(:partial => 'ajax_workflow', :layout => false)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def show\n if params[:action] == 'show'\n Log.add_info(request, params.inspect)\n end\n\n @mail_filter = MailFilter.find_by_id(params[:id])\n if @mail_filter.nil?\n render(:text => 'ERROR:' + t('msg.already_deleted', :name => MailFilter.model_name.human))\n return\n else\n if @mail_filter.mail_account.user_id != @login_user.id\n render(:text => 'ERROR:' + t('msg.need_to_be_owner'))\n return\n end\n end\n render(:action => 'show', :layout => (!request.xhr?))\n end", "label_name": "CWE-89", "label": 89} -{"code": " def check_import(mode, address_names) #, address_emails\n\n err_msgs = []\n\n # Existing Addresss\n unless self.id.nil? or self.id == 0 or self.id == ''\n if mode == 'add'\n err_msgs << I18n.t('address.import.dont_specify_id')\n else\n begin\n org_address = Address.find(self.id)\n rescue\n end\n if org_address.nil?\n err_msgs << I18n.t('address.import.not_found')\n end\n end\n end\n\n # Requierd\n if self.name.nil? or self.name.empty?\n err_msgs << Address.human_attribute_name('name') + I18n.t('msg.is_required')\n end\n\n # Groups\n unless self.groups.nil? or self.groups.empty?\n\n if (/^|([0-9]+|)+$/ =~ self.groups) == 0\n\n self.get_groups_a.each do |group_id|\n group = Group.find_by_id(group_id)\n if group.nil?\n err_msgs << I18n.t('address.import.not_valid_groups') + ': '+group_id.to_s\n break\n end\n end\n else\n err_msgs << I18n.t('address.import.invalid_groups_format')\n end\n end\n\n # Teams\n unless self.teams.nil? or self.teams.empty?\n\n if (/^|([0-9]+|)+$/ =~ self.teams) == 0\n\n self.get_teams_a.each do |team_id|\n team = Team.find_by_id(team_id)\n if team.nil?\n err_msgs << I18n.t('address.import.not_valid_teams') + ': '+team_id.to_s\n break\n end\n end\n\n else\n err_msgs << I18n.t('address.import.invalid_teams_format')\n end\n end\n\n return err_msgs\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.parse_csv_row(row, book, idxs, user)\n\n imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip)\n unless imp_id.nil? or imp_id.empty?\n org_address = Address.find_by_id(imp_id)\n end\n\n if org_address.nil?\n address = Address.new\n else\n address = org_address\n end\n\n address.id = imp_id\n attr_names = [\n :name,\n :name_ruby,\n :nickname,\n :screenname,\n :email1,\n :email2,\n :email3,\n :postalcode,\n :address,\n :tel1_note,\n :tel1,\n :tel2_note,\n :tel2,\n :tel3_note,\n :tel3,\n :fax,\n :url,\n :organization,\n :title,\n :memo,\n :xorder,\n :groups,\n :teams\n ]\n attr_names.each_with_index do |attr_name, idx|\n row_idx = idxs[idx+1]\n break if row_idx.nil?\n\n val = (row[row_idx].nil?)?(nil):(row[row_idx].strip)\n address.send(attr_name.to_s + '=', val)\n end\n if (address.groups == Address::EXP_IMP_FOR_ALL) \\\n or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?)\n address.groups = nil\n address.teams = nil\n address.owner_id = 0\n elsif !address.groups.blank? or !address.teams.blank?\n address.owner_id = 0\n else\n address.owner_id = user.id\n end\n\n return address\n end", "label_name": "CWE-89", "label": 89} -{"code": " def rename\n Log.add_info(request, params.inspect)\n\n @folder = Folder.find(params[:id])\n\n unless Folder.check_user_auth(@folder.id, @login_user, 'w', true)\n flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')\n render(:partial => 'ajax_folder_name', :layout => false)\n return\n end\n\n unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?\n @folder.name = params[:thetisBoxEdit]\n @folder.save\n end\n render(:partial => 'ajax_folder_name', :layout => false)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def wf_issue\n Log.add_info(request, params.inspect)\n\n begin\n @item = Item.find(params[:id])\n @workflow = @item.workflow\n rescue => evar\n Log.add_error(request, evar)\n end\n \n attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now})\n @workflow.update_attributes(attrs.permit(Workflow::PERMIT_BASE))\n\n @orders = @workflow.get_orders\n\n render(:partial => 'ajax_workflow', :layout => false)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def set_workflow\n Log.add_info(request, params.inspect)\n\n @item = Item.find(params[:id])\n\n orders_hash = params.dup\n orders_hash.reject! { |key, value|\n key.index(/order-/) != 0\n }\n orders_hash.sort_by { |key, value|\n key.split('-').last.to_i\n }\n\n orders = []\n orders_hash.each do |key, value|\n\n orders << '|' + value.split(',').join('|') + '|'\n end\n @item.workflow.update_attribute(:users, orders.join(','))\n\n render(:partial => 'ajax_item_workflow', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n\n render(:partial => 'ajax_item_workflow', :layout => false)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def search\n Log.add_info(request, params.inspect)\n\n unless params[:select_sorting].nil? or params[:select_sorting].empty?\n sort_a = params[:select_sorting].split(' ')\n params[:sort_col] = sort_a.first\n params[:sort_type] = sort_a.last\n end\n\n list\n\n if params[:keyword].nil? or params[:keyword].empty?\n if params[:from_action].nil? or params[:from_action] == 'bbs'\n render(:action => 'bbs')\n else\n render(:action => 'list')\n end\n end\n end", "label_name": "CWE-89", "label": 89} -{"code": " def on_moved\n Log.add_info(request, params.inspect)\n\n location_id = params[:id]\n\n if location_id.nil? or location_id.empty?\n location = Location.get_for(@login_user)\n if location.nil?\n location = Location.new\n location.user_id = @login_user.id\n end\n else\n begin\n location = Location.find(location_id)\n rescue\n end\n end\n\n unless location.nil?\n group_id = params[:group_id]\n group_id = nil if group_id.empty?\n attrs = ActionController::Parameters.new({group_id: group_id, x: params[:x], y: params[:y]})\n location.update_attributes(attrs.permit(Location::PERMIT_BASE))\n end\n\n render(:text => (location.nil?)?'':location.id.to_s)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def check_member\n\n return if params[:id].nil? or params[:id].empty? or @login_user.nil?\n\n if Item.find(params[:id]).user_id != @login_user.id\n Log.add_check(request, '[check_member]'+request.to_s)\n\n flash[:notice] = t('team.need_to_be_member')\n redirect_to(:controller => 'desktop', :action => 'show')\n end\n end", "label_name": "CWE-89", "label": 89} -{"code": " def create_title\n\n titles = User.get_config_titles\n titles = [] if titles.nil?\n titles << t('user.new_title')\n User.save_config_titles titles\n\n render(:partial => 'ajax_title', :layout => false)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def add_to_group\n Log.add_info(request, params.inspect)\n\n if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?\n render(:partial => 'ajax_groups', :layout => false)\n return\n end\n\n group_id = params[:thetisBoxSelKeeper].split(':').last\n unless group_id == '0' # '0' for ROOT\n begin\n group = Group.find(group_id)\n rescue => evar\n Log.add_error(request, evar)\n ensure\n if group.nil?\n render(:partial => 'ajax_groups', :layout => false)\n return\n end\n end\n end\n\n begin\n @user = User.find(params[:user_id])\n rescue => evar\n Log.add_error(request, evar)\n end\n\n unless @user.nil?\n\n is_modified = false\n\n # Change, not simply Add\n unless params[:current_id] == nil or params[:current_id].empty?\n if @user.exclude_from(params[:current_id])\n is_modified = true\n end\n end\n\n is_modified = true if @user.add_to(group_id)\n\n if is_modified == true\n# @user.update_attribute(:groups, @user.groups)\n @user.save!\n\n if @user.id == @login_user.id\n @login_user = @user\n end\n end\n end\n\n render(:partial => 'ajax_groups', :layout => false)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def check_owner\n return if params[:id].nil? or params[:id].empty? or @login_user.nil?\n\n begin\n owner_id = Workflow.find(params[:id]).user_id\n rescue\n owner_id = -1\n end\n if !@login_user.admin?(User::AUTH_WORKFLOW) and owner_id != @login_user.id\n Log.add_check(request, '[check_owner]'+request.to_s)\n\n flash[:notice] = t('msg.need_to_be_owner')\n redirect_to(:controller => 'desktop', :action => 'show')\n end\n end", "label_name": "CWE-89", "label": 89} -{"code": " def copy\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n tmpl_id = params[:thetisBoxSelKeeper].split(':').last\n tmpl_item = Item.find(tmpl_id)\n\n item = tmpl_item.copy(@login_user.id, @login_user.get_my_folder.id)\n if item.public != false\n item.update_attribute(:public, false)\n end\n\n redirect_to(:controller => 'items', :action => 'edit', :id => item.id)\n\n rescue => evar\n Log.add_error(request, evar)\n\n redirect_to(:controller => 'items', :action => 'new')\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_comment_of(item_id, user_id)\n\n SqlHelper.validate_token([item_id, user_id])\n begin\n comment = Comment.where(\"(user_id=#{user_id}) and (item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')\").first\n rescue => evar\n Log.add_error(nil, evar)\n end\n\n return comment\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_tree_by_group_for_admin(group_id)\n\n SqlHelper.validate_token([group_id])\n\n folder_tree = {}\n tree_id = '0'\n\n if group_id.to_s == '0'\n sql = 'select distinct * from folders'\n\n where = \" where (parent_id = #{tree_id})\"\n where << \" and ((xtype is null) or not(xtype = '#{XTYPE_GROUP}' or xtype = '#{XTYPE_USER}'))\"\n\n order_by = ' order by xorder ASC, id ASC'\n else\n sql = 'select distinct Folder.* from folders Folder, users User'\n\n where = \" where (Folder.parent_id = #{tree_id})\"\n where << ' and ('\n where << \"(Folder.xtype = '#{XTYPE_GROUP}' and Folder.owner_id = #{group_id})\"\n where << ' or '\n where << \"(Folder.xtype = '#{XTYPE_USER}' and Folder.owner_id = User.id and #{SqlHelper.get_sql_like(['User.groups'], \"|#{group_id}|\")})\"\n where << ' )'\n\n order_by = ' order by Folder.xorder ASC, Folder.id ASC'\n end\n\n sql << where + order_by\n\n folder_tree[tree_id] = Folder.find_by_sql(sql)\n\n folder_tree[tree_id].each do |folder|\n folder_tree = Folder.get_tree(folder_tree, nil, folder, true)\n end\n\n return Folder.sort_tree(folder_tree)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_tree(folder_tree, conditions, parent, admin)\n\n if parent.instance_of?(Folder)\n tree_id = parent.id.to_s\n else\n tree_id = parent.to_s\n parent = nil\n if tree_id != '0'\n begin\n parent = Folder.find(tree_id)\n rescue\n end\n return folder_tree if parent.nil?\n end\n end\n\n group_obj_cache = {}\n folder_tree[tree_id] = []\n if !parent.nil? and (parent.xtype == Folder::XTYPE_GROUP)\n Group.get_childs(parent.owner_id, false, true).each do |group|\n group_obj_cache[group.id] = group\n con = Marshal.load(Marshal.dump(conditions)) unless conditions.nil?\n if con.nil?\n con = ''\n else\n con << ' and '\n end\n con << \"(xtype='#{Folder::XTYPE_GROUP}') and (owner_id=#{group.id})\"\n begin\n group_folder = Folder.where(con).first\n rescue => evar\n Log.add_error(nil, evar)\n end\n unless group_folder.nil?\n folder_tree[tree_id] << group_folder\n end\n end\n end\n\n con = Marshal.load(Marshal.dump(conditions)) unless conditions.nil?\n if con.nil?\n con = ''\n else\n con << ' and '\n end\n con << \"parent_id=#{tree_id}\"\n folder_tree[tree_id] += Folder.where(con).order('xorder ASC, id ASC').to_a\n\n delete_ary = []\n\n folder_tree[tree_id].each do |folder|\n\n if !admin and (folder.xtype == Folder::XTYPE_SYSTEM)\n delete_ary << folder\n next\n end\n\n if (tree_id == '0') and (folder.xtype == Folder::XTYPE_GROUP)\n group = Group.find_with_cache(folder.owner_id, group_obj_cache)\n unless group.nil?\n if group.parent_id != 0\n delete_ary << folder\n next\n end\n end\n end\n\n folder_tree = Folder.get_tree(folder_tree, conditions, folder, admin)\n end\n\n folder_tree[tree_id] -= delete_ary\n\n return folder_tree\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_for_group(group_id)\n\n SqlHelper.validate_token([group_id])\n if group_id.nil?\n con = 'group_id is null'\n else\n con = \"group_id=#{group_id}\"\n end\n\n Location.do_expire(con)\n\n return Location.where(con).to_a\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_for(group_id, include_parents=false, enabled=nil)\n\n SqlHelper.validate_token([group_id])\n\n con = []\n #con << \"(disabled=#{!enabled})\" unless enabled.nil?\n\n if include_parents\n group_con = '(group_id is null)'\n\n unless group_id.nil? or group_id.to_s == '0'\n group_obj_cache = {}\n group = Group.find_with_cache(group_id, group_obj_cache)\n group_ids = group.get_parents(false, group_obj_cache)\n group_ids << group_id\n group_con << \" or (group_id in (#{group_ids.join(',')}))\"\n end\n\n con << '(' + group_con + ')'\n else\n con << \"(group_id=#{group_id})\"\n end\n\n order_by = 'order by xorder ASC, id ASC'\n #order_by = 'order by disabled ASC, xorder ASC, id ASC'\n\n sql = 'select * from official_titles where ' + con.join(' and ') + ' ' + order_by\n\n return OfficialTitle.find_by_sql(sql)\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_for(user_id, fiscal_year=nil)\n\n SqlHelper.validate_token([user_id, fiscal_year])\n\n begin\n con = []\n con << \"(user_id=#{user_id})\"\n if fiscal_year.nil?\n return PaidHoliday.where(con).order('year ASC').to_a\n else\n con << \"(year=#{fiscal_year})\"\n return PaidHoliday.where(con.join(' and ')).first\n end\n rescue\n end\n return nil\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.save_value(user_id, category, key, value)\n\n SqlHelper.validate_token([user_id, category, key])\n\n con = []\n con << \"(user_id=#{user_id})\"\n con << \"(category='#{category}')\"\n con << \"(xkey='#{key}')\"\n\n setting = Setting.where(con.join(' and ')).first\n\n if value.nil?\n unless setting.nil?\n setting.destroy\n end\n else\n if setting.nil?\n setting = Setting.new\n setting.user_id = user_id\n setting.category = category\n setting.xkey = key\n setting.xvalue = value\n setting.save!\n else\n setting.update_attribute(:xvalue, value)\n end\n end\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_value(user_id, category, key)\n\n SqlHelper.validate_token([user_id, category, key])\n\n con = []\n con << \"(user_id=#{user_id})\"\n con << \"(category='#{category}')\"\n con << \"(xkey='#{key}')\"\n\n setting = Setting.where(con.join(' and ')).first\n\n return setting.xvalue unless setting.nil?\n\n return nil\n end", "label_name": "CWE-89", "label": 89} -{"code": " def self.get_by_email(mail_addr, user, book=Address::BOOK_BOTH)\n\n SqlHelper.validate_token([mail_addr])\n\n email_con = []\n email_con.push(\"(email1='#{mail_addr}')\")\n email_con.push(\"(email2='#{mail_addr}')\")\n email_con.push(\"(email3='#{mail_addr}')\")\n con = []\n con.push('('+email_con.join(' or ')+')')\n con.push(AddressbookHelper.get_scope_condition_for(user, book))\n\n return Address.where(con.join(' and ')).to_a\n end", "label_name": "CWE-89", "label": 89} -{"code": " def clean_text(text)\n text.gsub(/[\\u0000-\\u0008\\u000b-\\u000c\\u000e-\\u001F\\u007f]/, \".\".freeze)\n end", "label_name": "CWE-94", "label": 94} -{"code": " def load_file(filename)\n Gem.load_yaml\n\n yaml_errors = [ArgumentError]\n yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError)\n\n return {} unless filename and File.exist? filename\n\n begin\n content = YAML.load(File.read(filename))\n unless content.kind_of? Hash\n warn \"Failed to load #{filename} because it doesn't contain valid YAML hash\"\n return {}\n end\n return content\n rescue *yaml_errors => e\n warn \"Failed to load #{filename}, #{e}\"\n rescue Errno::EACCES\n warn \"Failed to load #{filename} due to permissions problem.\"\n end\n\n {}\n end", "label_name": "CWE-502", "label": 502} -{"code": " def read_checksums gem\n Gem.load_yaml\n\n @checksums = gem.seek 'checksums.yaml.gz' do |entry|\n Zlib::GzipReader.wrap entry do |gz_io|\n YAML.load gz_io.read\n end\n end\n end", "label_name": "CWE-502", "label": 502} -{"code": " def extract_tar_gz io, destination_dir, pattern = \"*\" # :nodoc:\n open_tar_gz io do |tar|\n tar.each do |entry|\n next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH\n\n destination = install_location entry.full_name, destination_dir\n\n FileUtils.rm_rf destination\n\n mkdir_options = {}\n mkdir_options[:mode] = entry.header.mode if entry.directory?\n mkdir =\n if entry.directory? then\n destination\n else\n File.dirname destination\n end\n\n FileUtils.mkdir_p mkdir, mkdir_options\n\n File.open destination, 'wb' do |out|\n out.write entry.read\n FileUtils.chmod entry.header.mode, destination\n end if entry.file?\n\n File.symlink(entry.header.linkname, destination) if entry.symlink?\n\n verbose destination\n end\n end\n end", "label_name": "CWE-22", "label": 22} -{"code": " def install_location filename, destination_dir # :nodoc:\n raise Gem::Package::PathError.new(filename, destination_dir) if\n filename.start_with? '/'\n\n destination_dir = File.realpath destination_dir if\n File.respond_to? :realpath\n destination_dir = File.expand_path destination_dir\n\n destination = File.join destination_dir, filename\n destination = File.realpath destination if\n File.respond_to? :realpath\n destination = File.expand_path destination\n\n raise Gem::Package::PathError.new(destination, destination_dir) unless\n destination.start_with? destination_dir + '/'\n\n destination.untaint\n destination\n end", "label_name": "CWE-22", "label": 22} -{"code": " def find(uuid, options = {})\n if uuid.nil? || uuid.to_s.empty?\n raise NotFound, \"can't find a record with nil identifier\"\n end\n\n uri = uuid =~ /^http/ ? uuid : member_path(uuid)\n begin\n from_response API.get(uri, {}, options)\n rescue API::NotFound => e\n raise NotFound, e.description\n end\n end", "label_name": "CWE-918", "label": 918} -{"code": " def _extend_marshalling(options)\n @marshalling = !(options[:marshalling] === false) # HACK - TODO delegate to Factory\n extend Marshalling if @marshalling\n end", "label_name": "CWE-502", "label": 502} -{"code": " def _marshal(val, options)\n yield marshal?(options) ? Marshal.dump(val) : val\n end", "label_name": "CWE-502", "label": 502} -{"code": " def self.map_library_name(lib)\n # Mangle the library name to reflect the native library naming conventions\n lib = lib.to_s unless lib.kind_of?(String)\n lib = Library::LIBC if lib == 'c'\n\n if lib && File.basename(lib) == lib\n lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/\n r = Platform::IS_GNU ? \"\\\\.so($|\\\\.[1234567890]+)\" : \"\\\\.#{Platform::LIBSUFFIX}$\"\n lib += \".#{Platform::LIBSUFFIX}\" unless lib =~ /#{r}/\n end\n\n lib\n end", "label_name": "CWE-426", "label": 426} -{"code": " it 'removes existing content types' do\n subject.content_type :xls, 'application/vnd.ms-excel'\n subject.get :excel do\n 'some binary content'\n end\n get '/excel.json'\n expect(last_response.status).to eq(406)\n expect(last_response.body).to eq(\"The requested format 'txt' is not supported.\")\n end", "label_name": "CWE-79", "label": 79} -{"code": " def set_member_and_redirect(member)\n set_member member\n Member::ActivityLog.create(\n cur_site: @cur_site,\n cur_member: member,\n activity_type: \"login\",\n remote_addr: remote_addr,\n user_agent: request.user_agent)\n\n ref = URI::decode(params[:ref] || flash[:ref] || \"\")\n ref = redirect_url if ref.blank?\n flash.discard(:ref)\n\n redirect_to ref\n end", "label_name": "CWE-601", "label": 601} -{"code": " it 'should verify a standard RS256 token' do\n domain = 'example.org'\n sub = 'abc123'\n payload = {\n sub: sub,\n exp: future_timecode,\n iss: \"https://#{domain}/\",\n iat: past_timecode,\n aud: client_id,\n kid: jwks_kid\n }\n token = make_rs256_token(payload)\n verified_token = make_jwt_validator(opt_domain: domain).verify(token)\n expect(verified_token['sub']).to eq(sub)\n end", "label_name": "CWE-347", "label": 347} -{"code": " def initialize(attribute = nil, direction = nil)\n @attribute = attribute\n @direction = direction || :asc\n end", "label_name": "CWE-89", "label": 89} -{"code": " it \"should raise an error if the image fails an integrity check when downloaded\" do\n stub_request(:get, \"www.example.com/test.jpg\").to_return(body: File.read(file_path(\"test.jpg\")))\n\n expect(running {\n @instance.remote_image_url = \"http://www.example.com/test.jpg\"\n }).to raise_error(CarrierWave::IntegrityError)\n end", "label_name": "CWE-918", "label": 918} -{"code": " def updated_ajax\n @user = current_site.users.find(params[:user_id])\n render inline: @user.update(params.require(:password).permit!) ? \"\" : @user.errors.full_messages.join(', ')\n end", "label_name": "CWE-613", "label": 613} -{"code": " def mime_magic_content_type(new_file)\n content_type = nil\n\n File.open(new_file.path) do |fd|\n content_type = Marcel::MimeType.for(fd)\n end\n\n content_type\n end", "label_name": "CWE-79", "label": 79} -{"code": " def group_link(uniqueid, data)\n notification = t(\n \"notifications.group.#{data[:type]}\",\n name: data[:user],\n group_name: data[:group]\n )\n link = \"/groups/#{data[:group_id]}\"\n notification_link(uniqueid, link, notification)\n end", "label_name": "CWE-79", "label": 79} -{"code": " it \"should get a 200 with html for an authorized user\" do\n\n def @bus.is_admin_lookup\n proc { |_| true }\n end\n\n get \"/message-bus/_diagnostics\"\n last_response.status.must_equal 200\n end", "label_name": "CWE-22", "label": 22} -{"code": " it \"should return a 403 if a user attempts to get at the _diagnostics path\" do\n get \"/message-bus/_diagnostics\"\n last_response.status.must_equal 403\n end", "label_name": "CWE-22", "label": 22} -{"code": " def base_api_url\n computed_api_endpoint = \"https://#{get_data_center_from_api_key(self.api_key)}api.mailchimp.com\"\n raise Gibbon::GibbonError, \"SSRF attempt\" unless URI(computed_api_endpoint).host.include?(\"api.mailchimp.com\")\n\n \"#{self.api_endpoint || computed_api_endpoint}/3.0/\"\n end", "label_name": "CWE-918", "label": 918} -{"code": "func TestReadRequest_BadConnectHost(t *testing.T) {\n\tdata := []byte(\"CONNECT []%20%48%54%54%50%2f%31%2e%31%0a%4d%79%48%65%61%64%65%72%3a%20%31%32%33%0a%0a HTTP/1.0\\n\\n\")\n\tr, err := ReadRequest(bufio.NewReader(bytes.NewReader(data)))\n\tif err == nil {\n\t\tt.Fatal(\"Got unexpected request = %#v\", r)\n\t}\n}", "label_name": "CWE-444", "label": 444} -{"code": "func SearchUserByName(opt SearchOption) (us []*User, err error) {\n\topt.Keyword = FilterSQLInject(opt.Keyword)\n\tif len(opt.Keyword) == 0 {\n\t\treturn us, nil\n\t}\n\topt.Keyword = strings.ToLower(opt.Keyword)\n\n\tus = make([]*User, 0, opt.Limit)\n\terr = x.Limit(opt.Limit).Where(\"type=0\").And(\"lower_name like '%\" + opt.Keyword + \"%'\").Find(&us)\n\treturn us, err\n}", "label_name": "CWE-89", "label": 89} -{"code": "func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {\n\tbuffer := make([]byte, len(aad)+len(nonce)+len(ciphertext)+8)\n\tn := 0\n\tn += copy(buffer, aad)\n\tn += copy(buffer[n:], nonce)\n\tn += copy(buffer[n:], ciphertext)\n\tbinary.BigEndian.PutUint64(buffer[n:], uint64(len(aad)*8))\n\n\t// According to documentation, Write() on hash.Hash never fails.\n\thmac := hmac.New(ctx.hash, ctx.integrityKey)\n\t_, _ = hmac.Write(buffer)\n\n\treturn hmac.Sum(nil)[:ctx.authtagBytes]\n}", "label_name": "CWE-190", "label": 190} -{"code": "func main() {\n\tif len(os.Args) < 3 {\n\t\tfatal(usage)\n\t}\n\n\tcmd, filename := os.Args[1], os.Args[2]\n\n\tff := archiver.MatchingFormat(filename)\n\tif ff == nil {\n\t\tfatalf(\"%s: Unsupported file extension\", filename)\n\t}\n\n\tvar err error\n\tswitch cmd {\n\tcase \"make\":\n\t\tif len(os.Args) < 4 {\n\t\t\tfatal(usage)\n\t\t}\n\t\terr = ff.Make(filename, os.Args[3:])\n\tcase \"open\":\n\t\tdest := \"\"\n\t\tif len(os.Args) == 4 {\n\t\t\tdest = os.Args[3]\n\t\t} else if len(os.Args) > 4 {\n\t\t\tfatal(usage)\n\t\t}\n\t\terr = ff.Open(filename, dest)\n\tdefault:\n\t\tfatal(usage)\n\t}\n\tif err != nil {\n\t\tfatal(err)\n\t}\n}", "label_name": "CWE-22", "label": 22} -{"code": "func validateAndCreateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) {\n\tc.Data[\"Webhook\"] = w\n\n\tif c.HasError() {\n\t\tc.Success(orCtx.TmplNew)\n\t\treturn\n\t}\n\n\tfield, msg, ok := validateWebhook(c.User, c.Locale, w)\n\tif !ok {\n\t\tc.FormErr(field)\n\t\tc.RenderWithErr(msg, orCtx.TmplNew, nil)\n\t\treturn\n\t}\n\n\tif err := w.UpdateEvent(); err != nil {\n\t\tc.Error(err, \"update event\")\n\t\treturn\n\t} else if err := db.CreateWebhook(w); err != nil {\n\t\tc.Error(err, \"create webhook\")\n\t\treturn\n\t}\n\n\tc.Flash.Success(c.Tr(\"repo.settings.add_hook_success\"))\n\tc.Redirect(orCtx.Link + \"/settings/hooks\")\n}", "label_name": "CWE-918", "label": 918} -{"code": "func TestSkipUnknownTypeBinaryProtocol(t *testing.T) {\n\tvar m MyTestStruct\n\td := NewDeserializer()\n\tf := NewBinaryProtocolFactoryDefault()\n\td.Protocol = f.GetProtocol(d.Transport)\n\t// skip over a map with invalid key/value type and 1.7B entries\n\tdata := []byte(\"\\n\\x10\\rO\\t6\\x03\\n\\n\\n\\x10\\r\\n\\tslice\\x00\")\n\tstart := time.Now()\n\terr := d.Read(&m, data)\n\tif err == nil {\n\t\tt.Fatalf(\"Parsed invalid message correctly\")\n\t} else if !strings.Contains(err.Error(), \"unknown type\") {\n\t\tt.Fatalf(\"Failed for reason besides unknown type\")\n\t}\n\n\tif time.Now().Sub(start).Seconds() > 5 {\n\t\tt.Fatalf(\"It should not take seconds to parse a small message\")\n\t}\n}", "label_name": "CWE-770", "label": 770} -{"code": "\tappendMessage = func(targetOffset uint32) bool {\n\t\tfor _, f := range frags {\n\t\t\tif f.handshakeHeader.FragmentOffset == targetOffset {\n\t\t\t\tfragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength)\n\t\t\t\tif fragmentEnd != f.handshakeHeader.Length {\n\t\t\t\t\tif !appendMessage(fragmentEnd) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trawMessage = append(f.data, rawMessage...)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}", "label_name": "CWE-835", "label": 835} -{"code": "func (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\th.L.Warnln(\"It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.\")\n\th.L.Warnln(\"A client requested the default login & consent URL, environment variable OAUTH2_CONSENT_URL or OAUTH2_LOGIN_URL or both are probably not set.\")\n\n\tw.Write([]byte(`\n\n\n\tMisconfigured consent/login URL\n\n\n

    \n\tIt looks like you forgot to set the consent/login provider url, which can be set using the OAUTH2_CONSENT_URL and OAUTH2_LOGIN_URL\n\tenvironment variable.\n

    \n

    \n\tIf you are an administrator, please read \n\tthe guide to understand what you need to do. If you are a user, please contact the administrator.\n

    \n\n\n`))\n}", "label_name": "CWE-79", "label": 79} -{"code": "func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\th.L.Warnln(\"A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.\")\n\n\tfmt.Fprintf(w, `\n\n\n\tAn OAuth 2.0 Error Occurred\n\n\n

    \n\tThe OAuth2 request resulted in an error.\n

    \n
      \n\t
    • Error: %s
    • \n\t
    • Description: %s
    • \n\t
    • Hint: %s
    • \n\t
    • Debug: %s
    • \n
    \n

    \n\tYou are seeing this default error page because the administrator has not set a dedicated error URL (environment variable OAUTH2_ERROR_URL is not set). \n\tIf you are an administrator, please read the guide to understand what you\n\tneed to do. If you are a user, please contact the administrator.\n

    \n\n\n`, r.URL.Query().Get(\"error\"), r.URL.Query().Get(\"error_description\"), r.URL.Query().Get(\"error_hint\"), r.URL.Query().Get(\"error_debug\"))\n}", "label_name": "CWE-79", "label": 79} -{"code": "\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}", "label_name": "CWE-843", "label": 843} -{"code": "\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}", "label_name": "CWE-915", "label": 915} -{"code": "func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {\n\tpluginID := web.Params(c.Req)[\":pluginId\"]\n\tplugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID)\n\tif !exists {\n\t\tc.JsonApiErr(404, \"Plugin not found\", nil)\n\t\treturn\n\t}\n\n\trequestedFile := filepath.Clean(web.Params(c.Req)[\"*\"])\n\tpluginFilePath := filepath.Join(plugin.PluginDir, requestedFile)\n\n\tif !plugin.IncludedInSignature(requestedFile) {\n\t\ths.log.Warn(\"Access to requested plugin file will be forbidden in upcoming Grafana versions as the file \"+\n\t\t\t\"is not included in the plugin signature\", \"file\", requestedFile)\n\t}\n\n\t// It's safe to ignore gosec warning G304 since we already clean the requested file path and subsequently\n\t// use this with a prefix of the plugin's directory, which is set during plugin loading\n\t// nolint:gosec\n\tf, err := os.Open(pluginFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tc.JsonApiErr(404, \"Plugin file not found\", err)\n\t\t\treturn\n\t\t}\n\t\tc.JsonApiErr(500, \"Could not open plugin file\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := f.Close(); err != nil {\n\t\t\ths.log.Error(\"Failed to close file\", \"err\", err)\n\t\t}\n\t}()\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\tc.JsonApiErr(500, \"Plugin file exists but could not open\", err)\n\t\treturn\n\t}\n\n\tif hs.Cfg.Env == setting.Dev {\n\t\tc.Resp.Header().Set(\"Cache-Control\", \"max-age=0, must-revalidate, no-cache\")\n\t} else {\n\t\tc.Resp.Header().Set(\"Cache-Control\", \"public, max-age=3600\")\n\t}\n\n\thttp.ServeContent(c.Resp, c.Req, pluginFilePath, fi.ModTime(), f)\n}", "label_name": "CWE-22", "label": 22} -{"code": "func (x *GetWalletLedgerRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[45]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 613} -{"code": "func (*MatchState) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{31}\n}", "label_name": "CWE-613", "label": 613} -{"code": "func (x *ListGroupsRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[27]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 613} -{"code": "func (x *ListSubscriptionsRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[29]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 613} -{"code": "func (*MatchStateRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{32}\n}", "label_name": "CWE-613", "label": 613} -{"code": "func (x *LeaderboardRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[25]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 613} -{"code": "func (s *ConsoleServer) Authenticate(ctx context.Context, in *console.AuthenticateRequest) (*console.ConsoleSession, error) {\n\trole := console.UserRole_USER_ROLE_UNKNOWN\n\tvar uname string\n\tvar email string\n\tvar id uuid.UUID\n\tswitch in.Username {\n\tcase s.config.GetConsole().Username:\n\t\tif in.Password == s.config.GetConsole().Password {\n\t\t\trole = console.UserRole_USER_ROLE_ADMIN\n\t\t\tuname = in.Username\n\t\t\tid = uuid.Nil\n\t\t}\n\tdefault:\n\t\tvar err error\n\t\tid, uname, email, role, err = s.lookupConsoleUser(ctx, in.Username, in.Password)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif role == console.UserRole_USER_ROLE_UNKNOWN {\n\t\treturn nil, status.Error(codes.Unauthenticated, \"Invalid credentials.\")\n\t}\n\n\texp := time.Now().UTC().Add(time.Duration(s.config.GetConsole().TokenExpirySec) * time.Second).Unix()\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, &ConsoleTokenClaims{\n\t\tExpiresAt: exp,\n\t\tID: id.String(),\n\t\tUsername: uname,\n\t\tEmail: email,\n\t\tRole: role,\n\t\tCookie: s.cookie,\n\t})\n\tkey := []byte(s.config.GetConsole().SigningKey)\n\tsignedToken, _ := token.SignedString(key)\n\n\ts.consoleSessionCache.Add(id, exp, signedToken, 0, \"\")\n\treturn &console.ConsoleSession{Token: signedToken}, nil\n}", "label_name": "CWE-307", "label": 307} -{"code": "func AppList(c *gin.Context) {\n\n\t//service.MyService.Docker().DockerContainerCommit(\"test2\")\n\n\tindex := c.DefaultQuery(\"index\", \"1\")\n\tsize := c.DefaultQuery(\"size\", \"10000\")\n\tt := c.DefaultQuery(\"type\", \"rank\")\n\tcategoryId := c.DefaultQuery(\"category_id\", \"0\")\n\tkey := c.DefaultQuery(\"key\", \"\")\n\trecommend, list, community := service.MyService.OAPI().GetServerList(index, size, t, categoryId, key)\n\t// for i := 0; i < len(recommend); i++ {\n\t// \tct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion)\n\t// \tif ct != nil {\n\t// \t\trecommend[i].State = ct.State\n\t// \t}\n\t// }\n\t// for i := 0; i < len(list); i++ {\n\t// \tct, _ := service.MyService.Docker().DockerListByImage(list[i].Image, list[i].ImageVersion)\n\t// \tif ct != nil {\n\t// \t\tlist[i].State = ct.State\n\t// \t}\n\t// }\n\t// for i := 0; i < len(community); i++ {\n\t// \tct, _ := service.MyService.Docker().DockerListByImage(community[i].Image, community[i].ImageVersion)\n\t// \tif ct != nil {\n\t// \t\tcommunity[i].State = ct.State\n\t// \t}\n\t// }\n\tdata := make(map[string]interface{}, 3)\n\tdata[\"recommend\"] = recommend\n\tdata[\"list\"] = list\n\tdata[\"community\"] = community\n\n\tc.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})\n}", "label_name": "CWE-78", "label": 78} -{"code": " content: Buffer.concat(buffers),\n mimeType: resp.headers[\"content-type\"] || null,\n });\n });", "label_name": "CWE-918", "label": 918} -{"code": " _resolvePath(path = '.') {\n const clientPath = (() => {\n path = nodePath.normalize(path);\n if (nodePath.isAbsolute(path)) {\n return nodePath.join(path);\n } else {\n return nodePath.join(this.cwd, path);\n }\n })();\n\n const fsPath = (() => {\n const resolvedPath = nodePath.join(this.root, clientPath);\n return nodePath.resolve(nodePath.normalize(nodePath.join(resolvedPath)));\n })();\n\n return {\n clientPath,\n fsPath\n };\n }", "label_name": "CWE-22", "label": 22} -{"code": "function networkStats(ifaces, callback) {\n\n let ifacesArray = [];\n // fallback - if only callback is given\n if (util.isFunction(ifaces) && !callback) {\n callback = ifaces;\n ifacesArray = [getDefaultNetworkInterface()];\n } else {\n ifaces = ifaces || getDefaultNetworkInterface();\n ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');\n ifacesArray = ifaces.split('|');\n }\n\n return new Promise((resolve) => {\n process.nextTick(() => {\n\n const result = [];\n\n const workload = [];\n if (ifacesArray.length && ifacesArray[0].trim() === '*') {\n ifacesArray = [];\n networkInterfaces(false).then(allIFaces => {\n for (let iface of allIFaces) {\n ifacesArray.push(iface.iface);\n }\n networkStats(ifacesArray.join(',')).then(result => {\n if (callback) { callback(result); }\n resolve(result);\n });\n });\n } else {\n for (let iface of ifacesArray) {\n workload.push(networkStatsSingle(iface.trim()));\n }\n if (workload.length) {\n Promise.all(\n workload\n ).then(data => {\n if (callback) { callback(data); }\n resolve(data);\n });\n } else {\n if (callback) { callback(result); }\n resolve(result);\n }\n }\n });\n });\n}", "label_name": "CWE-78", "label": 78} -{"code": "function has(target, path) {\n \"use strict\";\n try {\n var test = reduce(target, path);\n if ( typeof test !== \"undefined\") {\n return true;\n }\n return false;\n } catch(ex) {\n console.error(ex);\n return;\n }\n}", "label_name": "CWE-915", "label": 915} -{"code": "\t\t([ key, value ]) => ({ [key]: exec.bind(null, value) }),\n\t),", "label_name": "CWE-78", "label": 78} -{"code": "\t\t([ key, value ]) => ({ [key]: list.bind(null, value) }),\n\t),", "label_name": "CWE-78", "label": 78} -{"code": " Object.keys(data).forEach((key) => {\n obj.add(deserializer(data[key], baseType) as T);\n });", "label_name": "CWE-915", "label": 915} -{"code": " schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propertyMetadata.type)};\n }\n\n schemaTypeOptions = cleanProps({...schemaTypeOptions, ...rawMongooseSchema});\n\n if (propertyMetadata.isCollection) {\n if (propertyMetadata.isArray) {\n schemaTypeOptions = [schemaTypeOptions];\n } else {\n // Can be a Map or a Set;\n // Mongoose implements only Map;\n if (propertyMetadata.collectionType !== Map) {\n throw new Error(`Invalid collection type. ${propertyMetadata.collectionName} is not supported.`);\n }\n\n schemaTypeOptions = {type: Map, of: schemaTypeOptions};\n }\n }\n\n return schemaTypeOptions;\n}", "label_name": "CWE-915", "label": 915} -{"code": " constructor({asset, message, onClick}: Params, element: HTMLElement) {\n super(message);\n this.asset = asset;\n this.message = message;\n this.isVisible = ko.observable(false);\n this.onClick = (_data, event) => onClick(message, event);\n\n this.dummyImageUrl = `data:image/svg+xml;utf8,`;\n\n this.imageUrl = ko.observable();\n\n this.isIdle = () => this.uploadProgress() === -1 && !this.asset.resource() && !this.message.isObfuscated();\n\n ko.computed(\n () => {\n if (this.isVisible() && asset.resource()) {\n this.assetRepository\n .load(asset.resource())\n .then(blob => {\n this.imageUrl(window.URL.createObjectURL(blob));\n })\n .catch(error => console.error(error));\n }\n },\n {disposeWhenNodeIsRemoved: element},\n );\n\n this.container = element;\n viewportObserver.onElementInViewport(this.container, () => this.isVisible(true));\n }", "label_name": "CWE-79", "label": 79} -{"code": "export async function loadFromGit(input: Input): Promise {\n try {\n return await new Promise((resolve, reject) => {\n exec(createCommand(input), { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout);\n }\n });\n });\n } catch (error) {\n throw createLoadError(error);\n }\n}", "label_name": "CWE-78", "label": 78} -{"code": " switchToInvites: async () => {\n await this.waitAndClick('.e_InvTabB');\n await this.invitedUsersList.waitUntilLoaded();\n },", "label_name": "CWE-613", "label": 613} -{"code": "export function html(m, keyPath, ...args) {\n const html = str(m, keyPath, ...args);\n\n return html ? React.createElement('span', { dangerouslySetInnerHTML: { __html: html } }) : null;\n}", "label_name": "CWE-79", "label": 79} -{"code": " `${c.amount(d.value, d.name)}${day(d.date)}`,\n });\n}", "label_name": "CWE-79", "label": 79} -{"code": "export function initSidebar(): void {\n const errorCountEl = document.getElementById(\"error-count\");\n if (errorCountEl instanceof HTMLLIElement) {\n errorCount.subscribe((errorCount_val) => {\n errorCountEl.classList.toggle(\"hidden\", errorCount_val === 0);\n const span = errorCountEl.querySelector(\"span\");\n if (span) {\n span.innerHTML = `${errorCount_val}`;\n }\n });\n }\n\n const asideButton = document.getElementById(\"aside-button\");\n if (asideButton instanceof HTMLButtonElement) {\n asideButton.addEventListener(\"click\", () => {\n document.querySelector(\"aside\")?.classList.toggle(\"active\");\n asideButton.classList.toggle(\"active\");\n });\n }\n}", "label_name": "CWE-79", "label": 79} -{"code": "function text({ url, host }: Record<\"url\" | \"host\", string>) {\n return `Sign in to ${host}\\n${url}\\n\\n`\n}", "label_name": "CWE-79", "label": 79} +{"code": "function layout_navbar() {\n\t$t_logo_url = config_get('logo_url');\n\n\techo '
    ';\n\techo '
    ';\n\n\techo '';\n\n\techo '
    ';\n\techo '';\n\techo ' ';\n\techo config_get('window_title');\n\techo ' ';\n\techo '';\n\n\t$t_toggle_class = (OFF == config_get('show_avatar') ? 'navbar-toggle' : 'navbar-toggle-img');\n\techo '';\n\n\techo '
    ';\n\n\techo '
    ';\n\techo '
      ';\n\tif (auth_is_user_authenticated()) {\n\t\t# shortcuts button bar\n\t\tlayout_navbar_button_bar();\n\t\t# projects dropdown menu\n\t\tlayout_navbar_projects_menu();\n\t\t# user buttons such as messages, notifications and user menu\n\t\tlayout_navbar_user_menu();\n\t}\n\techo '
    ';\n\techo '
    ';\n\n\techo '
    ';\n\techo '
    ';\n}", "label_name": "CWE-79", "label": 1} +{"code": "function PMA_importAjaxStatus($id)\n{\n header('Content-type: application/json');\n echo json_encode(\n $_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getUploadStatus($id)\n );\n}", "label_name": "CWE-79", "label": 1} +{"code": "function get_abs_item($dir, $item) {\t\t// get absolute file+path\n\treturn get_abs_dir($dir).DIRECTORY_SEPARATOR.$item;\n}", "label_name": "CWE-22", "label": 2} +{"code": " function get_allowed_files_extensions_for_upload($fileTypes = 'images', $returnAsArray = false)\n {\n\n $are_allowed = '';\n switch ($fileTypes) {\n\n case 'img':\n case 'image':\n case 'images':\n $are_allowed .= ',png,gif,jpg,jpeg,tiff,bmp,svg,webp,ico';\n break;\n case 'audio':\n case 'audios':\n $are_allowed .= ',mp3,mp4,ogg,wav,flac';\n break;\n case 'video':\n case 'videos':\n $are_allowed .= ',avi,asf,mpg,mpeg,mp4,flv,mkv,webm,ogg,ogv,3gp,3g2,wma,mov,wmv';\n break;\n case 'file':\n case 'files':\n $are_allowed .= ',css,json,zip,gzip,csv,7z';\n break;\n case 'documents':\n case 'doc':\n $are_allowed .= ',doc,docx,pdf,odt,pages,rtf,txt,pps,ppt,pptx,xls,xlsx';\n break;\n case 'archives':\n case 'arc':\n case 'arch':\n $are_allowed .= ',zip,zipx,gzip,rar,gz,7z,cbr,tar.gz';\n break;\n case 'all':\n $are_allowed .= ',*';\n break;\n case '*':\n $are_allowed .= ',*';\n break;\n default:\n $are_allowed .= ',' . $fileTypes;\n }\n\n if($are_allowed){\n $are_allowed = explode(',',$are_allowed);\n array_unique($are_allowed);\n $are_allowed = array_filter($are_allowed);\n\n if ($returnAsArray) {\n return $are_allowed;\n }\n\n $are_allowed = implode(',', $are_allowed);\n }\n\n if ($returnAsArray) {\n return [];\n }\n\n return $are_allowed;\n }", "label_name": "CWE-79", "label": 1} +{"code": "function prepareExchangedData($data, $type)\n{\n global $SETTINGS;\n\n //load ClassLoader\n require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';\n //Load AES\n $aes = new SplClassLoader('Encryption\\Crypt', '../includes/libraries');\n $aes->register();\n\n if ($type == \"encode\") {\n if (isset($SETTINGS['encryptClientServer'])\n && $SETTINGS['encryptClientServer'] === \"0\"\n ) {\n return json_encode(\n $data,\n JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP\n );\n } else {\n return Encryption\\Crypt\\aesctr::encrypt(\n json_encode(\n $data,\n JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP\n ),\n $_SESSION['key'],\n 256\n );\n }\n } elseif ($type == \"decode\") {\n if (isset($SETTINGS['encryptClientServer'])\n && $SETTINGS['encryptClientServer'] === \"0\"\n ) {\n return json_decode(\n $data,\n true\n );\n } else {\n return json_decode(\n Encryption\\Crypt\\aesctr::decrypt(\n $data,\n $_SESSION['key'],\n 256\n ),\n true\n );\n }\n }\n}", "label_name": "CWE-434", "label": 5} +{"code": "function teampass_decrypt_pw($encrypted, $salt, $rand_key, $itcount = 2072)\n{\n $encrypted = base64_decode($encrypted);\n $pass_salt = substr($encrypted, -64);\n $encrypted = substr($encrypted, 0, -64);\n $key = teampass_pbkdf2_hash($salt, $pass_salt, $itcount, 16, 32);\n $iv = base64_decode(substr($encrypted, 0, 43) . '==');\n $encrypted = substr($encrypted, 43);\n $mac = substr($encrypted, -64);\n $encrypted = substr($encrypted, 0, -64);\n if ($mac !== hash_hmac('sha256', $encrypted, $salt)) return null;\n return substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), \"\\0\\4\"), strlen($rand_key));\n}", "label_name": "CWE-79", "label": 1} +{"code": "function teampass_whitelist() {\n $bdd = teampass_connect();\n\t$apiip_pool = teampass_get_ips();\n\tif (count($apiip_pool) > 0 && !array_search($_SERVER['REMOTE_ADDR'], $apiip_pool)) {\n\t\trest_error('IPWHITELIST');\n\t}\n}", "label_name": "CWE-89", "label": 0} +{"code": "function _getHtmlHeaderColumn($title, $name, $pageName, $entityIds, $listorder, $orderdirection, $showColumn = true)\n{\n $str = '';\n $entity = _getEntityString($entityIds);\n if ($listorder == $name) {\n if (($orderdirection == '') || ($orderdirection == 'down')) {\n $str = \"\";\n } else {\n $str = \"\";\n }\n }\n return $showColumn ? \"$title$str\" : '';\n}", "label_name": "CWE-79", "label": 1} +{"code": "function _getEntityString($entityIds)\n{\n $entity = '';\n if (!empty($entityIds)) {\n $entityArr = array();\n foreach ($entityIds as $entityId => $entityValue) {\n $entityArr[] = \"$entityId=$entityValue\";\n }\n $entity = implode('&',$entityArr) . '&';\n }\n\n return $entity;\n}", "label_name": "CWE-79", "label": 1} +{"code": " public function stripClean($str)\n {\n return $this->xssClean($this->stripTags($str));\n }", "label_name": "CWE-89", "label": 0} +{"code": " function ac_checkme($id, $name) {\n global $cms_db;\n\n $ret = true;\n $cquery = sprintf(\"select count(*) from %s where sid='%s' and name='%s'\",\n $cms_db['sessions'],\n $id,\n $name);\n $squery = sprintf(\"select sid from %s where sid = '%s' and name = '%s'\",\n $cms_db['sessions'],\n $id,\n addslashes($name));\n $this->db->query($squery);\n if ( $this->db->affected_rows() == 0\n && $this->db->query($cquery)\n\t && $this->db->next_record() && $this->db->f(0) == 0 ) {\n // nothing found here\n $ret = false;\n }\n return $ret;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function error ($vars=\"\") {\n if( isset($vars) && $vars != \"\" ) {\n include(GX_PATH.'/inc/lib/Control/Error/'.$vars.'.control.php');\n }else{\n include(GX_PATH.'/inc/lib/Control/Error/404.control.php');\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " $q = self::$mysqli->query($vars) ;\n if($q === false) {\n user_error(\"Query failed: \".self::$mysqli->error.\"
    \\n$vars\"); \n return false; \n }\n }\n \n return $q;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function makeConfig ($file) {\n $config = \"getMessage();\n }\n \n return $config;\n }", "label_name": "CWE-89", "label": 0} +{"code": " function __construct()\n {\n # code...\n self::$smtphost = Options::get('smtphost');\n self::$smtpuser = Options::get('smtpuser');\n self::$smtppass = Options::get('smtppass');\n self::$smtpssl = Options::get('smtpssl');\n self::$siteemail = Options::get('siteemail');\n self::$sitename = Options::get('sitename');\n }", "label_name": "CWE-79", "label": 1} +{"code": " $logo = \"\";\n }else{\n $logo = \"\";\n }\n return $logo;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function go($input, $path, $allowed='', $uniq=false, $size='', $width = '', $height = ''){\n $filename = Typo::cleanX($_FILES[$input]['name']);\n $filename = str_replace(' ', '_', $filename);\n if(isset($_FILES[$input]) && $_FILES[$input]['error'] == 0){\n if($uniq == true){\n $uniqfile = sha1(microtime().$filename);\n }else{\n $uniqfile = '';\n }\n\n $extension = pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION);\n $filetmp = $_FILES[$input]['tmp_name'];\n $filepath = GX_PATH.$path.$uniqfile.$filename;\n\n if(!in_array(strtolower($extension), $allowed)){\n $result['error'] = 'File not allowed';\n }else{\n if(move_uploaded_file(\n $filetmp, \n $filepath)\n ){\n $result['filesize'] = filesize($filepath);\n $result['filename'] = $uniqfile.$filename;\n $result['path'] = $path.$uniqfile.$filename;\n $result['filepath'] = $filepath;\n $result['fileurl'] = Options::get('siteurl').$path.$uniqfile.$filename;\n\n }else{\n $result['error'] = 'Cannot upload to directory, please check \n if directory is exist or You had permission to write it.';\n }\n }\n\n \n }else{\n //$result['error'] = $_FILES[$input]['error'];\n $result['error'] = '';\n }\n\n return $result;\n\n }", "label_name": "CWE-79", "label": 1} +{"code": " public static function sitemap() {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/sitemap\".GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?page=sitemap\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function page($vars) {\n switch (SMART_URL) {\n case true:\n # code...\n $url = Options::get('siteurl').\"/\".self::slug($vars).GX_URL_PREFIX;\n break;\n \n default:\n # code...\n $url = Options::get('siteurl').\"/index.php?page={$vars}\";\n break;\n\n }\n\n return $url;\n }", "label_name": "CWE-79", "label": 1} +{"code": " }elseif ($k == 'lang') {\r\n\r\n self::incFront('default');\r\n\r\n }elseif($k == \"error\"){\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function local($date, $format=''){\r\n setlocale(LC_TIME, Options::v('country_id'));\r\n (empty($format))? $format = \"%#d %B %Y %H:%M %p\" : $format = $format;\r\n $timezone = Options::v('timezone');\r\n $date = new DateTime($date);\r\n $date->setTimezone(new DateTimeZone($timezone));\r\n $newdate = $date->format(\"Y/m/j H:i:s\");\r\n $newdate = strftime($format, strtotime($newdate));\r\n return $newdate.\" \".$date->format(\"T\");\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $vars = self::$mysqli->escape_string($vars);\r\n }else{\r\n $vars = $vars;\r\n }\r\n return $vars;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function add() {\r\n \r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public function __construct () {\r\n\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function makeConfig ($file) {\r\n $config = \"getMessage();\r\n }\r\n\r\n return $config;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public function __construct () {\r\n self::setActive();\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function url($mod) {\r\n $url = Site::$url.\"/inc/mod/\".$mod;\r\n return $url;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public function __construct() {\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $posts_arr = json_decode(json_encode($posts), FALSE);\r\n // $posts[] = $posts;\r\n $post_arr[] = $posts_arr;\r\n $post = $post_arr;\r\n }\r\n }else{\r\n $post = $post;\r\n }\r\n\r\n }else{\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function existParam($param, $post_id) {\r\n $sql = \"SELECT * FROM `posts_param` WHERE `post_id` = '{$post_id}' AND `param` = '{$param}' LIMIT 1\";\r\n $q = Db::result($sql);\r\n if (Db::$num_rows > 0) {\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " function __construct () {\r\n\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function options($var) {\r\n if (self::optionsExist($var)) {\r\n include(GX_THEME.$var.'/options.php');\r\n }\r\n\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function flag($vars) {\r\n switch (SMART_URL) {\r\n case true:\r\n $lang = '?lang=' . $vars;\r\n if (isset($_GET['lang'])) {\r\n\r\n $uri = explode('?', $_SERVER['REQUEST_URI']);\r\n $uri = $uri[0];\r\n }else{\r\n $uri = $_SERVER['REQUEST_URI'];\r\n }\r\n $url = $uri . $lang;\r\n\r\n break;\r\n\r\n default:\r\n // print_r($_GET);\r\n if (!empty($_GET)) {\r\n\r\n $val = '';\r\n foreach ($_GET as $key => $value) {\r\n if ($key == 'lang') {\r\n $val .= '&lang='.$vars;\r\n }else{\r\n $val .= $key . '=' . $value;\r\n }\r\n }\r\n }else{\r\n $val = \"lang=\".$vars;\r\n }\r\n $lang = !isset($_GET['lang'])? '&lang=' . $vars: $val;\r\n $url = Site::$url . '/?' . $lang;\r\n break;\r\n\r\n }\r\n\r\n return $url;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function custom($vars) {\r\n $url = $vars;\r\n return $url;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function email($id){\r\n $usr = Db::result(\r\n sprintf(\"SELECT * FROM `user` WHERE `id` = '%d' OR `userid` = '%s' LIMIT 1\", \r\n Typo::int($id), \r\n Typo::cleanX($id)\r\n )\r\n );\r\n return $usr[0]->email;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public function __toString()\n {\n $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';\n foreach ($this->data as $k => $v) {\n if ($k != 'Name' && $k != 'Value' && $v !== null && $v !== false) {\n if ($k == 'Expires') {\n $str .= 'Expires=' . gmdate('D, d M Y H:i:s \\G\\M\\T', $v) . '; ';\n } else {\n $str .= ($v === true ? $k : \"{$k}={$v}\") . '; ';\n }\n }\n }\n\n return rtrim($str, '; ');\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function hasHeader($header)\n {\n return isset($this->headers[strtolower($header)]);\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function getRequestTarget()\n {\n if ($this->requestTarget !== null) {\n return $this->requestTarget;\n }\n\n $target = $this->uri->getPath();\n if ($target == null) {\n $target = '/';\n }\n if ($this->uri->getQuery()) {\n $target .= '?' . $this->uri->getQuery();\n }\n\n return $target;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function getPath()\n {\n return $this->path == null ? '' : $this->path;\n }", "label_name": "CWE-89", "label": 0} +{"code": "function parse_request($message)\n{\n $data = _parse_message($message);\n $matches = [];\n if (!preg_match('/^[a-zA-Z]+\\s+([a-zA-Z]+:\\/\\/|\\/).*/', $data['start-line'], $matches)) {\n throw new \\InvalidArgumentException('Invalid request string');\n }\n $parts = explode(' ', $data['start-line'], 3);\n $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';\n\n $request = new Request(\n $parts[0],\n $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1],\n $data['headers'],\n $data['body'],\n $version\n );\n\n return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);\n}", "label_name": "CWE-89", "label": 0} +{"code": " public function testNewInstanceWhenAddingHeaderThatWasNotThereBefore()\n {\n $r = new Response(200, ['Foo' => 'Bar']);\n $r2 = $r->withAddedHeader('Baz', 'Bam');\n $this->assertNotSame($r, $r2);\n $this->assertEquals('Bam', $r2->getHeaderLine('Baz'));\n $this->assertEquals('Bar', $r2->getHeaderLine('Foo'));\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function testAlwaysReturnsBody()\n {\n $r = new Response();\n $this->assertInstanceOf('Psr\\Http\\Message\\StreamInterface', $r->getBody());\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function testSameInstanceWhenSameBody()\n {\n $r = new Response(200, [], 'foo');\n $b = $r->getBody();\n $this->assertSame($r, $r->withBody($b));\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function testCompletePurchaseCustomOptions()\n {\n\n $this->setMockHttpResponse('ExpressPurchaseSuccess.txt');\n\n // Those values should not be used if custom token or payerid are passed\n $this->getHttpRequest()->query->replace(array(\n 'token' => 'GET_TOKEN',\n 'PayerID' => 'GET_PAYERID',\n ));\n\n $response = $this->gateway->completePurchase(array(\n 'amount' => '10.00',\n 'currency' => 'BYR',\n 'token' => 'CUSTOM_TOKEN',\n 'payerid' => 'CUSTOM_PAYERID'\n ))->send();\n\n $httpRequests = $this->getMockedRequests();\n $httpRequest = $httpRequests[0];\n $queryArguments = $httpRequest->getQuery()->toArray();\n $this->assertSame('CUSTOM_TOKEN', $queryArguments['TOKEN']);\n $this->assertSame('CUSTOM_PAYERID', $queryArguments['PAYERID']);\n\n }", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic static function sessionWrite() {\n\t\t$this->session->close();\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\t protected function curl_get_contents( &$url, $timeout, $redirect_max, $ua, $outfp ){\n\t\t$ch = curl_init();\n\t\tcurl_setopt( $ch, CURLOPT_URL, $url );\n\t\tcurl_setopt( $ch, CURLOPT_HEADER, false );\n\t\tif ($outfp) {\n\t\t\tcurl_setopt( $ch, CURLOPT_FILE, $outfp );\n\t\t} else {\n\t\t\tcurl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );\n\t\t\tcurl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );\n\t\t}\n\t\tcurl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 1 );\n\t\tcurl_setopt( $ch, CURLOPT_LOW_SPEED_TIME, $timeout );\n\t\tcurl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );\n\t\tcurl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);\n\t\tcurl_setopt( $ch, CURLOPT_MAXREDIRS, $redirect_max);\n\t\tcurl_setopt( $ch, CURLOPT_USERAGENT, $ua);\n\t\t$result = curl_exec( $ch );\n\t\t$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);\n\t\tcurl_close( $ch );\n\t\treturn $outfp? $outfp : $result;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tprivate function deleteDir($dirPath)\n\t{\n\t\tif (!is_dir($dirPath)) {\n\t\t\t$success = unlink($dirPath);\n\t\t} else {\n\t\t\t$success = true;\n\t\t\tforeach (array_reverse(elFinderVolumeFTP::listFilesInDirectory($dirPath, false)) as $path) {\n\t\t\t\t$path = $dirPath . DIRECTORY_SEPARATOR . $path;\n\t\t\t\tif(is_link($path)) {\n\t\t\t\t\tunlink($path);\n\t\t\t\t} else if (is_dir($path)) {\n\t\t\t\t\t$success = rmdir($path);\n\t\t\t\t} else {\n\t\t\t\t\t$success = unlink($path);\n\t\t\t\t}\n\t\t\t\tif (!$success) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($success) {\n\t\t\t\t$success = rmdir($dirPath);\n\t\t\t}\n\t\t}\n\t\tif(!$success) {\n\t\t\t$this->setError(elFinder::ERROR_RM, $dirPath);\n\t\t\treturn false;\n\t\t}\n\t\treturn $success;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tprotected function connect() {\n\t\tif (!($this->connect = @ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {\n\t\t\treturn $this->setError('Unable to connect to FTP server '.$this->options['host']);\n\t\t}\n\t\tif (!@ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {\n\t\t\t$this->umount();\n\t\t\treturn $this->setError('Unable to login into '.$this->options['host']);\n\t\t}\n\t\t\n\t\t// try switch utf8 mode\n\t\tif ($this->encoding) {\n\t\t\t@ftp_exec($this->connect, 'OPTS UTF8 OFF');\n\t\t} else {\n\t\t\t@ftp_exec($this->connect, 'OPTS UTF8 ON' );\n\t\t}\n\t\t\n\t\t// switch off extended passive mode - may be usefull for some servers\n\t\t@ftp_exec($this->connect, 'epsv4 off' );\n\t\t// enter passive mode if required\n\t\t$pasv = ($this->options['mode'] == 'passive');\n\t\tif (! ftp_pasv($this->connect, $pasv)) {\n\t\t\tif ($pasv) {\n\t\t\t\t$this->options['mode'] = 'active';\n\t\t\t}\n\t\t}\n\n\t\t// enter root folder\n\t\tif (! @ftp_chdir($this->connect, $this->root) \n\t\t|| $this->root != @ftp_pwd($this->connect)) {\n\t\t\t$this->umount();\n\t\t\treturn $this->setError('Unable to open root folder.');\n\t\t}\n\t\t\n\t\t// check for MLST support\n\t\t$features = ftp_raw($this->connect, 'FEAT');\n\t\tif (!is_array($features)) {\n\t\t\t$this->umount();\n\t\t\treturn $this->setError('Server does not support command FEAT.');\n\t\t}\n\n\t\tforeach ($features as $feat) {\n\t\t\tif (strpos(trim($feat), 'MLST') === 0) {\n\t\t\t\t$this->MLSTsupprt = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tprotected function _save($fp, $dir, $name, $stat) {\n\t\t$this->clearcache();\n\t\t\n\t\t$mime = $stat['mime'];\n\t\t$w = !empty($stat['width']) ? $stat['width'] : 0;\n\t\t$h = !empty($stat['height']) ? $stat['height'] : 0;\n\t\t\n\t\t$id = $this->_joinPath($dir, $name);\n\t\trewind($fp);\n\t\t$stat = fstat($fp);\n\t\t$size = $stat['size'];\n\t\t\n\t\tif (($tmpfile = tempnam($this->tmpPath, $this->id))) {\n\t\t\tif (($trgfp = fopen($tmpfile, 'wb')) == false) {\n\t\t\t\tunlink($tmpfile);\n\t\t\t} else {\n\t\t\t\twhile (!feof($fp)) {\n\t\t\t\t\tfwrite($trgfp, fread($fp, 8192));\n\t\t\t\t}\n\t\t\t\tfclose($trgfp);\n\t\t\t\tchmod($tmpfile, 0644);\n\t\t\t\t\n\t\t\t\t$sql = $id > 0\n\t\t\t\t\t? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, \"%s\", LOAD_FILE(\"%s\"), %d, %d, \"%s\", %d, %d)'\n\t\t\t\t\t: 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, \"%s\", LOAD_FILE(\"%s\"), %d, %d, \"%s\", %d, %d)';\n\t\t\t\t$sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->loadFilePath($tmpfile), $size, time(), $mime, $w, $h);\n\n\t\t\t\t$res = $this->query($sql);\n\t\t\t\tunlink($tmpfile);\n\t\t\t\t\n\t\t\t\tif ($res) {\n\t\t\t\t\treturn $id > 0 ? $id : $this->db->insert_id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\n\t\t$content = '';\n\t\trewind($fp);\n\t\twhile (!feof($fp)) {\n\t\t\t$content .= fread($fp, 8192);\n\t\t}\n\t\t\n\t\t$sql = $id > 0\n\t\t\t? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, \"%s\", \"%s\", %d, %d, \"%s\", %d, %d)'\n\t\t\t: 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, \"%s\", \"%s\", %d, %d, \"%s\", %d, %d)';\n\t\t$sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->db->real_escape_string($content), $size, time(), $mime, $w, $h);\n\t\t\n\t\tunset($content);\n\n\t\tif ($this->query($sql)) {\n\t\t\treturn $id > 0 ? $id : $this->db->insert_id;\n\t\t}\n\t\t\n\t\treturn false;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tprotected function make($path, $name, $mime) {\n\t\t$sql = 'INSERT INTO %s (`parent_id`, `name`, `size`, `mtime`, `mime`, `content`, `read`, `write`) VALUES (\"%s\", \"%s\", 0, %d, \"%s\", \"\", \"%d\", \"%d\")';\n\t\t$sql = sprintf($sql, $this->tbf, $path, $this->db->real_escape_string($name), time(), $mime, $this->defaults['read'], $this->defaults['write']);\n\t\t// echo $sql;\n\t\treturn $this->query($sql) && $this->db->affected_rows > 0;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tprotected function _fopen($path, $mode='rb') {\n\t\t$fp = $this->tmbPath\n\t\t\t? @fopen($this->getTempFile($path), 'w+')\n\t\t\t: @tmpfile();\n\t\t\n\t\t\n\t\tif ($fp) {\n\t\t\tif (($res = $this->query('SELECT content FROM '.$this->tbf.' WHERE id=\"'.$path.'\"'))\n\t\t\t&& ($r = $res->fetch_assoc())) {\n\t\t\t\tfwrite($fp, $r['content']);\n\t\t\t\trewind($fp);\n\t\t\t\treturn $fp;\n\t\t\t} else {\n\t\t\t\t$this->_fclose($fp, $path);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\t\t$args['name'][$i] = $this->sanitizeFileName($name, $opts);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$args['name'] = $this->sanitizeFileName($args['name'], $opts);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "label_name": "CWE-89", "label": 0} +{"code": " call_user_func($listener, $event, $eventName, $this);\n if ($event->isPropagationStopped()) {\n break;\n }\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function getIterator()\n {\n @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be removed in 3.0.', E_USER_DEPRECATED);\n\n return new \\ArrayIterator($this->all());\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function regenerate($destroy = false, $lifetime = null)\n {\n // Cannot regenerate the session ID for non-active sessions.\n if (PHP_VERSION_ID >= 50400 && \\PHP_SESSION_ACTIVE !== session_status()) {\n return false;\n }\n\n // Check if session ID exists in PHP 5.3\n if (PHP_VERSION_ID < 50400 && '' === session_id()) {\n return false;\n }\n\n if (null !== $lifetime) {\n ini_set('session.cookie_lifetime', $lifetime);\n }\n\n if ($destroy) {\n $this->metadataBag->stampNew();\n }\n\n $isRegenerated = session_regenerate_id($destroy);\n\n // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.\n // @see https://bugs.php.net/bug.php?id=70013\n $this->loadSession();\n\n return $isRegenerated;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function setActive($flag)\n {\n if (PHP_VERSION_ID >= 50400) {\n throw new \\LogicException('This method is disabled in PHP 5.4.0+');\n }\n\n $this->active = (bool) $flag;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function testGetDeepWithInvalidPaths($path)\n {\n $bag = new ParameterBag(array('foo' => array('bar' => 'moo')));\n\n $bag->get($path, null, true);\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function testSetSaveHandler54()\n {\n $this->iniSet('session.save_handler', 'files');\n $storage = $this->getStorage();\n $storage->setSaveHandler();\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(null);\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler()));\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new NativeSessionHandler());\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n $storage->setSaveHandler(new NullSessionHandler());\n $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Storage\\Proxy\\SessionHandlerProxy', $storage->getSaveHandler());\n }", "label_name": "CWE-89", "label": 0} +{"code": " foreach ($usr as $u) {\r\n # code...\r\n $msgs = str_replace('{{userid}}', $u->userid, $msg);\r\n $vars = array(\r\n 'to' => $u->email,\r\n 'to_name' => $u->userid,\r\n 'message' => $msgs,\r\n 'subject' => $subject,\r\n 'msgtype' => $_POST['type']\r\n );\r\n $mailsend = Mail::send($vars);\r\n if($mailsend !== null){\r\n $alermailsend[] = $mailsend;\r\n }\r\n sleep(3);\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " foreach ($post as $p) {\n if ($p->id != $id) {\n $title = (strlen($p->title) > 40) ? substr($p->title, 0, 38).'...' : $p->title;\n $img = self::getImage(Typo::Xclean($p->content));\n if ($img != '') {\n $img = Url::thumb($img, 'square', 200);\n } else {\n $img = Url::thumb('assets/images/noimage.png', '', 200);\n }\n $related .= '
  • id).'\">\n '.$title.'

  • ';\n } else {\n $related .= '';\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " $resultItem['qtip'] = $item->getDescription() ? $item->getDescription() : ' ';\n $result[] = $resultItem;\n }\n\n return $this->adminJson($result);\n }", "label_name": "CWE-79", "label": 1} +{"code": " protected function renderText ($field, $makeLinks, $textOnly, $encode) {\n $fieldName = $field->fieldName;\n $value = preg_replace(\"/(\\
    )|\\n/\",\" \",$this->owner->$fieldName);\n return Yii::app()->controller->convertUrls($this->render ($value, $encode));\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function getItems2 (\n $prefix='', $page=0, $limit=20, $valueAttr='name', $nameAttr='name') {\n\n $modelClass = get_class ($this->owner);\n $model = CActiveRecord::model ($modelClass);\n $table = $model->tableName ();\n $offset = intval ($page) * intval ($limit);\n\n AuxLib::coerceToArray ($valueAttr);\n $modelClass::checkThrowAttrError (array_merge ($valueAttr, array ($nameAttr)));\n $params = array ();\n if ($prefix !== '') {\n $params[':prefix'] = $prefix . '%';\n }\n $offset = abs ((int) $offset);\n $limit = abs ((int) $limit);\n $command = Yii::app()->db->createCommand (\"\n SELECT \" . implode (',', $valueAttr) . \", $nameAttr as __name\n FROM $table\n WHERE \" . ($prefix === '' ? \n '1=1' : ($nameAttr . ' LIKE :prefix')\n ) . \"\n ORDER BY __name\n LIMIT $offset, $limit\n \");", "label_name": "CWE-79", "label": 1} +{"code": " public function AddBCC($address, $name = '') {\n return $this->AddAnAddress('bcc', $address, $name);\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function IsMail() {\n $this->Mailer = 'mail';\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function getViewFileParams () {\n if (!isset ($this->_viewFileParams)) {\n $this->_viewFileParams = array_merge (\n parent::getViewFileParams (),\n array (\n 'chartType' => $this->chartType,\n\t\t\t 'chartSettingsDataProvider' => self::getChartSettingsProvider (\n $this->chartType),\n 'eventTypes' =>\n array ('all'=>Yii::t('app', 'All Events')) + Events::$eventLabels,\n 'socialSubtypes' => json_decode (\n\t\t\t Dropdowns::model()->findByPk(113)->options,true),\n 'visibilityFilters' => array (\n '1'=>'Public',\n '0'=>'Private',\n ),\n 'suppressChartSettings' => false,\n 'chartType' => 'usersChart',\n 'widgetUID' => $this->widgetUID,\n 'metricTypes' => User::getUserOptions (),\n )\n );\n }\n return $this->_viewFileParams;\n }", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function paramRules() {\n\t\treturn array(\n\t\t\t'title' => Yii::t('studio',$this->title),\n\t\t\t'info' => Yii::t('studio',$this->info),\n\t\t\t'modelRequired' => 'Contacts',\n\t\t\t'options' => array(\n\t\t\t\tarray(\n 'name'=>'listId',\n 'label'=>Yii::t('studio','List'),\n 'type'=>'link',\n 'linkType'=>'X2List',\n 'linkSource'=>Yii::app()->createUrl(\n\t\t\t\t\t CActiveRecord::model('X2List')->autoCompleteSource\n\t\t\t\t )\n ),\n\t\t\t));\n\t}", "label_name": "CWE-79", "label": 1} +{"code": " public function actionHideWidget() {\n if (isset($_POST['name'])) {\n $name = $_POST['name'];\n\n $layout = Yii::app()->params->profile->getLayout();\n\n // the widget could be in any of the blocks in the page, so check all of them\n foreach ($layout as $b => &$block) {\n if (isset($block[$name])) {\n if ($b == 'right') {\n $layout['hiddenRight'][$name] = $block[$name];\n } else {\n $layout['hidden'][$name] = $block[$name];\n }\n unset($block[$name]);\n Yii::app()->params->profile->saveLayout($layout);\n break;\n }\n }\n\n // make a list of hidden widgets, using
  • , to send back to the browser\n $list = \"\";\n foreach ($layout['hidden'] as $name => $widget) {\n $list .= \"
  • {$widget['title']}
  • \";\n }\n foreach ($layout['hiddenRight'] as $name => $widget) {\n $list .= \"
  • {$widget['title']}
  • \";\n }\n\n echo Yii::app()->params->profile->getWidgetMenu();\n }\n }", "label_name": "CWE-79", "label": 1} +{"code": " $layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair\n $changed = true;\n }\n\n // remove obsolete widgets\n $arrayDiff =\n array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));\n foreach($arrayDiff as $elem){\n if(in_array ($elem, array_keys ($layout[$position]))) {\n unset($layout[$position][$elem]);\n $changed = true;\n } else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {\n unset($layout['hidden'][$elem]);\n $changed = true;\n }\n }\n\n\n // ensure that widget properties are the same as those in the default layout\n foreach($layout[$position] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n if ($position === 'center') {\n foreach($layout['hidden'] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n }\n\n if($changed){\n $this->layout = json_encode($layout);\n $this->update(array('layout'));\n }\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function actionGetItems() {\n $sql = 'SELECT id, name as value FROM x2_accounts WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'] . '%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('calendar', 'Calendar');\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function actionGetItems(){\n $model = X2Model::model ($this->modelClass);\n if (isset ($model)) {\n $tableName = $model->tableName ();\n $sql = \n 'SELECT id, fileName as value\n FROM '.$tableName.' \n WHERE associationType!=\"theme\" and fileName LIKE :qterm \n ORDER BY fileName ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function search(){\n // Warning: Please modify the following code to remove attributes that\n // should not be searched.\n\n $criteria = new CDbCriteria;\n $username = Yii::app()->user->name;\n $criteria->addCondition(\"uploadedBy='$username' OR private=0 OR private=null\");\n $criteria->addCondition(\"associationType != 'theme'\");\n return $this->searchBase($criteria);\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function actionGetItems(){\n // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.\n $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-79", "label": 1} +{"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-79", "label": 1} +{"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-829", "label": 86} +{"code": "\tfunction check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {\n\t\tif ( -1 == $action ) {\n\t\t\t_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2.0' );\n\t\t}\n\n\t\t$adminurl = strtolower( admin_url() );\n\t\t$referer = strtolower( wp_get_referer() );\n\t\t$result = isset( $_REQUEST[ $query_arg ] ) ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action ) : false;\n\n\t\t/**\n\t\t * Fires once the admin request has been validated or not.\n\t\t *\n\t\t * @since 1.5.1\n\t\t *\n\t\t * @param string $action The nonce action.\n\t\t * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between\n\t\t * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.\n\t\t */\n\t\tdo_action( 'check_admin_referer', $action, $result );\n\n\t\tif ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {\n\t\t\twp_nonce_ays( $action );\n\t\t\tdie();\n\t\t}\n\n\t\treturn $result;\n\t}", "label_name": "CWE-843", "label": 43} +{"code": "\tpublic function column_title( $post ) {\n\t\tlist( $mime ) = explode( '/', $post->post_mime_type );\n\n\t\t$title = _draft_or_post_title();\n\t\t$thumb = wp_get_attachment_image( $post->ID, array( 60, 60 ), true, array( 'alt' => '' ) );\n\t\t$link_start = $link_end = '';\n\n\t\tif ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {\n\t\t\t$link_start = sprintf(\n\t\t\t\t'',\n\t\t\t\tget_edit_post_link( $post->ID ),\n\t\t\t\t/* translators: %s: attachment title */\n\t\t\t\tesc_attr( sprintf( __( '“%s” (Edit)' ), $title ) )\n\t\t\t);\n\t\t\t$link_end = '';\n\t\t}\n\n\t\t$class = $thumb ? ' class=\"has-media-icon\"' : '';\n\t\t?>\n\t\t>\n\t\t\t\n\t\t\t\t\">\n\t\t\t\n\t\t\n\t\t

    \n\t\t\t \n\t\t\tID );\n\t\t\techo wp_basename( $file );\n\t\t\t?>\n\t\t

    \n\t\tprocess_fields( $table, $data, $format );\n\t\tif ( false === $data ) {\n\t\t\treturn false;\n\t\t}\n\t\t$where = $this->process_fields( $table, $where, $where_format );\n\t\tif ( false === $where ) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$fields = $conditions = $values = array();\n\t\tforeach ( $data as $field => $value ) {\n\t\t\tif ( is_null( $value['value'] ) ) {\n\t\t\t\t$fields[] = \"`$field` = NULL\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$fields[] = \"`$field` = \" . $value['format'];\n\t\t\t$values[] = $value['value'];\n\t\t}\n\t\tforeach ( $where as $field => $value ) {\n\t\t\tif ( is_null( $value['value'] ) ) {\n\t\t\t\t$conditions[] = \"`$field` IS NULL\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t$conditions[] = \"`$field` = \" . $value['format'];\n\t\t\t$values[] = $value['value'];\n\t\t}\n\n\t\t$fields = implode( ', ', $fields );\n\t\t$conditions = implode( ' AND ', $conditions );\n\n\t\t$sql = \"UPDATE `$table` SET $fields WHERE $conditions\";\n\t\t\n\t\t$this->check_current_query = false;\n\t\treturn $this->query( $this->prepare( $sql, $values ) );\n\t}", "label_name": "CWE-89", "label": 0} +{"code": " public function index($id)\n {\n\n //check permissions\n $template = $this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), false);\n if (!$this->_isSiteAdmin() && !$template) {\n throw new MethodNotAllowedException('No template with the provided ID exists, or you are not authorised to see it.');\n }\n\n $templateElements = $this->TemplateElement->find('all', array(\n 'conditions' => array(\n 'template_id' => $id,\n ),\n 'contain' => array(\n 'TemplateElementAttribute',\n 'TemplateElementText',\n 'TemplateElementFile'\n ),\n 'order' => array('TemplateElement.position ASC')\n ));\n $this->loadModel('Attribute');\n $this->set('validTypeGroups', $this->Attribute->validTypeGroups);\n $this->set('id', $id);\n $this->layout = 'ajaxTemplate';\n $this->set('elements', $templateElements);\n $mayModify = false;\n if ($this->_isSiteAdmin() || $template['Template']['org'] == $this->Auth->user('Organisation')['name']) {\n $mayModify = true;\n }\n $this->set('mayModify', $mayModify);\n $this->render('ajax/ajaxIndex');\n }", "label_name": "CWE-79", "label": 1} +{"code": "\t\t\tform_selectable_cell(filter_value($vdef['name'], get_request_var('filter'), 'vdef.php?action=edit&id=' . $vdef['id']), $vdef['id']);\n form_selectable_cell($disabled ? __('No'):__('Yes'), $vdef['id'], '', 'text-align:right');\n form_selectable_cell(number_format_i18n($vdef['graphs'], '-1'), $vdef['id'], '', 'text-align:right');\n form_selectable_cell(number_format_i18n($vdef['templates'], '-1'), $vdef['id'], '', 'text-align:right');\n form_checkbox_cell($vdef['name'], $vdef['id'], $disabled);\n form_end_row();\n }", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function meta_box_subject() {\n\n\t\t$placeholder = __( 'What is your conversation about?', 'supportflow' );\n\t\techo '

    ' . __( 'Subject', 'supportflow' ) . '

    ';\n\t\techo '';\n\t\techo '

    ' . __( 'Please describe what this ticket is about in several words', 'supportflow' ) . '

    ';\n\n\t}", "label_name": "CWE-79", "label": 1} +{"code": " foreach ($value as $valueKey => $valueValue) {\n if (\\is_int($valueKey)) {\n $filteredKey = $valueKey;\n } else {\n $filteredKey = self::filterValue($valueKey, $regex, $stripTags);\n }\n\n if ($filteredKey === '' || $filteredKey === null) {\n continue;\n }\n\n $filteredValue = $valueValue;\n\n if (\\is_array($valueValue)) {\n $filteredValue = self::filterArrayValue($valueValue, $regex, $stripTags);\n }\n\n if (\\is_string($valueValue)) {\n $filteredValue = self::filterValue($valueValue, $regex, $stripTags);\n }\n\n $newReturn[$filteredKey] = $filteredValue;\n }", "label_name": "CWE-79", "label": 1} +{"code": " public static function filterValue($value, $regex, $stripTags = true)\n {\n if (empty($value)) {\n return $value;\n }\n\n if ($stripTags) {\n $value = strip_tags($value);\n }\n\n if (preg_match($regex, $value)) {\n return null;\n }\n\n return $value;\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function setArticles($articles)\n {\n $return = $this->setOneToMany($articles, Article::class, 'articles', 'container');\n $this->setType('ctArticles');\n\n return $return;\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function buildCurrentUrl() {\n $url = URL_BASE;\n if ($this->url_style == 'sef') {\n $url .= substr(PATH_RELATIVE,0,-1).$this->sefPath;\n } else {\n $url .= urldecode((empty($_SERVER['REQUEST_URI'])) ? $_ENV['REQUEST_URI'] : $_SERVER['REQUEST_URI']);\n }\n return expString::sanitize($url);\n }", "label_name": "CWE-89", "label": 0} +{"code": " $module_views[$key]['name'] = gt($value['name']);\n }\n\n // look for a config form for this module's current view \n// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }\n \n // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);\n\n if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);\n\n return $views;\n}", "label_name": "CWE-89", "label": 0} +{"code": " function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {\n\n if ($is_revisioned) {\n $object->revision_id++;\n //if ($table==\"text\") eDebug($object);\n $res = $this->insertObject($object, $table);\n //if ($table==\"text\") eDebug($object,true); \n $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);\n return $res;\n }\n $sql = \"UPDATE \" . $this->prefix . \"$table SET \";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n //if($is_revisioned && $var=='revision_id') $val++;\n if ($var{0} != '_') {\n if (is_array($val) || is_object($val)) {\n $val = serialize($val); \n $sql .= \"`$var`='\".$val.\"',\";\n } else {\n $sql .= \"`$var`='\" . $this->escapeString($val) . \"',\";\n }\n }\n }\n $sql = substr($sql, 0, -1) . \" WHERE \";\n if ($where != null)\n $sql .= $this->injectProof($where);\n else\n $sql .= \"`\" . $identifier . \"`=\" . $object->$identifier;\n //if ($table == 'text') eDebug($sql,true); \n $res = (@mysqli_query($this->connection, $sql) != false);\n return $res;\n }", "label_name": "CWE-89", "label": 0} +{"code": " private function runCallback() {\n foreach ($this->records as &$record) {\n if (isset($record->ref_type)) {\n $refType = $record->ref_type;\n if (class_exists($record->ref_type)) {\n $type = new $refType();\n $classinfo = new ReflectionClass($type);\n if ($classinfo->hasMethod('paginationCallback')) {\n $item = new $type($record->original_id);\n $item->paginationCallback($record);\n }\n }\n }\n } \n }", "label_name": "CWE-89", "label": 0} +{"code": " $count += $db->dropTable($basename);\n }\n \n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-89", "label": 0} +{"code": " public function toolbar() {\n// global $user;\n\n $menu = array();\n\t\t$dirs = array(\n\t\t\tBASE.'framework/modules/administration/menus',\n\t\t\tBASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'\n\t\t);\n\n\t\tforeach ($dirs as $dir) {\n\t\t if (is_readable($dir)) {\n\t\t\t $dh = opendir($dir);\n\t\t\t while (($file = readdir($dh)) !== false) {\n\t\t\t\t if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {\n\t\t\t\t\t $menu[substr($file,0,-4)] = include($dir.'/'.$file);\n if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t}\n\n // sort the top level menus alphabetically by filename\n\t\tksort($menu);\t\t\n\t\t$sorted = array();\n\t\tforeach($menu as $m) $sorted[] = $m;\n \n // slingbar position\n if (isset($_COOKIE['slingbar-top'])){\n $top = $_COOKIE['slingbar-top'];\n } else {\n $top = SLINGBAR_TOP;\n }\n \n\t\tassign_to_template(array(\n 'menu'=>(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function configure() {\n $this->config['defaultbanner'] = array();\n if (!empty($this->config['defaultbanner_id'])) {\n $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);\n } \n\t parent::configure();\n\t $banners = $this->banner->find('all', null, 'companies_id');\n\t assign_to_template(array(\n 'banners'=>$banners,\n 'title'=>static::displayname()\n ));\n\t}", "label_name": "CWE-89", "label": 0} +{"code": " function reset_stats() {\n// global $db;\n\n // reset the counters\n// $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');\n banner::resetImpressions();\n// $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');\n banner::resetClicks();\n \n // let the user know we did stuff. \n flash('message', gt(\"Banner statistics reset.\"));\n expHistory::back();\n }", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"code": "\tpublic function approve() {\n\t expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n\t \n\t $comment = new expComment($this->params['id']);\n\t assign_to_template(array(\n 'comment'=>$comment\n ));\n\t}", "label_name": "CWE-89", "label": 0} +{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\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 $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\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-89", "label": 0} +{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\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 $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\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-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tfunction selectBillingOptions() {\n\t\t\n\t}", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": " function edit_optiongroup_master() {\n expHistory::set('editable', $this->params);\n \n $id = isset($this->params['id']) ? $this->params['id'] : null;\n $record = new optiongroup_master($id); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

    ' . $result->message);\n expHistory::back();\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function manage() {\n expHistory::set('viewable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'rank',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n //'columns'=>array('Name'=>'title')\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function manage_messages() {\n expHistory::set('manageable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'body',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n ));\n\n //eDebug($page);\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": " static function displayname() {\n return gt(\"e-Commerce Category Manager\");\n }", "label_name": "CWE-89", "label": 0} +{"code": " function edit() {\r\n global $template;\r\n\r\n parent::edit();\r\n $allforms = array();\r\n $allforms[\"\"] = gt('Disallow Feedback');\r\n // calculate which event date is the one being edited\r\n $event_key = 0;\r\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\r\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\r\n \t}\r\n\r\n assign_to_template(array(\r\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\r\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\r\n 'event_key' => $event_key,\r\n ));\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " } elseif (!empty($this->params['src'])) {\r\n if ($this->params['src'] == $loc->src) {\r\n $this->config = $config->config;\r\n break;\r\n }\r\n }\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " function searchName() {\r\n return gt(\"Calendar Event\");\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " 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", "label_name": "CWE-89", "label": 0} +{"code": " static function author() {\r\n return \"Dave Leffler\";\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $date->delete(); // event automatically deleted if all assoc eventdates are deleted\r\n }\r\n expHistory::back();\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $body = str_replace(array(\"\\n\"), \"
    \", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function canImportData() {\r\n return true;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " static function description() {\r\n return \"Manage events and schedules, and optionally publish them.\";\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt 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 echo json_encode($file); //FIXME we exit before hitting this\n } ", "label_name": "CWE-89", "label": 0} +{"code": " public function upload() {\n \n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n } ", "label_name": "CWE-89", "label": 0} +{"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": "\tpublic function update_version() {\n\t // get the current version\n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-89", "label": 0} +{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label_name": "CWE-89", "label": 0} +{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " static function description() { return gt(\"Places navigation links/menus on the page.\"); }\r", "label_name": "CWE-89", "label": 0} +{"code": " function process_subsections($parent_section, $subtpl) {\r\n global $db, $router;\r\n\r\n $section = new stdClass();\r\n $section->parent = $parent_section->id;\r\n $section->name = $subtpl->name;\r\n $section->sef_name = $router->encode($section->name);\r\n $section->subtheme = $subtpl->subtheme;\r\n $section->active = $subtpl->active;\r\n $section->public = $subtpl->public;\r\n $section->rank = $subtpl->rank;\r\n $section->page_title = $subtpl->page_title;\r\n $section->keywords = $subtpl->keywords;\r\n $section->description = $subtpl->description;\r\n $section->id = $db->insertObject($section, 'section');\r\n self::process_section($section, $subtpl);\r\n }\r", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"code": " self::removeLevel($kid->id);\r\n }\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"code": " static function displayname() { return gt(\"Navigation\"); }\r", "label_name": "CWE-89", "label": 0} +{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\r\n if (expPermissions::check('manage', $loc)) return true;\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function isPublic($s) {\r\n if ($s == null) {\r\n return false;\r\n }\r\n while ($s->public && $s->parent > 0) {\r\n $s = new section($s->parent);\r\n }\r\n $lineage = (($s->public) ? 1 : 0);\r\n return $lineage;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " function searchName() { return gt('Webpage'); }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function getTemplateHierarchyFlat($parent, $depth = 1) {\r\n global $db;\r\n\r\n $arr = array();\r\n $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');\r\n//\t\t$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));\r\n for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {\r\n $page = $kids[$i];\r\n $page->depth = $depth;\r\n $page->first = ($i == 0 ? 1 : 0);\r\n $page->last = ($i == count($kids) - 1 ? 1 : 0);\r\n $arr[] = $page;\r\n $arr = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));\r\n }\r\n return $arr;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $section = new section(intval($page));\r\n if ($section) {\r\n// self::deleteLevel($section->id);\r\n $section->delete();\r\n }\r\n }\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " function edit_section() {\r\n global $db, $user;\r\n\r\n $parent = new section($this->params['parent']);\r\n if (empty($parent->id)) $parent->id = 0;\r\n assign_to_template(array(\r\n 'haveStandalone' => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),\r\n 'parent' => $parent,\r\n 'isAdministrator' => $user->isAdmin(),\r\n ));\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " static function isSearchable() { return true; }\r", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {\n $limit = '0';\n }\n $order = isset($this->config['order']) ? $this->config['order'] : \"rank\";\n $page = new expPaginator(array(\n 'model'=>'photo',\n 'where'=>$this->aggregateWhereClause(),\n 'limit'=>$limit,\n 'order'=>$order,\n 'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],\n 'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),\n 'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),\n 'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-89", "label": 0} +{"code": " function productFeed() {\n// global $db;\n //check query password to avoid DDOS\n /*\n * condition = new\n * description \n * id - SKU \n * link \n * price \n * title \n * brand - manufacturer \n * image link - fullsized image, up to 10, comma seperated \n * product type - category - \"Electronics > Audio > Audio Accessories MP3 Player Accessories\",\"Health & Beauty > Healthcare > Biometric Monitors > Pedometers\" \n */\n $out = '\"id\",\"condition\",\"description\",\"like\",\"price\",\"title\",\"brand\",\"image link\",\"product type\"' . chr(13) . chr(10);\n\n $p = new product();\n $prods = $p->find('all', 'parent_id=0 AND ');\n //$prods = $db->selectObjects('product','parent_id=0 AND');\n }", "label_name": "CWE-89", "label": 0} +{"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-89", "label": 0} +{"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-89", "label": 0} +{"code": "\tpublic function jsonError(Exception $exception) {\n\t\t$message = $exception->getMessage();\n\t\t$code = $this->getHttpStatusCode($exception);\n\n\t\treturn new JSONResponse(\n\t\t\t[\n\t\t\t\t'message' => $message . ' (' . $code . ')',\n\t\t\t\t'success' => false\n\t\t\t],\n\t\t\t$code\n\t\t);\n\t}", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function testGetFilesWithBrokenSetup() {\n\t\t$location = '';\n\t\t$features = '';\n\t\t$etag = 1111222233334444;\n\t\t$mediatypes = 'image/png';\n\t\t$exceptionMessage = 'A\u00efe!';\n\t\t$this->searchFolderService->expects($this->once())\n\t\t\t\t\t\t\t\t ->method('getCurrentFolder')\n\t\t\t\t\t\t\t\t ->with(\n\t\t\t\t\t\t\t\t\t $location,\n\t\t\t\t\t\t\t\t\t [$features]\n\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t ->willThrowException(new ServiceException($exceptionMessage));\n\t\t// Default status code when something breaks\n\t\t$status = Http::STATUS_INTERNAL_SERVER_ERROR;\n\t\t$errorMessage = [\n\t\t\t'message' => $exceptionMessage . ' (' . $status . ')',\n\t\t\t'success' => false\n\t\t];\n\t\t/** @type JSONResponse $response */\n\t\t$response = $this->controller->getList($location, $features, $etag, $mediatypes);\n\n\t\t$this->assertEquals($errorMessage, $response->getData());\n\t}", "label_name": "CWE-79", "label": 1} +{"code": "\tprotected function LoadSize($blob)\n\t{\n\t\tif (!$blob)\n\t\t\treturn;\n\n\t\t$args = array();\n\t\t$args[] = '-s';\n\t\t$args[] = $blob->GetHash();\n\n\t\treturn $this->exe->Execute($blob->GetProject()->GetPath(), GIT_CAT_FILE, $args);\n\t}", "label_name": "CWE-78", "label": 6} +{"code": "\t\t\t$trimmed = trim($line);\n\n\t\t\tif ((strlen($trimmed) > 0) || ($readInitialData === true)) {\n\t\t\t\t$comment[] = $line;\n\t\t\t}\n\t\t\t$readInitialData = true;\n\n\t\t}\n\n\t\tswitch ($type) {\n\t\t\tcase 'commit':\n\t\t\t\t$object = $objectHash;\n\t\t\t\t$commitHash = $objectHash;\n\t\t\t\tbreak;\n\t\t\tcase 'tag':\n\t\t\t\t$args = array();\n\t\t\t\t$args[] = 'tag';\n\t\t\t\t$args[] = $objectHash;\n\t\t\t\t$ret = $this->exe->Execute($tag->GetProject()->GetPath(), GIT_CAT_FILE, $args);\n\t\t\t\t$lines = explode(\"\\n\", $ret);\n\t\t\t\tforeach ($lines as $i => $line) {\n\t\t\t\t\tif (preg_match('/^tag (.+)$/', $line, $regs)) {\n\t\t\t\t\t\t$name = trim($regs[1]);\n\t\t\t\t\t\t$object = $name;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'blob':\n\t\t\t\t$object = $objectHash;\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn array(\n\t\t\t$type,\n\t\t\t$object,\n\t\t\t$commitHash,\n\t\t\t$tagger,\n\t\t\t$taggerEpoch,\n\t\t\t$taggerTimezone,\n\t\t\t$comment\n\t\t);\n\n\t}", "label_name": "CWE-78", "label": 6} +{"code": " return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2'] = new \\Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C2(${($_ = isset($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3']) ? $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3'] : ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3'] = new \\Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\includes\\HotPath\\C3())) && false ?: '_'});", "label_name": "CWE-89", "label": 0} +{"code": " protected function getFooService()\n {\n $a = new \\App\\Bar();\n\n $b = new \\App\\Baz($a);\n $b->bar = $a;\n\n $this->services['App\\Foo'] = $instance = new \\App\\Foo($b);\n\n $a->foo = $instance;\n\n return $instance;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $category = $this->getCategory();\n\n if ($this->categoryModel->remove($category['id'])) {\n $this->flash->success(t('Category removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this category.'));\n }\n\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 9} +{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-639", "label": 9} +{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-639", "label": 9} +{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function save()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->categoryValidator->validateCreation($values);\n\n if ($valid) {\n if ($this->categoryModel->create($values) !== false) {\n $this->flash->success(t('Your category have been created successfully.'));\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);\n return;\n } else {\n $errors = array('name' => array(t('Another category with the same name exists in this project')));\n }\n }\n\n $this->create($values, $errors);\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 9} +{"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-639", "label": 9} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($this->tagModel->remove($tag_id)) {\n $this->flash->success(t('Tag removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-639", "label": 9} +{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane();\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"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-639", "label": 9} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-639", "label": 9} +{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-639", "label": 9} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getTaskLink();\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-639", "label": 9} +{"code": "function shibboleth_login_form() {\n\t$login_url = add_query_arg('action', 'shibboleth');\n\t$login_url = remove_query_arg('reauth', $login_url);\n\techo '

    ' . __('Login with Shibboleth', 'shibboleth') . '

    ';\n}", "label_name": "CWE-79", "label": 1} +{"code": " public function delete($fileName = null)\n {\n $this->validateFileName();\n\n list($name, $extension) = $this->model->getFileNameParts();\n\n return $this->datasource->delete(\n $this->model->getObjectTypeDirName(),\n $name,\n $extension\n );\n }", "label_name": "CWE-22", "label": 2} +{"code": " public function get($columns = ['*'])\n {\n if (!is_null($this->cacheMinutes)) {\n $results = $this->getCached($columns);\n }\n else {\n $results = $this->getFresh($columns);\n }\n\n $models = $this->getModels($results ?: []);\n\n return $this->model->newCollection($models);\n }", "label_name": "CWE-79", "label": 1} +{"code": "function sqlrequest($database,$sql,$id=false){\n\n\t// Get the global value\n\tglobal $database_host;\n\tglobal $database_username;\n\tglobal $database_password;\n\n\t$connexion = mysqli_connect($database_host, $database_username, $database_password, $database);\n\tif (!$connexion) {\n\t\techo \"
      \";\n\t\techo \"
    • Alert EyesOfNetwork - Message EON-database connect
    • \";\n\t\techo \"
    • Could not connect to database : $database ($database_host)
    • \";\n\t\techo \"
    \";\n\t\texit(1);\n\t}\n\n\tif ( $database == \"eonweb\" ) {\n\t\t// Force UTF-8\n\t\tmysqli_query($connexion, \"SET NAMES 'utf8'\");\n\t}\n\t$result=mysqli_query($connexion, \"$sql\");\n\n\tif($id==true)\n\t\t$result=mysqli_insert_id($connexion);\n\t\t\n\tmysqli_close($connexion);\n\treturn $result;\n}", "label_name": "CWE-78", "label": 6} +{"code": "function editEvent($selected_events, $queue, $comments)\n{\n\tglobal $database_ged;\n\n\t// get all needed infos into variables\n\t$value_parts = explode(\":\", $selected_events);\n\t$id = $value_parts[0];\n\t$ged_type = $value_parts[1];\n\n\t// format comment string to avoid errors\n\t$comments = str_replace(\"'\", \"\\'\", $comments);\n\t$comments = str_replace(\"#\", \"\\#\", $comments);\n\n\t$sql = \"UPDATE \".$ged_type.\"_queue_\".$queue.\" SET comments='$comments' WHERE id = $id\";\n\t$result = sqlrequest($database_ged, $sql);\n\tif($result){\n\t\tmessage(11, \" : \".getLabel(\"message.event_edited\"), \"ok\");\n\t} else {\n\t\tmessage(11, \" : \".getLabel(\"message.event_edited_error\"), \"danger\");\n\t}\n}", "label_name": "CWE-78", "label": 6} +{"code": "\tpublic function set_controller($controller, $action)\n\t{\n\t\tinclude CLASS_DIR . 'module.php';\n\n\t\t$module = new Module($controller);\n\n\t\tdefine ('MODULE_NAME', $module->get_name());\n\n\t\t$class_file = APP_DIR . 'controller/' . MODULE_NAME . '.php';\n\t\t$class_name = ucfirst(MODULE_NAME) . '_Controller';\n\t\t$class_method = ucfirst($action) . '_Action';\n\n\t\t// tworzy obiekt kontrolera:\n\n\t\tif (file_exists($class_file))\n\t\t{\n\t\t\tinclude $class_file;\n\n\t\t\tif (class_exists($class_name))\n\t\t\t{\n\t\t\t\t$this->controller_object = new $class_name($this);\n\n\t\t\t\t$this->set_acl($this);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdie ('Class:

    '.$class_name.'

    not found.');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdie ('File:

    '.$class_file.'

    not found.');\n\t\t}\n\n\t\t// tworzy obiekt modelu:\n\n\t\t$this->set_model_object(MODULE_NAME);\n\n\t\t// tworzy obiekt widoku:\n\n\t\t$this->set_view_object(MODULE_NAME);\n\n\t\t// wywo\u0142uje akcj\u0119 (metod\u0119) kontrolera:\n\n\t\tif (method_exists($class_name, $class_method))\n\t\t{\n\t\t\t$this->controller_object->{$class_method}();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdie ('Method:

    '.$class_method.'

    in class:

    '.$class_name.'

    not found.');\n\t\t}\n\t}", "label_name": "CWE-79", "label": 1} +{"code": " public function dispatch($messages, $final)\n {\n $targetErrors = [];\n foreach ($this->targets as $target) {\n if ($target->enabled) {\n try {\n $target->collect($messages, $final);\n } catch (\\Exception $e) {\n $target->enabled = false;\n $targetErrors[] = [\n 'Unable to send log via ' . get_class($target) . ': ' . ErrorHandler::convertExceptionToString($e),\n Logger::LEVEL_WARNING,\n __METHOD__,\n microtime(true),\n [],\n ];\n }\n }\n }\n\n if (!empty($targetErrors)) {\n $this->dispatch($targetErrors, true);\n }\n }", "label_name": "CWE-79", "label": 1} +{"code": " public static function remove_spam()\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n $count = $DB->query_single(\r\n\t 'count(*) as total',\r\n\t 'nv_comments',\r\n\t 'website = '.protect($website->id).' AND status = 3'\r\n );\r\n\r\n $ok = $DB->execute('\r\n\t\t\tDELETE FROM nv_comments\r\n WHERE website = '.protect($website->id).'\r\n AND status = 3\r\n ');\r\n\r\n if($ok)\r\n return $count;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function remove($id)\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n if(empty($id))\r\n return 'invalid_id';\r\n\r\n $DB->execute('\r\n DELETE FROM nv_notes\r\n WHERE website = '.protect($website->id).'\r\n AND id = '.protect($id).'\r\n LIMIT 1'\r\n );\r\n\r\n return 'true';\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public function load_lines()\r\n {\r\n global $DB;\r\n\r\n $DB->query('\r\n SELECT * \r\n FROM nv_orders_lines \r\n WHERE `order` = '.protect($this->id).' \r\n ORDER BY position ASC'\r\n );\r\n $this->lines = $DB->result();\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function find_by_reference($reference, $website_id=null)\r\n {\r\n global $DB;\r\n global $website;\r\n\r\n if(empty($website_id))\r\n $website_id = $website->id;\r\n\r\n $order_id = $DB->query_single(\r\n 'id',\r\n 'nv_orders',\r\n 'reference = '.protect($reference).' AND website = \"'.$website_id.'\"'\r\n );\r\n\r\n return $order_id;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": " public static function country_name_by_code($code, $language=\"\")\r\n {\r\n global $DB;\r\n\r\n $lang = core_get_language($language);\r\n\r\n $DB->query('SELECT name\r\n\t\t\t\t\tFROM nv_countries\r\n\t\t \t\t\tWHERE lang = '.protect($lang).'\r\n\t\t\t\t\t AND country_code = '.protect($code));\r\n\r\n $row = $DB->first();\r\n\r\n return $row->name;\r\n }\r", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic static function countries_regions($country_id=\"\")\r\n\t{\r\n\t\tglobal $DB;\r\n\r\n\t\t// note: regions have no translation to any language right now\r\n\r\n $country_query = \" 1=1 \";\r\n if(!empty($country_id))\r\n $country_query = ' AND r.country = '.protect($country_id);\r\n\r\n\t\t$DB->query('\r\n SELECT r.`numeric` AS region_id, c.country_code, r.name\r\n FROM nv_countries c, nv_countries_regions r\r\n WHERE c.lang = \"en\" AND\r\n c.`numeric` = r.country AND\r\n r.lang = \"\" AND\r\n '.$country_query.'\r\n ORDER BY name ASC\r\n ');\r\n\r\n\t\t$rs = $DB->result();\r\n\r\n\t\treturn $rs;\r\n\t}\r", "label_name": "CWE-89", "label": 0} +{"code": " AND lang = '.protect($lang).'\r\n AND subtype IN ('.implode(\",\", array_map(function($k){ return protect($k);}, $subtypes)).')'\r\n );\r", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic static function object_votes_by_score($object, $object_id)\r\n\t{\r\n\t\tglobal $DB;\r\n\t\tglobal $website;\r\n\t\t\r\n\t\t$DB->query('\r\n\t\t\tSELECT value, COUNT(*) as votes\r\n\t\t\t FROM nv_webuser_votes\r\n WHERE website = '.protect($website->id).'\r\n\t\t\t AND object = '.protect($object).'\r\n AND object_id = '.protect($object_id).'\r\n\t\t\t GROUP BY value\r\n\t\t\t ORDER BY value ASC\r\n\t\t ');\r\n\t\t\t\t\t \r\n\t\t$data = $DB->result();\r\n\t\t\r\n\t\treturn $data;\r\n\t}\r", "label_name": "CWE-89", "label": 0} +{"code": "\tpublic function update()\r\n\t{\r\n\t\tglobal $DB;\r\n\t\tglobal $events;\r\n\r\n\t\tif(!is_array($this->categories))\r\n\t\t\t$this->categories = array();\r\n\t\t\t\r\n\t\t$ok = $DB->execute(' \r\n \t\t\tUPDATE nv_feeds\r\n\t\t\t SET categories = :categories, format = :format, image = :image, entries = :entries, \r\n\t\t\t \t content = :content, views = :views, permission = :permission, enabled = :enabled\r\n\t\t\tWHERE id = :id\tAND\twebsite = :website',\r\n\t\t\tarray(\r\n\t\t\t\t'id' => $this->id,\r\n\t\t\t\t'website' => $this->website,\r\n\t\t\t\t'categories' => implode(',', $this->categories),\r\n\t\t\t\t'format' => $this->format,\r\n\t\t\t\t'image' => value_or_default($this->image, 0),\r\n\t\t\t\t'entries' => value_or_default($this->entries, 10),\r\n\t\t\t\t'content' => $this->content,\r\n\t\t\t\t'views' => value_or_default($this->views, 0),\r\n\t\t\t\t'permission' => value_or_default($this->permission, 0),\r\n\t\t\t\t'enabled' => value_or_default($this->enabled, 0)\r\n\t\t\t)\r\n\t\t);\r\n\t\t\t\t\t\t\t \r\n\t\tif(!$ok)\r\n\t\t throw new Exception($DB->get_last_error());\r\n\t\t\r\n\t\twebdictionary::save_element_strings('feed', $this->id, $this->dictionary);\r\n\t\tpath::saveElementPaths('feed', $this->id, $this->paths);\r\n\r\n if(method_exists($events, 'trigger'))\r\n {\r\n $events->trigger(\r\n 'feed',\r\n 'save',\r\n array(\r\n 'feed' => $this\r\n )\r\n );\r\n }\r\n\t\t\r\n\t\treturn true;\r\n\t}\r", "label_name": "CWE-79", "label": 1} +{"code": "\t\t\tforeach($fields as $field)\r\n\t\t\t{\r\n\t\t\t\tif(substr($key, 0, strlen($field.'-'))==$field.'-')\r\n {\r\n $this->dictionary[substr($key, strlen($field.'-'))][$field] = $value;\r\n }\r\n\t\t\t}\r", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function load_from_post()\r\n\t{\r\n\t\tif(intval($_REQUEST['parent'])!=$this->id)\t// protection against selecting this same category as parent of itself\r\n {\r\n $this->parent \t\t= intval($_REQUEST['parent']);\r\n }\r\n\t\t\t\r\n\t\t$this->template \t= $_REQUEST['template'];\r\n\t\t$this->access\t\t= intval($_REQUEST['access']);\r\n\r\n $this->groups\t = $_REQUEST['groups'];\r\n if($this->access < 3)\r\n {\r\n $this->groups = array();\r\n }\r\n\r\n\t\t$this->permission\t= intval($_REQUEST['permission']);\t\t\r\n\t\t$this->visible\t\t= intval($_REQUEST['visible']);\t\t\r\n\t\t\r\n\t\t$this->date_published\t= (empty($_REQUEST['date_published'])? '' : core_date2ts($_REQUEST['date_published']));\t\r\n\t\t$this->date_unpublish\t= (empty($_REQUEST['date_unpublish'])? '' : core_date2ts($_REQUEST['date_unpublish']));\t\r\n\t\t\r\n\t\t// language strings and options\r\n\t\t$this->dictionary = array();\r\n\t\t$this->paths = array();\r\n\r\n\t\t$fields = array('title', 'action-type', 'action-jump-item', 'action-jump-branch', 'action-new-window', 'action-masked-redirect'); //, 'path', 'visible');\r\n\t\tforeach($_REQUEST as $key => $value)\r\n\t\t{\r\n\t\t\tif(empty($value))\r\n {\r\n continue;\r\n }\r\n\t\t\t\r\n\t\t\tforeach($fields as $field)\r\n\t\t\t{\r\n\t\t\t\tif(substr($key, 0, strlen($field.'-'))==$field.'-')\r\n {\r\n $this->dictionary[substr($key, strlen($field.'-'))][$field] = $value;\r\n }\r\n\t\t\t}\r\n\t\t\r\n\t\t\tif(substr($key, 0, strlen('path-'))=='path-')\r\n {\r\n $this->paths[substr($key, strlen('path-'))] = $value;\r\n }\r\n\t\t}\t\t\r\n\t}\r", "label_name": "CWE-79", "label": 1} +{"code": " $sort = in_array(strtolower($val), array('asc', 'desc')) ? ' ' . $val : '';\n $array[] = $this->parseKey($key, true) . $sort;\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function display_sdm_stats_meta_box($post) { //Stats metabox\n\t$old_count = get_post_meta($post->ID, 'sdm_count_offset', true);\n\t$value = isset($old_count) && $old_count != '' ? $old_count : '0';\n\n\t// Get checkbox for \"disable download logging\"\n\t$no_logs = get_post_meta($post->ID, 'sdm_item_no_log', true);\n\t$checked = isset($no_logs) && $no_logs === 'on' ? 'checked=\"checked\"' : '';\n\n\t_e('These are the statistics for this download item.', 'simple-download-monitor');\n\techo '

    ';\n\n\tglobal $wpdb;\n\t$wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'sdm_downloads WHERE post_id=%s', $post->ID));\n\n\techo '
    ';\n\t_e('Number of Downloads:', 'simple-download-monitor');\n\techo ' ' . $wpdb->num_rows . '';\n\techo '
    ';\n\n\techo '
    ';\n\t_e('Offset Count: ', 'simple-download-monitor');\n\techo '
    ';\n\techo ' ';\n\techo '

    ' . __('Enter any positive or negative numerical value; to offset the download count shown to the visitors (when using the download counter shortcode).', 'simple-download-monitor') . '

    ';\n\techo '
    ';\n\n\techo '
    ';\n\techo '
    ';\n\techo '';\n\techo '';\n\t_e('Disable download logging for this item.', 'simple-download-monitor');\n\techo '
    ';\n\n\twp_nonce_field('sdm_count_offset_nonce', 'sdm_count_offset_nonce_check');\n }", "label_name": "CWE-79", "label": 1} +{"code": "function init_args()\n{\n\t$_REQUEST=strings_stripSlashes($_REQUEST);\n\t\n\n\t$args = new stdClass();\n\t$args->req_spec_id = isset($_REQUEST['req_spec_id']) ? $_REQUEST['req_spec_id'] : 0;\n\t$args->doCompare = isset($_REQUEST['doCompare']) ? true : false;\n\t$args->left_item_id = isset($_REQUEST['left_item_id']) ? intval($_REQUEST['left_item_id']) : -1;\n\t$args->right_item_id = isset($_REQUEST['right_item_id']) ? intval($_REQUEST['right_item_id']) : -1;\n\t$args->tproject_id = isset($_SESSION['testprojectID']) ? $_SESSION['testprojectID'] : 0;\n\t$args->useDaisyDiff = (isset($_REQUEST['diff_method']) && ($_REQUEST['diff_method'] == 'htmlCompare')) ? 1 : 0;\n\t\n\n\t$diffEngineCfg = config_get(\"diffEngine\");\n\t$args->context = null;\n\tif( !isset($_REQUEST['context_show_all'])) \n\t{\n\t\t$args->context = (isset($_REQUEST['context']) && is_numeric($_REQUEST['context'])) ? $_REQUEST['context'] : $diffEngineCfg->context;\n\t}\n\t\n\treturn $args;\n}", "label_name": "CWE-89", "label": 0} +{"code": "function init_args() {\n\t\n\t$args = new stdClass();\n\t\n\t$_REQUEST = strings_stripSlashes($_REQUEST);\n\t\n\t$args->build_id = isset($_REQUEST['build_id']) ? $_REQUEST['build_id'] : 0;\n\t$args->confirmed = isset($_REQUEST['confirmed']) && $_REQUEST['confirmed'] == 'yes' ? true : false;\n\t\n\t$args->user_id = $_SESSION['userID'];\n\t$args->testproject_id = $_SESSION['testprojectID'];\n\t$args->testproject_name = $_SESSION['testprojectName'];\n\t\n\t$args->refreshTree = isset($_SESSION['setting_refresh_tree_on_action']) ?\n\t $_SESSION['setting_refresh_tree_on_action'] : false;\n\t\n\treturn $args;\n}", "label_name": "CWE-89", "label": 0} +{"code": " public function getRawRevisionsAndCount($limit, PFUser $author)\n {\n return svn_get_revisions(\n $this->project,\n 0,\n $limit,\n '',\n $author->getUserName(),\n '',\n '',\n 0,\n false\n );\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function getQueryGroupby()\n {\n return '';\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function getQuerySelect()\n {\n return \"a.per_tracker_artifact_id AS `\" . $this->name . \"`\";\n }", "label_name": "CWE-89", "label": 0} +{"code": " $parent = $dIF->getItemFromDb($item->getParentId());\n $content .= '';\n $content .= '' . 'getId() . '\">' . $item->getTitle() . '';\n $content .= '';\n if ($parent === null || $dIF->isRoot($parent)) {\n $content .= '';\n } else {\n $content .= 'defaultUrl . '&action=show&id=' . $parent->getId() . '\">' . $parent->getTitle() . '';\n }\n $content .= '' . $hp->purify($uH->getDisplayNameFromUserId($row['user_id'])) . '';\n $content .= '' . format_date($GLOBALS['Language']->getText('system', 'datefmt'), $row['lock_date']) . '';\n $content .= '';\n }\n }", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function column_description( $item ) {\n\t\t$return = $item->object_name;\n\t\t\n\t\tswitch ( $item->object_type ) {\n\t\t\tcase 'Post' :\n\t\t\t\t$return = sprintf( '%s', get_edit_post_link( $item->object_id ), $item->object_name );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'Taxonomy' :\n\t\t\t\tif ( ! empty( $item->object_id ) )\n\t\t\t\t\t$return = sprintf( '%s', get_edit_term_link( $item->object_id, $item->object_subtype ), $item->object_name );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'Comments' :\n\t\t\t\tif ( ! empty( $item->object_id ) && $comment = get_comment( $item->object_id ) ) {\n\t\t\t\t\t$return = sprintf( '%s #%d', get_edit_comment_link( $item->object_id ), $item->object_name, $item->object_id );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'Export' :\n\t\t\t\tif ( 'all' === $item->object_name ) {\n\t\t\t\t\t$return = __( 'All', 'aryo-activity-log' );\n\t\t\t\t} else {\n\t\t\t\t\t$pt = get_post_type_object( $item->object_name );\n\t\t\t\t\t$return = ! empty( $pt->label ) ? $pt->label : $item->object_name;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'Options' :\n\t\t\tcase 'Core' :\n\t\t\t\t$return = __( $item->object_name, 'aryo-activity-log' );\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\t$return = apply_filters( 'aal_table_list_column_description', $return, $item );\n\t\t\n\t\treturn $return;\n\t}", "label_name": "CWE-79", "label": 1} +{"code": " protected function itemLock($hashes, $autoUnlock = true)\n {\n if (!elFinder::$commonTempPath) {\n return;\n }\n if (!is_array($hashes)) {\n $hashes = array($hashes);\n }\n foreach ($hashes as $hash) {\n $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';\n if ($this->itemLocked($hash)) {\n $cnt = file_get_contents($lock) + 1;\n } else {\n $cnt = 1;\n }\n if (file_put_contents($lock, $cnt, LOCK_EX)) {\n if ($autoUnlock) {\n $this->autoUnlocks[] = $hash;\n }\n }\n }\n }", "label_name": "CWE-918", "label": 16} +{"code": " $files[$i] = '.' . DIRECTORY_SEPARATOR . basename($file);\n }\n $files = array_map('escapeshellarg', $files);\n\n $cmd = $arc['cmd'] . ' ' . $arc['argc'] . ' ' . escapeshellarg($name) . ' ' . implode(' ', $files);\n $err_out = '';\n $this->procExec($cmd, $o, $c, $err_out, $dir);\n chdir($cwd);\n } else {\n return false;\n }\n }\n $path = $dir . DIRECTORY_SEPARATOR . $name;\n return file_exists($path) ? $path : false;\n }", "label_name": "CWE-78", "label": 6} +{"code": " protected function remove($path, $force = false)\n {\n $stat = $this->stat($path);\n\n if (empty($stat)) {\n return $this->setError(elFinder::ERROR_RM, $path, elFinder::ERROR_FILE_NOT_FOUND);\n }\n\n $stat['realpath'] = $path;\n $this->rmTmb($stat);\n $this->clearcache();\n\n if (!$force && !empty($stat['locked'])) {\n return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));\n }\n\n if ($stat['mime'] == 'directory' && empty($stat['thash'])) {\n $ret = $this->delTree($this->convEncIn($path));\n $this->convEncOut();\n if (!$ret) {\n return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));\n }\n } else {\n if ($this->convEncOut(!$this->_unlink($this->convEncIn($path)))) {\n return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));\n }\n $this->clearstatcache();\n }\n\n $this->removed[] = $stat;\n return true;\n }", "label_name": "CWE-918", "label": 16} +{"code": " protected function _copy($source, $targetDir, $name)\n {\n $res = false;\n\n $target = $this->_joinPath($targetDir, $name);\n if ($this->tmp) {\n $local = $this->getTempFile();\n\n if ($this->connect->get($source, $local)\n && $this->connect->put($target, $local, NET_SFTP_LOCAL_FILE)) {\n $res = true;\n }\n unlink($local);\n } else {\n //not memory efficient\n $res = $this->_filePutContents($target, $this->_getContents($source));\n }\n\n return $res;\n }", "label_name": "CWE-918", "label": 16} +{"code": " protected function _mkfile($path, $name)\n {\n $path = $this->_joinPath($path, $name);\n return $this->connect->put($path, '') ? $path : false;\n/*\n if ($this->tmp) {\n $path = $this->_joinPath($path, $name);\n $local = $this->getTempFile();\n $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);\n unlink($local);\n return $res ? $path : false;\n }\n\n return false;\n */\n }", "label_name": "CWE-22", "label": 2} +{"code": " protected function _mkfile($path, $name)\n {\n $path = $this->_joinPath($path, $name);\n return $this->connect->put($path, '') ? $path : false;\n/*\n if ($this->tmp) {\n $path = $this->_joinPath($path, $name);\n $local = $this->getTempFile();\n $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);\n unlink($local);\n return $res ? $path : false;\n }\n\n return false;\n */\n }", "label_name": "CWE-918", "label": 16} +{"code": " protected function _save($fp, $dir, $name, $stat)\n {\n //TODO optionally encrypt $fp before uploading if mime is not already encrypted type\n $path = $this->_joinPath($dir, $name);\n return $this->connect->put($path, $fp)\n ? $path\n : false;\n }", "label_name": "CWE-78", "label": 6} +{"code": " function prepareInputForAdd($input) {\n\n if (isset($input[\"passwd\"])) {\n if (empty($input[\"passwd\"])) {\n unset($input[\"passwd\"]);\n } else {\n $input[\"passwd\"] = Toolbox::encrypt(stripslashes($input[\"passwd\"]), GLPIKEY);\n }\n }\n\n if (isset($input['mail_server']) && !empty($input['mail_server'])) {\n $input[\"host\"] = Toolbox::constructMailServerConfig($input);\n }\n\n if (!NotificationMailing::isUserAddressValid($input['name'])) {\n Session::addMessageAfterRedirect(__('Invalid email address'), false, ERROR);\n }\n\n return $input;\n }", "label_name": "CWE-798", "label": 18} +{"code": " public function boot()\n {\n // Configure the debugbar\n Config::set('debugbar', Config::get('rainlab.debugbar::config'));\n\n // Service provider\n App::register('\\Barryvdh\\Debugbar\\ServiceProvider');\n\n // Register alias\n $alias = AliasLoader::getInstance();\n $alias->alias('Debugbar', '\\Barryvdh\\Debugbar\\Facade');\n\n // Register middleware\n if (Config::get('app.debugAjax', false)) {\n $this->app['Illuminate\\Contracts\\Http\\Kernel']->pushMiddleware('\\RainLab\\Debugbar\\Middleware\\Debugbar');\n }\n\n Event::listen('cms.page.beforeDisplay', function ($controller, $url, $page) {\n // Only show for authenticated backend users\n if (!BackendAuth::check()) {\n Debugbar::disable();\n }\n\n // Twig extensions\n $twig = $controller->getTwig();\n if (!$twig->hasExtension(\\Barryvdh\\Debugbar\\Twig\\Extension\\Debug::class)) {\n $twig->addExtension(new \\Barryvdh\\Debugbar\\Twig\\Extension\\Debug($this->app));\n $twig->addExtension(new \\Barryvdh\\Debugbar\\Twig\\Extension\\Stopwatch($this->app));\n }\n });\n }", "label_name": "CWE-532", "label": 28} +{"code": " public function redirect($route, $code = null)\n {\n /** @var Uri $uri */\n $uri = $this['uri'];\n\n //Check for code in route\n $regex = '/.*(\\[(30[1-7])\\])$/';\n preg_match($regex, $route, $matches);\n if ($matches) {\n $route = str_replace($matches[1], '', $matches[0]);\n $code = $matches[2];\n }\n\n if ($code === null) {\n $code = $this['config']->get('system.pages.redirect_default_code', 302);\n }\n\n if (isset($this['session'])) {\n $this['session']->close();\n }\n\n if ($uri->isExternal($route)) {\n $url = $route;\n } else {\n $url = rtrim($uri->rootUrl(), '/') . '/';\n\n if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {\n $url .= trim($route, '/'); // Remove trailing slash\n } else {\n $url .= ltrim($route, '/'); // Support trailing slash default routes\n }\n }\n\n header(\"Location: {$url}\", true, $code);\n exit();\n }", "label_name": "CWE-601", "label": 11} +{"code": " $contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('manufacturers.php', 'page=' . $_GET['page'] . '&mID=' . (int)$mInfo->manufacturers_id), null, null, 'btn-light')];", "label_name": "CWE-79", "label": 1} +{"code": " $contents = ['form' => tep_draw_form('reviews', 'reviews.php', 'page=' . $_GET['page'] . '&rID=' . $rInfo->reviews_id . '&action=deleteconfirm')];", "label_name": "CWE-79", "label": 1} +{"code": " $contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, null, null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('tax_classes.php', 'page=' . $_GET['page']), null, null, 'btn-light')];", "label_name": "CWE-79", "label": 1} +{"code": " $contents = ['form' => tep_draw_form('zones', 'zones.php', 'page=' . $_GET['page'] . '&action=insert')];", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function admin_log($mode = '')\n\t{\n\t\t$errorLogPath = TMP . 'logs' . DS . 'error.log';\n\t\tswitch($mode) {\n\t\t\tcase 'download':\n\t\t\t\tset_time_limit(0);\n\t\t\t\tif ($this->_downloadErrorLog()) {\n\t\t\t\t\texit();\n\t\t\t\t}\n\t\t\t\t$this->BcMessage->setInfo('\u30a8\u30e9\u30fc\u30ed\u30b0\u304c\u5b58\u5728\u3057\u307e\u305b\u3093\u3002');\n\t\t\t\t$this->redirect(['action' => 'log']);\n\t\t\t\tbreak;\n\t\t\tcase 'delete':\n\t\t\t\t$this->_checkSubmitToken();\n\t\t\t\tif (file_exists($errorLogPath)) {\n\t\t\t\t\tif (unlink($errorLogPath)) {\n\t\t\t\t\t\t$messages[] = __d('baser', '\u30a8\u30e9\u30fc\u30ed\u30b0\u3092\u524a\u9664\u3057\u307e\u3057\u305f\u3002');\n\t\t\t\t\t\t$error = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$messages[] = __d('baser', '\u30a8\u30e9\u30fc\u30ed\u30b0\u304c\u524a\u9664\u3067\u304d\u307e\u305b\u3093\u3067\u3057\u305f\u3002');\n\t\t\t\t\t\t$error = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t$messages[] = __d('baser', '\u30a8\u30e9\u30fc\u30ed\u30b0\u304c\u5b58\u5728\u3057\u307e\u305b\u3093\u3002');\n\t\t\t\t\t$error = false;\n\t\t\t\t}\n\n\t\t\t\tif ($messages) {\n\t\t\t\t\t$this->BcMessage->set(implode(\"\\n\", $messages), $error);\n\t\t\t\t}\n\t\t\t\t$this->redirect(['action' => 'log']);\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\t$fileSize = 0;\n\t\tif (file_exists($errorLogPath)) {\n\t\t\t$fileSize = filesize($errorLogPath);\n\t\t}\n\n\t\t$this->pageTitle = __d('baser', '\u30c7\u30fc\u30bf\u30e1\u30f3\u30c6\u30ca\u30f3\u30b9');\n\t\t$this->help = 'tools_log';\n\t\t$this->set('fileSize', $fileSize);\n\t}", "label_name": "CWE-78", "label": 6} +{"code": "\tpublic function admin_write_schema()\n\t{\n\t\t$path = TMP . 'schemas' . DS;\n\n\t\t/* \u8868\u793a\u8a2d\u5b9a */\n\t\t$this->pageTitle = __d('baser', '\u30b9\u30ad\u30fc\u30de\u30d5\u30a1\u30a4\u30eb\u751f\u6210');\n\t\t$this->help = 'tools_write_schema';\n\n\t\tif (!$this->request->data) {\n\t\t\t$this->request->data['Tool']['connection'] = 'core';\n\t\t\treturn;\n\t\t}\n\n\t\tif (empty($this->request->data['Tool'])) {\n\t\t\t$this->BcMessage->setError(__d('baser', '\u30c6\u30fc\u30d6\u30eb\u3092\u9078\u629e\u3057\u3066\u304f\u3060\u3055\u3044\u3002'));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!$this->_resetTmpSchemaFolder()) {\n\t\t\t$this->BcMessage->setError('\u30d5\u30a9\u30eb\u30c0\uff1a' . $path . ' \u304c\u5b58\u5728\u3059\u308b\u304b\u78ba\u8a8d\u3057\u3001\u5b58\u5728\u3059\u308b\u5834\u5408\u306f\u3001\u524a\u9664\u3059\u308b\u304b\u66f8\u8fbc\u6a29\u9650\u3092\u4e0e\u3048\u3066\u304f\u3060\u3055\u3044\u3002');\n\t\t\t$this->redirect(['action' => 'write_schema']);\n\t\t}\n\t\tif (!$this->Tool->writeSchema($this->request->data, $path)) {\n\t\t\t$this->BcMessage->setError(__d('baser', '\u30b9\u30ad\u30fc\u30de\u30d5\u30a1\u30a4\u30eb\u306e\u751f\u6210\u306b\u5931\u6557\u3057\u307e\u3057\u305f\u3002'));\n\t\t\treturn;\n\t\t}\n\n\t\t$Simplezip = new Simplezip();\n\t\t$Simplezip->addFolder($path);\n\t\t$Simplezip->download('schemas');\n\t\texit();\n\t}", "label_name": "CWE-78", "label": 6} +{"code": " protected function redirectToOperator(Thread $thread, $operator_id)\n {\n if ($thread->state != Thread::STATE_CHATTING) {\n // We can redirect only threads which are in proggress now.\n return false;\n }\n\n // Redirect the thread\n $thread->state = Thread::STATE_WAITING;\n $thread->nextAgent = $operator_id;\n $thread->agentId = 0;\n\n // Check if the target operator belongs to the current thread's group.\n // If not reset the current thread's group.\n if ($thread->groupId != 0) {\n $db = Database::getInstance();\n list($groups_count) = $db->query(\n (\"SELECT count(*) AS count \"\n . \"FROM {operatortoopgroup} \"\n . \"WHERE operatorid = ? AND groupid = ?\"),\n array($operator_id, $thread->groupId),\n array(\n 'return_rows' => Database::RETURN_ONE_ROW,\n 'fetch_type' => Database::FETCH_NUM,\n )\n );\n if ($groups_count === 0) {\n $thread->groupId = 0;\n }\n }\n\n $thread->save();\n\n // Send notification message\n $thread->postMessage(\n Thread::KIND_EVENTS,\n getlocal(\n 'Operator {0} redirected you to another operator. Please wait a while.',\n array(get_operator_name($this->getOperator())),\n $thread->locale,\n true\n )\n );\n\n return true;\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function rename(){\n\n if($this->request->isMethod('POST')){\n\n if(\\Storage::move($this->request->input('old_file'), $this->request->input('new_file'))){\n if($this->request->ajax()){\n return response()->json(['success' => trans('File successfully renamed!')]);\n }\n }else{\n if($this->request->ajax()){\n return response()->json(['danger' => trans('message.something_went_wrong')]);\n }\n }\n\n }\n\n }", "label_name": "CWE-434", "label": 5} +{"code": " public static function loadFrom(Db $zdb, $id, $mailing, $new = true)\n {\n try {\n $select = $zdb->select(self::TABLE);\n $select->where('mailing_id = ' . $id);\n\n $results = $zdb->execute($select);\n $result = $results->current();\n\n return $mailing->loadFromHistory($result, $new);\n } catch (Throwable $e) {\n Analog::log(\n 'Unable to load mailing model #' . $id . ' | ' .\n $e->getMessage(),\n Analog::WARNING\n );\n throw $e;\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " public static function loadFieldType(Db $zdb, $id)\n {\n try {\n $select = $zdb->select(self::TABLE);\n $select->where('field_id = ' . $id);\n\n $results = $zdb->execute($select);\n $result = $results->current();\n if ($result) {\n $field_type = $result->field_type;\n $field_type = self::getFieldType($zdb, $field_type);\n $field_type->loadFromRs($result);\n return $field_type;\n }\n } catch (Throwable $e) {\n Analog::log(\n __METHOD__ . ' | Unable to retrieve field `' . $id .\n '` information | ' . $e->getMessage(),\n Analog::ERROR\n );\n return false;\n }\n return false;\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function load($id)\n {\n try {\n $select = $this->zdb->select($this->table);\n $select->where($this->fpk . ' = ' . $id);\n\n $results = $this->zdb->execute($select);\n if ($results->count() > 0) {\n $result = $results->current();\n $this->loadFromRS($result);\n\n return true;\n } else {\n Analog::log(\n 'Unknown ID ' . $id,\n Analog::ERROR\n );\n return false;\n }\n } catch (Throwable $e) {\n Analog::log(\n 'Cannot load ' . $this->getType() . ' from id `' . $id . '` | ' .\n $e->getMessage(),\n Analog::WARNING\n );\n throw $e;\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function delete($id)\n {\n $ret = $this->get($id);\n if (!$ret) {\n /* get() already logged */\n return self::ID_NOT_EXITS;\n }\n\n if ($this->isUsed($id)) {\n $this->errors[] = _T(\"Cannot delete this label: it's still used\");\n return false;\n }\n\n try {\n $this->zdb->connection->beginTransaction();\n $delete = $this->zdb->delete($this->table);\n $delete->where($this->fpk . ' = ' . $id);\n\n $this->zdb->execute($delete);\n $this->deleteTranslation($ret->{$this->flabel});\n\n Analog::log(\n $this->getType() . ' ' . $id . ' deleted successfully.',\n Analog::INFO\n );\n\n $this->zdb->connection->commit();\n return true;\n } catch (Throwable $e) {\n $this->zdb->connection->rollBack();\n Analog::log(\n 'Unable to delete ' . $this->getType() . ' ' . $id .\n ' | ' . $e->getMessage(),\n Analog::ERROR\n );\n throw $e;\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": " $subgroup->remove(true);\n }\n }\n\n Analog::log(\n 'Cascading remove ' . $this->group_name .\n '. Members and managers will be detached.',\n Analog::INFO\n );\n\n //delete members\n $delete = $zdb->delete(self::GROUPSUSERS_TABLE);\n $delete->where(\n self::PK . ' = ' . $this->id\n );\n $zdb->execute($delete);\n\n //delete managers\n $delete = $zdb->delete(self::GROUPSMANAGERS_TABLE);\n $delete->where(\n self::PK . ' = ' . $this->id\n );\n $zdb->execute($delete);\n }\n\n //delete group itself\n $delete = $zdb->delete(self::TABLE);\n $delete->where(\n self::PK . ' = ' . $this->id\n );\n $zdb->execute($delete);\n\n //commit all changes\n if ($transaction) {\n $zdb->connection->commit();\n }\n\n return true;\n } catch (Throwable $e) {\n if ($transaction) {\n $zdb->connection->rollBack();\n }\n if ($e->getCode() == 23000) {\n Analog::log(\n str_replace(\n '%group',\n $this->group_name,\n 'Group \"%group\" still have members!'\n ),\n Analog::WARNING\n );\n $this->isempty = false;\n } else {\n Analog::log(\n 'Unable to delete group ' . $this->group_name .\n ' (' . $this->id . ') |' . $e->getMessage(),\n Analog::ERROR\n );\n throw $e;\n }\n return false;\n }\n }", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\t\t\tunset($return[$key]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn @array_change_key_case($return, CASE_UPPER);\n}", "label_name": "CWE-22", "label": 2} +{"code": "function db_properties($table)\n{\n\tglobal $DatabaseType, $DatabaseUsername;\n\n\tswitch ($DatabaseType) {\n\t\tcase 'mysqli':\n\t\t\t$result = DBQuery(\"SHOW COLUMNS FROM $table\");\n\t\t\twhile ($row = db_fetch_row($result)) {\n\t\t\t\t$properties[strtoupper($row['FIELD'])]['TYPE'] = strtoupper($row['TYPE'], strpos($row['TYPE'], '('));\n\t\t\t\tif (!$pos = strpos($row['TYPE'], ','))\n\t\t\t\t\t$pos = strpos($row['TYPE'], ')');\n\t\t\t\telse\n\t\t\t\t\t$properties[strtoupper($row['FIELD'])]['SCALE'] = substr($row['TYPE'], $pos + 1);\n\n\t\t\t\t$properties[strtoupper($row['FIELD'])]['SIZE'] = substr($row['TYPE'], strpos($row['TYPE'], '(') + 1, $pos);\n\n\t\t\t\tif ($row['NULL'] != '')\n\t\t\t\t\t$properties[strtoupper($row['FIELD'])]['NULL'] = \"Y\";\n\t\t\t\telse\n\t\t\t\t\t$properties[strtoupper($row['FIELD'])]['NULL'] = \"N\";\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn $properties;\n}", "label_name": "CWE-79", "label": 1} +{"code": "function DateInputAY($value, $name, $counter = 1, $placeholder = _enterDate)\n{\n\n $show = \"\";\n $date_sep = \"\";\n $monthVal = \"\";\n $yearVal = \"\";\n $dayVal = \"\";\n $display = \"\";\n\n if ($value != '')\n return '
    ' . ProperDateAY($value) . '     
    ';\n else {\n if ($counter == 2)\n return '';\n else\n return '';\n }\n}", "label_name": "CWE-22", "label": 2} +{"code": "function db_case($array)\n{\n global $DatabaseType;\n\n $counter = 0;\n if ($DatabaseType == 'mysqli') {\n $array_count = count($array);\n $string = \" CASE WHEN $array[0] =\";\n $counter++;\n $arr_count = count($array);\n for ($i = 1; $i < $arr_count; $i++) {\n $value = $array[$i];\n\n if ($value == \"''\" && substr($string, -1) == '=') {\n $value = ' IS NULL';\n $string = substr($string, 0, -1);\n }\n\n $string .= \"$value\";\n if ($counter == ($array_count - 2) && $array_count % 2 == 0)\n $string .= \" ELSE \";\n elseif ($counter == ($array_count - 1))\n $string .= \" END \";\n elseif ($counter % 2 == 0)\n $string .= \" WHEN $array[0]=\";\n elseif ($counter % 2 == 1)\n $string .= \" THEN \";\n\n $counter++;\n }\n }\n\n return $string;\n}", "label_name": "CWE-79", "label": 1} +{"code": "function singleQuoteReplace($param1 = false, $param2 = false, $param3)\n{\n return str_replace(\"'\", \"''\", str_replace(\"\\'\", \"'\", $param3));\n}", "label_name": "CWE-22", "label": 2} +{"code": " $percent = round($percent, 0);\n } else {\n $percent = round($percent, 2); // school default\n }\n if ($ret == '%')\n return $percent;\n\n if (!$_openSIS['_makeLetterGrade']['grades'][$grade_scale_id])\n $_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] = DBGet(DBQuery('SELECT TITLE,ID,BREAK_OFF FROM report_card_grades WHERE SYEAR=\\'' . $cp[1]['SYEAR'] . '\\' AND SCHOOL_ID=\\'' . $cp[1]['SCHOOL_ID'] . '\\' AND GRADE_SCALE_ID=\\'' . $grade_scale_id . '\\' ORDER BY BREAK_OFF IS NOT NULL DESC,BREAK_OFF DESC,SORT_ORDER'));\n\n foreach ($_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] as $grade) {\n if ($does_breakoff == 'Y' ? $percent >= $programconfig[$staff_id][$course_period_id . '-' . $grade['ID']] && is_numeric($programconfig[$staff_id][$course_period_id . '-' . $grade['ID']]) : $percent >= $grade['BREAK_OFF'])\n return $ret == 'ID' ? $grade['ID'] : $grade['TITLE'];\n }\n}", "label_name": "CWE-22", "label": 2} +{"code": "function db_start()\n{\n global $DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort, $DatabaseType;\n\n switch ($DatabaseType) {\n case 'mysqli':\n $connection = new mysqli($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);\n break;\n }\n\n // Error code for both.\n if ($connection === false) {\n switch ($DatabaseType) {\n case 'mysqli':\n $errormessage = mysqli_error($connection);\n break;\n }\n db_show_error(\"\", \"\" . _couldNotConnectToDatabase . \": $DatabaseServer\", $errormessage);\n }\n return $connection;\n}", "label_name": "CWE-79", "label": 1} +{"code": "function db_seq_nextval($seqname)\n{\n global $DatabaseType;\n\n if ($DatabaseType == 'mysqli')\n $seq = \"fn_\" . strtolower($seqname) . \"()\";\n\n return $seq;\n}", "label_name": "CWE-79", "label": 1} +{"code": " echo '' . htmlentities($value_arr['LANGUAGE']) . '';\n foreach ($value_arr['ENROLLMENT_INFO'] as $eid => $ed) {\n echo '';\n echo '' . htmlentities($ed['SCHOOL_ID']) . '';\n echo '' . htmlentities($ed['CALENDAR']) . '';\n echo '' . htmlentities($ed['GRADE']) . '';\n echo '
    ' . htmlentities($ed['SECTION']) . '
    ';\n echo '' . htmlentities($ed['START_DATE']) . '';\n echo '' . htmlentities($ed['DROP_DATE']) . '';\n echo '' . htmlentities($ed['ENROLLMENT_CODE']) . '';\n echo '' . htmlentities($ed['DROP_CODE']) . '';\n echo '
    ';\n }\n echo '';\n }\n echo '';\n }", "label_name": "CWE-79", "label": 1} +{"code": " foreach($course_RET as $period_day)\n {\n $period_days_append_sql .=\"(sp.start_time<='$period_day[END_TIME]' AND '$period_day[START_TIME]'<=sp.end_time AND DAYS LIKE '%$period_day[DAYS]%') OR \";\n }", "label_name": "CWE-22", "label": 2} +{"code": "function _makeMpName($value) {\n if ($value != '') {\n $get_name = DBGet(DBQuery('SELECT TITLE FROM marking_periods WHERE marking_period_id=' . $value));\n return $get_name[1]['TITLE'];\n } else\n return ''._customCoursePeriod.'';\n}", "label_name": "CWE-22", "label": 2} +{"code": " foreach ($value as $i => $j) {\n\n\n $column_check = explode('_', $i);\n if ($column_check[0] == 'CUSTOM') {\n $check_validity = DBGet(DBQuery('SELECT COUNT(*) as REC_EX FROM school_custom_fields WHERE ID=' . $column_check[1] . ' AND (SCHOOL_ID=' . $get_school_info[$key]['ID'].' OR SCHOOL_ID=0)'));\n if ($check_validity[1]['REC_EX'] == 0)\n $j = 'NOT_AVAILABLE_FOR';\n }\n $get_school_info[$key][$i] = trim($j);\n }", "label_name": "CWE-22", "label": 2} +{"code": " public function __construct($message, $code = 0, Exception $previous = null)\n {\n parent::__construct($message, $code, $previous);\n }", "label_name": "CWE-307", "label": 26} +{"code": " public function __construct($message, $code = 0, Exception $previous = null)\n {\n parent::__construct($message, $code, $previous);\n }", "label_name": "CWE-307", "label": 26} +{"code": " public function pageToContainedHtml(Page $page)\n {\n $page->html = (new PageContent($page))->render();\n $pageHtml = view('pages.export', [\n 'page' => $page,\n 'format' => 'html',\n ])->render();\n\n return $this->containHtml($pageHtml);\n }", "label_name": "CWE-79", "label": 1} +{"code": " protected function configure()\n {\n $this\n ->setName('kimai:version')\n ->setDescription('Receive version information')\n ->setHelp('This command allows you to fetch various version information about Kimai.')\n ->addOption('name', null, InputOption::VALUE_NONE, 'Display the major release name')\n ->addOption('candidate', null, InputOption::VALUE_NONE, 'Display the current version candidate (e.g. \"stable\" or \"dev\")')\n ->addOption('short', null, InputOption::VALUE_NONE, 'Display the version only')\n ->addOption('semver', null, InputOption::VALUE_NONE, 'Semantical versioning (SEMVER) compatible version string')\n ;\n }", "label_name": "CWE-1236", "label": 12} +{"code": " public function testBuild()\n {\n $version = Constants::VERSION;\n $versionParts = explode('.', $version);\n $major = (int) $versionParts[0];\n $minor = (int) $versionParts[1];\n $patch = isset($versionParts[2]) ? (int) $versionParts[2] : 0;\n\n $expectedId = $major * 10000 + $minor * 100 + $patch;\n\n self::assertEquals('1.14', Constants::VERSION, 'Invalid release number');\n self::assertTrue(\\in_array(Constants::STATUS, ['dev', 'stable']), 'Invalid status');\n self::assertEquals($expectedId, Constants::VERSION_ID, 'Invalid version ID');\n }", "label_name": "CWE-1236", "label": 12} +{"code": " public function uploadCompanyLogo(Request $request)\n {\n $company = Company::find($request->header('company'));\n\n $this->authorize('manage company', $company);\n\n $data = json_decode($request->company_logo);\n\n if ($data) {\n $company = Company::find($request->header('company'));\n\n if ($company) {\n $company->clearMediaCollection('logo');\n\n $company->addMediaFromBase64($data->data)\n ->usingFileName($data->name)\n ->toMediaCollection('logo');\n }\n }\n\n return response()->json([\n 'success' => true,\n ]);\n }", "label_name": "CWE-434", "label": 5} +{"code": "\t\t\tlist($h, $m) = explode('.', $row['RunAt']);\n\n\t\t\t$main .= '
    ';\n\t\t\t$main .= '

    ' . $row['Title'] . '

    ';\n\n\t\t\tif(!empty($systems_for_schedule))\n\t\t\t{\n\t\t\t\tif($row['RunAt'] > date('H.i'))\n\t\t\t\t{\n\t\t\t\t\t$run_in_future = true;\n\t\t\t\t\t$main .= '

    Runs In ' . pts_strings::format_time((($h * 60) + $m) - ((date('H') * 60) + date('i')), 'MINUTES') . '

    ';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$run_in_future = false;\n\t\t\t\t\t$main .= '

    Triggered ' . pts_strings::format_time(max(1, (date('H') * 60) + date('i') - (($h * 60) + $m)), 'MINUTES') . ' Ago

    ';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach($systems_for_schedule as $system_id)\n\t\t\t{\n\t\t\t\t$pprid = self::result_match($row['ScheduleID'], $system_id, date('Y-m-d'));\n\n\t\t\t\tif($pprid)\n\t\t\t\t\t$main .= '';\n\n\t\t\t\t$main .= phoromatic_server::system_id_to_name($system_id);\n\n\t\t\t\tif($pprid)\n\t\t\t\t\t$main .= '';\n\t\t\t\telse if(!$run_in_future)\n\t\t\t\t{\n\t\t\t\t\t$sys_info = self::system_info($system_id);\n\t\t\t\t\t$last_comm_diff = time() - strtotime($sys_info['LastCommunication']);\n\n\t\t\t\t\t$main .= ' ';\n\t\t\t\t\tif($last_comm_diff > 3600)\n\t\t\t\t\t{\n\t\t\t\t\t\t$main .= 'Last Communication: ' . pts_strings::format_time($last_comm_diff, 'SECONDS', true, 60) . ' Ago';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$main .= $sys_info['CurrentTask'];\n\t\t\t\t\t}\n\t\t\t\t\t$main .= '';\n\t\t\t\t}\n\t\t\t\t$main .= '
    ';\n\t\t\t}\n\n\t\t\t$main .= '
    ';\n\t\t}\n\t\t$main .= '

    ';\n\n\t\t$main .= '';\n\n\t\techo '
    ' . $main . '
    ';\n\t\t//echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());\n\t\techo phoromatic_webui_footer();\n\t}", "label_name": "CWE-79", "label": 1} +{"code": "function phoromatic_account_id_to_group_name($account_id)\n{\n\t// XXX deprecated\n\treturn phoromatic_server::account_id_to_group_name($account_id);\n}", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function testDolEval()\n\t{\n\t\tglobal $conf,$user,$langs,$db;\n\t\t$conf=$this->savconf;\n\t\t$user=$this->savuser;\n\t\t$langs=$this->savlangs;\n\t\t$db=$this->savdb;\n\n\t\t$result=dol_eval('1==1', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertTrue($result);\n\n\t\t$result=dol_eval('1==2', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertFalse($result);\n\n\t\tinclude_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';\n\t\tinclude_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';\n\t\t$result=dol_eval('(($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref: \"Parent project not found\"', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertEquals('Parent project not found', $result);\n\n\t\t$result=dol_eval('$a=function() { }; $a;', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('$a=exec(\"ls\");', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('$a=exec (\"ls\")', 1, 1);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('$a=\"test\"; $$a;', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\n\t\t$result=dol_eval('`ls`', 1, 0);\n\t\tprint \"result = \".$result.\"\\n\";\n\t\t$this->assertContains('Bad string syntax to evaluate', $result);\n\t}", "label_name": "CWE-94", "label": 14} +{"code": " private function section($nodes, $id, $filters, $start, $end, $otag, $ctag, $level)\n {\n $source = var_export(substr($this->source, $start, $end - $start), true);\n $callable = $this->getCallable();\n\n if ($otag !== '{{' || $ctag !== '}}') {\n $delimTag = var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);\n $helper = sprintf('$this->lambdaHelper->withDelimiters(%s)', $delimTag);\n $delims = ', ' . $delimTag;\n } else {\n $helper = '$this->lambdaHelper';\n $delims = '';\n }\n\n $key = ucfirst(md5($delims . \"\\n\" . $source));\n\n if (!isset($this->sections[$key])) {\n $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $helper, $delims, $this->walk($nodes, 2));\n }\n\n $method = $this->getFindMethod($id);\n $id = var_export($id, true);\n $filters = $this->getFilters($filters, $level);\n\n return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $method, $id, $filters, $key);\n }", "label_name": "CWE-1336", "label": 30} +{"code": " public static function getIconName($module)\n {\n return isset(static::$iconNames[$module])\n ? static::$iconNames[$module]\n : strtolower(str_replace('_', '-', $module));\n }", "label_name": "CWE-89", "label": 0} +{"code": " public function tableCleanup(int $maxInactiveMinutes = 30)\n {\n $now = new \\DateTime();\n $minutesBack = new \\DateInterval('PT' . $maxInactiveMinutes . 'M');\n $timestamp = $now->sub($minutesBack)->format('Y-m-d H:i:s');\n\n $sql = 'DELETE FROM '.TBL_SESSIONS.'\n WHERE ses_timestamp < ? -- $timestamp\n AND ses_session_id <> ? -- $this->getValue(\\'ses_session_id\\')';\n $this->db->queryPrepared($sql, array($timestamp, $this->getValue('ses_session_id')));\n }", "label_name": "CWE-613", "label": 7} +{"code": "\tpublic function addTab($array)\n\t{\n\t\tif (!$array) {\n\t\t\t$this->setAPIResponse('error', 'no data was sent', 422);\n\t\t\treturn null;\n\t\t}\n\t\t$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);\n\t\t$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();\n\t\t$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();\n\t\t$array['enabled'] = ($array['enabled']) ?? 0;\n\t\t$array['default'] = ($array['default']) ?? 0;\n\t\t$array['type'] = ($array['type']) ?? 1;\n\t\t$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;\n\t\tif (array_key_exists('name', $array)) {\n\t\t\t$array['name'] = htmlspecialchars($array['name']);\n\t\t\tif ($this->isTabNameTaken($array['name'])) {\n\t\t\t\t$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\t$this->setAPIResponse('error', 'Tab name was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('image', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab image was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\t$response = [\n\t\t\tarray(\n\t\t\t\t'function' => 'query',\n\t\t\t\t'query' => array(\n\t\t\t\t\t'INSERT INTO [tabs]',\n\t\t\t\t\t$array\n\t\t\t\t)\n\t\t\t),\n\t\t];\n\t\t$this->setAPIResponse(null, 'Tab added');\n\t\t$this->setLoggerChannel('Tab Management');\n\t\t$this->logger->debug('Added Tab for [' . $array['name'] . ']');\n\t\treturn $this->processQueries($response);\n\t}", "label_name": "CWE-434", "label": 5} +{"code": "\tpublic function addTab($array)\n\t{\n\t\tif (!$array) {\n\t\t\t$this->setAPIResponse('error', 'no data was sent', 422);\n\t\t\treturn null;\n\t\t}\n\t\t$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);\n\t\t$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();\n\t\t$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();\n\t\t$array['enabled'] = ($array['enabled']) ?? 0;\n\t\t$array['default'] = ($array['default']) ?? 0;\n\t\t$array['type'] = ($array['type']) ?? 1;\n\t\t$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;\n\t\tif (array_key_exists('name', $array)) {\n\t\t\t$array['name'] = htmlspecialchars($array['name']);\n\t\t\tif ($this->isTabNameTaken($array['name'])) {\n\t\t\t\t$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\t$this->setAPIResponse('error', 'Tab name was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\tif (!array_key_exists('image', $array)) {\n\t\t\t$this->setAPIResponse('error', 'Tab image was not supplied', 422);\n\t\t\treturn false;\n\t\t}\n\t\t$response = [\n\t\t\tarray(\n\t\t\t\t'function' => 'query',\n\t\t\t\t'query' => array(\n\t\t\t\t\t'INSERT INTO [tabs]',\n\t\t\t\t\t$array\n\t\t\t\t)\n\t\t\t),\n\t\t];\n\t\t$this->setAPIResponse(null, 'Tab added');\n\t\t$this->setLoggerChannel('Tab Management');\n\t\t$this->logger->debug('Added Tab for [' . $array['name'] . ']');\n\t\treturn $this->processQueries($response);\n\t}", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic function updateTab($id, $array)\n\t{\n\t\tif (!$id || $id == '') {\n\t\t\t$this->setAPIResponse('error', 'id was not set', 422);\n\t\t\treturn null;\n\t\t}\n\t\tif (!$array) {\n\t\t\t$this->setAPIResponse('error', 'no data was sent', 422);\n\t\t\treturn null;\n\t\t}\n\t\t$tabInfo = $this->getTabById($id);\n\t\tif ($tabInfo) {\n\t\t\t$array = $this->checkKeys($tabInfo, $array);\n\t\t} else {\n\t\t\t$this->setAPIResponse('error', 'No tab info found', 404);\n\t\t\treturn false;\n\t\t}\n\t\tif (array_key_exists('name', $array)) {\n\t\t\t$array['name'] = htmlspecialchars($array['name']);\n\t\t\tif ($this->isTabNameTaken($array['name'], $id)) {\n\t\t\t\t$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (array_key_exists('default', $array)) {\n\t\t\tif ($array['default']) {\n\t\t\t\t$this->clearTabDefault();\n\t\t\t}\n\t\t}\n\t\t$response = [\n\t\t\tarray(\n\t\t\t\t'function' => 'query',\n\t\t\t\t'query' => array(\n\t\t\t\t\t'UPDATE tabs SET',\n\t\t\t\t\t$array,\n\t\t\t\t\t'WHERE id = ?',\n\t\t\t\t\t$id\n\t\t\t\t)\n\t\t\t),\n\t\t];\n\t\t$this->setAPIResponse(null, 'Tab info updated');\n\t\t$this->setLoggerChannel('Tab Management');\n\t\t$this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');\n\t\treturn $this->processQueries($response);\n\t}", "label_name": "CWE-79", "label": 1} +{"code": "function URLEscape( $string )\n{\n\t$string = preg_replace_callback(\n\t\t// Match both decimal & hex code (although hex codes can contain a-f letters).\n\t\t// Should be enough as the alphabet hex codes only have numbers.\n\t\t\"/(&#x?[0-9]+;?)/i\",\n\t\tfunction( $match ) {\n\t\t\tif ( mb_substr( $match[1], -1 ) !== ';' )\n\t\t\t{\n\t\t\t\t// Fix stored XSS security issue: add semicolon to HTML entity so it can be decoded.\n\t\t\t\t// @link https://www.php.net/manual/en/function.html-entity-decode.php#104617\n\t\t\t\t$match[1] .= ';';\n\t\t\t}\n\n\t\t\treturn $match[1];\n\t\t},\n\t\t$string\n\t);\n\n\t// Fix stored XSS security issue: decode HTML entities from URL.\n\t$string = html_entity_decode( (string) $string );\n\n\t$remove = [\n\t\t// Fix stored XSS security issue: remove inline JS from URL.\n\t\t'javascript:',\n\t];\n\n\tforeach ( $remove as $remove_string )\n\t{\n\t\twhile ( strpos( $string, $remove_string ) !== false )\n\t\t{\n\t\t\t$string = str_ireplace( $remove, '', $string );\n\t\t}\n\t}\n\n\t$entities = [\n\t\t'%21',\n\t\t'%2A',\n\t\t'%27',\n\t\t'%28',\n\t\t'%29',\n\t\t'%3B',\n\t\t'%3A',\n\t\t'%40',\n\t\t'%26',\n\t\t'%3D',\n\t\t'%2B',\n\t\t'%24',\n\t\t'%2C',\n\t\t'%2F',\n\t\t'%3F',\n\t\t'%25',\n\t\t'%23',\n\t\t'%5B',\n\t\t'%5D',\n\t];\n\n\t$replacements = [\n\t\t'!',\n\t\t'*',\n\t\t\"'\",\n\t\t'(',\n\t\t')',\n\t\t';',\n\t\t':',\n\t\t'@',\n\t\t'&',\n\t\t'=',\n\t\t'+',\n\t\t'$',\n\t\t',',\n\t\t'/',\n\t\t'?',\n\t\t'%',\n\t\t'#',\n\t\t'[',\n\t\t']',\n\t];\n\n\treturn str_replace(\n\t\t$entities,\n\t\t$replacements,\n\t\trawurlencode( $string )\n\t);\n}", "label_name": "CWE-79", "label": 1} +{"code": " public function store(CreateAppointmentCalendarRequest $request)\n {\n \n $client_id = null;\n $user = User::where('external_id', $request->user)->first();\n\n if ($request->client_external_id) {\n $client_id = Client::where('external_id', $request->client_external_id)->first()->id;\n if (!$client_id) {\n return response(__(\"Client not found\"), 422);\n }\n }\n\n $request_type = null;\n $request_id = null;\n if ($request->source_type && $request->source_external_id) {\n $request_type = $request->source_type;\n\n $entry = $request_type::whereExternalId($request->source_external_id);\n $request_id = $entry->id;\n }\n\n if (!$user) {\n return response(__(\"User not found\"), 422);\n }\n\n $startTime = str_replace([\"am\", \"pm\", ' '], \"\", $request->start_time) . ':00';\n $endTime = str_replace([\"am\", \"pm\", ' '], \"\", $request->end_time) . ':00';\n\n \n\n $appointment = Appointment::create([\n 'external_id' => Uuid::uuid4()->toString(),\n 'source_type' => $request_type,\n 'source_id' => $request_id,\n 'client_id' => $client_id,\n 'title' => $request->title,\n 'start_at' => Carbon::parse($request->start_date . \" \" . $startTime),\n 'end_at' => Carbon::parse($request->end_date . \" \" . $endTime),\n 'user_id' => $user->id,\n 'color' => $request->color\n ]);\n $appointment->user_external_id = $user->external_id;\n $appointment->start_at = $appointment->start_at;\n\n return response($appointment);\n }", "label_name": "CWE-521", "label": 4} +{"code": " public function anyData()\n {\n $tasks = Task::with(['user', 'status', 'client'])->select(\n collect(['external_id', 'title', 'created_at', 'deadline', 'user_assigned_id', 'status_id', 'client_id'])\n ->map(function ($field) {\n return (new Task())->qualifyColumn($field);\n })\n ->all()\n );\n\n return Datatables::of($tasks)\n ->addColumn('titlelink', '{{$title}}')\n ->editColumn('client', function ($projects) {\n return $projects->client->company_name;\n })\n ->editColumn('created_at', function ($tasks) {\n return $tasks->created_at ? with(new Carbon($tasks->created_at))\n ->format(carbonDate()) : '';\n })\n ->editColumn('deadline', function ($tasks) {\n return $tasks->created_at ? with(new Carbon($tasks->deadline))\n ->format(carbonDate()) : '';\n })\n ->editColumn('user_assigned_id', function ($tasks) {\n return $tasks->user->name;\n })\n ->editColumn('status_id', function ($tasks) {\n return 'status->color . '\"> ' .\n $tasks->status->title . '';\n })\n ->addColumn('view', function ($tasks) {\n return 'external_id) . '\" class=\"btn btn-link\">' . __('View') .''\n . 'external_id) . '\" data-title=\"'. $tasks->title . '\" data-target=\"#deletion\" class=\"btn btn-link\">' . __('Delete') .''\n ;\n })\n ->rawColumns(['titlelink','view', 'status_id'])\n ->make(true);\n }", "label_name": "CWE-79", "label": 1} +{"code": " public function testInfoWithoutUrl()\n {\n $this->assertRequestIsRedirect('info');\n }", "label_name": "CWE-601", "label": 11} +{"code": " public function testInfoWithoutUrl()\n {\n $this->assertRequestIsRedirect('info');\n }", "label_name": "CWE-918", "label": 16} +{"code": "function updateBasicSettings(PDFStructure &$structure) {\n\t// set headline\n\tif (isset($_POST['headline'])) {\n\t\t$structure->setTitle(str_replace('<', '', str_replace('>', '', $_POST['headline'])));\n\t}\n\t// set logo\n\tif (isset($_POST['logoFile'])) {\n\t\t$structure->setLogo($_POST['logoFile']);\n\t}\n\t// set folding marks\n\tif (isset($_POST['foldingmarks'])) {\n\t\t$structure->setFoldingMarks($_POST['foldingmarks']);\n\t}\n}", "label_name": "CWE-79", "label": 1} +{"code": " function get(&$dbh, $proposalId, $handle)\n {\n $sql = \"SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = \". $dbh->quoteSmart($proposalId) .\" AND user_handle= \". $dbh->quoteSmart($handle);\n $res = $dbh->query($sql);\n if (DB::isError($res)) {\n return $res;\n }\n if (!$res->numRows()) {\n return null;\n }\n $set = $res->fetchRow(DB_FETCHMODE_ASSOC);\n $set['reviews'] = unserialize($set['reviews']);\n $vote = new ppVote($set);\n return $vote;\n }", "label_name": "CWE-640", "label": 20} +{"code": "\t\thtml: function (token, attrs, content) {\n\t\t\tvar size = $.inArray(attrs.defaultattr, mybbCmd.fsStr) + 1;\n\t\t\tif (!isNaN(attrs.defaultattr)) {\n\t\t\t\tsize = attrs.defaultattr;\n\t\t\t\tif (size > 7)\n\t\t\t\t\tsize = 7;\n\t\t\t\tif (size < 1)\n\t\t\t\t\tsize = 1;\n\t\t\t}\n\t\t\tif (size < 0) {\n\t\t\t\tsize = 0;\n\t\t\t}\n\t\t\treturn '' + content + '';\n\t\t}", "label_name": "CWE-79", "label": 1} +{"code": " function ComponentRawSourceDialogController(scope, $mdDialog) {\n scope.close = function() {\n $mdDialog.hide();\n };\n }", "label_name": "CWE-79", "label": 1} +{"code": " var url2FilePath = function(url){\n var subPath = url.substr(\"/tests/frontend\".length);\n if (subPath == \"\"){\n subPath = \"index.html\"\n }\n subPath = subPath.split(\"?\")[0];\n\n var filePath = path.normalize(npm.root + \"/../tests/frontend/\")\n filePath += subPath.replace(\"..\", \"\");\n return filePath;\n }", "label_name": "CWE-22", "label": 2} +{"code": " Tooltip.prototype.hide = function (callback) {\n var that = this\n var $tip = $(this.$tip)\n var e = $.Event('hide.bs.' + this.type)\n\n function complete() {\n if (that.hoverState != 'in') $tip.detach()\n that.$element\n .removeAttr('aria-describedby')\n .trigger('hidden.bs.' + that.type)\n callback && callback()\n }\n\n this.$element.trigger(e)\n\n if (e.isDefaultPrevented()) return\n\n $tip.removeClass('in')\n\n $.support.transition && $tip.hasClass('fade') ?\n $tip\n .one('bsTransitionEnd', complete)\n .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :\n complete()\n\n this.hoverState = null\n\n return this\n }", "label_name": "CWE-89", "label": 0} +{"code": "\t_removeCurrentsFromItems: function() {\n\n\t\tvar list = this.currentItem.find(\":data(\" + this.widgetName + \"-item)\");\n\n\t\tthis.items = $.grep(this.items, function (item) {\n\t\t\tfor (var j=0; j < list.length; j++) {\n\t\t\t\tif(list[j] === item.item[0]) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\n\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\tupdate: function(container, p) {\n\n\t\t\t\t\t// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that\n\t\t\t\t\t// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified\n\t\t\t\t\tif(className && !o.forcePlaceholderSize) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item\n\t\t\t\t\tif(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css(\"paddingTop\")||0, 10) - parseInt(that.currentItem.css(\"paddingBottom\")||0, 10)); }\n\t\t\t\t\tif(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css(\"paddingLeft\")||0, 10) - parseInt(that.currentItem.css(\"paddingRight\")||0, 10)); }\n\t\t\t\t}", "label_name": "CWE-89", "label": 0} +{"code": "function hd(a,b,c,d){var e={m:[\"eine Minute\",\"einer Minute\"],h:[\"eine Stunde\",\"einer Stunde\"],d:[\"ein Tag\",\"einem Tag\"],dd:[a+\" Tage\",a+\" Tagen\"],M:[\"ein Monat\",\"einem Monat\"],MM:[a+\" Monate\",a+\" Monaten\"],y:[\"ein Jahr\",\"einem Jahr\"],yy:[a+\" Jahre\",a+\" Jahren\"]};return b?e[c][0]:e[c][1]}", "label_name": "CWE-89", "label": 0} +{"code": "function Md(a,b,c,d){var e=a+\" \";switch(c){case\"s\":return b||d?\"nekaj sekund\":\"nekaj sekundami\";case\"m\":return b?\"ena minuta\":\"eno minuto\";case\"mm\":return e+=1===a?b?\"minuta\":\"minuto\":2===a?b||d?\"minuti\":\"minutama\":5>a?b||d?\"minute\":\"minutami\":b||d?\"minut\":\"minutami\";case\"h\":return b?\"ena ura\":\"eno uro\";case\"hh\":return e+=1===a?b?\"ura\":\"uro\":2===a?b||d?\"uri\":\"urama\":5>a?b||d?\"ure\":\"urami\":b||d?\"ur\":\"urami\";case\"d\":return b||d?\"en dan\":\"enim dnem\";case\"dd\":return e+=1===a?b||d?\"dan\":\"dnem\":2===a?b||d?\"dni\":\"dnevoma\":b||d?\"dni\":\"dnevi\";case\"M\":return b||d?\"en mesec\":\"enim mesecem\";case\"MM\":return e+=1===a?b||d?\"mesec\":\"mesecem\":2===a?b||d?\"meseca\":\"mesecema\":5>a?b||d?\"mesece\":\"meseci\":b||d?\"mesecev\":\"meseci\";case\"y\":return b||d?\"eno leto\":\"enim letom\";case\"yy\":return e+=1===a?b||d?\"leto\":\"letom\":2===a?b||d?\"leti\":\"letoma\":5>a?b||d?\"leta\":\"leti\":b||d?\"let\":\"leti\"}}function Nd(a){var b=a;return b=-1!==a.indexOf(\"jaj\")?b.slice(0,-3)+\"leS\":-1!==a.indexOf(\"jar\")?b.slice(0,-3)+\"waQ\":-1!==a.indexOf(\"DIS\")?b.slice(0,-3)+\"nem\":b+\" pIq\"}function Od(a){var b=a;return b=-1!==a.indexOf(\"jaj\")?b.slice(0,-3)+\"Hu\u2019\":-1!==a.indexOf(\"jar\")?b.slice(0,-3)+\"wen\":-1!==a.indexOf(\"DIS\")?b.slice(0,-3)+\"ben\":b+\" ret\"}function Pd(a,b,c,d){var e=Qd(a);switch(c){case\"mm\":return e+\" tup\";case\"hh\":return e+\" rep\";case\"dd\":return e+\" jaj\";case\"MM\":return e+\" jar\";case\"yy\":return e+\" DIS\"}}function Qd(a){var b=Math.floor(a%1e3/100),c=Math.floor(a%100/10),d=a%10,e=\"\";return b>0&&(e+=Sg[b]+\"vatlh\"),c>0&&(e+=(\"\"!==e?\" \":\"\")+Sg[c]+\"maH\"),d>0&&(e+=(\"\"!==e?\" \":\"\")+Sg[d]),\"\"===e?\"pagh\":e}function Rd(a,b,c,d){var e={s:[\"viensas secunds\",\"'iensas secunds\"],m:[\"'n m\u00edut\",\"'iens m\u00edut\"],mm:[a+\" m\u00eduts\",\"\"+a+\" m\u00eduts\"],h:[\"'n \u00feora\",\"'iensa \u00feora\"],hh:[a+\" \u00feoras\",\"\"+a+\" \u00feoras\"],d:[\"'n ziua\",\"'iensa ziua\"],dd:[a+\" ziuas\",\"\"+a+\" ziuas\"],M:[\"'n mes\",\"'iens mes\"],MM:[a+\" mesen\",\"\"+a+\" mesen\"],y:[\"'n ar\",\"'iens ar\"],yy:[a+\" ars\",\"\"+a+\" ars\"]};return d?e[c][0]:b?e[c][0]:e[c][1]}", "label_name": "CWE-89", "label": 0} +{"code": "renderer:\"foundation\"});a.ext.renderer.pageButton.foundation=function(b,j,q,r,g,k){var l=new a.Api(b),s=b.oClasses,h=b.oLanguage.oPaginate,t=b.oLanguage.oAria.paginate||{},e,f,p=function(a,m){var i,n,o,c,j=function(a){a.preventDefault();!d(a.currentTarget).hasClass(\"unavailable\")&&l.page()!=a.data.action&&l.page(a.data.action).draw(\"page\")};i=0;for(n=m.length;i\").css({width:\"100%\",height:10}))).appendTo(\"body\"),d=c.children(),e=d.children();b.barWidth=d[0].offsetWidth-d[0].clientWidth;b.bScrollOversize=100===e[0].offsetWidth&&100!==d[0].clientWidth;b.bScrollbarLeft=1!==Math.round(e.offset().left);b.bBounding=c[0].getBoundingClientRect().width?!0:!1;c.remove()}h.extend(a.oBrowser,m.__browser);a.oScroll.iBarWidth=m.__browser.barWidth}function hb(a,b,c,d,e,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;d!==e;)a.hasOwnProperty(d)&&\n(g=j?b(g,a[d],d,a):a[d],j=!0,d+=f);return g}function Ga(a,b){var c=m.defaults.column,d=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:H.createElement(\"th\"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML:\"\",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.mData:d,idx:d});a.aoColumns.push(c);c=a.aoPreSearchCols;c[d]=h.extend({},m.models.oSearch,c[d]);la(a,d,h(b).data())}function la(a,b,c){var b=a.aoColumns[b],d=a.oClasses,e=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=e.attr(\"width\")||null;var f=", "label_name": "CWE-89", "label": 0} +{"code": "(function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case\"mousedown\":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,\"mousemove mouseup\",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&\"mousemove\":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)/g, '>');\n};", "label_name": "CWE-89", "label": 0} +{"code": "\t\tstart : function(e, ui) {\n\t\t\tvar targets = $.map(ui.helper.data('files')||[], function(h) { return h || null ;}),\n\t\t\tlocked = false,\n\t\t\tcnt, h;\n\t\t\tself.draggingUiHelper = ui.helper;\n\t\t\tcnt = targets.length;\n\t\t\twhile (cnt--) {\n\t\t\t\th = targets[cnt];\n\t\t\t\tif (files[h].locked) {\n\t\t\t\t\tlocked = true;\n\t\t\t\t\tui.helper.data('locked', true);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t!locked && self.trigger('lockfiles', {files : targets});\n\n\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\tthis.upload = function(files) {\n\t\t\treturn this.transport.upload(files, this);\n\t\t}", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\t\t\tfm.trigger('unlockfiles', {files : helper.data('files'), helper: helper});\n\t\t\t\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\tthis.diff = function(incoming, onlydir) {\n\t\tvar raw = {},\n\t\t\tadded = [],\n\t\t\tremoved = [],\n\t\t\tchanged = [],\n\t\t\tisChanged = function(hash) {\n\t\t\t\tvar l = changed.length;\n\n\t\t\t\twhile (l--) {\n\t\t\t\t\tif (changed[l].hash == hash) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t$.each(incoming, function(i, f) {\n\t\t\traw[f.hash] = f;\n\t\t});\n\t\t\t\n\t\t// find removed\n\t\t$.each(files, function(hash, f) {\n\t\t\tif (!onlydir || f.phash === onlydir) {\n\t\t\t\t!raw[hash] && removed.push(hash);\n\t\t\t}\n\t\t});\n\t\t\n\t\t// compare files\n\t\t$.each(raw, function(hash, file) {\n\t\t\tvar origin = files[hash];\n\n\t\t\tif (!origin) {\n\t\t\t\tadded.push(file);\n\t\t\t} else {\n\t\t\t\t$.each(file, function(prop) {\n\t\t\t\t\tif (file[prop] != origin[prop]) {\n\t\t\t\t\t\tchanged.push(file)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\t\n\t\t// parents of removed dirs mark as changed (required for tree correct work)\n\t\t$.each(removed, function(i, hash) {\n\t\t\tvar file = files[hash], \n\t\t\t\tphash = file.phash;\n\n\t\t\tif (phash \n\t\t\t&& file.mime == 'directory' \n\t\t\t&& $.inArray(phash, removed) === -1 \n\t\t\t&& raw[phash] \n\t\t\t&& !isChanged(phash)) {\n\t\t\t\tchanged.push(raw[phash]);\n\t\t\t}\n\t\t});\n\t\t\n\t\treturn {\n\t\t\tadded : added,\n\t\t\tremoved : removed,\n\t\t\tchanged : changed\n\t\t};\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\tthis.exec = function() {\n\t\tif (!this.dialog) {\n\t\t\tcontent.find('#apiver').text(this.fm.api);\n\t\t\tthis.dialog = this.fm.dialog(content, {title : this.title, width : 530, autoOpen : false, destroyOnClose : false});\n\t\t}\n\t\t\n\t\tthis.dialog.elfinderdialog('open').find('.ui-tabs-nav li a:first').click();\n\t};", "label_name": "CWE-89", "label": 0} +{"code": "elFinder.prototype.commands.forward = function() {\n\tthis.alwaysEnabled = true;\n\tthis.updateOnSelect = true;\n\tthis.shortcuts = [{\n\t\tpattern : 'ctrl+right'\n\t}];\n\t\n\tthis.getstate = function() {\n\t\treturn this.fm.history.canForward() ? 0 : -1;\n\t}\n\t\n\tthis.exec = function() {\n\t\treturn this.fm.history.forward();\n\t}\n\t\n}", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\tcancel = function() {\n\t\t\t\t\tvar close = function(){\n\t\t\t\t\t\tdfrd.reject();\n\t\t\t\t\t\tta.elfinderdialog('close');\n\t\t\t\t\t};\n\t\t\t\t\tta.editor && ta.editor.save(ta[0], ta.editor.instance);\n\t\t\t\t\tif (rtrim(old) !== rtrim(ta.val())) {\n\t\t\t\t\t\told = ta.val();\n\t\t\t\t\t\tfm.confirm({\n\t\t\t\t\t\t\ttitle : self.title,\n\t\t\t\t\t\t\ttext : 'confirmNotSave',\n\t\t\t\t\t\t\taccept : {\n\t\t\t\t\t\t\t\tlabel : 'btnSaveClose',\n\t\t\t\t\t\t\t\tcallback : function() {\n\t\t\t\t\t\t\t\t\tsave();\n\t\t\t\t\t\t\t\t\tclose();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcancel : {\n\t\t\t\t\t\t\t\tlabel : 'btnClose',\n\t\t\t\t\t\t\t\tcallback : close\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclose();\n\t\t\t\t\t}\n\t\t\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\t\t\t\ttop : parseInt(nav.scrollTop())+'px',\n\t\t\t\t\t\t\tleft : ltr ? 'auto' : parseInt(nav.scrollLeft() + offset),\n\t\t\t\t\t\t\tright: ltr ? parseInt(nav.scrollLeft() - offset) * -1 : 'auto'\n\t\t\t\t\t\t});", "label_name": "CWE-89", "label": 0} +{"code": "\t\tthis.trigger('resize', {width : node.width(), height : node.height()});\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\t\t\t\tleft : parseInt($(window).scrollLeft())+'px',\n\t\t\t\t\t\t\ttop : parseInt($(window).scrollTop()) +'px'\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\t.bind(self.resize, function(e) {\n\t\t\t\t\t\tself.preview.trigger('changesize');\n\t\t\t\t\t})\n\t\t\t\t\t.trigger(scroll)\n\t\t\t\t\t.trigger(self.resize);\n\t\t\t\t\t\n\t\t\t\t\twin.bind('mousemove', function(e) {\n\t\t\t\t\t\tnavbar.stop(true, true).show().delay(3000).fadeOut('slow');\n\t\t\t\t\t})\n\t\t\t\t\t.mousemove();\n\t\t\t\t\t\n\t\t\t\t\tnavbar.mouseenter(function() {\n\t\t\t\t\t\tnavbar.stop(true, true).show();\n\t\t\t\t\t})\n\t\t\t\t\t.mousemove(function(e) {\n\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t});\n\t\t\t\t}", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\ttext : fm.i18n('confirmUnmount', drive.name),\n\t\t\t\taccept : {\n\t\t\t\t\tlabel : 'btnUnmount',\n\t\t\t\t\tcallback : function() { \n\t\t\t\t\t\tfm.request({\n\t\t\t\t\t\t\tdata : {cmd : 'netmount', protocol : 'netunmount', host: drive.netkey, user : drive.hash, pass : 'dum'}, \n\t\t\t\t\t\t\tnotify : {type : 'netunmount', cnt : 1, hideCnt : true},\n\t\t\t\t\t\t\tpreventFail : true\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.fail(function(error) {\n\t\t\t\t\t\t\tdfrd.reject(error);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.done(function(data) {\n\t\t\t\t\t\t\tvar chDrive = (fm.root() == drive.hash);\n\t\t\t\t\t\t\tdata.removed = [ drive.hash ];\n\t\t\t\t\t\t\tfm.remove(data);\n\t\t\t\t\t\t\tif (chDrive) {\n\t\t\t\t\t\t\t\tvar files = fm.files();\n\t\t\t\t\t\t\t\tfor (var i in files) {\n\t\t\t\t\t\t\t\t\tif (fm.file(i).mime == 'directory') {\n\t\t\t\t\t\t\t\t\t\tfm.exec('open', i);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcancel : {\n\t\t\t\t\tlabel : 'btnCancel',\n\t\t\t\t\tcallback : function() { dfrd.reject(); }\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\t\n\t\treturn dfrd;\n\t};", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\tdoScan = function(items, isEntry) {\n\t\t\t\t\tvar dirReader, entry;\n\t\t\t\t\tentries = [];\n\t\t\t\t\tvar length = items.length;\n\t\t\t\t\tfor (var i = 0; i < length; i++) {\n\t\t\t\t\t\tif (! isEntry) {\n\t\t\t\t\t\t\tentry = !!items[i].getAsEntry? items[i].getAsEntry() : items[i].webkitGetAsEntry();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tentry = items[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (entry) {\n\t\t\t\t\t\t\tif (entry.isFile) {\n\t\t\t\t\t\t\t\tprocessing++;\n\t\t\t\t\t\t\t\tentry.file(function (file) {\n\t\t\t\t\t\t\t\t\tpaths.push('');\n\t\t\t\t\t\t\t\t\tfiles.push(file);\n\t\t\t\t\t\t\t\t\tprocessing--;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else if (entry.isDirectory) {\n\t\t\t\t\t\t\t\tif (fm.api >= 2.1) {\n\t\t\t\t\t\t\t\t\tif (processing > 0) {\n\t\t\t\t\t\t\t\t\t\tdirctorys.push(entry);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tprocessing = 0;\n\t\t\t\t\t\t\t\t\t\tdirReader = entry.createReader();\n\t\t\t\t\t\t\t\t\t\tprocessing++;\n\t\t\t\t\t\t\t\t\t\treadEntries(dirReader);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\tadd = function(files) {\n\t\t\t\tvar place = list ? cwd.find('tbody') : cwd,\n\t\t\t\t\tl = files.length, \n\t\t\t\t\tltmb = [],\n\t\t\t\t\tatmb = {},\n\t\t\t\t\tdirs = false,\n\t\t\t\t\tfindNode = function(file) {\n\t\t\t\t\t\tvar pointer = cwd.find('[id]:first'), file2;\n\n\t\t\t\t\t\twhile (pointer.length) {\n\t\t\t\t\t\t\tfile2 = fm.file(fm.cwdId2Hash(pointer.attr('id')));\n\t\t\t\t\t\t\tif (!pointer.hasClass('elfinder-cwd-parent') && file2 && fm.compare(file, file2) < 0) {\n\t\t\t\t\t\t\t\treturn pointer;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpointer = pointer.next('[id]');\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tfindIndex = function(file) {\n\t\t\t\t\t\tvar l = buffer.length, i;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (i =0; i < l; i++) {\n\t\t\t\t\t\t\tif (fm.compare(file, buffer[i]) < 0) {\n\t\t\t\t\t\t\t\treturn i;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn l || -1;\n\t\t\t\t\t},\n\t\t\t\t\tfile, hash, node, ndx;\n\n\t\t\t\tl && wrapper.removeClass('elfinder-cwd-wrapper-empty');\n\t\t\t\t\n\t\t\t\twhile (l--) {\n\t\t\t\t\tfile = files[l];\n\t\t\t\t\thash = file.hash;\n\t\t\t\t\t\n\t\t\t\t\tif ($('#'+fm.cwdHash2Id(hash)).length) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ((node = findNode(file)) && node.length) {\n\t\t\t\t\t\tnode.before(itemhtml(file)); \n\t\t\t\t\t} else if ((ndx = findIndex(file)) >= 0) {\n\t\t\t\t\t\tbuffer.splice(ndx, 0, file);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tplace.append(itemhtml(file));\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ($('#'+fm.cwdHash2Id(hash)).length) {\n\t\t\t\t\t\tif (file.mime == 'directory') {\n\t\t\t\t\t\t\tdirs = true;\n\t\t\t\t\t\t} else if (file.tmb) {\n\t\t\t\t\t\t\tfile.tmb === 1 ? ltmb.push(hash) : (atmb[hash] = file.tmb);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbottomMarkerShow(place);\n\t\t\t\tattachThumbnails(atmb);\n\t\t\t\tltmb.length && loadThumbnails(ltmb);\n\t\t\t\tdirs && !mobile && makeDroppable();\n\t\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\tupdateDroppable = function(target) {\n\t\t\t\tvar limit = 100,\n\t\t\t\t\tnext;\n\t\t\t\t\n\t\t\t\tif (!target) {\n\t\t\t\t\ttree.find('div.'+uploadable).find(selNavdir+':not(.elfinder-ro,.elfinder-na)').addClass('native-droppable');\n\t\t\t\t\ttarget = tree.find('div.'+pastable).find(selNavdir+':not(.'+droppable+',.elfinder-ro,.elfinder-na)');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (target.length > limit) {\n\t\t\t\t\tnext = target.slice(limit);\n\t\t\t\t\ttarget = target.slice(0, limit);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttarget.droppable(droppableopts);\n\t\t\t\t\n\t\t\t\tif (next) {\n\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\tupdateDroppable(next);\n\t\t\t\t\t}, 20);\n\t\t\t\t}\n\t\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\tsetstat = function(files, cwd) {\n\t\t\t\tvar c = 0, \n\t\t\t\t\ts = 0;\n\n\t\t\t\t$.each(files, function(i, file) {\n\t\t\t\t\tif (!cwd || file.phash == cwd) {\n\t\t\t\t\t\tc++;\n\t\t\t\t\t\ts += parseInt(file.size)||0;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tsize.html(titleitems+': '+c+', '+titlesize+': '+fm.formatSize(s));\n\t\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\t\tmulti = function(files, num){\n\t\t\t\t\tvar sfiles = [], cid;\n\t\t\t\t\tif (!abort) {\n\t\t\t\t\t\twhile(files.length && sfiles.length < num) {\n\t\t\t\t\t\t\tsfiles.push(files.shift());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (sfiles.length) {\n\t\t\t\t\t\t\tfor (var i=0; i < sfiles.length; i++) {\n\t\t\t\t\t\t\t\tif (abort) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcid = isDataType? (sfiles[i][0][0]._cid || null) : (sfiles[i][0]._cid || null);\n\t\t\t\t\t\t\t\tif (!!failChunk[cid]) {\n\t\t\t\t\t\t\t\t\tlast--;\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfm.exec('upload', {\n\t\t\t\t\t\t\t\t\ttype: data.type,\n\t\t\t\t\t\t\t\t\tisDataType: isDataType,\n\t\t\t\t\t\t\t\t\tfiles: sfiles[i],\n\t\t\t\t\t\t\t\t\tchecked: true,\n\t\t\t\t\t\t\t\t\ttarget: target,\n\t\t\t\t\t\t\t\t\trenames: renames,\n\t\t\t\t\t\t\t\t\thashes: hashes,\n\t\t\t\t\t\t\t\t\tmultiupload: true})\n\t\t\t\t\t\t\t\t.fail(function(error) {\n\t\t\t\t\t\t\t\t\tif (cid) {\t\n\t\t\t\t\t\t\t\t\t\tfailChunk[cid] = true;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.always(function(e) {\n\t\t\t\t\t\t\t\t\tif (e && e.added) added = $.merge(added, e.added);\n\t\t\t\t\t\t\t\t\tif (last <= ++done) {\n\t\t\t\t\t\t\t\t\t\tfm.trigger('multiupload', {added: added});\n\t\t\t\t\t\t\t\t\t\tnotifyto && clearTimeout(notifyto);\n\t\t\t\t\t\t\t\t\t\tif (checkNotify()) {\n\t\t\t\t\t\t\t\t\t\t\tself.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tmulti(files, 1); // Next one\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (sfiles.length < 1 || abort) {\n\t\t\t\t\t\tif (abort) {\n\t\t\t\t\t\t\tnotifyto && clearTimeout(notifyto);\n\t\t\t\t\t\t\tif (cid) {\n\t\t\t\t\t\t\t\tfailChunk[cid] = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdfrd.reject();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdfrd.resolve();\n\t\t\t\t\t\t\tself.uploads.xhrUploading = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\tshortcuts = function() {\n\t\t\tvar sh = fm.shortcuts();\n\t\t\t// shortcuts tab\n\t\t\thtml.push('
    ');\n\t\t\t\n\t\t\tif (sh.length) {\n\t\t\t\thtml.push('
    ');\n\t\t\t\t$.each(sh, function(i, s) {\n\t\t\t\t\thtml.push(stpl.replace(/\\{pattern\\}/, s[0]).replace(/\\{descrip\\}/, s[1]));\n\t\t\t\t});\n\t\t\t\n\t\t\t\thtml.push('
    ');\n\t\t\t} else {\n\t\t\t\thtml.push('
    '+fm.i18n('shortcutsof')+'
    ');\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\thtml.push('
    ');\n\t\t\t\n\t\t},", "label_name": "CWE-89", "label": 0} +{"code": "\t\t\treturn {changed : [this.normalizeFile(data.target, phash)]};\n\t\t}\n\t\t\n\t\tphash = data.cwd.hash;\n\t\t\n\t\tif (data.tree) {\n\t\t\t$.each(this.normalizeTree(data.tree), function(i, file) {\n\t\t\t\tfiles[file.hash] = file;\n\t\t\t});\n\t\t}\n\t\t\n\t\t$.each(data.cdc||[], function(i, file) {\n\t\t\tvar hash = file.hash;\n\n\t\t\tif (files[hash]) {\n\t\t\t\tfiles[hash].date = file.date;\n\t\t\t\tfiles[hash].locked = file.hash == phash ? true : file.rm === void(0) ? false : !file.rm;\n\t\t\t} else {\n\t\t\t\tfiles[hash] = self.normalizeFile(file, phash, data.tmb);\n\t\t\t}\n\t\t});\n\t\t\n\t\tif (!data.tree) {\n\t\t\t$.each(this.fm.files(), function(hash, file) {\n\t\t\t\tif (!files[hash] && file.phash != phash && file.mime == 'directory') {\n\t\t\t\t\tfiles[hash] = file;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\n\t\tif (cmd == 'open') {\n\t\t\treturn {\n\t\t\t\t\tcwd : files[phash] || this.normalizeFile(data.cwd),\n\t\t\t\t\tfiles : $.map(files, function(f) { return f }),\n\t\t\t\t\toptions : self.normalizeOptions(data),\n\t\t\t\t\tinit : !!data.params,\n\t\t\t\t\tdebug : data.debug\n\t\t\t\t};\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\treturn $.extend({\n\t\t\tcurrent : data.cwd.hash,\n\t\t\terror : data.error,\n\t\t\twarning : data.warning,\n\t\t\toptions : {tmb : !!data.tmb}\n\t\t}, this.fm.diff($.map(files, filter)));\n\t\t\n\t}", "label_name": "CWE-89", "label": 0} +{"code": "pimcore.helpers.grid.getTranslationColumnRenderer = function (value, metaData, record, rowIndex, colIndex, store) {\n return t(value);\n};", "label_name": "CWE-79", "label": 1} +{"code": "window.ocJSON=function(json){var jsonString=parse(json);return JSON.parse(jsonString);};}(window);", "label_name": "CWE-79", "label": 1} +{"code": "function uploadSizeError( up, file, over100mb ) {\n\tvar message;\n\n\tif ( over100mb )\n\t\tmessage = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '').replace('%2$s', '');\n\telse\n\t\tmessage = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);\n\n\tjQuery('#media-items').append('

    ' + message + '

    ');\n\tup.removeFile(file);\n}", "label_name": "CWE-79", "label": 1} +{"code": "\t\tsuccess:function (data, textStatus) {\n\t\t\tupdateIndex(context_id, context);\n\t\t\thandleGenericAjaxResponse(data);\n\t\t},", "label_name": "CWE-79", "label": 1} +{"code": "\t\tbeforeSend: function (XMLHttpRequest) {\n\t\t\t$(\".loading\").show();\n\t\t},", "label_name": "CWE-79", "label": 1} +{"code": "\t__uuidv4() {\n\t\treturn 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n\t\t\tvar r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n\t\t\treturn v.toString(16);\n\t\t});\n\t}", "label_name": "CWE-79", "label": 1} +{"code": " var policy = function (tagName, attribs) {\n if (!(html4.ELEMENTS[tagName] & html4.eflags.UNSAFE)) {\n return {\n 'attribs': sanitizeAttribs(tagName, attribs,\n noop, noop, record_messages)\n };\n } else {\n record_messages(tagName + \" removed\", {\n change: \"removed\",\n tagName: tagName\n });\n }\n };\n \n var sanitized = caja.sanitizeWithPolicy(html, policy);\n \n if (allow_css) {\n // sanitize style tags as stylesheets\n sanitized = sanitize_stylesheets(sanitized, policy);\n }\n \n return sanitized;\n };", "label_name": "CWE-79", "label": 1} +{"code": "LdapAuth.prototype._findUser = function (username, callback) {\n var self = this;\n if (!username) {\n return callback(\"empty username\");\n }\n\n var searchFilter = self.opts.searchFilter.replace(/{{username}}/g, username);\n var opts = {filter: searchFilter, scope: self.opts.searchScope};\n if (self.opts.searchAttributes) {\n opts.attributes = self.opts.searchAttributes;\n }\n\n self._search(self.opts.searchBase, opts, function (err, result) {\n if (err) {\n self.log && self.log.trace('ldap authenticate: user search error: %s %s %s', err.code, err.name, err.message);\n return callback(err);\n }\n\n switch (result.length) {\n case 0:\n return callback();\n case 1:\n return callback(null, result[0])\n default:\n return callback(format(\n 'unexpected number of matches (%s) for \"%s\" username',\n result.length, username));\n }\n });\n};", "label_name": "CWE-90", "label": 96} +{"code": "Note.renderNote = function(note) {\n if (!note) {\n return;\n }\n // title\n $(\"#noteTitle\").val(note.Title);\n\n // \u5f53\u524d\u6b63\u5728\u7f16\u8f91\u7684\n // tags\n Tag.input.setTags(note.Tags);\n};", "label_name": "CWE-79", "label": 1} +{"code": " function parseAssignment () {\n var name, args, value, valid;\n\n var node = parseConditional();\n\n if (token == '=') {\n if (type.isSymbolNode(node)) {\n // parse a variable assignment like 'a = 2/3'\n name = node.name;\n getTokenSkipNewline();\n value = parseAssignment();\n return new AssignmentNode(new SymbolNode(name), value);\n }\n else if (type.isAccessorNode(node)) {\n // parse a matrix subset assignment like 'A[1,2] = 4'\n getTokenSkipNewline();\n value = parseAssignment();\n return new AssignmentNode(node.object, node.index, value);\n }\n else if (type.isFunctionNode(node)) {\n // parse function assignment like 'f(x) = x^2'\n valid = true;\n args = [];\n\n name = node.name;\n node.args.forEach(function (arg, index) {\n if (type.isSymbolNode(arg)) {\n args[index] = arg.name;\n }\n else {\n valid = false;\n }\n });\n\n if (valid) {\n getTokenSkipNewline();\n value = parseAssignment();\n return new FunctionAssignmentNode(name, args, value);\n }\n }\n\n throw createSyntaxError('Invalid left hand side of assignment operator =');\n }\n\n return node;\n }", "label_name": "CWE-94", "label": 14} +{"code": " text: Ext.util.Format.htmlEncode(record.get('name')),\n qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),\n leaf: false,\n cls: 'felamimail-node-account',\n delimiter: record.get('delimiter'),\n ns_personal: record.get('ns_personal'),\n account_id: record.data.id,\n listeners: {\n scope: this,\n load: function(node) {\n var account = this.accountStore.getById(node.id);\n this.updateAccountStatus(account);\n }\n }\n });", "label_name": "CWE-79", "label": 1} +{"code": " qtip: Tine.Tinebase.common.doubleEncode(attr.name.name)\n });\n }\n \n // copy 'real' data to a node record NOTE: not a full record as we have no record reader here\n var nodeData = Ext.copyTo({}, attr, Tine.Filemanager.Model.Node.getFieldNames());\n attr.nodeRecord = new Tine.Filemanager.Model.Node(nodeData);\n },", "label_name": "CWE-79", "label": 1} +{"code": " text : Ext.util.Format.htmlEncode(this.app.i18n._hidden(attr.name)),\n qtip : Tine.Tinebase.common.doubleEncode(attr.description ? this.app.i18n._hidden(attr.description) + ' ' + addText : addText),\n selected : attr.id === this.selectedFilterId,\n id : attr.id,\n\n sorting : attr.sorting,\n draggable : true,\n allowDrop : false,\n\n leaf : attr.leaf === false ? attr.leaf : true,\n cls : 'tinebase-westpanel-node-favorite' + addClass\n });\n }", "label_name": "CWE-79", "label": 1} +{"code": " menuItemTemplate: function (item) {\n return `${item.string}`;\n },", "label_name": "CWE-79", "label": 1} +{"code": " $scope.save = function() {\n var form = this.fsForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(\n function() { // success\n growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.addRequisition = function() {\n bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {\n if (foreignSource) {\n RequisitionsService.addRequisition(foreignSource).then(\n function() { // success\n RequisitionsService.synchronizeRequisition(foreignSource, false).then(\n function() {\n growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');\n $scope.foreignSources.push(foreignSource);\n },\n $scope.errorHandler\n );\n },\n $scope.errorHandler\n );\n } else {\n window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?\n }\n });\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.add = function() {\n bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {\n if (foreignSource) {\n // Validate Requisition\n if (foreignSource.match(/[/\\\\?:&*'\"]/)) {\n bootbox.alert('Cannot add the requisition ' + foreignSource + ' because the following characters are invalid:
    :, /, \\\\, ?, &, *, \\', \"');\n return;\n }\n var r = $scope.requisitionsData.getRequisition(foreignSource);\n if (r) {\n bootbox.alert('Cannot add the requisition ' + foreignSource+ ' because there is already a requisition with that name');\n return;\n }\n // Create Requisition\n RequisitionsService.addRequisition(foreignSource).then(\n function(r) { // success\n growl.success('The requisition ' + r.foreignSource + ' has been created.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.clone = function(foreignSource) {\n var availableForeignSources = [];\n angular.forEach($scope.requisitionsData.requisitions, function(r) {\n if (r.foreignSource !== foreignSource) {\n availableForeignSources.push(r.foreignSource);\n }\n });\n var modalInstance = $uibModal.open({\n backdrop: 'static',\n keyboard: false,\n controller: 'CloneForeignSourceController',\n templateUrl: cloneForeignsourceView,\n resolve: {\n foreignSource: function() { return foreignSource; },\n availableForeignSources: function() { return availableForeignSources; }\n }\n });\n modalInstance.result.then(function(targetForeignSource) {\n bootbox.confirm('This action will override the existing foreign source definition for the requisition named ' + targetForeignSource + ', using ' + foreignSource + ' as a template. Are you sure you want to continue ? This cannot be undone.', function(ok) {\n if (!ok) {\n return;\n }\n RequisitionsService.startTiming();\n RequisitionsService.cloneForeignSourceDefinition(foreignSource, targetForeignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + foreignSource + ' has been cloned to ' + targetForeignSource);\n },\n $scope.errorHandler\n );\n });\n });\n };", "label_name": "CWE-79", "label": 1} +{"code": " synchronize: function(requisition, errorHandler) {\n /**\n * @param {object} requisition The requisition object\n * @param {string} rescanExisting true to perform a full scan, false to only add/remove nodes without scan, dbonly for all DB operations without scan\n */\n var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };\n bootbox.prompt({\n title: 'Synchronize Requisition ' + requisition.foreignSource,\n message: '

    Choose a scan option:

    ',\n inputType: 'radio',\n inputOptions: [\n {\n text: 'Scan all nodes',\n value: 'true',\n },\n {\n text: 'Scan added nodes only',\n value: 'false',\n },\n {\n text: 'No scanning',\n value: 'dbonly',\n }\n ],\n buttons: {\n confirm: {\n label: 'Synchronize',\n },\n cancel: {\n label: 'Cancel',\n }\n },\n swapButtonOrder: 'true',\n callback: function (result) {\n if (result !== null) {\n doSynchronize(requisition, result);\n }\n }\n });\n }", "label_name": "CWE-79", "label": 1} +{"code": " $scope.reset = function() {\n bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(\n function() { // success\n growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');\n $scope.initialize();\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.refresh = function() {\n growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');\n RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(\n function(node) { // success\n $scope.node = node;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.save = function() {\n var form = this.nodeForm;\n RequisitionsService.startTiming();\n RequisitionsService.saveNode($scope.node).then(\n function() { // success\n growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.');\n $scope.foreignId = $scope.node.foreignId;\n form.$dirty = false;\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.provision = function() {\n $scope.isSaving = true;\n growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));\n var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);\n RequisitionsService.quickAddNode($scope.node).then(\n function() { // success\n $scope.reset();\n bootbox.dialog({\n message: successMessage,\n title: 'Success',\n buttons: {\n main: {\n label: 'Ok',\n className: 'btn-secondary'\n }\n }\n });\n },\n $scope.errorHandler\n );\n };", "label_name": "CWE-79", "label": 1} +{"code": " $scope.deleteNode = function(node) {\n bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {\n if (ok) {\n RequisitionsService.startTiming();\n RequisitionsService.deleteNode(node).then(\n function() { // success\n var index = -1;\n for(var i = 0; i < $scope.filteredNodes.length; i++) {\n if ($scope.filteredNodes[i].foreignId === node.foreignId) {\n index = i;\n }\n }\n if (index > -1) {\n $scope.filteredNodes.splice(index,1);\n }\n growl.success('The node ' + node.nodeLabel + ' has been deleted.');\n },\n $scope.errorHandler\n );\n }\n });\n };", "label_name": "CWE-79", "label": 1} +{"code": " var doSynchronize = function(requisition, rescanExisting) {\n RequisitionsService.startTiming();\n RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(\n function() { // success\n growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
    Use refresh to update the deployed statistics');\n requisition.setDeployed(true);\n },\n errorHandler\n );\n };", "label_name": "CWE-79", "label": 1} +{"code": "function dialog_form(a,b,c,e,d){\"undefined\"==typeof e&&(e=\"json\");a.submit(function(f){f.preventDefault();a.ajaxSubmit({context:a,dataType:e,beforeSerialize:function(a,b){\"undefined\"!=typeof d&&!1!==d&&d.call(this,a,b)},beforeSend:function(c,d,e){var f=0 \\\"\"+d+'\"\\n';else c=\"===>\"+a+\"<===(\"+typeof a+\")\";return c};(function(a){a.fn.fc_set_tab_list=function(b){var c={toggle_speed:300,fc_list_forms:a(\".fc_list_forms\"),fc_list_add:a(\"#fc_list_add\")};b=a.extend(c,b);return this.each(function(){var c=a(this),d=c.closest(\"ul\").children(\"li\"),f=\"fc_list_\"+c.children(\"input\").val(),g=a(\"#\"+f),h=a(\"#fc_install_new\");b.fc_list_forms.not(\":first\").slideUp(0);0===b.fc_list_add.size()?d.filter(\":first\").addClass(\"fc_active\"):b.fc_list_add.unbind().click(function(){d.removeClass(\"fc_active\");b.fc_list_forms.not(h).slideUp(0);", "label_name": "CWE-79", "label": 1} +{"code": "1;buttonsOpts.push({text:cattranslate(\"Yes\"),click:function(){$.ajax({type:d,context:k,url:c,dataType:f,data:e,cache:!1,beforeSend:function(a){a.process=set_activity(b);$(\".fc_popup\").dialog(\"destroy\").remove();\"undefined\"!=typeof g&&!1!==g&&g.call(this,a)},success:function(a,b,c){!0===a.success||0<$(a).find(\".fc_success_box\").size()?return_success(c.process,a.message):return_error(c.process,a.message);\"undefined\"!=typeof h&&!1!==h&&h.call(this,a)}})},\"class\":\"submit\"});buttonsOpts.push({text:cattranslate(\"No\"),", "label_name": "CWE-79", "label": 1} +{"code": "1;buttonsOpts.push({text:cattranslate(\"Yes\"),click:function(){$.ajax({type:d,context:k,url:c,dataType:f,data:e,cache:!1,beforeSend:function(a){a.process=set_activity(b);$(\".fc_popup\").dialog(\"destroy\").remove();\"undefined\"!=typeof g&&!1!==g&&g.call(this,a)},success:function(a,b,c){!0===a.success||0<$(a).find(\".fc_success_box\").size()?return_success(c.process,a.message):return_error(c.process,a.message);\"undefined\"!=typeof h&&!1!==h&&h.call(this,a)}})},\"class\":\"submit\"});buttonsOpts.push({text:cattranslate(\"No\"),\nclick:function(){$(\".fc_popup\").dialog(\"destroy\")},\"class\":\"reset\"});$(\".fc_popup\").dialog({modal:!0,show:\"fade\",closeOnEscape:!0,title:b,buttons:buttonsOpts})}", "label_name": "CWE-79", "label": 1} +{"code": "function stat(dir, files, cb) {\n var batch = new Batch();\n\n batch.concurrency(10);\n\n files.forEach(function(file, i){\n batch.push(function(done){\n fs.stat(join(dir, file), done);\n });\n });\n\n batch.end(cb);\n}", "label_name": "CWE-79", "label": 1} +{"code": "exports = module.exports = function directory(root, options){\n options = options || {};\n\n // root required\n if (!root) throw new Error('directory() root path required');\n var hidden = options.hidden\n , icons = options.icons\n , view = options.view || 'tiles'\n , filter = options.filter\n , root = normalize(root + sep)\n , template = options.template || defaultTemplate;\n\n return function directory(req, res, next) {\n if ('GET' != req.method && 'HEAD' != req.method) return next();\n\n var url = parse(req.url)\n , dir = decodeURIComponent(url.pathname)\n , path = normalize(join(root, dir))\n , originalUrl = parse(req.originalUrl)\n , originalDir = decodeURIComponent(originalUrl.pathname)\n , showUp = path != root;\n\n // null byte(s), bad request\n if (~path.indexOf('\\0')) return next(utils.error(400));\n\n // malicious path, forbidden\n if (0 != path.indexOf(root)) return next(utils.error(403));\n\n // check if we have a directory\n fs.stat(path, function(err, stat){\n if (err) return 'ENOENT' == err.code\n ? next()\n : next(err);\n\n if (!stat.isDirectory()) return next();\n\n // fetch files\n fs.readdir(path, function(err, files){\n if (err) return next(err);\n if (!hidden) files = removeHidden(files);\n if (filter) files = files.filter(filter);\n files.sort();\n\n // content-negotiation\n var type = new Negotiator(req).preferredMediaType(mediaTypes);\n\n // not acceptable\n if (!type) return next(utils.error(406));\n exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template);\n });\n });\n };\n};", "label_name": "CWE-79", "label": 1} +{"code": "function merge(target, obj) {\n for (var key in obj) {\n if (key === '__proto__' || !hasOwn(obj, key)) {\n continue;\n }\n\n var oldVal = obj[key];\n var newVal = target[key];\n\n if (isObject(newVal) && isObject(oldVal)) {\n target[key] = merge(newVal, oldVal);\n } else if (Array.isArray(newVal)) {\n target[key] = union([], newVal, oldVal);\n } else {\n target[key] = clone(oldVal);\n }\n }\n return target;\n}", "label_name": "CWE-915", "label": 35} +{"code": "function toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !url.host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n result += url.host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}", "label_name": "CWE-639", "label": 9} +{"code": "function main(){\n //Try using pkg-config, but if it fails and it is on Windows, try the fallback\n exec(\"pkg-config \" + opencv + \" \" + flag, function(error, stdout, stderr){\n if(error){\n if(process.platform === \"win32\"){\n fallback();\n }\n else{\n throw new Error(\"ERROR: failed to run: pkg-config\", opencv, flag);\n }\n }\n else{\n console.log(stdout);\n }\n });\n}", "label_name": "CWE-78", "label": 6} +{"code": "function main() {\r\n // adapter.subscribeForeignStates('*');\r\n // adapter.subscribeForeignObjects('*');\r\n\r\n adapter.config.defaultUser = adapter.config.defaultUser || 'admin';\r\n if (!adapter.config.defaultUser.match(/^system\\.user\\./)) {\r\n adapter.config.defaultUser = 'system.user.' + adapter.config.defaultUser;\r\n }\r\n\r\n if (adapter.config.secure) {\r\n // Load certificates\r\n adapter.getCertificates((err, certificates, leConfig) => {\r\n adapter.config.certificates = certificates;\r\n adapter.config.leConfig = leConfig;\r\n\r\n getData(() => webServer = new Web(adapter.config, adapter, initSocket));\r\n });\r\n } else {\r\n getData(() => webServer = new Web(adapter.config, adapter, initSocket));\r\n }\r\n\r\n patchRepos(() => {\r\n // By default update repository every 24 hours\r\n if (adapter.config.autoUpdate === undefined) {\r\n adapter.config.autoUpdate = 24;\r\n }\r\n adapter.config.autoUpdate = parseInt(adapter.config.autoUpdate, 10) || 0;\r\n if (adapter.config.autoUpdate) {\r\n setInterval(() => updateRegister(), adapter.config.autoUpdate * 3600000);\r\n updateRegister();\r\n }\r\n });\r\n}\r", "label_name": "CWE-22", "label": 2} +{"code": " main.unsubscribeStates = function (patterns) {\n if (!patterns) return;\n if (typeof patterns === 'object') {\n for (var s = 0; s < patterns.length; s++) {\n if (main.subscribesStates[patterns[s]]) {\n main.subscribesStates[patterns[s]]--;\n }\n if (main.subscribesStates[patterns[s]] === 0) {\n console.debug('Unsibscribe: ' + patterns[s]);\n main.socket.emit('unsubscribe', patterns[s]);\n delete main.subscribesStates[patterns[s]];\n }\n }\n } else {\n if (main.subscribesStates[patterns]) {\n main.subscribesStates[patterns]--;\n }\n if (main.subscribesStates[patterns] === 0) {\n console.debug('Unsibscribe: ' + patterns);\n main.socket.emit('unsubscribe', patterns);\n delete main.subscribesStates[patterns];\n }\n }\n };", "label_name": "CWE-22", "label": 2} +{"code": " main.getHostIcon = function (obj, classes) {\n var icon = '';\n var alt = '';\n\n if (obj && obj.common && obj.common.icon) {\n var result = getIconHtml(obj);\n icon = result.icon;\n alt = result.alt;\n }\n icon = icon || 'img/no-image.png';\n alt = alt || '';\n\n return '\"'';\n };", "label_name": "CWE-22", "label": 2} +{"code": " _delObject: function (idOrList, callback) {\n var id;\n if (!Array.isArray(idOrList)) {\n if (typeof idOrList !== 'string') return callback && callback('invalid idOrList parameter');\n idOrList = [idOrList];\n }\n\n function doIt() {\n if (idOrList.length === 0) {\n return callback && setTimeout(callback, 0, null, id);\n }\n id = idOrList.pop();\n if (main.objects[id] && main.objects[id].common && (main.objects[id].common['object-non-deletable'] || main.objects[id].common.dontDelete)) {\n main.showMessage (_ ('Cannot delete \"%s\" because not allowed', id), '', 'notifications');\n setTimeout(doIt, 0);\n } else {\n var obj = main.objects[id];\n main.socket.emit('delObject', id, function (err) {\n if (err && err !== 'Not exists') {\n main.showError (err);\n return callback(err);\n }\n if (obj && obj.type === 'state') {\n main.socket.emit ('delState', id, function (err) {\n if (err && err !== 'Not exists') {\n main.showError (err);\n return callback(err);\n }\n setTimeout(doIt, 0);\n });\n } else {\n setTimeout(doIt, 0);\n }\n });\n }\n }\n doIt();\n }, ", "label_name": "CWE-22", "label": 2} +{"code": " this.objectChange = function (id, obj) {\n // Update Adapter Table\n if (id.match(/^system\\.adapter\\.[a-zA-Z0-9-_]+$/)) {\n if (obj) {\n if (this.list.indexOf(id) === -1) this.list.push(id);\n } else {\n var j = this.list.indexOf(id);\n if (j !== -1) {\n this.list.splice(j, 1);\n }\n }\n\n if (typeof this.$grid !== 'undefined' && this.$grid[0]._isInited) {\n this.init(true);\n }\n }\n };", "label_name": "CWE-22", "label": 2} +{"code": " this.stateChange = function (id, state) {\n if (id && state) {\n var adapter = id.match(/^system\\.adapter\\.([\\w\\d-]+)\\.upload$/);\n if (adapter) {\n var $adapter = this.$tab.find('.adapter-upload-progress[data-adapter-name=\"' + adapter[1] + '\"]');\n var text = showUploadProgress(state.val);\n $adapter.html(text).css({opacity: state.val ? 0.7 : 0});\n this.$tab.find('.group-upload-progress[data-adapter-group=\"' + $adapter.data('adapter-group') + '\"]').html(text).css({opacity: state.val ? 0.7 : 0});\n }\n }\n };", "label_name": "CWE-22", "label": 2} +{"code": "function sanitizePath(id, name, callback) {\n if (name[0] === '/') name = name.substring(1);\n\n if (!id) {\n if (typeof callback === 'function') {\n callback('Empty ID');\n }\n return;\n }\n\n if (id) {\n id = id.replace(/\\.\\./g, ''); // do not allow to write in parent directories\n }\n\n if (name.indexOf('..') !== -1) {\n name = path.normalize(name);\n name = name.replace(/\\\\/g, '/');\n }\n if (name[0] === '/') name = name.substring(1); // do not allow absolute paths\n\n return {id: id, name: name};\n}", "label_name": "CWE-22", "label": 2} +{"code": "module.exports = function(path, opts, cb) {\n if (!cb) {\n cb = opts;\n opts = {};\n }\n\n var cmd = module.exports.cmd(path, opts);\n opts.timeout = opts.timeout || 5000;\n\n exec(cmd, opts, function(e, stdout, stderr) {\n if (e) { return cb(e); }\n if (stderr) { return cb(new Error(stderr)); }\n\n return cb(null, module.exports.parse(path, stdout, opts));\n });\n};", "label_name": "CWE-78", "label": 6} +{"code": "export function mergeConfig(...configs) {\n return configs.reduce((out, source) => {\n for (var key in source) {\n if (key === 'signals') {\n // for signals, we merge the signals arrays\n // source signals take precedence over\n // existing signals with the same name\n out.signals = mergeNamed(out.signals, source.signals);\n } else {\n // otherwise, merge objects subject to recursion constraints\n // for legend block, recurse for the layout entry only\n // for style block, recurse for all properties\n // otherwise, no recursion: objects overwrite, no merging\n var r = key === 'legend' ? {'layout': 1}\n : key === 'style' ? true\n : null;\n writeConfig(out, key, source[key], r);\n }\n }\n return out;\n }, {});\n}", "label_name": "CWE-915", "label": 35} +{"code": " setup: function () {\n var data = this.model.get('data');\n\n this.assignedUserId = data.assignedUserId || null;\n this.assignedUserName = data.assignedUserName || null;\n\n this.messageData['assignee'] = '' + data.assignedUserName + '';\n\n if (this.isUserStream) {\n if (this.assignedUserId) {\n if (this.assignedUserId == this.model.get('createdById')) {\n this.messageName += 'Self';\n } else {\n if (this.assignedUserId == this.getUser().id) {\n this.messageName += 'You';\n }\n }\n } else {\n this.messageName += 'Void';\n }\n } else {\n if (this.assignedUserId) {\n if (this.assignedUserId == this.model.get('createdById')) {\n this.messageName += 'Self';\n }\n } else {\n this.messageName += 'Void';\n }\n }\n\n this.createMessage();\n },", "label_name": "CWE-79", "label": 1} +{"code": " emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''\n }, Dep.prototype.data.call(this));\n },\n\n setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + data.emailName + '';\n\n this.messageName = 'emailReceived';\n\n if (data.isInitial) {\n this.messageName += 'Initial';\n }\n\n if (data.personEntityId) {\n this.messageName += 'From';\n this.messageData['from'] = '' + data.personEntityName + '';\n }\n\n if (this.model.get('parentType') === data.personEntityType && this.model.get('parentId') == data.personEntityId) {\n this.isThis = true;\n }\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },\n\n });\n});", "label_name": "CWE-79", "label": 1} +{"code": " setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + data.emailName + '';\n\n this.messageName = 'emailReceived';\n\n if (data.isInitial) {\n this.messageName += 'Initial';\n }\n\n if (data.personEntityId) {\n this.messageName += 'From';\n this.messageData['from'] = '' + data.personEntityName + '';\n }\n\n if (this.model.get('parentType') === data.personEntityType && this.model.get('parentId') == data.personEntityId) {\n this.isThis = true;\n }\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },", "label_name": "CWE-79", "label": 1} +{"code": " emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''\n }, Dep.prototype.data.call(this));\n },\n\n setup: function () {\n var data = this.model.get('data') || {};\n\n this.emailId = data.emailId;\n this.emailName = data.emailName;\n\n if (\n this.parentModel\n &&\n (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)\n ) {\n if (this.model.get('post')) {\n this.createField('post', null, null, 'views/stream/fields/post');\n this.hasPost = true;\n }\n if ((this.model.get('attachmentsIds') || []).length) {\n this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');\n this.hasAttachments = true;\n }\n }\n\n this.messageData['email'] = '' + data.emailName + '';\n\n this.messageName = 'emailSent';\n\n this.messageData['by'] = '' + data.personEntityName + '';\n\n\n if (this.isThis) {\n this.messageName += 'This';\n }\n\n this.createMessage();\n },\n\n });\n});", "label_name": "CWE-79", "label": 1} +{"code": " value = value.replace(/src=\" *javascript\\:(.*?)\"/gi, function(m, $1) {\n return 'removed=\"\"';\n });", "label_name": "CWE-79", "label": 1} +{"code": " getItemHtml: function (value) {\n var translatedValue = this.translatedOptions[value] || value;\n\n var html = '' +\n '
    ' +\n '
    ' +\n '' +\n '
    ' +\n '
    ' +\n '' +\n '

    ' +\n '
    ';\n\n return html;\n },", "label_name": "CWE-79", "label": 1} +{"code": "exports.onAccountGetDepositAddress = function(req, res)\n{\n const dataParsed = url.parse(req.url);\n if (!dataParsed || !dataParsed.query || !req.headers['apisign'])\n return onError(req, res, 'Bad request');\n\n const queryStr = querystring.parse(dataParsed.query);\n if (!queryStr.apikey || !queryStr.nonce || !queryStr.currency)\n return onError(req, res, 'Bad request. Required parameter (apikey or nonce or currency) not found.');\n \n utils.GetCoinFromTicker(queryStr.currency, coin => {\n if (!coin || !coin.name) \n return onError(req, res, 'Coin ticker not found');\n\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n \n CheckAPIkey(queryStr.apikey, req.headers['apisign'], fullUrl, ret => {\n try\n {\n if (ret.success == false) throw new Error(ret.message);\n if (ret.key.read == 0) throw new Error('apikey disabled for read');\n \n wallet.GetAccountAddress(ret.key.userid, coin.name, ret => {\n if (ret.result != 'success' || !ret.data) \n return onError(req, res, ret.message);\n\n onSuccess(req, res, {Currency: coin.ticker, Address: ret.data});\n });\n }\n catch(e) {\n return onError(req, res, e.message);\n }\n })\n }); \n}", "label_name": "CWE-89", "label": 0} +{"code": " parsePath (rawPath, opts = {}) {\n let pathObj = {\n locale: WIKI.config.lang.code,\n path: 'home',\n private: false,\n privateNS: '',\n explicitLocale: false\n }\n\n // Clean Path\n rawPath = _.trim(qs.unescape(rawPath))\n if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }\n if (rawPath === '') { rawPath = 'home' }\n\n // Extract Info\n let pathParts = _.filter(_.split(rawPath, '/'), p => !_.isEmpty(p))\n if (pathParts[0].length === 1) {\n pathParts.shift()\n }\n if (localeSegmentRegex.test(pathParts[0])) {\n pathObj.locale = pathParts[0]\n pathObj.explicitLocale = true\n pathParts.shift()\n }\n\n // Strip extension\n if (opts.stripExt && pathParts.length > 0) {\n const lastPart = _.last(pathParts)\n if (lastPart.indexOf('.') > 0) {\n pathParts.pop()\n const lastPartMeta = path.parse(lastPart)\n pathParts.push(lastPartMeta.name)\n }\n }\n\n pathObj.path = _.join(pathParts, '/')\n return pathObj\n },", "label_name": "CWE-22", "label": 2} +{"code": "function usercheck_init_mod(i, opt) {\r\n var obj = document.getElementById('ajax_output_' + opt);\r\n obj.innerHTML = '';\r\n\r\n if (i.value.length < 1)\r\n return;\r\n\r\n var err = new Array();\r\n if (i.value.match(/[^A-Za-z0-9_]/))\r\n err[err.length] = 'Username can only contain letters, numbers and underscores';\r\n if (i.value.length < 3)\r\n err[err.length] = 'Username Too Short';\r\n if (err != '') {\r\n obj.style.color = '#ff0000';\r\n obj.innerHTML = err.join('
    ');\r\n return;\r\n }\r\n\r\n var pqr = i.value;\r\n\r\n if (opt == '1')\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_p, usercheck_error);\r\n\r\n if (opt == '2')\r\n ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_s, usercheck_error);\r\n}\r", "label_name": "CWE-22", "label": 2} +{"code": " reply: () => Promise.resolve()\n };\n const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);\n\n beforeEach(() => {\n sandbox = sinon.sandbox.create().usingPromise(Promise);\n\n sandbox.spy(mockClient, 'reply');\n sandbox.stub(ActiveConnector.prototype, 'setupConnection').resolves();\n });\n afterEach(() => {\n sandbox.restore();\n });\n\n it('// unsuccessful | no argument', () => {\n return cmdFn()\n .then(() => {\n expect(mockClient.reply.args[0][0]).to.equal(504);\n });\n });\n\n it('// unsuccessful | invalid argument', () => {\n return cmdFn({command: {arg: 'blah'}})\n .then(() => {\n expect(mockClient.reply.args[0][0]).to.equal(504);\n });\n });\n\n it('// successful IPv4', () => {\n return cmdFn({command: {arg: '|1|192.168.0.100|35286|'}})\n .then(() => {\n const [ip, port, family] = ActiveConnector.prototype.setupConnection.args[0];\n expect(mockClient.reply.args[0][0]).to.equal(200);\n expect(ip).to.equal('192.168.0.100');\n expect(port).to.equal('35286');\n expect(family).to.equal(4);\n });\n });\n\n it('// successful IPv6', () => {\n return cmdFn({command: {arg: '|2|8536:933f:e7f3:3e91:6dc1:e8c6:8482:7b23|35286|'}})\n .then(() => {\n const [ip, port, family] = ActiveConnector.prototype.setupConnection.args[0];\n expect(mockClient.reply.args[0][0]).to.equal(200);\n expect(ip).to.equal('8536:933f:e7f3:3e91:6dc1:e8c6:8482:7b23');\n expect(port).to.equal('35286');\n expect(family).to.equal(6);\n });\n });\n});", "label_name": "CWE-918", "label": 16} +{"code": "ServerStderr.prototype._write = function(data, encoding, cb) {\n var channel = this._channel;\n var sshstream = channel._client._sshstream;\n var outgoing = channel.outgoing;\n var packetSize = outgoing.packetSize;\n var id = outgoing.id;\n var window = outgoing.window;\n var len = data.length;\n var p = 0;\n var ret;\n var buf;\n var sliceLen;\n\n if (channel.outgoing.state !== 'open')\n return;\n\n while (len - p > 0 && window > 0) {\n sliceLen = len - p;\n if (sliceLen > window)\n sliceLen = window;\n if (sliceLen > packetSize)\n sliceLen = packetSize;\n\n ret = sshstream.channelExtData(id, data.slice(p, p + sliceLen), STDERR);\n\n p += sliceLen;\n window -= sliceLen;\n\n if (!ret) {\n channel._waitClientDrain = true;\n channel._chunkErr = undefined;\n channel._chunkcbErr = cb;\n break;\n }\n }\n\n outgoing.window = window;\n\n if (len - p > 0) {\n if (window === 0)\n channel._waitWindow = true;\n if (p > 0) {\n // partial\n buf = Buffer.allocUnsafe(len - p);\n data.copy(buf, 0, p);\n channel._chunkErr = buf;\n } else\n channel._chunkErr = data;\n channel._chunkcbErr = cb;\n return;\n }\n\n if (!channel._waitClientDrain)\n cb();\n};", "label_name": "CWE-78", "label": 6} +{"code": " function onFinish() {\n self.eof();\n if (server || (!server && !self.allowHalfOpen))\n self.close();\n self.writable = false;\n }", "label_name": "CWE-78", "label": 6} +{"code": " function onError(err) {\n sftp.removeListener('ready', onReady);\n stream.removeListener('exit', onExit);\n cb(err);\n }", "label_name": "CWE-78", "label": 6} +{"code": " function reqCb(err) {\n if (err) {\n chan.close();\n return cb(err);\n }\n if (todo.length)\n todo.shift()();\n }", "label_name": "CWE-78", "label": 6} +{"code": " this._cbfinal = function(allowed, methodsLeft, isPartial) {\n if (!self._finalResponse) {\n self._finalResponse = true;\n cb(self, allowed, methodsLeft, isPartial);\n }\n };", "label_name": "CWE-78", "label": 6} +{"code": " function setReply(type, buf) {\n reply.type = type;\n reply.buf = buf;\n sendReplies();\n }", "label_name": "CWE-78", "label": 6} +{"code": "Server.createServer = function(cfg, listener) {\n return new Server(cfg, listener);\n};", "label_name": "CWE-78", "label": 6} +{"code": "AuthContext.prototype.accept = function() {\n this._cleanup && this._cleanup();\n this._initialResponse = true;\n this._cbfinal(true);\n};", "label_name": "CWE-78", "label": 6} +{"code": " { run: function() {\n var client;\n var server;\n var r;\n\n r = setup(\n this,\n { username: USER,\n privateKey: CLIENT_KEY_RSA_RAW\n },\n { hostKeys: [HOST_KEY_RSA] }\n );\n client = r.client;\n server = r.server;\n\n server.on('connection', function(conn) {\n conn.on('authentication', function(ctx) {\n if (ctx.method === 'none')\n return ctx.reject();\n assert(ctx.method === 'publickey',\n makeMsg('Unexpected auth method: ' + ctx.method));\n assert(ctx.username === USER,\n makeMsg('Unexpected username: ' + ctx.username));\n assert(ctx.key.algo === 'ssh-rsa',\n makeMsg('Unexpected key algo: ' + ctx.key.algo));\n assert.deepEqual(CLIENT_KEY_RSA.getPublicSSH(),\n ctx.key.data,\n makeMsg('Public key mismatch'));\n if (ctx.signature) {\n assert(CLIENT_KEY_RSA.verify(ctx.blob, ctx.signature) === true,\n makeMsg('Could not verify PK signature'));\n ctx.accept();\n } else\n ctx.accept();\n }).on('ready', function() {\n conn.end();\n });\n });\n },", "label_name": "CWE-78", "label": 6} +{"code": "function next() {\n if (Array.isArray(process._events.exit))\n process._events.exit = process._events.exit[1];\n if (++t === tests.length)\n return;\n\n var v = tests[t];\n v.run.call(v);\n}", "label_name": "CWE-78", "label": 6} +{"code": " sock: new net.Socket()\n },\n { hostKeys: [HOST_KEY_RSA] }\n );\n client = r.client;\n server = r.server;\n\n server.on('connection', function(conn) {\n conn.on('authentication', function(ctx) {\n ctx.accept();\n }).on('ready', function() {});\n });\n client.on('ready', function() {\n client.end();\n });\n },", "label_name": "CWE-78", "label": 6} +{"code": " clientcfg.debug = function() {\n var args = new Array(arguments.length + 1);\n args[0] = '[CLIENT]';\n for (var i = 0; i < arguments.length; ++i)\n args[i + 1] = arguments[i];\n console.log.apply(null, args);\n };", "label_name": "CWE-78", "label": 6} +{"code": " function onError(err) {\n var which = (arguments.length >= 3 ? 'client' : 'server');\n assert(false, makeMsg(self.what, 'Unexpected ' + which + ' error: ' + err));\n }", "label_name": "CWE-78", "label": 6} +{"code": "function cleanup() {\n\tclean('.');\n\tclean('async-execute');\n}", "label_name": "CWE-78", "label": 6} +{"code": "module.exports.commit = function (files, message, newVer, tagName, callback) {\n message = escapeQuotes(message.replace(\"%s\", newVer));\n files = files.map(escapeQuotes).join(\" \");\n var functionSeries = [\n function (done) {\n cp.exec(gitApp + \" add \" + files, gitExtra, done);\n },\n\n function (done) {\n cp.exec([gitApp, \"commit\", \"-m\", message].join(\" \"), gitExtra, done);\n },\n\n function (done) {\n cp.exec(\n [gitApp, \"tag\", \"-a\", tagName, \"-m\", message].join(\" \"),\n gitExtra,\n done\n );\n },\n ];\n contra.series(functionSeries, callback);\n};", "label_name": "CWE-78", "label": 6} +{"code": " function parsePaste()\n {\n // skip parsing if no text is given\n if (text === '') {\n return;\n }\n\n if (format === 'markdown') {\n const converter = new showdown.Converter({\n strikethrough: true,\n tables: true,\n tablesHeaderId: true,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true\n });\n // let showdown convert the HTML and sanitize HTML *afterwards*!\n $plainText.html(\n DOMPurify.sanitize(\n converter.makeHtml(text)\n )\n );\n // add table classes from bootstrap css\n $plainText.find('table').addClass('table-condensed table-bordered');\n } else {\n if (format === 'syntaxhighlighting') {\n // yes, this is really needed to initialize the environment\n if (typeof prettyPrint === 'function')\n {\n prettyPrint();\n }\n\n $prettyPrint.html(\n prettyPrintOne(\n Helper.htmlEntities(text), null, true\n )\n );\n } else {\n // = 'plaintext'\n $prettyPrint.text(text);\n }\n Helper.urls2links($prettyPrint);\n $prettyPrint.css('white-space', 'pre-wrap');\n $prettyPrint.css('word-break', 'normal');\n $prettyPrint.removeClass('prettyprint');\n }\n }", "label_name": "CWE-79", "label": 1} +{"code": "pushState:function pushState(condition) {\n this.begin(condition);\n },", "label_name": "CWE-94", "label": 14} +{"code": "!function(a,b){if(a){var c=function(){b(a.lazySizes),a.removeEventListener(\"lazyunveilread\",c,!0)};b=b.bind(null,a,a.document),\"object\"==typeof module&&module.exports?b(require(\"lazysizes\")):a.lazySizes?c():a.addEventListener(\"lazyunveilread\",c,!0)}}(\"undefined\"!=typeof window?window:0,function(a,b,c){\"use strict\";function d(c,d){var e=\"vimeoCallback\"+j,f=b.createElement(\"script\");c+=\"&callback=\"+e,j++,a[e]=function(b){f.parentNode.removeChild(f),delete a[e],d(b)},f.src=c,b.head.appendChild(f)}function e(a,b){d(p.replace(k,a),function(a){a&&a.thumbnail_url&&(b.style.backgroundImage=\"url(\"+a.thumbnail_url+\")\")}),b.addEventListener(\"click\",f)}function f(a){var b=a.currentTarget,c=b.getAttribute(\"data-vimeo\"),d=b.getAttribute(\"data-vimeoparams\")||\"\";d&&!m.test(d)&&(d=\"&\"+d),a.preventDefault(),b.innerHTML='',b.removeEventListener(\"click\",f)}function g(a,b){var d=b.getAttribute(\"data-thumb-size\")||c.cfg.ytThumb||\"hqdefault\";b.style.backgroundImage=\"url(\"+n.replace(k,a).replace(l,d)+\")\",b.addEventListener(\"click\",h)}function h(a){var b=a.currentTarget,c=b.getAttribute(\"data-youtube\"),d=b.getAttribute(\"data-ytparams\")||\"\";d&&!m.test(d)&&(d=\"&\"+d),a.preventDefault(),b.innerHTML='',b.removeEventListener(\"click\",h)}if(b.getElementsByClassName){var i=\"https:\"==location.protocol?\"https:\":\"http:\",j=Date.now(),k=/\\{\\{id}}/,l=/\\{\\{hqdefault}}/,m=/^&/,n=i+\"//img.youtube.com/vi/{{id}}/{{hqdefault}}.jpg\",o=i+\"//www.youtube.com/embed/{{id}}?autoplay=1\",p=i+\"//vimeo.com/api/oembed.json?url=https%3A//vimeo.com/{{id}}\",q=i+\"//player.vimeo.com/video/{{id}}?autoplay=1\";b.addEventListener(\"lazybeforeunveil\",function(a){if(a.detail.instance==c){var b=a.target,d=b.getAttribute(\"data-youtube\"),f=b.getAttribute(\"data-vimeo\");d&&b&&g(d,b),f&&b&&e(f,b)}})}});", "label_name": "CWE-79", "label": 1} +{"code": " replaceInValue: function(value, context) {\n return interpreter.replace(value, context, parseContext);\n }", "label_name": "CWE-915", "label": 35} +{"code": " var digest = function() {\n var updated = false;\n\n entries.forEach(function(e) {\n var interpreter = ConnieLang.firstInnermostInterpreterFromValue(e.value, context);\n if (!interpreter) return;\n\n var newValue = interpreter.replaceInValue(e.value, context);\n if (newValue !== e.value) {\n e.value = newValue;\n updated = true;\n }\n });\n\n return updated;\n };", "label_name": "CWE-915", "label": 35} +{"code": "Cache.prototype.clear = function() {\n this._size = 0\n this._values = Object.create(null)\n}", "label_name": "CWE-915", "label": 35} +{"code": " 'readYAML': function(test) {\n test.expect(4);\n var obj;\n obj = grunt.file.readYAML('test/fixtures/utf8.yaml');\n test.deepEqual(obj, this.object, 'file should be read as utf8 by default and parsed correctly.');\n\n obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml', {encoding: 'iso-8859-1'});\n test.deepEqual(obj, this.object, 'file should be read using the specified encoding.');\n\n test.throws(function() {\n obj = grunt.file.readYAML('test/fixtures/error.yaml');\n }, function(err) {\n return err.message.indexOf('undefined') === -1;\n }, 'error thrown should not contain undefined.');\n\n grunt.file.defaultEncoding = 'iso-8859-1';\n obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml');\n test.deepEqual(obj, this.object, 'changing the default encoding should work.');\n test.done();\n },", "label_name": "CWE-1188", "label": 39} +{"code": "function createDefaultLogger(levels) {\n let levelMaxLen = 0;\n let levelNames = new Map();\n levels.forEach(level => {\n if (level.length > levelMaxLen) {\n levelMaxLen = level.length;\n }\n });\n\n levels.forEach(level => {\n let levelName = level.toUpperCase();\n if (levelName.length < levelMaxLen) {\n levelName += ' '.repeat(levelMaxLen - levelName.length);\n }\n levelNames.set(level, levelName);\n });\n\n let print = (level, entry, message, ...args) => {\n let prefix = '';\n if (entry) {\n if (entry.tnx === 'server') {\n prefix = 'S: ';\n } else if (entry.tnx === 'client') {\n prefix = 'C: ';\n }\n\n if (entry.sid) {\n prefix = '[' + entry.sid + '] ' + prefix;\n }\n\n if (entry.cid) {\n prefix = '[#' + entry.cid + '] ' + prefix;\n }\n }\n\n message = util.format(message, ...args);\n message.split(/\\r?\\n/).forEach(line => {\n console.log(\n '[%s] %s %s',\n new Date()\n .toISOString()\n .substr(0, 19)\n .replace(/T/, ' '),\n levelNames.get(level),\n prefix + line\n );\n });\n };\n\n let logger = {};\n levels.forEach(level => {\n logger[level] = print.bind(null, level);\n });\n\n return logger;\n}", "label_name": "CWE-88", "label": 3} +{"code": " getSocket(options, callback) {\n let socket = net.connect(PORT_NUMBER, 'localhost');\n let errHandler = function(err) {\n callback(err);\n };\n socket.on('error', errHandler);\n socket.on('connect', function() {\n socket.removeListener('error', errHandler);\n callback(null, {\n connection: socket\n });\n });\n }", "label_name": "CWE-88", "label": 3} +{"code": " getSocket(options, callback) {\n let socket = net.connect(PORT_NUMBER, 'localhost');\n let errHandler = function(err) {\n callback(err);\n };\n socket.on('error', errHandler);\n socket.on('connect', function() {\n socket.removeListener('error', errHandler);\n callback(null, {\n connection: socket\n });\n });\n }", "label_name": "CWE-88", "label": 3} +{"code": "OAuthServer.prototype.validateAccessToken = function(username, accessToken) {\n if (!this.users[username] || this.users[username].accessToken !== accessToken || this.users[username].expiresIn < Date.now()) {\n return false;\n } else {\n return true;\n }\n};", "label_name": "CWE-88", "label": 3} +{"code": "module.exports = function apply(doc, patch) {\n if (typeof patch !== OBJECT || patch === null || Array.isArray(patch)) {\n return patch;\n }\n\n if (typeof doc !== OBJECT || doc === null || Array.isArray(doc)) {\n doc = Object.create(null);\n }\n\n const keys = Object.keys(patch);\n for (const key of keys) {\n const v = patch[key];\n if (v === null) {\n delete doc[key];\n continue;\n }\n doc[key] = apply(doc[key], v);\n }\n\n return doc;\n};", "label_name": "CWE-915", "label": 35} +{"code": "\t\t\tfunction uploadFile(file) {\n\t\t\t\tif (file.size> attachmentMaxSize) {\n\t\t\t\t\tvar message = \"!!Upload should be less than \" + Math.round(attachmentMaxSize/1024/1024) + \" Mb!!\";\n\t\t\t\t\tonedev.server.markdown.updateUploadMessage($input, message);\n\t\t\t\t} else {\n\t\t\t\t\tvar xhr = new XMLHttpRequest();\n\t\t\t\t\tvar val = $input.val();\n\t\t\t\t\tvar i=1;\n\t\t\t\t\tvar message = \"[Uploading file...]\";\n\t\t\t\t\twhile (val.indexOf(message) != -1) {\n\t\t\t\t\t\tmessage = \"[Uploading file\" + (++i) + \"...]\";\n\t\t\t\t\t}\n\n\t\t\t\t\txhr.replaceMessage = message;\n\t\t\t\t\tif ($input.range().length == 0) {\n\t\t\t\t\t\t$input.caret(message);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$input.range(message);\n\t\t\t\t\t\t$input.caret($input.caret()+message.length);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\txhr.onload = function() {\n\t\t\t\t\t\tif (xhr.status == 200) { \n\t\t\t\t\t\t\tcallback(\"insertUrl\", xhr.responseText, xhr.replaceMessage);\n\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\tonedev.server.markdown.updateUploadMessage($input, \n\t\t\t\t\t\t\t\t\t\"!!\" + xhr.responseText + \"!!\", xhr.replaceMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\txhr.onerror = function() {\n\t\t\t\t\t\tonedev.server.markdown.updateUploadMessage($input, \n\t\t\t\t\t\t\t\t\"!!Unable to connect to server!!\", xhr.replaceMessage);\n\t\t\t\t\t};\n\t\t\t\t\txhr.open(\"POST\", \"/attachment_upload\", true);\n\t\t\t\t\txhr.setRequestHeader(\"File-Name\", encodeURIComponent(file.name));\n\t\t\t\t\txhr.setRequestHeader(\"Attachment-Support\", attachmentSupport);\n\t\t\t\t\txhr.send(file);\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-502", "label": 15} +{"code": " var update_selected_labels = function() {\n var count = 0;\n $(\".ui-selected\", div_all_tags).not(\".filtered\").each(function() {\n var $this = $(this);\n if ($this.hasClass('alltags-tagset')) {\n count += $this.nextUntil(\":not(.alltags-childtag)\").not(\n \".filtered, .ui-selected\").length;\n } else {\n count++;\n }\n });\n $(\"#id_tags_selected\").text(count ? count + \" selected\" : \"\");\n var tagset = get_selected_tagset();\n if (tagset) {\n $(\"#id_selected_tag_set\").html(\n \"Add a new tag in \" +\n tagset.text() + \" tag set and select it immediately:\");\n } else {\n $(\"#id_selected_tag_set\").text(\n \"Add a new tag and select it immediately:\");\n }\n };", "label_name": "CWE-79", "label": 1} +{"code": "String.prototype.escapeHTML = function(){\n /*\n HTML Escape Before Inserting Untrusted Data into HTML Element Content\n https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention\n _Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into\n _HTML_Element_Content\n */\n var s = this;\n if (!s) {\n return \"\";\n }\n s = s + \"\";\n return s.replace(/[\\&\"<>\\\\]/g, function(s) {\n switch(s) {\n case \"&\": return \"&\";\n case \"\\\\\": return \"\\";\n case '\"': return '\\\"';\n case \"<\": return \"<\";\n case \">\": return \">\";\n default: return s;\n }\n });\n};", "label_name": "CWE-79", "label": 1} +{"code": "\" \"+d.sSortDesc).addClass(\"asc\"==g[e]?d.sSortAsc:\"desc\"==g[e]?d.sSortDesc:c.sSortingClass),b.find(\"span.\"+d.sSortIcon).removeClass(d.sSortJUIAsc+\" \"+d.sSortJUIDesc+\" \"+d.sSortJUI+\" \"+d.sSortJUIAscAllowed+\" \"+d.sSortJUIDescAllowed).addClass(\"asc\"==g[e]?d.sSortJUIAsc:\"desc\"==g[e]?d.sSortJUIDesc:c.sSortingClassJUI))})}}});var yb=function(a){return\"string\"===typeof a?a.replace(/&/g,\"&\").replace(//g,\">\").replace(/\"/g,\""\"):a};u.render={number:function(a,b,c,d,e){return{display:function(h){if(\"number\"!==\ntypeof h&&\"string\"!==typeof h)return h;var f=0>h?\"-\":\"\",g=parseFloat(h);if(isNaN(g))return yb(h);g=g.toFixed(c);h=Math.abs(g);g=parseInt(h,10);h=c?b+(h-g).toFixed(c).substring(2):\"\";0===g&&0===parseFloat(h)&&(f=\"\");return f+(d||\"\")+g.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g,a)+h+(e||\"\")}}},text:function(){return{display:yb,filter:yb}}};l.extend(u.ext.internal,{_fnExternApiFunc:fc,_fnBuildAjax:Oa,_fnAjaxUpdate:Gb,_fnAjaxParameters:Pb,_fnAjaxUpdateDraw:Qb,_fnAjaxDataSrc:Aa,_fnAddColumn:Xa,_fnColumnOptions:Ga,", "label_name": "CWE-79", "label": 1} +{"code": "\tparse: function (text) {\r\n\t\t// not yet possible as we still return new type() JSON\r\n\t\t//\t\tif (!(!(/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/.test(\r\n\t\t//\t\ttext.replace(/\"(\\\\.|[^\"\\\\])*\"/g, ''))) ))\r\n\t\t//\t\t\tthrow new Error(\"Invalid characters in JSON parse string.\"); \r\n\t\tvar regEx = /(\\\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}.*?\\\")|(\\\"\\\\\\/Date\\(.*?\\)\\\\\\/\")/g;\r\n\t\ttext = text.replace(regEx, this.regExDate);\r\n\t\treturn eval('(' + text + ')');\r\n\t},\r", "label_name": "CWE-502", "label": 15} +{"code": "export function esc(value) {\n\tif (typeof value !== 'string') return value;\n\tlet last=ESCAPE.lastIndex=0, tmp=0, out='';\n\twhile (ESCAPE.test(value)) {\n\t\ttmp = ESCAPE.lastIndex - 1;\n\t\tout += value.substring(last, tmp) + CHARS[value[tmp]];\n\t\tlast = tmp + 1;\n\t}\n\treturn out + value.substring(last);\n}", "label_name": "CWE-79", "label": 1} +{"code": "function formcheck_Timetable_course_F4(this_DET) {\n var this_button_id = this_DET.id;\n\n var frmvalidator = new Validator(\"F4\", this_button_id);\n\n var subject_id = document.getElementById(\"subject_id_div\").value;\n if (subject_id == \"new\") {\n frmvalidator.addValidation(\n \"tables[course_subjects][new][TITLE]\",\n \"req\",\n \"Please enter the subject name\"\n );\n frmvalidator.addValidation(\n \"tables[course_subjects][new][TITLE]\",\n \"maxlen=100\",\n \"Max length for subject is 100 characters\"\n );\n } else {\n frmvalidator.addValidation(\n \"inputtables[course_subjects][\" + subject_id + \"][TITLE]\",\n \"req\",\n \"Please enter the course title \"\n );\n frmvalidator.addValidation(\n \"inputtables[course_subjects][\" + subject_id + \"][TITLE]\",\n \"maxlen=100\",\n \"Max length for course title is 100 characters\"\n );\n }\n}", "label_name": "CWE-22", "label": 2} +{"code": " queue.onData = function(paths, end) {\n var escapedPaths = paths.map(\n function(path) {\n return '\"' + path.replace(/\"/g, '\\\\\"') + '\"';\n }\n );\n var command = 'lsof -F n -- ' + escapedPaths.join(' ');\n var options = {\n encoding: 'utf-8',\n maxBuffer: 2 * 1024 * 1024\n };\n Node.child.exec(command, options,\n function(error, stdout, stderr) {\n // lsof returns an error and a status code of 1 if a file is not open:\n if (error && error.code === 1 && stderr.length === 0) error = undefined;\n if (error) {\n if (/No such file or directory/i.test(stderr)) {\n error.code = 'ENOENT';\n }\n return end(error);\n }\n var lines = stdout.split('\\n');\n for (var index = 0, length = lines.length; index < length; index++) {\n var line = lines[index];\n if (line[0] != 'n') continue;\n var candidate = self.unescape(line.slice(1));\n if (files.hasOwnProperty(candidate)) files[candidate] = true;\n }\n end();\n }\n );\n };", "label_name": "CWE-78", "label": 6} +{"code": "generate_mail_credentials = function() {\n var div = $('.mail-infoblock').clone();\n div.find('#mail_configuration').remove();\n var pass=div.find('#v_password').text();\n if (pass==\"\") div.find('#v_password').html(' ');\n var output = div.text();\n output=output.replace(/(?:\\r\\n|\\r|\\n|\\t)/g, \"|\");\n output=output.replace(/ /g, \"\");\n output=output.replace(/\\|\\|/g, \"|\");\n output=output.replace(/\\|\\|/g, \"|\");\n output=output.replace(/\\|\\|/g, \"|\");\n output=output.replace(/^\\|+/g, \"\");\n output=output.replace(/\\|$/, \"\");\n output=output.replace(/ $/, \"\");\n output=output.replace(/:\\|/g, \": \");\n output=output.replace(/\\|/g, \"\\n\");\n //console.log(output);\n $('#v_credentials').val(output);\n}", "label_name": "CWE-79", "label": 1} +{"code": " AnsiUp.prototype.escape_txt_for_html = function (txt) {\n return txt.replace(/[&<>]/gm, function (str) {\n if (str === \"&\")\n return \"&\";\n if (str === \"<\")\n return \"<\";\n if (str === \">\")\n return \">\";\n });\n };", "label_name": "CWE-79", "label": 1} +{"code": " attributeDisplayType(attributeValue) {\n if (this.isAttributeNumber(attributeValue)) {\n return 'number';\n }\n if (this.isAttributeLink(attributeValue)) {\n return 'link';\n }\n return 'text';\n },", "label_name": "CWE-79", "label": 1} +{"code": " notifies.prepare = function prepare() {\n\n var translate = client.translate;\n\n var html = '
    ';\n var messages = client.notifies.notifies;\n var messageCount = client.notifies.notifyCount;\n\n if (messages && messages.length > 0) {\n html += '

    ' + translate('You have administration messages') + '

    ';\n for(var i = 0 ; i < messages.length; i++) {\n /* eslint-disable-next-line security/detect-object-injection */ // verified false positive\n var m = messages[i];\n const ago = Math.round((Date.now() - m.lastRecorded) / 60000);\n html += wrapmessage(translate(m.title), translate(m.message), m.count, ago, m.persistent);\n }\n } else {\n if (messageCount > 0) {\n html = wrapmessage(translate('Admin messages in queue'), translate('Please sign in using the API_SECRET to see your administration messages'));\n } else {\n html = wrapmessage(translate('Queue empty'), translate('There are no admin messages in queue'));\n }\n }\n html += '
    ';\n notifies.drawer.html(html);\n }", "label_name": "CWE-79", "label": 1} +{"code": "http.ServerResponse.prototype.safeRedirect = function (url) {\n const fullURL = new URL(url, config.urlPrefix);\n if (!fullURL.toString().startsWith(config.urlPrefix)) return this.forbidden();\n this.redirect(url);\n};", "label_name": "CWE-601", "label": 11} +{"code": " language: this.getConfiguration('locale').replace('_', '-'),\n theme: \"bootstrap\",\n matcher: matcher\n }};\n\n const templateResultFunc = function (state) {\n console.log(state);\n return jQuery(' ' + state.text + '');\n };\n\n let optionsColor = {...options, ...{\n templateSelection: templateResultFunc,\n templateResult: templateResultFunc\n }};\n\n jQuery(selector + ' ' + elementSelector + ':not([data-renderer=color])').select2(options);\n jQuery(selector + ' ' + elementSelector + '[data-renderer=color]').select2(optionsColor);\n\n jQuery('body').on('reset', 'form', function(event){\n setTimeout(function() {\n jQuery(event.target).find(elementSelector).trigger('change');\n }, 10);\n });\n }", "label_name": "CWE-1236", "label": 12} +{"code": "\tfunction imagePreview(src) {\n\t\timgPreview.getElement().setHtml('');\n\t\tif (isFReaderSupported) {\n\t\t\tvar fileI = t.getContentElement('tab-source', 'file');\n\t\t\tvar n = null;\n\t\t\ttry {\n\t\t\t\tn = fileI.getInputElement().$;\n\t\t\t} catch (e) {\n\t\t\t\tn = null;\n\t\t\t}\n\t\t\tif (n && 'files' in n && n.files && n.files.length > 0 && n.files[0]) {\n\t\t\t\tif ('type' in n.files[0] && !n.files[0].type.match('image.*')) return;\n\t\t\t\tif (!FileReader) return;\n\t\t\t\timgPreview.getElement().setHtml('Loading...');\n\t\t\t\tvar fr = new FileReader();\n\t\t\t\tfr.onload = (function (f) {\n\t\t\t\t\treturn function (e) {\n\t\t\t\t\t\timgPreview.getElement().setHtml('');\n\t\t\t\t\t\timagePreviewLoad(e.target.result);\n\t\t\t\t\t};\n\t\t\t\t})(n.files[0]);\n\t\t\t\tfr.onerror = function () {\n\t\t\t\t\timgPreview.getElement().setHtml('');\n\t\t\t\t};\n\t\t\t\tfr.onabort = function () {\n\t\t\t\t\timgPreview.getElement().setHtml('');\n\t\t\t\t};\n\t\t\t\tfr.readAsDataURL(n.files[0]);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-434", "label": 5} +{"code": "\t\ti.onload = function () {\n\t\t\t/* Remove preview */\n\t\t\timgPreview.getElement().setHtml('');\n\n\t\t\t/* Set attributes */\n\t\t\tif (orgWidth == null || orgHeight == null) {\n\t\t\t\tt.setValueOf('tab-properties', 'width', this.width);\n\t\t\t\tt.setValueOf('tab-properties', 'height', this.height);\n\t\t\t\timgScal = 1;\n\t\t\t\tif (this.height > 0 && this.width > 0) imgScal = this.width / this.height;\n\t\t\t\tif (imgScal <= 0) imgScal = 1;\n\t\t\t} else {\n\t\t\t\torgWidth = null;\n\t\t\t\torgHeight = null;\n\t\t\t}\n\t\t\tthis.id = editor.id + 'previewimage';\n\t\t\tthis.setAttribute('style', 'max-width:400px;max-height:100px;');\n\t\t\tthis.setAttribute('alt', '');\n\n\t\t\t/* Insert preview image */\n\t\t\ttry {\n\t\t\t\tvar p = imgPreview.getElement().$;\n\t\t\t\tif (p) p.appendChild(this);\n\t\t\t} catch (e) {}\n\t\t};", "label_name": "CWE-434", "label": 5} +{"code": " var filter = function(data) {\r\n if (data) {\r\n data = data.replace(new RegExp('', 'gsi'), '');\r\n }\r\n var span = document.createElement('span');\r\n span.innerHTML = data;\r\n parse(span);\r\n return span;\r\n } \r", "label_name": "CWE-79", "label": 1} +{"code": " var parse = function(element) {\r\n // Remove attributes\r\n if (element.attributes && element.attributes.length) {\r\n var image = null;\r\n var style = null;\r\n // Process style attribute\r\n var elementStyle = element.getAttribute('style');\r\n if (elementStyle) {\r\n style = [];\r\n var t = elementStyle.split(';');\r\n for (var j = 0; j < t.length; j++) {\r\n var v = t[j].trim().split(':');\r\n if (validStyle.indexOf(v[0].trim()) >= 0) {\r\n var k = v.shift();\r\n var v = v.join(':');\r\n style.push(k + ':' + v);\r\n }\r\n }\r\n }\r\n // Process image\r\n if (element.tagName == 'IMG') {\r\n if (! obj.options.acceptImages) {\r\n element.remove();\r\n } else {\r\n // Check if is data\r\n element.setAttribute('tabindex', '900');\r\n // Check attributes for persistance\r\n obj.addImage(element.src);\r\n }\r\n } else {\r\n // Remove attributes\r\n var numAttributes = element.attributes.length - 1;\r\n for (var i = numAttributes; i >= 0 ; i--) {\r\n element.removeAttribute(element.attributes[i].name);\r\n }\r\n }\r\n element.style = '';\r\n // Add valid style\r\n if (style && style.length) {\r\n element.setAttribute('style', style.join(';'));\r\n }\r\n }\r\n // Parse children\r\n if (element.children.length) {\r\n for (var i = 0; i < element.children.length; i++) {\r\n parse(element.children[i]);\r\n }\r\n }\r\n\r\n if (remove.indexOf(element.constructor) >= 0) {\r\n element.remove();\r\n }\r\n }\r", "label_name": "CWE-79", "label": 1} +{"code": " obj.refresh = function() {\r\n if (obj.options.responsive == true) {\r\n // Remove arrow\r\n toolbarArrow.remove();\r\n // Move all items to the toolbar\r\n while (toolbarFloating.firstChild) {\r\n toolbarContent.appendChild(toolbarFloating.firstChild);\r\n }\r\n // Width of the c\r\n var rect = el.parentNode.getBoundingClientRect();\r\n // Available parent space\r\n var available = rect.width;\r\n // Toolbar is larger than the parent, move elements to the floating element\r\n if (available < toolbarContent.offsetWidth) {\r\n // Give space to the floating element\r\n available -= 50;\r\n // Move to the floating option\r\n while (toolbarContent.lastChild && available < toolbarContent.offsetWidth) {\r\n toolbarFloating.insertBefore(toolbarContent.lastChild, toolbarFloating.firstChild);\r\n }\r\n }\r\n // Show arrow\r\n if (toolbarFloating.children.length > 0) {\r\n toolbarContent.appendChild(toolbarArrow);\r\n }\r\n }\r\n }\r", "label_name": "CWE-79", "label": 1} +{"code": " var parse = function(element) {\r\n // Remove attributes\r\n if (element.attributes && element.attributes.length) {\r\n var image = null;\r\n var style = null;\r\n // Process style attribute\r\n var elementStyle = element.getAttribute('style');\r\n if (elementStyle) {\r\n style = [];\r\n var t = elementStyle.split(';');\r\n for (var j = 0; j < t.length; j++) {\r\n var v = t[j].trim().split(':');\r\n if (validStyle.indexOf(v[0].trim()) >= 0) {\r\n var k = v.shift();\r\n var v = v.join(':');\r\n style.push(k + ':' + v);\r\n }\r\n }\r\n }\r\n // Process image\r\n if (element.tagName.toUpperCase() == 'IMG') {\r\n if (! obj.options.acceptImages) {\r\n element.parentNode.removeChild(element);\r\n } else {\r\n // Check if is data\r\n element.setAttribute('tabindex', '900');\r\n // Check attributes for persistance\r\n obj.addImage(element.src);\r\n }\r\n } else {\r\n // Remove attributes\r\n var numAttributes = element.attributes.length - 1;\r\n for (var i = numAttributes; i >= 0 ; i--) {\r\n element.removeAttribute(element.attributes[i].name);\r\n }\r\n }\r\n element.style = '';\r\n // Add valid style\r\n if (style && style.length) {\r\n element.setAttribute('style', style.join(';'));\r\n }\r\n }\r\n // Parse children\r\n if (element.children.length) {\r\n for (var i = 0; i < element.children.length; i++) {\r\n parse(element.children[i]);\r\n }\r\n }\r\n\r\n if (remove.indexOf(element.constructor) >= 0) {\r\n element.remove();\r\n }\r\n }\r", "label_name": "CWE-79", "label": 1} +{"code": " _mdEmStrong(str) {\n return str.replace(/(^|\\s|\")(\\\\?)(\\*+)(\\w[^<]*?)\\3/g, (all, b, esc, md, text) => {\n if (md.length == 1) return esc ? all.replace(/^\\\\/, '') : b + '' + text + '';\n if (md.length == 2) return esc ? all.replace(/^\\\\/, '') : b + '' + text + '';\n if (md.length == 3) return esc ? all.replace(/^\\\\/, '') : b + '' + text + '';\n return all;\n });\n }", "label_name": "CWE-79", "label": 1} +{"code": " function clean_data(data, text) {\n if (data === '') {\n return text;\n } else {\n return data.replace(/]/g, ']')\n .replace(/>/g, '>').replace(/W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||\nc(\"cursor\",{hide:!0})};b.addListener(\"shareCursorPositionChanged\",this.shareCursorPositionListener);this.selectionChangeListener=function(M,W){M=function(u){return null!=u?u.id:null};var U=null!=b.currentPage?b.currentPage.getId():null,X=W.getProperty(\"added\");W=W.getProperty(\"removed\");c(\"selectionChange\",{pageId:U,removed:X?X.map(M):[],added:W?W.map(M):[]})};l.getSelectionModel().addListener(mxEvent.CHANGE,this.selectionChangeListener);this.cursorHandler=mxUtils.bind(this,function(){for(var M in y)n(y[M])});", "label_name": "CWE-79", "label": 1} +{"code": "ca,la,ia){function ma(Ma,Ta){null==Ka?(Ia=Ma,Ia=/^https?:\\/\\//.test(Ia)&&!b.editor.isCorsEnabledForUrl(Ia)?PROXY_URL+\"?url=\"+encodeURIComponent(Ia):TEMPLATE_PATH+\"/\"+Ia,mxUtils.get(Ia,mxUtils.bind(this,function(Ua){200<=Ua.getStatus()&&299>=Ua.getStatus()&&(Ka=Ua.getText());Ta(Ka,Ia)}))):Ta(Ka,Ia)}function qa(Ma,Ta,Ua){if(null!=Ma&&mxUtils.isAncestorNode(document.body,na)){Ma=mxUtils.parseXml(Ma);Ma=Editor.parseDiagramNode(Ma.documentElement);var Za=new mxCodec(Ma.ownerDocument),Wa=new mxGraphModel;\nZa.decode(Ma,Wa);Ma=Wa.root.getChildAt(0).children;b.sidebar.createTooltip(na,Ma,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!=ya?mxResources.get(ya,null,ya):null,!0,new mxPoint(Ta,Ua),!0,function(){Ya=null!=b.sidebar.tooltip&&\"none\"!=b.sidebar.tooltip.style.display;z(na,null,null,oa,ha,ia)},!0,!1)}}function pa(Ma,Ta){null==oa||Ra||", "label_name": "CWE-79", "label": 1} +{"code": "document.createElement(\"div\");pa.className=\"geTempDlgNewDiagramCatItemLbl\";pa.innerHTML=qa;ma.appendChild(pa);Ca.appendChild(ma);mxEvent.addListener(ma,\"click\",function(){function Ka(){var Ra=Ia.querySelector(\".geTemplateDrawioCatLink\");null!=Ra?Ra.click():setTimeout(Ka,200)}Z=!0;var Ia=M.querySelector(\".geTemplatesList\");Ia.style.display=\"block\";Ba.style.width=\"\";Na.style.display=\"\";Na.value=\"\";ba=null;Ka()});fa.style.display=ha.length<=ca?\"none\":\"\"}function G(ha,da,ca){function la(Qa,Ya){var Ma=", "label_name": "CWE-79", "label": 1} +{"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-79", "label": 1} +{"code": "D=this.editor.graph.getModel().getStyle(D),this.styleInput.value=D||\"\",this.styleInput.style.visibility=\"visible\"):this.styleInput.style.visibility=\"hidden\"})));var L=this.isSelectionAllowed;this.isSelectionAllowed=function(D){return mxEvent.getSource(D)==this.styleInput?!0:L.apply(this,arguments)}}z=document.getElementById(\"geInfo\");null!=z&&z.parentNode.removeChild(z);if(Graph.fileSupport&&(!this.editor.chromeless||this.editor.editable)){var C=null;mxEvent.addListener(g.container,\"dragleave\",function(D){g.isEnabled()&&", "label_name": "CWE-79", "label": 1} +{"code": "urlParams.edge;Graph.prototype.hiddenTags=null;Graph.prototype.defaultMathEnabled=!1;var A=Graph.prototype.init;Graph.prototype.init=function(){function u(N){E=N}A.apply(this,arguments);this.hiddenTags=[];window.mxFreehand&&(this.freehand=new mxFreehand(this));var E=null;mxEvent.addListener(this.container,\"mouseenter\",u);mxEvent.addListener(this.container,\"mousemove\",u);mxEvent.addListener(this.container,\"mouseleave\",function(N){E=null});this.isMouseInsertPoint=function(){return null!=E};var J=this.getInsertPoint;", "label_name": "CWE-79", "label": 1} +{"code": "var GoogleSitesDialog=function(b,e){function f(){var D=null!=C&&null!=C.getTitle()?C.getTitle():this.defaultFilename;if(z.checked&&\"\"!=q.value){var G=\"https://www.draw.io/gadget.xml?type=4&diagram=\"+encodeURIComponent(mxUtils.htmlEntities(q.value));null!=D&&(G+=\"&title=\"+encodeURIComponent(D));0\")}var B=this.editor.graph.getGraphBounds(),I=this.getSelectedPageIndex();if(this.isExportToCanvas())this.editor.exportToCanvas(mxUtils.bind(this,function(z){var L=l?this.getFileData(!0):null;z=", "label_name": "CWE-79", "label": 1} +{"code": "function(e){var f=e.split(\"/\");return 1=u.length)){for(var Z=ea=0;ZmxUtils.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-79", "label": 1} +{"code": "\"rough\")?this.createComicCanvas(Q):this.createRoughCanvas(Q)};var J=mxImageShape.prototype.paintVertexShape;mxImageShape.prototype.paintVertexShape=function(Q,R,Y,ba,ea){null!=Q.handJiggle&&Q.handJiggle.passThrough||J.apply(this,arguments)};var T=mxShape.prototype.paint;mxShape.prototype.paint=function(Q){var R=Q.addTolerance,Y=!0;null!=this.style&&(Y=\"1\"==mxUtils.getValue(this.style,mxConstants.STYLE_POINTER_EVENTS,\"1\"));if(null!=Q.handJiggle&&Q.handJiggle.constructor==u&&!this.outline){Q.save();\nvar ba=this.fill,ea=this.stroke;this.stroke=this.fill=null;var Z=this.configurePointerEvents,fa=Q.setStrokeColor;Q.setStrokeColor=function(){};var aa=Q.setFillColor;Q.setFillColor=function(){};Y||null==ba||(this.configurePointerEvents=function(){});Q.handJiggle.passThrough=!0;T.apply(this,arguments);Q.handJiggle.passThrough=!1;Q.setFillColor=aa;Q.setStrokeColor=fa;this.configurePointerEvents=Z;this.stroke=ea;this.fill=ba;Q.restore();Y&&null!=ba&&(Q.addTolerance=function(){})}T.apply(this,arguments);\nQ.addTolerance=R};var N=mxShape.prototype.paintGlassEffect;mxShape.prototype.paintGlassEffect=function(Q,R,Y,ba,ea,Z){null!=Q.handJiggle&&Q.handJiggle.constructor==u?(Q.handJiggle.passThrough=!0,N.apply(this,arguments),Q.handJiggle.passThrough=!1):N.apply(this,arguments)}})();Editor.fastCompress=function(u){return null==u||0==u.length||\"undefined\"===typeof pako?u:Graph.arrayBufferToString(pako.deflateRaw(u))};Editor.fastDecompress=function(u){return null==u||0==u.length||\"undefined\"===typeof pako?", "label_name": "CWE-79", "label": 1} +{"code": "T.appendChild(T.importNode(u[0],!0)),T=T.documentElement));return T};Editor.getDiagramNodeXml=function(u){var E=mxUtils.getTextContent(u),J=null;0N){J=u.substring(N,ba);break}}10==Y&&(\"endobj\"==E?R=null:\"obj\"==E.substring(E.length-3,E.length)||\"xref\"==E||\"trailer\"==E?(R=[],Q[E.split(\" \")[0]]=R):null!=R&&R.push(E),\nE=\"\")}null==J&&(J=Editor.extractGraphModelFromXref(Q));null!=J&&(J=decodeURIComponent(J.replace(/\\\\\\(/g,\"(\").replace(/\\\\\\)/g,\")\")));return J};Editor.extractGraphModelFromXref=function(u){var E=u.trailer,J=null;null!=E&&(E=/.* \\/Info (\\d+) (\\d+) R/g.exec(E.join(\"\\n\")),null!=E&&0T.indexOf(\"mxPageSelector\")&&0q.length){A.view.validate();var ca=new mxFastOrganicLayout(A);ca.forceConstant=3*W;ca.disableEdgeStyle=!1;ca.resetEdges=!1;var la=ca.isVertexIgnored;ca.isVertexIgnored=function(ia){return la.apply(this,arguments)||0>mxUtils.indexOf(q,\nia)};this.executeLayout(function(){ca.execute(A.getDefaultParent());ya()},!0,u);u=null}}this.hideDialog()}finally{A.model.endUpdate()}null!=u&&u()}}catch(ia){this.handleError(ia)}};EditorUi.prototype.getSearch=function(d){var g=\"\";if(\"1\"!=urlParams.offline&&\"1\"!=urlParams.demo&&null!=d&&0mxUtils.indexOf(d,l)&&null!=urlParams[l]&&(g+=k+l+\"=\"+urlParams[l],k=\"&\")}else g=window.location.search;return g};EditorUi.prototype.getUrl=function(d){d=", "label_name": "CWE-79", "label": 1} +{"code": "function(K){var F=x.length;if(1===F%2||F>=f){var H=0,S=0,V,M=0;for(V=K;Vc&&!mxClient.IS_IOS?C.firstChild.nextSibling.setAttribute(\"title\",D.shortcut):l.apply(this,arguments)};var p=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){p.apply(this,arguments);if(null!=this.userElement){var C=this.userElement;C.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+C.style.display;C.className=\"geToolbarButton\";C.innerHTML=\"\";C.style.backgroundImage=\"url(\"+Editor.userImage+\")\";C.style.backgroundPosition=\"center center\";", "label_name": "CWE-79", "label": 1} +{"code": "function(J){mxEvent.isConsumed(J)||((mxEvent.isControlDown(J)||mxClient.IS_MAC&&mxEvent.isMetaDown(J))&&13==J.keyCode?(E.click(),mxEvent.consume(J)):27==J.keyCode&&(u.click(),mxEvent.consume(J)))}));E.focus();E.className=\"geCommentEditBtn gePrimaryBtn\";X.appendChild(E);F.insertBefore(X,M);W.style.display=\"none\";M.style.display=\"none\";U.focus()}function g(K,F){F.innerHTML=\"\";K=new Date(K.modifiedDate);var H=b.timeSince(K);null==H&&(H=mxResources.get(\"lessThanAMinute\"));mxUtils.write(F,mxResources.get(\"timeAgo\",\n[H],\"{1} ago\"));F.setAttribute(\"title\",K.toLocaleDateString()+\" \"+K.toLocaleTimeString())}function k(K){var F=document.createElement(\"img\");F.className=\"geCommentBusyImg\";F.src=IMAGE_PATH+\"/spin.gif\";K.appendChild(F);K.busyImg=F}function l(K){K.style.border=\"1px solid red\";K.removeChild(K.busyImg)}function p(K){K.style.border=\"\";K.removeChild(K.busyImg)}function q(K,F,H,S,V){function M(N,Q,R){var Y=document.createElement(\"li\");Y.className=\"geCommentAction\";var ba=document.createElement(\"a\");ba.className=", "label_name": "CWE-79", "label": 1} +{"code": "function(u,E,J,T){for(var N=0;N'+Graph.compress('')+\"\",qa(Ta,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma))):(b.sidebar.currentElt=\nna,Ra=!0,ma(oa,function(Ua){Ra&&b.sidebar.currentElt==na&&qa(Ua,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma));Ra=!1})))}var na=document.createElement(\"div\");na.className=\"geTemplate\";na.style.position=\"relative\";na.style.height=Ha+\"px\";na.style.width=ra+\"px\";var Ka=null,Ia=oa;Editor.isDarkMode()&&(na.style.filter=\"invert(100%)\");null!=ya?na.setAttribute(\"title\",mxResources.get(ya,null,ya)):null!=wa&&0ka.max&&(ja=ka.max);ja=encodeURIComponent((\"int\"==va?parseInt(ja):ja)+\"\");T(za,ja,ka)}var ba=document.createElement(\"input\");P(wa,ba,!0);ba.value=decodeURIComponent(ta);ba.className=\"gePropEditor\";\"int\"!=va&&\"float\"!=va||ka.allowAuto||(ba.type=\"number\",ba.step=\"int\"==va?\"1\":\"any\",null!=ka.min&&(ba.min=parseFloat(ka.min)),null!=ka.max&&(ba.max=parseFloat(ka.max)));p.appendChild(ba);mxEvent.addListener(ba,\"keypress\",function(ja){13==ja.keyCode&&ca()});ba.focus();mxEvent.addListener(ba,", "label_name": "CWE-79", "label": 1} +{"code": "this.startDrawing=function(){n(!0)};this.isDrawing=function(){return x};var y=mxUtils.bind(this,function(J){if(d){var E=c.length,H=A&&0c.length;H||D.push.apply(D,c);c=[];D.push(null);u.push(d);d=null;(H||k)&&this.stopDrawing();k&&2<=E&&this.startDrawing();mxEvent.consume(J)}}),K=new mxCell;K.edge=!0;var B=function(){var J=b.getCurrentCellStyle(K);J=mxUtils.getValue(b.currentVertexStyle,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(J,mxConstants.STYLE_STROKECOLOR,\"#000\"));\"default\"==", "label_name": "CWE-79", "label": 1} +{"code": "function(y){this.spinner.stop();this.handleError(y)})})))}}),mxUtils.bind(this,function(){this.hideDialog()}),mxResources.get(\"saveAs\"),mxResources.get(\"download\"),!1,!1,v,null,1=n.getStatus()?(this.updateDiagram(n.getText()),L()):this.handleError({message:mxResources.get(\"error\")+\" \"+n.getStatus()}))}),mxUtils.bind(this,function(n){this.handleError(n)}))}),L=mxUtils.bind(this,function(){window.clearTimeout(A);A=window.setTimeout(z,x)});this.editor.addListener(\"pageSelected\",mxUtils.bind(this,function(){L();z()}));L();z()}null!=e&&e()});null!=c.url&&0 Bob: Authentication Request\\nBob --\\x3e Alice: Authentication Response\\n\\nAlice -> Bob: Another authentication Request\\nAlice <-- Bob: Another authentication Response\\n@enduml\"==", "label_name": "CWE-79", "label": 1} +{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-79", "label": 1} +{"code": "d.executeLayoutList(K);d.customLayoutConfig=K}catch(B){d.handleError(B),null!=window.console&&console.error(B)}},null,null,null,null,null,!0,null,null,\"https://www.diagrams.net/doc/faq/apply-layouts\");d.showDialog(n.container,620,460,!0,!0);n.init()});k=this.get(\"layout\");var x=k.funct;k.funct=function(n,y){x.apply(this,arguments);n.addItem(mxResources.get(\"orgChart\"),null,function(){function K(){\"undefined\"!==typeof mxOrgChartLayout||d.loadingOrgChart||d.isOffline(!0)?J():d.spinner.spin(document.body,\nmxResources.get(\"loading\"))&&(d.loadingOrgChart=!0,\"1\"==urlParams.dev?mxscript(\"js/orgchart/bridge.min.js\",function(){mxscript(\"js/orgchart/bridge.collections.min.js\",function(){mxscript(\"js/orgchart/OrgChart.Layout.min.js\",function(){mxscript(\"js/orgchart/mxOrgChartLayout.js\",J)})})}):mxscript(\"js/extensions.min.js\",J))}var B=null,F=20,G=20,N=!0,J=function(){d.loadingOrgChart=!1;d.spinner.stop();if(\"undefined\"!==typeof mxOrgChartLayout&&null!=B&&N){var X=d.editor.graph,p=new mxOrgChartLayout(X,B,", "label_name": "CWE-79", "label": 1} +{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-79", "label": 1} +{"code": "Math.min(Y,Math.max(parseInt(aa.value),parseInt(ea.value))));ea.value=Math.max(1,Math.min(Y,Math.min(parseInt(aa.value),parseInt(ea.value))))}function T(ya){function va(Ha,Na,Pa){var Qa=Ha.useCssTransforms,Ya=Ha.currentTranslate,La=Ha.currentScale,Ta=Ha.view.translate,Ua=Ha.view.scale;Ha.useCssTransforms&&(Ha.useCssTransforms=!1,Ha.currentTranslate=new mxPoint(0,0),Ha.currentScale=1,Ha.view.translate=new mxPoint(0,0),Ha.view.scale=1);var Za=Ha.getGraphBounds(),Wa=0,bb=0,Va=pa.get(),ab=1/Ha.pageScale,\n$a=xa.checked;if($a){ab=parseInt(ta.value);var hb=parseInt(ka.value);ab=Math.min(Va.height*hb/(Za.height/Ha.view.scale),Va.width*ab/(Za.width/Ha.view.scale))}else ab=parseInt(Fa.value)/(100*Ha.pageScale),isNaN(ab)&&(ra=1/Ha.pageScale,Fa.value=\"100 %\");Va=mxRectangle.fromRectangle(Va);Va.width=Math.ceil(Va.width*ra);Va.height=Math.ceil(Va.height*ra);ab*=ra;!$a&&Ha.pageVisible?(Za=Ha.getPageLayout(),Wa-=Za.x*Va.width,bb-=Za.y*Va.height):$a=!0;if(null==Na){Na=PrintDialog.createPrintPreview(Ha,ab,Va,", "label_name": "CWE-79", "label": 1} +{"code": "A=this.editor.graph,z=null,L=null,M=null,n=null,y=null,K=null,B=null,F=\"whiteSpace=wrap;html=1;\",G=null,N=null,J=\"\",E=\"auto\",H=\"auto\",S=null,U=null,Q=40,W=40,V=100,X=0,p=function(){null!=e?e(ta):(A.setSelectionCells(ta),A.scrollCellToVisible(A.getSelectionCell()))},C=A.getFreeInsertPoint(),I=C.x,T=C.y;C=T;var P=null,O=\"auto\";N=null;for(var R=[],Y=null,da=null,ha=0;hae};EditorUi.prototype.resizeImage=function(c,e,g,k,m,q,v){m=null!=m?m:this.maxImageSize;var x=Math.max(1,c.width),A=Math.max(1,c.height);if(k&&this.isResampleImageSize(null!=v?v:e.length,q))try{var z=Math.max(x/m,A/m);if(1\");2<=S.length&&(N=J(S[0]),E=J(S[S.length-1]),S=new mxCell(2=Math.max(V.x,U.x)||S&&Math.min(V.y+V.height,U.y+U.height)>=Math.max(V.y,U.y))&&Q.push(V)}Q.sort(function(X,p){return S?X.x+X.width-p.x-p.width:X.y+X.height-\np.y-p.height})}return Q}function q(H,S){var U=c(H),Q=S==mxConstants.DIRECTION_EAST||S==mxConstants.DIRECTION_WEST;(U==mxConstants.DIRECTION_EAST||U==mxConstants.DIRECTION_WEST)==Q&&U!=S?v.actions.get(\"selectParent\").funct():U==S?(S=x.getOutgoingTreeEdges(H),null!=S&&0u;u++)for(var t=u,D=0;8>D;D++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[u]=t;Editor.updateCRC=function(p,C,I,T){for(var P=\n0;P>>8;return p};Editor.crc32=function(p){for(var C=-1,I=0;I>>8^Editor.crcTable[(C^p.charCodeAt(I))&255];return(C^-1)>>>0};Editor.writeGraphModelToPng=function(p,C,I,T,P){function O(Z,ea){var aa=da;da+=ea;return Z.substring(aa,da)}function R(Z){Z=O(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}p=p.substring(p.indexOf(\",\")+", "label_name": "CWE-79", "label": 1} +{"code": "ia){ja=fa.getAttribute(\"section\");ba=fa.getAttribute(\"subsection\");if(null==ja&&(ma=ia.indexOf(\"/\"),ja=ia.substring(0,ma),null==ba)){var qa=ia.indexOf(\"/\",ma+1);-1'),d.showDialog(y.container,450,240,!0,!0),y.init()):d.handleError({message:mxResources.get(\"invalidPublicUrl\")})})}));d.actions.put(\"embedImage\",", "label_name": "CWE-79", "label": 1} +{"code": "Ga),!0,null,!0);var Ha=document.createElement(\"div\");Ha.className=\"geTempDlgDialogMask\";Q.appendChild(Ha);var Na=b.sidebar.hideTooltip;b.sidebar.hideTooltip=function(){Ha&&(Q.removeChild(Ha),Ha=null,Na.apply(this,arguments),b.sidebar.hideTooltip=Na)};mxEvent.addListener(Ha,\"click\",function(){b.sidebar.hideTooltip()})}}var qa=null;if(Ca||b.sidebar.currentElt==ca)b.sidebar.hideTooltip();else{var oa=function(na){Ca&&b.sidebar.currentElt==ca&&ma(na,mxEvent.getClientX(ja),mxEvent.getClientY(ja));Ca=!1;\nba.src=\"/images/icon-search.svg\"};b.sidebar.hideTooltip();b.sidebar.currentElt=ca;Ca=!0;ba.src=\"/images/aui-wait.gif\";fa.isExt?e(fa,oa,function(){A(mxResources.get(\"cantLoadPrev\"));Ca=!1;ba.src=\"/images/icon-search.svg\"}):ia(fa.url,oa)}}function n(fa,ca,ba){if(null!=C){for(var ja=C.className.split(\" \"),ia=0;iamxUtils.indexOf(d,va))&&(Ca=mxUtils.setStyle(Ca,va,Ra))}Editor.simpleLabels&&(Ca=mxUtils.setStyle(mxUtils.setStyle(Ca,\"html\",null),\"whiteSpace\",null));Q.setStyle(J,Ca)}}finally{Q.endUpdate()}return I};n.addListener(\"cellsInserted\",function(I,V){q(V.getProperty(\"cells\"),null,null,null,null,!0,!0)});n.addListener(\"textInserted\",function(I,V){q(V.getProperty(\"cells\"),!0)});this.insertHandler=q;this.createDivs();this.createUi();this.refresh();var y=mxUtils.bind(this,", "label_name": "CWE-79", "label": 1} +{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-79", "label": 1} +{"code": "ma);H.moveCells(ma,N,W)},!0,u);u=null}else if(\"organic\"==P||\"auto\"==P&&ma.length>y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=u&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=", "label_name": "CWE-79", "label": 1} +{"code": "this.buttonContainer.style.top=\"6px\";this.editor.fireEvent(new mxEventObject(\"statusChanged\"))}};var E=Sidebar.prototype.getTooltipOffset;Sidebar.prototype.getTooltipOffset=function(O,X){if(null==this.editorUi.sidebarWindow||mxUtils.isAncestorNode(this.editorUi.picker,O)){var ea=mxUtils.getOffset(this.editorUi.picker);ea.x+=this.editorUi.picker.offsetWidth+4;ea.y+=O.offsetTop-X.height/2+16;return ea}var ka=E.apply(this,arguments);ea=mxUtils.getOffset(this.editorUi.sidebarWindow.window.div);ka.x+=\nea.x-16;ka.y+=ea.y;return ka};var C=Menus.prototype.createPopupMenu;Menus.prototype.createPopupMenu=function(O,X,ea){var ka=this.editorUi.editor.graph;O.smartSeparators=!0;C.apply(this,arguments);\"1\"==urlParams.sketch?ka.isEnabled()&&(O.addSeparator(),1==ka.getSelectionCount()&&this.addMenuItems(O,[\"-\",\"lockUnlock\"],null,ea)):1==ka.getSelectionCount()?(ka.isCellFoldable(ka.getSelectionCell())&&this.addMenuItems(O,ka.isCellCollapsed(X)?[\"expand\"]:[\"collapse\"],null,ea),this.addMenuItems(O,[\"collapsible\",", "label_name": "CWE-79", "label": 1} +{"code": "function(z){var L=null;null!=z&&0S.offsetTop-S.offsetHeight/2?\"70px\":\"10px\");else{for(var za=", "label_name": "CWE-79", "label": 1} +{"code": "S&&S(M)}}))}catch(L){null!=S&&S(L)}}),N,sa)}catch(Pa){null!=S&&S(Pa)}};Editor.crcTable=[];for(var D=0;256>D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=\nva;va+=Ba;return sa.substring(ta,va)}function Z(sa){sa=P(sa,4);return sa.charCodeAt(3)+(sa.charCodeAt(2)<<8)+(sa.charCodeAt(1)<<16)+(sa.charCodeAt(0)<<24)}function oa(sa){return String.fromCharCode(sa>>24&255,sa>>16&255,sa>>8&255,sa&255)}u=u.substring(u.indexOf(\",\")+1);u=window.atob?atob(u):Base64.decode(u,!0);var va=0;if(P(u,8)!=String.fromCharCode(137)+\"PNG\"+String.fromCharCode(13,10,26,10))null!=S&&S();else if(P(u,4),\"IHDR\"!=P(u,4))null!=S&&S();else{P(u,17);S=u.substring(0,va);do{var Aa=Z(u);if(\"IDAT\"==", "label_name": "CWE-79", "label": 1} +{"code": "mxEvent.getClientX(za);I.popupMenuHandler.hideMenu();mxEvent.consume(za)});mxEvent.addGestureListeners(document.body,null,function(za){var wa=!1;null!=Ma&&(U.diagramContainer.style.width=Math.max(20,Qa+mxEvent.getClientX(za)-Ma)+\"px\",wa=!0);null!=Oa&&(U.diagramContainer.style.height=Math.max(20,Ta+mxEvent.getClientY(za)-Oa)+\"px\",wa=!0);wa&&((window.opener||window.parent).postMessage(JSON.stringify({event:\"resize\",fullscreen:Editor.inlineFullscreen,rect:U.diagramContainer.getBoundingClientRect()}),\n\"*\"),Z(),U.refresh())},function(za){null==Ma&&null==Oa||mxEvent.consume(za);Oa=Ma=null});this.diagramContainer.style.borderRadius=\"4px\";document.body.style.backgroundColor=\"transparent\";U.bottomResizer.style.visibility=\"hidden\";U.rightResizer.style.visibility=\"hidden\";P.style.visibility=\"hidden\";W.style.visibility=\"hidden\";S.style.display=\"none\"}\"1\"==urlParams.prefetchFonts&&U.editor.loadFonts()}}};", "label_name": "CWE-79", "label": 1} +{"code": "function pa(){mxEllipse.call(this)}function ua(){mxEllipse.call(this)}function ya(){mxRhombus.call(this)}function Fa(){mxEllipse.call(this)}function Ma(){mxEllipse.call(this)}function Oa(){mxEllipse.call(this)}function Qa(){mxEllipse.call(this)}function Ta(){mxActor.call(this)}function za(){mxActor.call(this)}function wa(){mxActor.call(this)}function Ea(c,l,x,p){mxShape.call(this);this.bounds=c;this.fill=l;this.stroke=x;this.strokewidth=null!=p?p:1;this.rectStyle=\"square\";this.size=10;this.absoluteCornerSize=", "label_name": "CWE-79", "label": 1} +{"code": "S&&S(La)}};za.onerror=function(wa){null!=S&&S(wa)};za.src=ua}else L()}catch(wa){null!=S&&S(wa)}});Za.onerror=function(L){null!=S&&S(L)};Aa&&this.graph.addSvgShadow(Pa);this.graph.mathEnabled&&this.addMathCss(Pa);var z=mxUtils.bind(this,function(){try{null!=this.resolvedFontCss&&this.addFontCss(Pa,this.resolvedFontCss),Za.src=Editor.createSvgDataUri(mxUtils.getXml(Pa))}catch(L){null!=S&&S(L)}});this.embedExtFonts(mxUtils.bind(this,function(L){try{null!=L&&this.addFontCss(Pa,L),this.loadFonts(z)}catch(M){null!=", "label_name": "CWE-79", "label": 1} +{"code": "eb);this.updateSvgLinks(Da,ua,!0);this.addForeignObjectWarning(eb,Da);return Da}finally{Qa&&(this.useCssTransforms=!0,this.view.revalidate(),this.sizeDidChange())}};Graph.prototype.addForeignObjectWarning=function(z,L){if(\"0\"!=urlParams[\"svg-warning\"]&&0y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=u&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=", "label_name": "CWE-79", "label": 1} +{"code": "fa,la,ra){R.addItem(la,null,mxUtils.bind(this,function(){var u=new CreateGraphDialog(O,la,ra);O.showDialog(u.container,620,420,!0,!1);u.init()}),fa)};this.put(\"insertLayout\",new Menu(mxUtils.bind(this,function(R,fa){for(var la=0;lathis.opacity?\"alpha(opacity=\"+this.opacity+\")\":\"\";this.node.style.filter=b;this.flipH&&this.flipV?b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)\":this.flipH?b+=\"progid:DXImageTransform.Microsoft.BasicImage(mirror=1)\":this.flipV&&(b+=\"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)\");a.style.filter!=b&&(a.style.filter=b);\"image\"==\na.nodeName?a.style.rotation=this.rotation:0!=this.rotation?mxUtils.setPrefixedStyle(a.style,\"transform\",\"rotate(\"+this.rotation+\"deg)\"):mxUtils.setPrefixedStyle(a.style,\"transform\",\"\");a.style.width=this.node.style.width;a.style.height=this.node.style.height;this.node.style.backgroundImage=\"\";this.node.appendChild(a)}else this.setTransparentBackgroundImage(this.node)};function mxLabel(a,b,c,d){mxRectangleShape.call(this,a,b,c,d)}mxUtils.extend(mxLabel,mxRectangleShape);", "label_name": "CWE-94", "label": 14} +{"code": "f.setCellStyles(mxConstants.STYLE_ROTATION,Number(L.value),[e[M]])}}finally{f.getModel().endUpdate()}});O.className=\"geBtn gePrimaryBtn\";mxEvent.addListener(m,\"keypress\",function(M){13==M.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(C){for(C=document.elementFromPoint(C.clientX,\nC.clientY);null!=C&&C.parentNode!=x;)C=C.parentNode;var G=null;if(null!=C){var N=x.firstChild;for(G=0;null!=N&&N!=C;)N=N.nextSibling,G++}return G}function d(C,G,N,I,F,H,R,W,J){try{if(b.spinner.stop(),null==G||\"image/\"==G.substring(0,6))if(null==C&&null!=R||null==z[C]){var V=function(){Q.innerHTML=\"\";Q.style.cursor=\"pointer\";Q.style.whiteSpace=\"nowrap\";Q.style.textOverflow=\"ellipsis\";mxUtils.write(Q,null!=S.title&&0
    \");a=this.replaceLinefeeds?a.replace(/\\n/g,\"
    \"):a;var b=null!=this.background&&this.background!=mxConstants.NONE?this.background:null,c=null!=this.border&&this.border!=mxConstants.NONE?this.border:null;if(\"fill\"==this.overflow||\n\"width\"==this.overflow)null!=b&&(this.node.style.backgroundColor=b),null!=c&&(this.node.style.border=\"1px solid \"+c);else{var d=\"\";null!=b&&(d+=\"background-color:\"+mxUtils.htmlEntities(b)+\";\");null!=c&&(d+=\"border:1px solid \"+mxUtils.htmlEntities(c)+\";\");a='
    '+a+\"
    \"}this.node.innerHTML=\na;a=this.node.getElementsByTagName(\"div\");0'],{type:\"text/html\"})});navigator.clipboard.write([d])[\"catch\"](l)};EditorUi.prototype.copyCells=function(d,g){var k=this.editor.graph;if(k.isSelectionEmpty())d.innerHTML=\"\";else{var l=\nmxUtils.sortCells(k.model.getTopmostCells(k.getSelectionCells())),p=mxUtils.getXml(k.encodeCells(l));mxUtils.setTextContent(d,encodeURIComponent(p));g?(k.removeCells(l,!1),k.lastPasteXml=null):(k.lastPasteXml=p,k.pasteCounter=0);d.focus();document.execCommand(\"selectAll\",!1,null)}};EditorUi.prototype.copyXml=function(){var d=null;if(Editor.enableNativeCipboard){var g=this.editor.graph;g.isSelectionEmpty()||(d=mxUtils.sortCells(g.getExportableCells(g.model.getTopmostCells(g.getSelectionCells()))),", "label_name": "CWE-94", "label": 14} +{"code": "null!=na){ca=ia.getAttribute(\"section\");aa=ia.getAttribute(\"subsection\");if(null==ca&&(la=na.indexOf(\"/\"),ca=na.substring(0,la),null==aa)){var qa=na.indexOf(\"/\",la+1);-1 0) ?\n\t\t\t\t\t\t\tentry.title : mxResources.get('untitled'));\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (entry.title == null || entry.title.length == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlabel.style.color = '#d0d0d0';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlabel.style.color = '';\n\t\t\t\t\t\t}\n\t\t\t\t\t};", "label_name": "CWE-94", "label": 14} +{"code": "\t\t\tfunction toggleResolve(evt)\n\t\t\t{\n\t\t\t\tfunction doToggle()\n\t\t\t\t{\n\t\t\t\t\tvar resolveActionLnk = evt.target;\n\t\t\t\t\tresolveActionLnk.innerHTML = '';\n\n\t\t\t\t\tcomment.isResolved = !comment.isResolved;\n\t\t\t\t\tmxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));\n\t\t\t\t\tvar actionsDisplay = comment.isResolved? 'none' : '';\n\t\t\t\t\tvar replies = collectReplies(comment).replies;\n\t\t\t\t\tvar color = (Editor.isDarkMode()) ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');\n\t\t\t\t\t\n\t\t\t\t\tfor (var i = 0; i < replies.length; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\treplies[i].style.backgroundColor = color;\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar forOpenActions = replies[i].querySelectorAll('.geCommentAction');\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (var j = 0; j < forOpenActions.length; j ++) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (forOpenActions[j] == resolveActionLnk.parentNode) continue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tforOpenActions[j].style.display = actionsDisplay;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!resolvedChecked)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treplies[i].style.display = 'none';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tupdateNoComments();\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tif (comment.isResolved)\n\t\t\t\t{\n\t\t\t\t\taddReply(mxResources.get('reOpened') + ': ', true, doToggle, false, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\taddReply(mxResources.get('markedAsResolved'), false, doToggle, true);\n\t\t\t\t}\n\t\t\t};", "label_name": "CWE-79", "label": 1} +{"code": "\t\t\t\t\t\t\tfunction fillUsersSelect()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tusersSelect.innerHTML = '';\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor (var i = 0; i < driveUsers.length; i++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar option = document.createElement('option');\n\t\t\t\t\t\t\t\t\tmxUtils.write(option, driveUsers[i].displayName);\n\t\t\t\t\t\t\t\t\toption.value = i;\n\t\t\t\t\t\t\t\t\tusersSelect.appendChild(option);\n\t\t\t\t\t\t\t\t\t//More info (email) about the user in a disabled option\n\t\t\t\t\t\t\t\t\toption = document.createElement('option');\n\t\t\t\t\t\t\t\t\toption.innerHTML = '   ';\n\t\t\t\t\t\t\t\t\tmxUtils.write(option, '<' + driveUsers[i].email + '>');\n\t\t\t\t\t\t\t\t\toption.setAttribute('disabled', 'disabled');\n\t\t\t\t\t\t\t\t\tusersSelect.appendChild(option);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//Add account option\n\t\t\t\t\t\t\t\tvar option = document.createElement('option');\n\t\t\t\t\t\t\t\tmxUtils.write(option, mxResources.get('addAccount'));\n\t\t\t\t\t\t\t\toption.value = driveUsers.length;\n\t\t\t\t\t\t\t\tusersSelect.appendChild(option);\n\t\t\t\t\t\t\t}", "label_name": "CWE-94", "label": 14} +{"code": "GraphViewer.processElements = function(classname)\n{\n\tmxUtils.forEach(GraphViewer.getElementsByClassName(classname || 'mxgraph'), function(div)\n\t{\n\t\ttry\n\t\t{\n\t\t\tdiv.innerHTML = '';\n\t\t\tGraphViewer.createViewerForElement(div);\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\tdiv.innerHTML = e.message;\n\t\t\t\n\t\t\tif (window.console != null)\n\t\t\t{\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t});\n};", "label_name": "CWE-79", "label": 1} +{"code": "Format.prototype.clear = function()\n{\n\tthis.container.innerHTML = '';\n\t\n\t// Destroy existing panels\n\tif (this.panels != null)\n\t{\n\t\tfor (var i = 0; i < this.panels.length; i++)\n\t\t{\n\t\t\tthis.panels[i].destroy();\n\t\t}\n\t}\n\t\n\tthis.panels = [];\n};", "label_name": "CWE-94", "label": 14} +{"code": "Graph.prototype.getTooltipForCell = function(cell)\n{\n\tvar tip = '';\n\t\n\tif (mxUtils.isNode(cell.value))\n\t{\n\t\tvar tmp = null;\n\n\t\tif (Graph.translateDiagram && Graph.diagramLanguage != null)\n\t\t{\n\t\t\ttmp = cell.value.getAttribute('tooltip_' + Graph.diagramLanguage);\n\t\t}\n\t\t\n\t\tif (tmp == null)\n\t\t{\n\t\t\ttmp = cell.value.getAttribute('tooltip');\n\t\t}\n\t\t\n\t\tif (tmp != null)\n\t\t{\n\t\t\tif (tmp != null && this.isReplacePlaceholders(cell))\n\t\t\t{\n\t\t\t\ttmp = this.replacePlaceholders(cell, tmp);\n\t\t\t}\n\t\t\t\n\t\t\ttip = this.sanitizeHtml(tmp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar ignored = this.builtInProperties;\n\t\t\tvar attrs = cell.value.attributes;\n\t\t\tvar temp = [];\n\n\t\t\t// Hides links in edit mode\n\t\t\tif (this.isEnabled())\n\t\t\t{\n\t\t\t\tignored.push('linkTarget');\n\t\t\t\tignored.push('link');\n\t\t\t}\n\t\t\t\n\t\t\tfor (var i = 0; i < attrs.length; i++)\n\t\t\t{\n\t\t\t\tif (mxUtils.indexOf(ignored, attrs[i].nodeName) < 0 && attrs[i].nodeValue.length > 0)\n\t\t\t\t{\n\t\t\t\t\ttemp.push({name: attrs[i].nodeName, value: attrs[i].nodeValue});\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// Sorts by name\n\t\t\ttemp.sort(function(a, b)\n\t\t\t{\n\t\t\t\tif (a.name < b.name)\n\t\t\t\t{\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\telse if (a.name > b.name)\n\t\t\t\t{\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tfor (var i = 0; i < temp.length; i++)\n\t\t\t{\n\t\t\t\tif (temp[i].name != 'link' || !this.isCustomLink(temp[i].value))\n\t\t\t\t{\n\t\t\t\t\ttip += ((temp[i].name != 'link') ? '' + temp[i].name + ': ' : '') +\n\t\t\t\t\t\tmxUtils.htmlEntities(temp[i].value) + '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (tip.length > 0)\n\t\t\t{\n\t\t\t\ttip = tip.substring(0, tip.length - 1);\n\t\t\t\t\n\t\t\t\tif (mxClient.IS_SVG)\n\t\t\t\t{\n\t\t\t\t\ttip = '
    ' +\n\t\t\t\t\t\ttip + '
    ';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn tip;\n};", "label_name": "CWE-94", "label": 14} +{"code": "Toolbar.prototype.setFontSize = function(value)\n{\n\tif (this.sizeMenu != null)\n\t{\n\t\tthis.sizeMenu.innerHTML = '';\n\t\tvar div = document.createElement('div');\n\t\tdiv.style.display = 'inline-block';\n\t\tdiv.style.overflow = 'hidden';\n\t\tdiv.style.textOverflow = 'ellipsis';\n\t\tdiv.style.maxWidth = '24px';\n\t\tmxUtils.write(div, value);\n\t\tthis.sizeMenu.appendChild(div);\n\t\t\n\t\tthis.appendDropDownImageHtml(this.sizeMenu);\n\t}\n};", "label_name": "CWE-79", "label": 1} +{"code": "var S=document.createElement(\"tbody\"),Q=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(p=f.length-1;0<=p;p--){var P=function(T){var X=new Date(T.modifiedDate),ba=null;if(0<=X.getTime()){var ja=function(ka){v.stop();E.innerHTML=\"\";var da=mxUtils.parseXml(ka),fa=b.editor.extractGraphModel(da.documentElement,!0);if(null!=fa){var ma=function(Ba){null!=Ba&&(Ba=ya(Editor.parseDiagramNode(Ba)));return Ba},ya=function(Ba){var Ha=Ba.getAttribute(\"background\");", "label_name": "CWE-94", "label": 14} +{"code": "var S=document.createElement(\"tbody\"),Q=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(p=f.length-1;0<=p;p--){var P=function(T){var X=new Date(T.modifiedDate),ba=null;if(0<=X.getTime()){var ja=function(ka){v.stop();E.innerHTML=\"\";var da=mxUtils.parseXml(ka),fa=b.editor.extractGraphModel(da.documentElement,!0);if(null!=fa){var ma=function(Ba){null!=Ba&&(Ba=ya(Editor.parseDiagramNode(Ba)));return Ba},ya=function(Ba){var Ha=Ba.getAttribute(\"background\");", "label_name": "CWE-79", "label": 1} +{"code": "\"top center\";da.style.backgroundRepeat=\"no-repeat\";da.setAttribute(\"title\",\"Minimize\");var fa=!1,ma=mxUtils.bind(this,function(){S.innerHTML=\"\";if(!fa){var aa=function(la,oa,ra){la=B(\"\",la.funct,null,oa,la,ra);la.style.width=\"40px\";la.style.opacity=\"0.7\";return ca(la,null,\"pointer\")},ca=function(la,oa,ra){null!=oa&&la.setAttribute(\"title\",oa);la.style.cursor=null!=ra?ra:\"default\";la.style.margin=\"2px 0px\";S.appendChild(la);mxUtils.br(S);return la};ca(F.sidebar.createVertexTemplate(\"text;strokeColor=none;fillColor=none;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\",", "label_name": "CWE-94", "label": 14} +{"code": "!0,0,mxUtils.bind(this,function(b){this.hsplitPosition=b;this.refresh()})))};EditorUi.prototype.createStatusContainer=function(){var a=document.createElement(\"a\");a.className=\"geItem geStatus\";return a};EditorUi.prototype.setStatusText=function(a){this.statusContainer.innerHTML=a;0==this.statusContainer.getElementsByTagName(\"div\").length&&(this.statusContainer.innerHTML=\"\",a=this.createStatusDiv(a),this.statusContainer.appendChild(a))};", "label_name": "CWE-79", "label": 1} +{"code": "this.sidebar.showEntries(\"search\")):(this.sidebar.showPalette(\"search\",mxSettings.settings.search),this.editor.chromeless&&!this.editor.editable||!(mxSettings.settings.isNew||8>=parseInt(mxSettings.settings.version||0))||(this.toggleScratchpad(),mxSettings.save())));this.addListener(\"formatWidthChanged\",function(){mxSettings.setFormatWidth(this.formatWidth);mxSettings.save()})}};EditorUi.prototype.copyImage=function(c,e,g){try{null!=navigator.clipboard&&this.spinner.spin(document.body,mxResources.get(\"exporting\"))&&\nthis.editor.exportToCanvas(mxUtils.bind(this,function(k,m){try{this.spinner.stop();var p=this.createImageDataUri(k,e,\"png\"),v=parseInt(m.getAttribute(\"width\")),x=parseInt(m.getAttribute(\"height\"));this.writeImageToClipboard(p,v,x,mxUtils.bind(this,function(z){this.handleError(z)}))}catch(z){this.handleError(z)}}),null,null,null,mxUtils.bind(this,function(k){this.spinner.stop();this.handleError(k)}),null,null,null!=g?g:4,null==this.editor.graph.background||this.editor.graph.background==mxConstants.NONE,\nnull,null,null,10,null,null,!1,null,0'],{type:\"text/html\"})});navigator.clipboard.write([c])[\"catch\"](k)};EditorUi.prototype.copyCells=function(c,e){var g=this.editor.graph;if(g.isSelectionEmpty())c.innerHTML=\"\";else{var k=", "label_name": "CWE-79", "label": 1} +{"code": "function(b,c){b=typeof c;\"function\"==b?c=mxStyleRegistry.getName(c):\"object\"==b&&(c=null);return c};a.decode=function(b,c,d){d=d||new this.template.constructor;var e=c.getAttribute(\"id\");null!=e&&(b.objects[e]=d);for(c=c.firstChild;null!=c;){if(!this.processInclude(b,c,d)&&\"add\"==c.nodeName&&(e=c.getAttribute(\"as\"),null!=e)){var f=c.getAttribute(\"extend\"),g=null!=f?mxUtils.clone(d.styles[f]):null;null==g&&(null!=f&&mxLog.warn(\"mxStylesheetCodec.decode: stylesheet \"+f+\" not found to extend\"),g={});\nfor(f=c.firstChild;null!=f;){if(f.nodeType==mxConstants.NODETYPE_ELEMENT){var k=f.getAttribute(\"as\");if(\"add\"==f.nodeName){var l=mxUtils.getTextContent(f);null!=l&&0';this.appendDropDownImageHtml(a);b=a.getElementsByTagName(\"div\")[0];b.style.marginLeft=g+\"px\";b.style.marginTop=e+\"px\";EditorUi.compactUi&&(a.getElementsByTagName(\"img\")[0].style.left=\"24px\",a.getElementsByTagName(\"img\")[0].style.top=\"5px\",a.style.width=\nf-10+\"px\")};Toolbar.prototype.setFontName=function(a){if(null!=this.fontMenu){this.fontMenu.innerHTML=\"\";var b=document.createElement(\"div\");b.style.display=\"inline-block\";b.style.overflow=\"hidden\";b.style.textOverflow=\"ellipsis\";b.style.maxWidth=\"66px\";mxUtils.write(b,a);this.fontMenu.appendChild(b);this.appendDropDownImageHtml(this.fontMenu)}};", "label_name": "CWE-79", "label": 1} +{"code": "for(ca=la=0;ca
    < '+mxResources.get(\"back\")+'
    '+", "label_name": "CWE-94", "label": 14} +{"code": "null,null,null,10,null,null,!1,null,0'],{type:\"text/html\"})});navigator.clipboard.write([c])[\"catch\"](k)};EditorUi.prototype.copyCells=function(c,e){var g=this.editor.graph;if(g.isSelectionEmpty())c.innerHTML=\"\";else{var k=\nmxUtils.sortCells(g.model.getTopmostCells(g.getSelectionCells())),m=mxUtils.getXml(g.encodeCells(k));mxUtils.setTextContent(c,encodeURIComponent(m));e?(g.removeCells(k,!1),g.lastPasteXml=null):(g.lastPasteXml=m,g.pasteCounter=0);c.focus();document.execCommand(\"selectAll\",!1,null)}};EditorUi.prototype.copyXml=function(){var c=null;if(Editor.enableNativeCipboard){var e=this.editor.graph;e.isSelectionEmpty()||(c=mxUtils.sortCells(e.getExportableCells(e.model.getTopmostCells(e.getSelectionCells()))),", "label_name": "CWE-94", "label": 14} +{"code": "mxCellEditor.prototype.installListeners=function(a){mxEvent.addListener(a,\"dragstart\",mxUtils.bind(this,function(d){this.graph.stopEditing(!1);mxEvent.consume(d)}));mxEvent.addListener(a,\"blur\",mxUtils.bind(this,function(d){this.blurEnabled&&this.focusLost(d)}));mxEvent.addListener(a,\"keydown\",mxUtils.bind(this,function(d){mxEvent.isConsumed(d)||(this.isStopEditingEvent(d)?(this.graph.stopEditing(!1),mxEvent.consume(d)):27==d.keyCode&&(this.graph.stopEditing(this.isCancelEditingKeyEvent(d)),mxEvent.consume(d)))}));\nvar b=mxUtils.bind(this,function(d){null!=this.editingCell&&this.clearOnChange&&a.innerHTML==this.getEmptyLabelText()&&(!mxClient.IS_FF||8!=d.keyCode&&46!=d.keyCode)&&(this.clearOnChange=!1,a.innerHTML=\"\")});mxEvent.addListener(a,\"keypress\",b);mxEvent.addListener(a,\"paste\",b);b=mxUtils.bind(this,function(d){null!=this.editingCell&&(0==this.textarea.innerHTML.length||\"
    \"==this.textarea.innerHTML?(this.textarea.innerHTML=this.getEmptyLabelText(),this.clearOnChange=0\nmxUtils.indexOf(k,b[D].nodeName)&&0E.name?1:0});for(D=0;D\"+n[D].name+\":
    \":\"\")+mxUtils.htmlEntities(n[D].value)+\"\\n\");0'+e+\"
    \"))}}return e};", "label_name": "CWE-79", "label": 1} +{"code": "this.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label_name": "CWE-94", "label": 14} +{"code": "this.graph.getTooltip(c,d,e,f);this.show(k,e,f);this.state=c;this.node=d;this.stateSource=g}}),this.delay)}};mxTooltipHandler.prototype.hide=function(){this.resetTimer();this.hideTooltip()};mxTooltipHandler.prototype.hideTooltip=function(){null!=this.div&&(this.div.style.visibility=\"hidden\",this.div.innerHTML=\"\")};", "label_name": "CWE-94", "label": 14} +{"code": "c.value&&c.value.nodeType==mxConstants.NODETYPE_ELEMENT){var e=d;d=mxUtils.importNode(b.document,c.value,!0);d.appendChild(e);b=e.getAttribute(\"id\");d.setAttribute(\"id\",b);e.removeAttribute(\"id\")}return d};a.beforeDecode=function(b,c,d){var e=c.cloneNode(!0),f=this.getName();c.nodeName!=f?(e=c.getElementsByTagName(f)[0],null!=e&&e.parentNode==c?(mxUtils.removeWhitespace(e,!0),mxUtils.removeWhitespace(e,!1),e.parentNode.removeChild(e)):e=null,d.value=c.cloneNode(!0),c=d.value.getAttribute(\"id\"),null!=\nc&&(d.setId(c),d.value.removeAttribute(\"id\"))):d.setId(c.getAttribute(\"id\"));if(null!=e)for(c=0;c\");this.div.style.visibility=\"\";mxUtils.fit(this.div)}};", "label_name": "CWE-94", "label": 14} +{"code": "mxShape.prototype.clear=function(){if(null!=this.node.ownerSVGElement)for(;null!=this.node.lastChild;)this.node.removeChild(this.node.lastChild);else this.node.style.cssText=\"position:absolute;\"+(null!=this.cursor?\"cursor:\"+this.cursor+\";\":\"\"),this.node.innerHTML=\"\"};", "label_name": "CWE-94", "label": 14} +{"code": "X){null!=X.shortcut&&900>n&&!mxClient.IS_IOS?O.firstChild.nextSibling.setAttribute(\"title\",X.shortcut):m.apply(this,arguments)};var q=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){q.apply(this,arguments);if(null!=this.userElement){var O=this.userElement;O.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+O.style.display;O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=\"url(\"+Editor.userImage+\")\";O.style.backgroundPosition=\"center center\";\nO.style.backgroundRepeat=\"no-repeat\";O.style.backgroundSize=\"24px 24px\";O.style.height=\"24px\";O.style.width=\"24px\";O.style.cssFloat=\"right\";O.setAttribute(\"title\",mxResources.get(\"changeUser\"));if(\"none\"!=O.style.display){O.style.display=\"inline-block\";var X=this.getCurrentFile();if(null!=X&&X.isRealtimeEnabled()&&X.isRealtimeSupported()){var ea=document.createElement(\"img\");ea.setAttribute(\"border\",\"0\");ea.style.position=\"absolute\";ea.style.left=\"18px\";ea.style.top=\"2px\";ea.style.width=\"12px\";ea.style.height=\n\"12px\";var ka=X.getRealtimeError();X=X.getRealtimeState();var ja=mxResources.get(\"realtimeCollaboration\");1==X?(ea.src=Editor.syncImage,ja+=\" (\"+mxResources.get(\"online\")+\")\"):(ea.src=Editor.syncProblemImage,ja=null!=ka&&null!=ka.message?ja+(\" (\"+ka.message+\")\"):ja+(\" (\"+mxResources.get(\"disconnected\")+\")\"));ea.setAttribute(\"title\",ja);O.style.paddingRight=\"4px\";O.appendChild(ea)}}}};var y=App.prototype.updateButtonContainer;App.prototype.updateButtonContainer=function(){y.apply(this,arguments);if(null!=", "label_name": "CWE-94", "label": 14} +{"code": "Ra,\"geMenuItem\");null!=Na?(Ra.style.backgroundImage=\"url(\"+Na+\")\",Ra.style.backgroundPosition=\"center center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.backgroundSize=\"24px 24px\",Ra.style.width=\"34px\",Ra.innerHTML=\"\"):ya||(Ra.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",Ra.style.backgroundPosition=\"right 6px center\",Ra.style.backgroundRepeat=\"no-repeat\",Ra.style.paddingRight=\"22px\");return Ra}function X(ua,ya,Na,Fa,Ra,db){var Va=document.createElement(\"a\");Va.className=\n\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Va.style.display=\"inline-block\";Va.style.boxSizing=\"border-box\";Va.style.height=\"30px\";Va.style.padding=\"6px\";Va.style.position=\"relative\";Va.style.verticalAlign=\"top\";Va.style.top=\"0px\";\"1\"==urlParams.sketch&&(Va.style.borderStyle=\"none\",Va.style.boxShadow=\"none\",Va.style.padding=\"6px\",Va.style.margin=\"0px\");null!=U.statusContainer?V.insertBefore(Va,U.statusContainer):V.appendChild(Va);null!=db?(Va.style.backgroundImage=\"url(\"+db+\")\",Va.style.backgroundPosition=\n\"center center\",Va.style.backgroundRepeat=\"no-repeat\",Va.style.backgroundSize=\"24px 24px\",Va.style.width=\"34px\"):mxUtils.write(Va,ua);mxEvent.addListener(Va,mxClient.IS_POINTER?\"pointerdown\":\"mousedown\",mxUtils.bind(this,function(fb){fb.preventDefault()}));mxEvent.addListener(Va,\"click\",function(fb){\"disabled\"!=Va.getAttribute(\"disabled\")&&ya(fb);mxEvent.consume(fb)});null==Na&&(Va.style.marginRight=\"4px\");null!=Fa&&Va.setAttribute(\"title\",Fa);null!=Ra&&(ua=function(){Ra.isEnabled()?(Va.removeAttribute(\"disabled\"),\nVa.style.cursor=\"pointer\"):(Va.setAttribute(\"disabled\",\"disabled\"),Va.style.cursor=\"default\")},Ra.addListener(\"stateChanged\",ua),J.addListener(\"enabledChanged\",ua),ua());return Va}function ea(ua,ya,Na){Na=document.createElement(\"div\");Na.className=\"geMenuItem\";Na.style.display=\"inline-block\";Na.style.verticalAlign=\"top\";Na.style.marginRight=\"6px\";Na.style.padding=\"0 4px 0 4px\";Na.style.height=\"30px\";Na.style.position=\"relative\";Na.style.top=\"0px\";\"1\"==urlParams.sketch&&(Na.style.boxShadow=\"none\");", "label_name": "CWE-79", "label": 1} +{"code": "mxEvent.consume(ua))},Za=U.actions.get(\"zoomIn\"),cb=U.actions.get(\"zoomOut\"),Ja=U.actions.get(\"resetView\");Q=U.actions.get(\"fullscreen\");var Ua=U.actions.get(\"undo\"),$a=U.actions.get(\"redo\"),z=X(\"\",Ua.funct,null,mxResources.get(\"undo\")+\" (\"+Ua.shortcut+\")\",Ua,Editor.undoImage),L=X(\"\",$a.funct,null,mxResources.get(\"redo\")+\" (\"+$a.shortcut+\")\",$a,Editor.redoImage),M=X(\"\",Q.funct,null,mxResources.get(\"fullscreen\"),Q,Editor.fullscreenImage);if(null!=N){Ja=function(){ra.style.display=null!=U.pages&&(\"0\"!=\nurlParams.pages||1document.documentMode)?mxUtils.importNodeImplementation(a,b,c):a.importNode(b,c)},importNodeImplementation:function(a,b,c){switch(b.nodeType){case 1:var d=a.createElement(b.nodeName);if(b.attributes&&0 task._id),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n })\n })\n }\n }\n })", "label_name": "CWE-79", "label": 1} +{"code": " labels: templateInstance.topTasks.get().map((task) => task._id),", "label_name": "CWE-79", "label": 1} +{"code": " labels: templateInstance.topTasks.get().map((task) => task._id),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n }\n })\n })\n }\n }\n })", "label_name": "CWE-79", "label": 1} +{"code": " labels: templateInstance.topTasks.get().map((task) => task._id),\n datasets: [{\n values: templateInstance.topTasks.get().map((task) => task.count),\n }],\n },\n tooltipOptions: {\n },\n })\n }\n })\n })\n }\n }\n })", "label_name": "CWE-79", "label": 1} +{"code": " async function doIt() {\n await test.server.serverCertificateManager.trustCertificate(certificate);\n const issuerCertificateFile = m(\"CA/public/cacert.pem\");\n const issuerCertificateRevocationListFile = m(\"CA/crl/revocation_list.der\");\n const issuerCertificate = readCertificate(issuerCertificateFile);\n const issuerCrl = await readCertificateRevocationList(issuerCertificateRevocationListFile);\n await test.server.serverCertificateManager.addIssuer(issuerCertificate);\n await test.server.serverCertificateManager.addRevocationList(issuerCrl);\n callback();\n }", "label_name": "CWE-770", "label": 37} +{"code": "PostgreSQL.prototype.buildExpression = function(columnName, operator,\n operatorValue, propertyDefinition) {\n switch (operator) {\n case 'like':\n return new ParameterizedSQL(columnName + \"::TEXT LIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'ilike':\n return new ParameterizedSQL(columnName + \"::TEXT ILIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'nlike':\n return new ParameterizedSQL(columnName + \"::TEXT NOT LIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'nilike':\n return new ParameterizedSQL(columnName + \"::TEXT NOT ILIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'regexp':\n if (operatorValue.global)\n g.warn('{{PostgreSQL}} regex syntax does not respect the {{`g`}} flag');\n\n if (operatorValue.multiline)\n g.warn('{{PostgreSQL}} regex syntax does not respect the {{`m`}} flag');\n\n const regexOperator = operatorValue.ignoreCase ? ' ~* ?' : ' ~ ?';\n return new ParameterizedSQL(columnName + regexOperator,\n [operatorValue.source]);\n case 'contains':\n return new ParameterizedSQL(columnName + ' @> array[' + operatorValue.map((v) => `'${v}'`) + ']::'\n + propertyDefinition.postgresql.dataType);\n case 'match':\n return new ParameterizedSQL(`to_tsvector(${columnName}) @@ to_tsquery('${operatorValue}')`);\n default:\n // invoke the base implementation of `buildExpression`\n return this.invokeSuper('buildExpression', columnName, operator,\n operatorValue, propertyDefinition);\n }\n};", "label_name": "CWE-89", "label": 0} +{"code": "spnego_gss_set_sec_context_option(\n\t\tOM_uint32 *minor_status,\n\t\tgss_ctx_id_t *context_handle,\n\t\tconst gss_OID desired_object,\n\t\tconst gss_buffer_t value)\n{\n\tOM_uint32 ret;\n\tret = gss_set_sec_context_option(minor_status,\n\t\t\t context_handle,\n\t\t\t desired_object,\n\t\t\t value);\n\treturn (ret);\n}", "label_name": "CWE-763", "label": 61} +{"code": "setv4key_principal_2_svc(setv4key_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n const char *errmsg = NULL;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n ret.api_version = handle->api_version;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n\n if (!(CHANGEPW_SERVICE(rqstp)) &&\n kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_SETKEY, arg->princ, NULL)) {\n ret.code = kadm5_setv4key_principal((void *)handle, arg->princ,\n arg->keyblock);\n } else {\n log_unauth(\"kadm5_setv4key_principal\", prime_arg,\n &client_name, &service_name, rqstp);\n ret.code = KADM5_AUTH_SETKEY;\n }\n\n if(ret.code != KADM5_AUTH_SETKEY) {\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n log_done(\"kadm5_setv4key_principal\", prime_arg, errmsg,\n &client_name, &service_name, rqstp);\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n }\n\n free(prime_arg);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n}", "label_name": "CWE-772", "label": 53} +{"code": "xfs_acl_from_disk(struct xfs_acl *aclp)\n{\n\tstruct posix_acl_entry *acl_e;\n\tstruct posix_acl *acl;\n\tstruct xfs_acl_entry *ace;\n\tint count, i;\n\n\tcount = be32_to_cpu(aclp->acl_cnt);\n\tif (count > XFS_ACL_MAX_ENTRIES)\n\t\treturn ERR_PTR(-EFSCORRUPTED);\n\n\tacl = posix_acl_alloc(count, GFP_KERNEL);\n\tif (!acl)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tfor (i = 0; i < count; i++) {\n\t\tacl_e = &acl->a_entries[i];\n\t\tace = &aclp->acl_entry[i];\n\n\t\t/*\n\t\t * The tag is 32 bits on disk and 16 bits in core.\n\t\t *\n\t\t * Because every access to it goes through the core\n\t\t * format first this is not a problem.\n\t\t */\n\t\tacl_e->e_tag = be32_to_cpu(ace->ae_tag);\n\t\tacl_e->e_perm = be16_to_cpu(ace->ae_perm);\n\n\t\tswitch (acl_e->e_tag) {\n\t\tcase ACL_USER:\n\t\tcase ACL_GROUP:\n\t\t\tacl_e->e_id = be32_to_cpu(ace->ae_id);\n\t\t\tbreak;\n\t\tcase ACL_USER_OBJ:\n\t\tcase ACL_GROUP_OBJ:\n\t\tcase ACL_MASK:\n\t\tcase ACL_OTHER:\n\t\t\tacl_e->e_id = ACL_UNDEFINED_ID;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto fail;\n\t\t}\n\t}\n\treturn acl;\n\nfail:\n\tposix_acl_release(acl);\n\treturn ERR_PTR(-EINVAL);\n}", "label_name": "CWE-190", "label": 19} +{"code": "static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,\n\tstruct cftype *cft, struct eventfd_ctx *eventfd)\n{\n\tstruct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);\n\tstruct mem_cgroup_thresholds *thresholds;\n\tstruct mem_cgroup_threshold_ary *new;\n\tint type = MEMFILE_TYPE(cft->private);\n\tu64 usage;\n\tint i, j, size;\n\n\tmutex_lock(&memcg->thresholds_lock);\n\tif (type == _MEM)\n\t\tthresholds = &memcg->thresholds;\n\telse if (type == _MEMSWAP)\n\t\tthresholds = &memcg->memsw_thresholds;\n\telse\n\t\tBUG();\n\n\t/*\n\t * Something went wrong if we trying to unregister a threshold\n\t * if we don't have thresholds\n\t */\n\tBUG_ON(!thresholds);\n\n\tusage = mem_cgroup_usage(memcg, type == _MEMSWAP);\n\n\t/* Check if a threshold crossed before removing */\n\t__mem_cgroup_threshold(memcg, type == _MEMSWAP);\n\n\t/* Calculate new number of threshold */\n\tsize = 0;\n\tfor (i = 0; i < thresholds->primary->size; i++) {\n\t\tif (thresholds->primary->entries[i].eventfd != eventfd)\n\t\t\tsize++;\n\t}\n\n\tnew = thresholds->spare;\n\n\t/* Set thresholds array to NULL if we don't have thresholds */\n\tif (!size) {\n\t\tkfree(new);\n\t\tnew = NULL;\n\t\tgoto swap_buffers;\n\t}\n\n\tnew->size = size;\n\n\t/* Copy thresholds and find current threshold */\n\tnew->current_threshold = -1;\n\tfor (i = 0, j = 0; i < thresholds->primary->size; i++) {\n\t\tif (thresholds->primary->entries[i].eventfd == eventfd)\n\t\t\tcontinue;\n\n\t\tnew->entries[j] = thresholds->primary->entries[i];\n\t\tif (new->entries[j].threshold < usage) {\n\t\t\t/*\n\t\t\t * new->current_threshold will not be used\n\t\t\t * until rcu_assign_pointer(), so it's safe to increment\n\t\t\t * it here.\n\t\t\t */\n\t\t\t++new->current_threshold;\n\t\t}\n\t\tj++;\n\t}\n\nswap_buffers:\n\t/* Swap primary and spare array */\n\tthresholds->spare = thresholds->primary;\n\trcu_assign_pointer(thresholds->primary, new);\n\n\t/* To be sure that nobody uses thresholds */\n\tsynchronize_rcu();\n\n\tmutex_unlock(&memcg->thresholds_lock);\n}", "label_name": "CWE-476", "label": 46} +{"code": "static int __init big_key_init(void)\n{\n\treturn register_key_type(&key_type_big_key);\n}", "label_name": "CWE-476", "label": 46} +{"code": "static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)\n{\n\tioapic->rtc_status.pending_eoi = 0;\n\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);\n}", "label_name": "CWE-125", "label": 47} +{"code": "int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user)\n{\n\tstruct net_device *dev = skb->dev;\n\tint fhoff, nhoff, ret;\n\tstruct frag_hdr *fhdr;\n\tstruct frag_queue *fq;\n\tstruct ipv6hdr *hdr;\n\tu8 prevhdr;\n\n\t/* Jumbo payload inhibits frag. header */\n\tif (ipv6_hdr(skb)->payload_len == 0) {\n\t\tpr_debug(\"payload len = 0\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0)\n\t\treturn -EINVAL;\n\n\tif (!pskb_may_pull(skb, fhoff + sizeof(*fhdr)))\n\t\treturn -ENOMEM;\n\n\tskb_set_transport_header(skb, fhoff);\n\thdr = ipv6_hdr(skb);\n\tfhdr = (struct frag_hdr *)skb_transport_header(skb);\n\n\tfq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr,\n\t\t skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr));\n\tif (fq == NULL) {\n\t\tpr_debug(\"Can't find and can't create new queue\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tspin_lock_bh(&fq->q.lock);\n\n\tif (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) {\n\t\tret = -EINVAL;\n\t\tgoto out_unlock;\n\t}\n\n\t/* after queue has assumed skb ownership, only 0 or -EINPROGRESS\n\t * must be returned.\n\t */\n\tret = -EINPROGRESS;\n\tif (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&\n\t fq->q.meat == fq->q.len &&\n\t nf_ct_frag6_reasm(fq, skb, dev))\n\t\tret = 0;\n\nout_unlock:\n\tspin_unlock_bh(&fq->q.lock);\n\tinet_frag_put(&fq->q, &nf_frags);\n\treturn ret;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static inline void mcryptd_check_internal(struct rtattr **tb, u32 *type,\n\t\t\t\t\t u32 *mask)\n{\n\tstruct crypto_attr_type *algt;\n\n\talgt = crypto_get_attr_type(tb);\n\tif (IS_ERR(algt))\n\t\treturn;\n\tif ((algt->type & CRYPTO_ALG_INTERNAL))\n\t\t*type |= CRYPTO_ALG_INTERNAL;\n\tif ((algt->mask & CRYPTO_ALG_INTERNAL))\n\t\t*mask |= CRYPTO_ALG_INTERNAL;\n}", "label_name": "CWE-476", "label": 46} +{"code": "int fscrypt_get_encryption_info(struct inode *inode)\n{\n\tstruct fscrypt_info *ci = inode->i_crypt_info;\n\n\tif (!ci ||\n\t\t(ci->ci_keyring_key &&\n\t\t (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) |\n\t\t\t\t\t (1 << KEY_FLAG_REVOKED) |\n\t\t\t\t\t (1 << KEY_FLAG_DEAD)))))\n\t\treturn fscrypt_get_crypt_info(inode);\n\treturn 0;\n}", "label_name": "CWE-476", "label": 46} +{"code": "\nvoid skb_complete_tx_timestamp(struct sk_buff *skb,\n\t\t\t struct skb_shared_hwtstamps *hwtstamps)\n{\n\tstruct sock *sk = skb->sk;\n\n\tif (!skb_may_tx_timestamp(sk, false))\n\t\treturn;\n\n\t/* Take a reference to prevent skb_orphan() from freeing the socket,\n\t * but only if the socket refcount is not zero.\n\t */\n\tif (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {\n\t\t*skb_hwtstamps(skb) = *hwtstamps;\n\t\t__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);\n\t\tsock_put(sk);\n\t}", "label_name": "CWE-125", "label": 47} +{"code": "void snd_msndmidi_input_read(void *mpuv)\n{\n\tunsigned long flags;\n\tstruct snd_msndmidi *mpu = mpuv;\n\tvoid *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF;\n\n\tspin_lock_irqsave(&mpu->input_lock, flags);\n\twhile (readw(mpu->dev->MIDQ + JQS_wTail) !=\n\t readw(mpu->dev->MIDQ + JQS_wHead)) {\n\t\tu16 wTmp, val;\n\t\tval = readw(pwMIDQData + 2 * readw(mpu->dev->MIDQ + JQS_wHead));\n\n\t\t\tif (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER,\n\t\t\t\t &mpu->mode))\n\t\t\t\tsnd_rawmidi_receive(mpu->substream_input,\n\t\t\t\t\t\t (unsigned char *)&val, 1);\n\n\t\twTmp = readw(mpu->dev->MIDQ + JQS_wHead) + 1;\n\t\tif (wTmp > readw(mpu->dev->MIDQ + JQS_wSize))\n\t\t\twritew(0, mpu->dev->MIDQ + JQS_wHead);\n\t\telse\n\t\t\twritew(wTmp, mpu->dev->MIDQ + JQS_wHead);\n\t}\n\tspin_unlock_irqrestore(&mpu->input_lock, flags);\n}", "label_name": "CWE-125", "label": 47} +{"code": "static int uas_switch_interface(struct usb_device *udev,\n\t\t\t\tstruct usb_interface *intf)\n{\n\tint alt;\n\n\talt = uas_find_uas_alt_setting(intf);\n\tif (alt < 0)\n\t\treturn alt;\n\n\treturn usb_set_interface(udev,\n\t\t\tintf->altsetting[0].desc.bInterfaceNumber, alt);\n}", "label_name": "CWE-125", "label": 47} +{"code": "static ssize_t o2nm_node_ipv4_address_store(struct config_item *item,\n\t\t\t\t\t const char *page,\n\t\t\t\t\t size_t count)\n{\n\tstruct o2nm_node *node = to_o2nm_node(item);\n\tstruct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);\n\tint ret, i;\n\tstruct rb_node **p, *parent;\n\tunsigned int octets[4];\n\t__be32 ipv4_addr = 0;\n\n\tret = sscanf(page, \"%3u.%3u.%3u.%3u\", &octets[3], &octets[2],\n\t\t &octets[1], &octets[0]);\n\tif (ret != 4)\n\t\treturn -EINVAL;\n\n\tfor (i = 0; i < ARRAY_SIZE(octets); i++) {\n\t\tif (octets[i] > 255)\n\t\t\treturn -ERANGE;\n\t\tbe32_add_cpu(&ipv4_addr, octets[i] << (i * 8));\n\t}\n\n\tret = 0;\n\twrite_lock(&cluster->cl_nodes_lock);\n\tif (o2nm_node_ip_tree_lookup(cluster, ipv4_addr, &p, &parent))\n\t\tret = -EEXIST;\n\telse if (test_and_set_bit(O2NM_NODE_ATTR_ADDRESS,\n\t\t\t&node->nd_set_attributes))\n\t\tret = -EBUSY;\n\telse {\n\t\trb_link_node(&node->nd_ip_node, parent, p);\n\t\trb_insert_color(&node->nd_ip_node, &cluster->cl_node_ip_tree);\n\t}\n\twrite_unlock(&cluster->cl_nodes_lock);\n\tif (ret)\n\t\treturn ret;\n\n\tmemcpy(&node->nd_ipv4_address, &ipv4_addr, sizeof(ipv4_addr));\n\n\treturn count;\n}", "label_name": "CWE-476", "label": 46} +{"code": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu->flags & PPMU_P10_DD1) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "label_name": "CWE-476", "label": 46} +{"code": "static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret)\n{\n\tstruct trace_array *tr = data;\n\tstruct ftrace_event_file *ftrace_file;\n\tstruct syscall_trace_exit *entry;\n\tstruct syscall_metadata *sys_data;\n\tstruct ring_buffer_event *event;\n\tstruct ring_buffer *buffer;\n\tunsigned long irq_flags;\n\tint pc;\n\tint syscall_nr;\n\n\tsyscall_nr = trace_get_syscall_nr(current, regs);\n\tif (syscall_nr < 0)\n\t\treturn;\n\n\t/* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE()) */\n\tftrace_file = rcu_dereference_sched(tr->exit_syscall_files[syscall_nr]);\n\tif (!ftrace_file)\n\t\treturn;\n\n\tif (ftrace_trigger_soft_disabled(ftrace_file))\n\t\treturn;\n\n\tsys_data = syscall_nr_to_meta(syscall_nr);\n\tif (!sys_data)\n\t\treturn;\n\n\tlocal_save_flags(irq_flags);\n\tpc = preempt_count();\n\n\tbuffer = tr->trace_buffer.buffer;\n\tevent = trace_buffer_lock_reserve(buffer,\n\t\t\tsys_data->exit_event->event.type, sizeof(*entry),\n\t\t\tirq_flags, pc);\n\tif (!event)\n\t\treturn;\n\n\tentry = ring_buffer_event_data(event);\n\tentry->nr = syscall_nr;\n\tentry->ret = syscall_get_return_value(current, regs);\n\n\tevent_trigger_unlock_commit(ftrace_file, buffer, event, entry,\n\t\t\t\t irq_flags, pc);\n}", "label_name": "CWE-476", "label": 46} +{"code": "static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,\n\t\t u8 *dst, unsigned int dlen)\n{\n\treturn crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen);\n}", "label_name": "CWE-476", "label": 46} +{"code": "static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tstruct ahash_request *req = &ctx->req;\n\tchar state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];\n\tstruct sock *sk2;\n\tstruct alg_sock *ask2;\n\tstruct hash_ctx *ctx2;\n\tint err;\n\n\terr = crypto_ahash_export(req, state);\n\tif (err)\n\t\treturn err;\n\n\terr = af_alg_accept(ask->parent, newsock);\n\tif (err)\n\t\treturn err;\n\n\tsk2 = newsock->sk;\n\task2 = alg_sk(sk2);\n\tctx2 = ask2->private;\n\tctx2->more = 1;\n\n\terr = crypto_ahash_import(&ctx2->req, state);\n\tif (err) {\n\t\tsock_orphan(sk2);\n\t\tsock_put(sk2);\n\t}\n\n\treturn err;\n}", "label_name": "CWE-476", "label": 46} +{"code": "struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,\n\t\t\t\t const struct bpf_insn *patch, u32 len)\n{\n\tu32 insn_adj_cnt, insn_rest, insn_delta = len - 1;\n\tstruct bpf_prog *prog_adj;\n\n\t/* Since our patchlet doesn't expand the image, we're done. */\n\tif (insn_delta == 0) {\n\t\tmemcpy(prog->insnsi + off, patch, sizeof(*patch));\n\t\treturn prog;\n\t}\n\n\tinsn_adj_cnt = prog->len + insn_delta;\n\n\t/* Several new instructions need to be inserted. Make room\n\t * for them. Likely, there's no need for a new allocation as\n\t * last page could have large enough tailroom.\n\t */\n\tprog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),\n\t\t\t\t GFP_USER);\n\tif (!prog_adj)\n\t\treturn NULL;\n\n\tprog_adj->len = insn_adj_cnt;\n\n\t/* Patching happens in 3 steps:\n\t *\n\t * 1) Move over tail of insnsi from next instruction onwards,\n\t * so we can patch the single target insn with one or more\n\t * new ones (patching is always from 1 to n insns, n > 0).\n\t * 2) Inject new instructions at the target location.\n\t * 3) Adjust branch offsets if necessary.\n\t */\n\tinsn_rest = insn_adj_cnt - off - len;\n\n\tmemmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,\n\t\tsizeof(*patch) * insn_rest);\n\tmemcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);\n\n\tbpf_adj_branches(prog_adj, off, insn_delta);\n\n\treturn prog_adj;\n}", "label_name": "CWE-120", "label": 44} +{"code": "static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)\n{\n\tif (cfs_rq->load.weight)\n\t\treturn false;\n\n\tif (cfs_rq->avg.load_sum)\n\t\treturn false;\n\n\tif (cfs_rq->avg.util_sum)\n\t\treturn false;\n\n\tif (cfs_rq->avg.runnable_load_sum)\n\t\treturn false;\n\n\treturn true;\n}", "label_name": "CWE-835", "label": 42} +{"code": "struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,\n\t\t\t\t u64 devid, u8 *uuid, u8 *fsid)\n{\n\tstruct btrfs_device *device;\n\n\twhile (fs_devices) {\n\t\tif (!fsid ||\n\t\t !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {\n\t\t\tdevice = find_device(fs_devices, devid, uuid);\n\t\t\tif (device)\n\t\t\t\treturn device;\n\t\t}\n\t\tfs_devices = fs_devices->seed;\n\t}\n\treturn NULL;\n}", "label_name": "CWE-476", "label": 46} +{"code": "int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,\n size_t size)\n{\n GetBitContext gb;\n AC3HeaderInfo *hdr;\n int err;\n\n if (!*phdr)\n *phdr = av_mallocz(sizeof(AC3HeaderInfo));\n if (!*phdr)\n return AVERROR(ENOMEM);\n hdr = *phdr;\n\n init_get_bits8(&gb, buf, size);\n err = ff_ac3_parse_header(&gb, hdr);\n if (err < 0)\n return AVERROR_INVALIDDATA;\n\n return get_bits_count(&gb);\n}", "label_name": "CWE-476", "label": 46} +{"code": "static enum AVPixelFormat h263_get_format(AVCodecContext *avctx)\n{\n /* MPEG-4 Studio Profile only, not supported by hardware */\n if (avctx->bits_per_raw_sample > 8) {\n av_assert1(avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);\n return avctx->pix_fmt;\n }\n\n if (avctx->codec->id == AV_CODEC_ID_MSS2)\n return AV_PIX_FMT_YUV420P;\n\n if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY)) {\n if (avctx->color_range == AVCOL_RANGE_UNSPECIFIED)\n avctx->color_range = AVCOL_RANGE_MPEG;\n return AV_PIX_FMT_GRAY8;\n }\n\n return avctx->pix_fmt = ff_get_format(avctx, avctx->codec->pix_fmts);\n}", "label_name": "CWE-617", "label": 51} +{"code": "atol8(const char *p, size_t char_cnt)\n{\n\tint64_t l;\n\tint digit;\n \n\tl = 0;\n\twhile (char_cnt-- > 0) {\n\t\tif (*p >= '0' && *p <= '7')\n\t\t\tdigit = *p - '0';\n\t\telse\n\t\t\tbreak;\n\t\tp++;\n\t\tl <<= 3;\n\t\tl |= digit;\n\t}\n\treturn (l);\n}", "label_name": "CWE-125", "label": 47} +{"code": "archive_write_disk_set_acls(struct archive *a, int fd, const char *name,\n struct archive_acl *abstract_acl, __LA_MODE_T mode)\n{\n\tint\t\tret = ARCHIVE_OK;\n\n#if !ARCHIVE_ACL_LIBRICHACL\n\t(void)mode;\t/* UNUSED */\n#endif\n\n#if ARCHIVE_ACL_LIBRICHACL\n\tif ((archive_acl_types(abstract_acl)\n\t & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {\n\t\tret = set_richacl(a, fd, name, abstract_acl, mode,\n\t\t ARCHIVE_ENTRY_ACL_TYPE_NFS4, \"nfs4\");\n\t}\n#if ARCHIVE_ACL_LIBACL\n\telse\n#endif\n#endif\t/* ARCHIVE_ACL_LIBRICHACL */\n#if ARCHIVE_ACL_LIBACL\n\tif ((archive_acl_types(abstract_acl)\n\t & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {\n\t\tif ((archive_acl_types(abstract_acl)\n\t\t & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {\n\t\t\tret = set_acl(a, fd, name, abstract_acl,\n\t\t\t ARCHIVE_ENTRY_ACL_TYPE_ACCESS, \"access\");\n\t\t\tif (ret != ARCHIVE_OK)\n\t\t\t\treturn (ret);\n\t\t}\n\t\tif ((archive_acl_types(abstract_acl)\n\t\t & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)\n\t\t\tret = set_acl(a, fd, name, abstract_acl,\n\t\t\t ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, \"default\");\n\t}\n#endif\t/* ARCHIVE_ACL_LIBACL */\n\treturn (ret);\n}", "label_name": "CWE-59", "label": 36} +{"code": "static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */\n{\n\tva_list va;\n\tchar *message = NULL;\n\n\tva_start(va, format);\n\tzend_vspprintf(&message, 0, format, va);\n\n\tif (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {\n\t\tzend_throw_error(exception_ce, message);\n\t} else {\n\t\tzend_error(E_ERROR, \"%s\", message);\n\t}\n\n\tefree(message);\n\tva_end(va);\n}", "label_name": "CWE-134", "label": 54} +{"code": "PHP_FUNCTION(locale_get_all_variants)\n{\n\tconst char* \tloc_name = NULL;\n\tint \t\tloc_name_len = 0;\n\n\tint\tresult\t\t= 0;\n\tchar*\ttoken\t\t= NULL;\n\tchar*\tvariant\t\t= NULL;\n\tchar*\tsaved_ptr\t= NULL;\n\n\tintl_error_reset( NULL TSRMLS_CC );\n\t\n\tif(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, \"s\",\n\t&loc_name, &loc_name_len ) == FAILURE)\n\t{\n\t\tintl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,\n\t \"locale_parse: unable to parse input params\", 0 TSRMLS_CC );\n\n\t\tRETURN_FALSE;\n\t}\n\n\tif(loc_name_len == 0) {\n\t\tloc_name = intl_locale_get_default(TSRMLS_C);\n\t}\n\n\n\tarray_init( return_value );\n\n\t/* If the locale is grandfathered, stop, no variants */\n\tif( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){ \n\t\t/* (\"Grandfathered Tag. No variants.\"); */\n\t}\n\telse {\t\n\t/* Call ICU variant */\n\t\tvariant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0);\n\t\tif( result > 0 && variant){\n\t\t\t/* Tokenize on the \"_\" or \"-\" */\n\t\t\ttoken = php_strtok_r( variant , DELIMITER , &saved_ptr);\t\n\t\t\tadd_next_index_stringl( return_value, token , strlen(token) ,TRUE );\n\t\t\t/* tokenize on the \"_\" or \"-\" and stop at singleton if any\t*/\n\t\t\twhile( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){\n \t\t\t\tadd_next_index_stringl( return_value, token , strlen(token) ,TRUE );\n\t\t\t}\n\t\t}\n\t\tif( variant ){\n\t\t\tefree( variant );\n\t\t}\n\t}\n\t\t\t\n\n}", "label_name": "CWE-125", "label": 47} +{"code": "static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)\n{\n\tzval**\tele_value\t= NULL;\n\n\tif(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {\n\t\tif(Z_TYPE_PP(ele_value)!= IS_STRING ){\n\t\t\t/* element value is not a string */\n\t\t\treturn FAILURE;\n\t\t}\n\t\tif(strcmp(key_name, LOC_LANG_TAG) != 0 && \n\t\t strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {\n\t\t\t/* not lang or grandfathered tag */\n\t\t\tsmart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);\n\t\t}\n\t\tsmart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));\n\t\treturn SUCCESS;\n\t}\n\n\treturn LOC_NOT_FOUND;\n}", "label_name": "CWE-125", "label": 47} +{"code": "SPL_METHOD(SplFileObject, getCsvControl)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar delimiter[2], enclosure[2];\n\n\tarray_init(return_value);\n\t\n\tdelimiter[0] = intern->u.file.delimiter;\n\tdelimiter[1] = '\\0';\n\tenclosure[0] = intern->u.file.enclosure;\n\tenclosure[1] = '\\0';\n\n\tadd_next_index_string(return_value, delimiter, 1);\n\tadd_next_index_string(return_value, enclosure, 1);\n}", "label_name": "CWE-190", "label": 19} +{"code": "SPL_METHOD(SplFileInfo, getLinkTarget)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tint ret;\n\tchar buff[MAXPATHLEN];\n\tzend_error_handling error_handling;\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tzend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\n\n#if defined(PHP_WIN32) || HAVE_SYMLINK\n\tif (intern->file_name == NULL) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Empty filename\");\n\t\tRETURN_FALSE;\n\t} else if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) {\n\t\tchar expanded_path[MAXPATHLEN];\n\t\tif (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"No such file or directory\");\n\t\t\tRETURN_FALSE;\n\t\t}\n\t\tret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1);\n\t} else {\n\t\tret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1);\n\t}\n#else\n\tret = -1; /* always fail if not implemented */\n#endif\n\n\tif (ret == -1) {\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Unable to read link %s, error: %s\", intern->file_name, strerror(errno));\n\t\tRETVAL_FALSE;\n\t} else {\n\t\t/* Append NULL to the end of the string */\n\t\tbuff[ret] = '\\0';\n\n\t\tRETVAL_STRINGL(buff, ret, 1);\n\t}\n\n\tzend_restore_error_handling(&error_handling TSRMLS_CC);\n}", "label_name": "CWE-190", "label": 19} +{"code": "SPL_METHOD(SplFileObject, next)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tspl_filesystem_file_free_line(intern TSRMLS_CC);\n\tif (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {\n\t\tspl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);\n\t}\n\tintern->u.file.current_line_num++;\n} /* }}} */", "label_name": "CWE-190", "label": 19} +{"code": "static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */\n{\n\tint ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);\n\n\twhile (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) {\n\t\tspl_filesystem_file_free_line(intern TSRMLS_CC);\n\t\tret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC);\n\t}\n\t\n\treturn ret;\n}", "label_name": "CWE-190", "label": 19} +{"code": "SPL_METHOD(SplFileObject, current)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!intern->u.file.current_line && !intern->u.file.current_zval) {\n\t\tspl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);\n\t}\n\tif (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) {\n\t\tRETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);\n\t} else if (intern->u.file.current_zval) {\n\t\tRETURN_ZVAL(intern->u.file.current_zval, 1, 0);\n\t}\n\tRETURN_FALSE;\n} /* }}} */", "label_name": "CWE-190", "label": 19} +{"code": "SPL_METHOD(SplFileObject, hasChildren)\n{\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\t\n\tRETURN_FALSE;\n} /* }}} */", "label_name": "CWE-190", "label": 19} +{"code": "SPL_METHOD(FilesystemIterator, getFlags)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tRETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));\n} /* }}} */", "label_name": "CWE-190", "label": 19} +{"code": "static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)\n{\n\tspl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;\n\tspl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);\n\t\n\tobject->u.dir.index++;\n\tdo {\n\t\tspl_filesystem_dir_read(object TSRMLS_CC);\n\t} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));\n\tif (object->file_name) {\n\t\tefree(object->file_name);\n\t\tobject->file_name = NULL;\n\t}\n\tif (iterator->current) {\n\t\tzval_ptr_dtor(&iterator->current);\n\t\titerator->current = NULL;\n\t}\n}", "label_name": "CWE-190", "label": 19} +{"code": "SPL_METHOD(SplFileObject, fgetcsv)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tchar delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape;\n\tchar *delim = NULL, *enclo = NULL, *esc = NULL;\n\tint d_len = 0, e_len = 0, esc_len = 0;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|sss\", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {\n\t\tswitch(ZEND_NUM_ARGS())\n\t\t{\n\t\tcase 3:\n\t\t\tif (esc_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"escape must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tescape = esc[0];\n\t\t\t/* no break */\n\t\tcase 2:\n\t\t\tif (e_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"enclosure must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tenclosure = enclo[0];\n\t\t\t/* no break */\n\t\tcase 1:\n\t\t\tif (d_len != 1) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"delimiter must be a character\");\n\t\t\t\tRETURN_FALSE;\n\t\t\t}\n\t\t\tdelimiter = delim[0];\n\t\t\t/* no break */\n\t\tcase 0:\n\t\t\tbreak;\n\t\t}\n\t\tspl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC);\n\t}\n}", "label_name": "CWE-190", "label": 19} +{"code": "zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */\n{\n\tspl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC);\n\t\n\tif (fsobj->u.dir.entry.d_name[0] == '\\0' && fsobj->orig_path == NULL) {\n\t\tmethod = \"_bad_state_ex\";\n\t\tmethod_len = sizeof(\"_bad_state_ex\") - 1;\n\t\tkey = NULL;\n\t}\n\t\n\treturn zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC);\n}", "label_name": "CWE-190", "label": 19} +{"code": "static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)\n{\n\tlong elements;\n\n\telements = parse_iv2((*p) + 2, p);\n\n\t(*p) += 2;\n\n\tif (ce->serialize == NULL) {\n\t\tobject_init_ex(*rval, ce);\n\t} else {\n\t\t/* If this class implements Serializable, it should not land here but in object_custom(). The passed string\n\t\tobviously doesn't descend from the regular serializer. */\n\t\tzend_error(E_WARNING, \"Erroneous data format for unserializing '%s'\", ce->name);\n\t\treturn 0;\n\t}\n\n\treturn elements;\n}", "label_name": "CWE-125", "label": 47} +{"code": "ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)\n{\n\tGC_REFCOUNT(ht) = 1;\n\tGC_TYPE_INFO(ht) = IS_ARRAY;\n\tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n\tht->nTableSize = zend_hash_check_size(nSize);\n\tht->nTableMask = HT_MIN_MASK;\n\tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n\tht->nNumUsed = 0;\n\tht->nNumOfElements = 0;\n\tht->nInternalPointer = HT_INVALID_IDX;\n\tht->nNextFreeElement = 0;\n\tht->pDestructor = pDestructor;\n}", "label_name": "CWE-190", "label": 19} +{"code": "static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\tDWORD nbWritten = 0;\n\n\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;\n\n\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */\n\t/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored\n\t * assert(Offset == 0);\n\t *\n\t * Using a serial printer, noticed though this field could be\n\t * set.\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"writing %\" PRIu32 \" bytes to %s\", Length,\n\t serial->device.name);\n\n\t/* FIXME: CommWriteFile to be replaced by WriteFile */\n\tif (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL))\n\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"write failure to %s, nbWritten=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbWritten, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}\n\n\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes written to %s\", nbWritten,\n\t serial->device.name);\n\tStream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "label_name": "CWE-125", "label": 47} +{"code": "BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)\n{\n\trdpGlyph* prevGlyph;\n\n\tif (id > 9)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache id: %\" PRIu32 \"\", id);\n\t\treturn FALSE;\n\t}\n\n\tif (index > glyphCache->glyphCache[id].number)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache index: %\" PRIu32 \" in cache id: %\" PRIu32 \"\", index, id);\n\t\treturn FALSE;\n\t}\n\n\tWLog_Print(glyphCache->log, WLOG_DEBUG, \"GlyphCachePut: id: %\" PRIu32 \" index: %\" PRIu32 \"\", id,\n\t index);\n\tprevGlyph = glyphCache->glyphCache[id].entries[index];\n\n\tif (prevGlyph)\n\t\tprevGlyph->Free(glyphCache->context, prevGlyph);\n\n\tglyphCache->glyphCache[id].entries[index] = glyph;\n\treturn TRUE;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision),\n trio_class_t* self, TRIO_CONST char* string,\n trio_flags_t flags, int width, int precision)\n{\n\tint length;\n\tint ch;\n\n\tassert(VALID(self));\n\tassert(VALID(self->OutStream));\n\n\tif (string == NULL)\n\t{\n\t\tstring = internalNullString;\n\t\tlength = sizeof(internalNullString) - 1;\n#if TRIO_FEATURE_QUOTE\n\t\t/* Disable quoting for the null pointer */\n\t\tflags &= (~FLAGS_QUOTE);\n#endif\n\t\twidth = 0;\n\t}\n\telse\n\t{\n\t\tif (precision == 0)\n\t\t{\n\t\t\tlength = trio_length(string);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlength = trio_length_max(string, precision);\n\t\t}\n\t}\n\tif ((NO_PRECISION != precision) && (precision < length))\n\t{\n\t\tlength = precision;\n\t}\n\twidth -= length;\n\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n\n\tif (!(flags & FLAGS_LEFTADJUST))\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n\n\twhile (length-- > 0)\n\t{\n\t\t/* The ctype parameters must be an unsigned char (or EOF) */\n\t\tch = (int)((unsigned char)(*string++));\n\t\tTrioWriteStringCharacter(self, ch, flags);\n\t}\n\n\tif (flags & FLAGS_LEFTADJUST)\n\t{\n\t\twhile (width-- > 0)\n\t\t\tself->OutStream(self, CHAR_ADJUST);\n\t}\n#if TRIO_FEATURE_QUOTE\n\tif (flags & FLAGS_QUOTE)\n\t\tself->OutStream(self, CHAR_QUOTE);\n#endif\n}", "label_name": "CWE-190", "label": 19} +{"code": "TRIO_PUBLIC_STRING size_t trio_length TRIO_ARGS1((string), TRIO_CONST char* string)\n{\n\treturn strlen(string);\n}", "label_name": "CWE-190", "label": 19} +{"code": "int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (fields->Len > 0)\n\t{\n\t\tif ((fields->BufferOffset + fields->Len) > Stream_Length(s))\n\t\t\treturn -1;\n\n\t\tfields->Buffer = (PBYTE) malloc(fields->Len);\n\n\t\tif (!fields->Buffer)\n\t\t\treturn -1;\n\n\t\tStream_SetPosition(s, fields->BufferOffset);\n\t\tStream_Read(s, fields->Buffer, fields->Len);\n\t}\n\n\treturn 1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,\n UINT32 width, UINT32 height,\n const BYTE* data, UINT32 length,\n BYTE* pDstData, UINT32 DstFormat,\n UINT32 nDstStride,\n UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,\n UINT32 nHeight, UINT32 flip)\n{\n\twStream* s;\n\tBOOL ret;\n\ts = Stream_New((BYTE*)data, length);\n\n\tif (!s)\n\t\treturn FALSE;\n\n\tif (nDstStride == 0)\n\t\tnDstStride = nWidth * GetBytesPerPixel(DstFormat);\n\n\tswitch (bpp)\n\t{\n\t\tcase 32:\n\t\t\tcontext->format = PIXEL_FORMAT_BGRA32;\n\t\t\tbreak;\n\n\t\tcase 24:\n\t\t\tcontext->format = PIXEL_FORMAT_BGR24;\n\t\t\tbreak;\n\n\t\tcase 16:\n\t\t\tcontext->format = PIXEL_FORMAT_BGR16;\n\t\t\tbreak;\n\n\t\tcase 8:\n\t\t\tcontext->format = PIXEL_FORMAT_RGB8;\n\t\t\tbreak;\n\n\t\tcase 4:\n\t\t\tcontext->format = PIXEL_FORMAT_A4;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tStream_Free(s, TRUE);\n\t\t\treturn FALSE;\n\t}\n\n\tcontext->width = width;\n\tcontext->height = height;\n\tret = nsc_context_initialize(context, s);\n\tStream_Free(s, FALSE);\n\n\tif (!ret)\n\t\treturn FALSE;\n\n\t/* RLE decode */\n\tPROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)\n\tnsc_rle_decompress_data(context);\n\tPROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)\n\t/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */\n\tPROFILER_ENTER(context->priv->prof_nsc_decode)\n\tcontext->decode(context);\n\tPROFILER_EXIT(context->priv->prof_nsc_decode)\n\n\tif (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,\n\t width, height, context->BitmapData,\n\t PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static int mount_entry_on_relative_rootfs(struct mntent *mntent,\n\t\t\t\t\t const char *rootfs)\n{\n\tchar path[MAXPATHLEN];\n\tint ret;\n\n\t/* relative to root mount point */\n\tret = snprintf(path, sizeof(path), \"%s/%s\", rootfs, mntent->mnt_dir);\n\tif (ret >= sizeof(path)) {\n\t\tERROR(\"path name too long\");\n\t\treturn -1;\n\t}\n\n\treturn mount_entry_on_generic(mntent, path);\n}", "label_name": "CWE-59", "label": 36} +{"code": "GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)\n{\n\tint r;\n\n\tstatic const char resp[] =\n\t\t\"\"\n\t\t\"%d\"\n\t\t\"\";\n\n\tchar body[512];\n\tint bodylen;\n\tstruct NameValueParserData data;\n\tchar * int_ip, * int_port, * rem_host, * rem_port, * protocol;\n\tint opt=0;\n\t/*int proto=0;*/\n\tunsigned short iport, rport;\n\n\tif (GETFLAG(IPV6FCFWDISABLEDMASK))\n\t{\n\t\tSoapError(h, 702, \"FirewallDisabled\");\n\t\treturn;\n\t}\n\n\tParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);\n\tint_ip = GetValueFromNameValueList(&data, \"InternalClient\");\n\tint_port = GetValueFromNameValueList(&data, \"InternalPort\");\n\trem_host = GetValueFromNameValueList(&data, \"RemoteHost\");\n\trem_port = GetValueFromNameValueList(&data, \"RemotePort\");\n\tprotocol = GetValueFromNameValueList(&data, \"Protocol\");\n\n\tif (!int_port || !ext_port || !protocol)\n\t{\n\t\tClearNameValueList(&data);\n\t\tSoapError(h, 402, \"Invalid Args\");\n\t\treturn;\n\t}\n\n\trport = (unsigned short)atoi(rem_port);\n\tiport = (unsigned short)atoi(int_port);\n\t/*proto = atoi(protocol);*/\n\n\tsyslog(LOG_INFO, \"%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s\", action, int_ip, iport,rem_host, rport, protocol);\n\n\t/* TODO */\n\tr = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/\n\n\tswitch(r)\n\t{\n\t\tcase 1:\t/* success */\n\t\t\tbodylen = snprintf(body, sizeof(body), resp,\n\t\t\t action, ns/*\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\"*/,\n\t\t\t opt, action);\n\t\t\tBuildSendAndCloseSoapResp(h, body, bodylen);\n\t\t\tbreak;\n\t\tcase -5:\t/* Protocol not supported */\n\t\t\tSoapError(h, 705, \"ProtocolNotSupported\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSoapError(h, 501, \"ActionFailed\");\n\t}\n\tClearNameValueList(&data);\n}", "label_name": "CWE-476", "label": 46} +{"code": "rs_filter_graph(RSFilter *filter)\n{\n\tg_return_if_fail(RS_IS_FILTER(filter));\n\tGString *str = g_string_new(\"digraph G {\\n\");\n\n\trs_filter_graph_helper(str, filter);\n\n\tg_string_append_printf(str, \"}\\n\");\n\tg_file_set_contents(\"/tmp/rs-filter-graph\", str->str, str->len, NULL);\n\n\tif (0 != system(\"dot -Tpng >/tmp/rs-filter-graph.png = '0' && *ptr <= '9')\n ptr++;\n /* 'lu' must follow here */\n if (*ptr++ != 'l')\n return 1;\n if (*ptr == 'u')\n ptr++;\n else\n return 1;\n n++;\n }\n }\n\n return (n != 3);\n}", "label_name": "CWE-134", "label": 54} +{"code": "juniper_atm2_print(netdissect_options *ndo,\n const struct pcap_pkthdr *h, register const u_char *p)\n{\n int llc_hdrlen;\n\n struct juniper_l2info_t l2info;\n\n l2info.pictype = DLT_JUNIPER_ATM2;\n if (juniper_parse_header(ndo, p, h, &l2info) == 0)\n return l2info.header_len;\n\n p+=l2info.header_len;\n\n if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */\n oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);\n return l2info.header_len;\n }\n\n if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n\n llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);\n if (llc_hdrlen > 0)\n return l2info.header_len;\n }\n\n if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */\n (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {\n ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);\n return l2info.header_len;\n }\n\n if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */\n isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);\n /* FIXME check if frame was recognized */\n return l2info.header_len;\n }\n\n if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */\n return l2info.header_len;\n\n if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */\n return l2info.header_len;\n\n\treturn l2info.header_len;\n}", "label_name": "CWE-125", "label": 47} +{"code": "handle_ppp(netdissect_options *ndo,\n u_int proto, const u_char *p, int length)\n{\n\tif ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */\n\t\tppp_hdlc(ndo, p - 1, length);\n\t\treturn;\n\t}\n\n\tswitch (proto) {\n\tcase PPP_LCP: /* fall through */\n\tcase PPP_IPCP:\n\tcase PPP_OSICP:\n\tcase PPP_MPLSCP:\n\tcase PPP_IPV6CP:\n\tcase PPP_CCP:\n\tcase PPP_BACP:\n\t\thandle_ctrl_proto(ndo, proto, p, length);\n\t\tbreak;\n\tcase PPP_ML:\n\t\thandle_mlppp(ndo, p, length);\n\t\tbreak;\n\tcase PPP_CHAP:\n\t\thandle_chap(ndo, p, length);\n\t\tbreak;\n\tcase PPP_PAP:\n\t\thandle_pap(ndo, p, length);\n\t\tbreak;\n\tcase PPP_BAP:\t\t/* XXX: not yet completed */\n\t\thandle_bap(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IP:\t/*XXX*/\n case PPP_VJNC:\n\tcase PPP_IP:\n\t\tip_print(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IPV6:\t/*XXX*/\n\tcase PPP_IPV6:\n\t\tip6_print(ndo, p, length);\n\t\tbreak;\n\tcase ETHERTYPE_IPX:\t/*XXX*/\n\tcase PPP_IPX:\n\t\tipx_print(ndo, p, length);\n\t\tbreak;\n\tcase PPP_OSI:\n\t\tisoclns_print(ndo, p, length, length);\n\t\tbreak;\n\tcase PPP_MPLS_UCAST:\n\tcase PPP_MPLS_MCAST:\n\t\tmpls_print(ndo, p, length);\n\t\tbreak;\n\tcase PPP_COMP:\n\t\tND_PRINT((ndo, \"compressed PPP data\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"%s \", tok2str(ppptype2str, \"unknown PPP protocol (0x%04x)\", proto)));\n\t\tprint_unknown_data(ndo, p, \"\\n\\t\", length);\n\t\tbreak;\n\t}\n}", "label_name": "CWE-125", "label": 47} +{"code": "parserep(netdissect_options *ndo,\n register const struct sunrpc_msg *rp, register u_int length)\n{\n\tregister const uint32_t *dp;\n\tu_int len;\n\tenum sunrpc_accept_stat astat;\n\n\t/*\n\t * Portability note:\n\t * Here we find the address of the ar_verf credentials.\n\t * Originally, this calculation was\n\t *\tdp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf\n\t * On the wire, the rp_acpt field starts immediately after\n\t * the (32 bit) rp_stat field. However, rp_acpt (which is a\n\t * \"struct accepted_reply\") contains a \"struct opaque_auth\",\n\t * whose internal representation contains a pointer, so on a\n\t * 64-bit machine the compiler inserts 32 bits of padding\n\t * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use\n\t * the internal representation to parse the on-the-wire\n\t * representation. Instead, we skip past the rp_stat field,\n\t * which is an \"enum\" and so occupies one 32-bit word.\n\t */\n\tdp = ((const uint32_t *)&rp->rm_reply) + 1;\n\tND_TCHECK(dp[1]);\n\tlen = EXTRACT_32BITS(&dp[1]);\n\tif (len >= length)\n\t\treturn (NULL);\n\t/*\n\t * skip past the ar_verf credentials.\n\t */\n\tdp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);\n\tND_TCHECK2(dp[0], 0);\n\n\t/*\n\t * now we can check the ar_stat field\n\t */\n\tastat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);\n\tif (astat != SUNRPC_SUCCESS) {\n\t\tND_PRINT((ndo, \" %s\", tok2str(sunrpc_str, \"ar_stat %d\", astat)));\n\t\tnfserr = 1;\t\t/* suppress trunc string */\n\t\treturn (NULL);\n\t}\n\t/* successful return */\n\tND_TCHECK2(*dp, sizeof(astat));\n\treturn ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));\ntrunc:\n\treturn (0);\n}", "label_name": "CWE-125", "label": 47} +{"code": "le64addr_string(netdissect_options *ndo, const u_char *ep)\n{\n\tconst unsigned int len = 8;\n\tregister u_int i;\n\tregister char *cp;\n\tregister struct enamemem *tp;\n\tchar buf[BUFSIZE];\n\n\ttp = lookup_bytestring(ndo, ep, len);\n\tif (tp->e_name)\n\t\treturn (tp->e_name);\n\n\tcp = buf;\n\tfor (i = len; i > 0 ; --i) {\n\t\t*cp++ = hex[*(ep + i - 1) >> 4];\n\t\t*cp++ = hex[*(ep + i - 1) & 0xf];\n\t\t*cp++ = ':';\n\t}\n\tcp --;\n\n\t*cp = '\\0';\n\n\ttp->e_name = strdup(buf);\n\tif (tp->e_name == NULL)\n\t\t(*ndo->ndo_error)(ndo, \"le64addr_string: strdup(buf)\");\n\n\treturn (tp->e_name);\n}", "label_name": "CWE-125", "label": 47} +{"code": "ip_optprint(netdissect_options *ndo,\n register const u_char *cp, u_int length)\n{\n\tregister u_int option_len;\n\tconst char *sep = \"\";\n\n\tfor (; length > 0; cp += option_len, length -= option_len) {\n\t\tu_int option_code;\n\n\t\tND_PRINT((ndo, \"%s\", sep));\n\t\tsep = \",\";\n\n\t\tND_TCHECK(*cp);\n\t\toption_code = *cp;\n\n\t\tND_PRINT((ndo, \"%s\",\n\t\t tok2str(ip_option_values,\"unknown %u\",option_code)));\n\n\t\tif (option_code == IPOPT_NOP ||\n option_code == IPOPT_EOL)\n\t\t\toption_len = 1;\n\n\t\telse {\n\t\t\tND_TCHECK(cp[1]);\n\t\t\toption_len = cp[1];\n\t\t\tif (option_len < 2) {\n\t\t\t\tND_PRINT((ndo, \" [bad length %u]\", option_len));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (option_len > length) {\n\t\t\tND_PRINT((ndo, \" [bad length %u]\", option_len));\n\t\t\treturn;\n\t\t}\n\n\t\tND_TCHECK2(*cp, option_len);\n\n\t\tswitch (option_code) {\n\t\tcase IPOPT_EOL:\n\t\t\treturn;\n\n\t\tcase IPOPT_TS:\n\t\t\tip_printts(ndo, cp, option_len);\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR: /* fall through */\n\t\tcase IPOPT_SSRR:\n\t\tcase IPOPT_LSRR:\n\t\t\tip_printroute(ndo, cp, option_len);\n\t\t\tbreak;\n\n\t\tcase IPOPT_RA:\n\t\t\tif (option_len < 4) {\n\t\t\t\tND_PRINT((ndo, \" [bad length %u]\", option_len));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tND_TCHECK(cp[3]);\n\t\t\tif (EXTRACT_16BITS(&cp[2]) != 0)\n\t\t\t\tND_PRINT((ndo, \" value %u\", EXTRACT_16BITS(&cp[2])));\n\t\t\tbreak;\n\n\t\tcase IPOPT_NOP: /* nothing to print - fall through */\n\t\tcase IPOPT_SECURITY:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"%s\", tstr));\n}", "label_name": "CWE-125", "label": 47} +{"code": "pimv2_addr_print(netdissect_options *ndo,\n const u_char *bp, enum pimv2_addrtype at, int silent)\n{\n\tint af;\n\tint len, hdrlen;\n\n\tND_TCHECK(bp[0]);\n\n\tif (pimv2_addr_len == 0) {\n\t\tND_TCHECK(bp[1]);\n\t\tswitch (bp[0]) {\n\t\tcase 1:\n\t\t\taf = AF_INET;\n\t\t\tlen = sizeof(struct in_addr);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\taf = AF_INET6;\n\t\t\tlen = sizeof(struct in6_addr);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t}\n\t\tif (bp[1] != 0)\n\t\t\treturn -1;\n\t\thdrlen = 2;\n\t} else {\n\t\tswitch (pimv2_addr_len) {\n\t\tcase sizeof(struct in_addr):\n\t\t\taf = AF_INET;\n\t\t\tbreak;\n\t\tcase sizeof(struct in6_addr):\n\t\t\taf = AF_INET6;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t\t}\n\t\tlen = pimv2_addr_len;\n\t\thdrlen = 0;\n\t}\n\n\tbp += hdrlen;\n\tswitch (at) {\n\tcase pimv2_unicast:\n\t\tND_TCHECK2(bp[0], len);\n\t\tif (af == AF_INET) {\n\t\t\tif (!silent)\n\t\t\t\tND_PRINT((ndo, \"%s\", ipaddr_string(ndo, bp)));\n\t\t}\n\t\telse if (af == AF_INET6) {\n\t\t\tif (!silent)\n\t\t\t\tND_PRINT((ndo, \"%s\", ip6addr_string(ndo, bp)));\n\t\t}\n\t\treturn hdrlen + len;\n\tcase pimv2_group:\n\tcase pimv2_source:\n\t\tND_TCHECK2(bp[0], len + 2);\n\t\tif (af == AF_INET) {\n\t\t\tif (!silent) {\n\t\t\t\tND_PRINT((ndo, \"%s\", ipaddr_string(ndo, bp + 2)));\n\t\t\t\tif (bp[1] != 32)\n\t\t\t\t\tND_PRINT((ndo, \"/%u\", bp[1]));\n\t\t\t}\n\t\t}\n\t\telse if (af == AF_INET6) {\n\t\t\tif (!silent) {\n\t\t\t\tND_PRINT((ndo, \"%s\", ip6addr_string(ndo, bp + 2)));\n\t\t\t\tif (bp[1] != 128)\n\t\t\t\t\tND_PRINT((ndo, \"/%u\", bp[1]));\n\t\t\t}\n\t\t}\n\t\tif (bp[0] && !silent) {\n\t\t\tif (at == pimv2_group) {\n\t\t\t\tND_PRINT((ndo, \"(0x%02x)\", bp[0]));\n\t\t\t} else {\n\t\t\t\tND_PRINT((ndo, \"(%s%s%s\",\n\t\t\t\t\tbp[0] & 0x04 ? \"S\" : \"\",\n\t\t\t\t\tbp[0] & 0x02 ? \"W\" : \"\",\n\t\t\t\t\tbp[0] & 0x01 ? \"R\" : \"\"));\n\t\t\t\tif (bp[0] & 0xf8) {\n\t\t\t\t\tND_PRINT((ndo, \"+0x%02x\", bp[0] & 0xf8));\n\t\t\t\t}\n\t\t\t\tND_PRINT((ndo, \")\"));\n\t\t\t}\n\t\t}\n\t\treturn hdrlen + 2 + len;\n\tdefault:\n\t\treturn -1;\n\t}\ntrunc:\n\treturn -1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "cisco_autorp_print(netdissect_options *ndo,\n register const u_char *bp, register u_int len)\n{\n\tint type;\n\tint numrps;\n\tint hold;\n\n\tND_TCHECK(bp[0]);\n\tND_PRINT((ndo, \" auto-rp \"));\n\ttype = bp[0];\n\tswitch (type) {\n\tcase 0x11:\n\t\tND_PRINT((ndo, \"candidate-advert\"));\n\t\tbreak;\n\tcase 0x12:\n\t\tND_PRINT((ndo, \"mapping\"));\n\t\tbreak;\n\tdefault:\n\t\tND_PRINT((ndo, \"type-0x%02x\", type));\n\t\tbreak;\n\t}\n\n\tND_TCHECK(bp[1]);\n\tnumrps = bp[1];\n\n\tND_TCHECK2(bp[2], 2);\n\tND_PRINT((ndo, \" Hold \"));\n\thold = EXTRACT_16BITS(&bp[2]);\n\tif (hold)\n\t\tunsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));\n\telse\n\t\tND_PRINT((ndo, \"FOREVER\"));\n\n\t/* Next 4 bytes are reserved. */\n\n\tbp += 8; len -= 8;\n\n\t/*XXX skip unless -v? */\n\n\t/*\n\t * Rest of packet:\n\t * numrps entries of the form:\n\t * 32 bits: RP\n\t * 6 bits: reserved\n\t * 2 bits: PIM version supported, bit 0 is \"supports v1\", 1 is \"v2\".\n\t * 8 bits: # of entries for this RP\n\t * each entry: 7 bits: reserved, 1 bit: negative,\n\t *\t 8 bits: mask 32 bits: source\n\t * lather, rinse, repeat.\n\t */\n\twhile (numrps--) {\n\t\tint nentries;\n\t\tchar s;\n\n\t\tND_TCHECK2(bp[0], 4);\n\t\tND_PRINT((ndo, \" RP %s\", ipaddr_string(ndo, bp)));\n\t\tND_TCHECK(bp[4]);\n\t\tswitch (bp[4] & 0x3) {\n\t\tcase 0: ND_PRINT((ndo, \" PIMv?\"));\n\t\t\tbreak;\n\t\tcase 1:\tND_PRINT((ndo, \" PIMv1\"));\n\t\t\tbreak;\n\t\tcase 2:\tND_PRINT((ndo, \" PIMv2\"));\n\t\t\tbreak;\n\t\tcase 3:\tND_PRINT((ndo, \" PIMv1+2\"));\n\t\t\tbreak;\n\t\t}\n\t\tif (bp[4] & 0xfc)\n\t\t\tND_PRINT((ndo, \" [rsvd=0x%02x]\", bp[4] & 0xfc));\n\t\tND_TCHECK(bp[5]);\n\t\tnentries = bp[5];\n\t\tbp += 6; len -= 6;\n\t\ts = ' ';\n\t\tfor (; nentries; nentries--) {\n\t\t\tND_TCHECK2(bp[0], 6);\n\t\t\tND_PRINT((ndo, \"%c%s%s/%d\", s, bp[0] & 1 ? \"!\" : \"\",\n\t\t\t ipaddr_string(ndo, &bp[2]), bp[1]));\n\t\t\tif (bp[0] & 0x02) {\n\t\t\t\tND_PRINT((ndo, \" bidir\"));\n\t\t\t}\n\t\t\tif (bp[0] & 0xfc) {\n\t\t\t\tND_PRINT((ndo, \"[rsvd=0x%02x]\", bp[0] & 0xfc));\n\t\t\t}\n\t\t\ts = ',';\n\t\t\tbp += 6; len -= 6;\n\t\t}\n\t}\n\treturn;\n\ntrunc:\n\tND_PRINT((ndo, \"[|autorp]\"));\n\treturn;\n}", "label_name": "CWE-125", "label": 47} +{"code": "mp_capable_print(netdissect_options *ndo,\n const u_char *opt, u_int opt_len, u_char flags)\n{\n const struct mp_capable *mpc = (const struct mp_capable *) opt;\n\n if (!(opt_len == 12 && flags & TH_SYN) &&\n !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK))\n return 0;\n\n if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) {\n ND_PRINT((ndo, \" Unknown Version (%d)\", MP_CAPABLE_OPT_VERSION(mpc->sub_ver)));\n return 1;\n }\n\n if (mpc->flags & MP_CAPABLE_C)\n ND_PRINT((ndo, \" csum\"));\n ND_PRINT((ndo, \" {0x%\" PRIx64, EXTRACT_64BITS(mpc->sender_key)));\n if (opt_len == 20) /* ACK */\n ND_PRINT((ndo, \",0x%\" PRIx64, EXTRACT_64BITS(mpc->receiver_key)));\n ND_PRINT((ndo, \"}\"));\n return 1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)\n{\n u_int tlen, pdu_type, pdu_len;\n const u_char *tptr;\n const rpki_rtr_pdu *pdu_header;\n\n tptr = pptr;\n tlen = len;\n\n if (!ndo->ndo_vflag) {\n\tND_PRINT((ndo, \", RPKI-RTR\"));\n\treturn;\n }\n\n while (tlen >= sizeof(rpki_rtr_pdu)) {\n\n ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));\n\n\tpdu_header = (const rpki_rtr_pdu *)tptr;\n pdu_type = pdu_header->pdu_type;\n pdu_len = EXTRACT_32BITS(pdu_header->length);\n ND_TCHECK2(*tptr, pdu_len);\n\n /* infinite loop check */\n if (!pdu_type || !pdu_len) {\n break;\n }\n\n if (tlen < pdu_len) {\n goto trunc;\n }\n\n\t/*\n\t * Print the PDU.\n\t */\n\tif (rpki_rtr_pdu_print(ndo, tptr, 8))\n\t\tgoto trunc;\n\n tlen -= pdu_len;\n tptr += pdu_len;\n }\n return;\ntrunc:\n ND_PRINT((ndo, \"\\n\\t%s\", tstr));\n}", "label_name": "CWE-125", "label": 47} +{"code": "static int parse_report(transport_smart *transport, git_push *push)\n{\n\tgit_pkt *pkt = NULL;\n\tconst char *line_end = NULL;\n\tgitno_buffer *buf = &transport->buffer;\n\tint error, recvd;\n\tgit_buf data_pkt_buf = GIT_BUF_INIT;\n\n\tfor (;;) {\n\t\tif (buf->offset > 0)\n\t\t\terror = git_pkt_parse_line(&pkt, buf->data,\n\t\t\t\t\t\t &line_end, buf->offset);\n\t\telse\n\t\t\terror = GIT_EBUFS;\n\n\t\tif (error < 0 && error != GIT_EBUFS) {\n\t\t\terror = -1;\n\t\t\tgoto done;\n\t\t}\n\n\t\tif (error == GIT_EBUFS) {\n\t\t\tif ((recvd = gitno_recv(buf)) < 0) {\n\t\t\t\terror = recvd;\n\t\t\t\tgoto done;\n\t\t\t}\n\n\t\t\tif (recvd == 0) {\n\t\t\t\tgiterr_set(GITERR_NET, \"early EOF\");\n\t\t\t\terror = GIT_EEOF;\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tgitno_consume(buf, line_end);\n\n\t\terror = 0;\n\n\t\tif (pkt == NULL)\n\t\t\tcontinue;\n\n\t\tswitch (pkt->type) {\n\t\t\tcase GIT_PKT_DATA:\n\t\t\t\t/* This is a sideband packet which contains other packets */\n\t\t\t\terror = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf);\n\t\t\t\tbreak;\n\t\t\tcase GIT_PKT_ERR:\n\t\t\t\tgiterr_set(GITERR_NET, \"report-status: Error reported: %s\",\n\t\t\t\t\t((git_pkt_err *)pkt)->error);\n\t\t\t\terror = -1;\n\t\t\t\tbreak;\n\t\t\tcase GIT_PKT_PROGRESS:\n\t\t\t\tif (transport->progress_cb) {\n\t\t\t\t\tgit_pkt_progress *p = (git_pkt_progress *) pkt;\n\t\t\t\t\terror = transport->progress_cb(p->data, p->len, transport->message_cb_payload);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\terror = add_push_report_pkt(push, pkt);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tgit_pkt_free(pkt);\n\n\t\t/* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */\n\t\tif (error == GIT_ITEROVER) {\n\t\t\terror = 0;\n\t\t\tif (data_pkt_buf.size > 0) {\n\t\t\t\t/* If there was data remaining in the pack data buffer,\n\t\t\t\t * then the server sent a partial pkt-line */\n\t\t\t\tgiterr_set(GITERR_NET, \"Incomplete pack data pkt-line\");\n\t\t\t\terror = GIT_ERROR;\n\t\t\t}\n\t\t\tgoto done;\n\t\t}\n\n\t\tif (error < 0) {\n\t\t\tgoto done;\n\t\t}\n\t}\ndone:\n\tgit_buf_free(&data_pkt_buf);\n\treturn error;\n}", "label_name": "CWE-476", "label": 46} +{"code": "static inline Quantum GetPixelChannel(const Image *magick_restrict image,\n const PixelChannel channel,const Quantum *magick_restrict pixel)\n{\n if (image->channel_map[image->channel_map[channel].offset].traits == UndefinedPixelTrait)\n return((Quantum) 0);\n return(pixel[image->channel_map[channel].offset]);\n}", "label_name": "CWE-787", "label": 24} +{"code": "static int dbConnect(char *host, char *user, char *passwd)\n{\n DBUG_ENTER(\"dbConnect\");\n if (verbose)\n {\n fprintf(stderr, \"# Connecting to %s...\\n\", host ? host : \"localhost\");\n }\n mysql_init(&mysql_connection);\n if (opt_compress)\n mysql_options(&mysql_connection, MYSQL_OPT_COMPRESS, NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n {\n mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n\t\t opt_ssl_capath, opt_ssl_cipher);\n mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n }\n#endif\n if (opt_protocol)\n mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n if (opt_bind_addr)\n mysql_options(&mysql_connection, MYSQL_OPT_BIND, opt_bind_addr);\n#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n if (shared_memory_base_name)\n mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);\n mysql_options(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_RESET, 0);\n mysql_options4(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_ADD,\n \"program_name\", \"mysqlcheck\");\n if (!(sock = mysql_real_connect(&mysql_connection, host, user, passwd,\n NULL, opt_mysql_port, opt_mysql_unix_port, 0)))\n {\n DBerror(&mysql_connection, \"when trying to connect\");\n DBUG_RETURN(1);\n }\n mysql_connection.reconnect= 1;\n DBUG_RETURN(0);\n} /* dbConnect */", "label_name": "CWE-295", "label": 52} +{"code": "static unsigned char *read_chunk(struct mschm_decompressor_p *self,\n\t\t\t\t struct mschmd_header *chm,\n\t\t\t\t struct mspack_file *fh,\n\t\t\t\t unsigned int chunk_num)\n{\n struct mspack_system *sys = self->system;\n unsigned char *buf;\n\n /* check arguments - most are already checked by chmd_fast_find */\n if (chunk_num > chm->num_chunks) return NULL;\n \n /* ensure chunk cache is available */\n if (!chm->chunk_cache) {\n\tsize_t size = sizeof(unsigned char *) * chm->num_chunks;\n\tif (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) {\n\t self->error = MSPACK_ERR_NOMEMORY;\n\t return NULL;\n\t}\n\tmemset(chm->chunk_cache, 0, size);\n }\n\n /* try to answer out of chunk cache */\n if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num];\n\n /* need to read chunk - allocate memory for it */\n if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) {\n\tself->error = MSPACK_ERR_NOMEMORY;\n\treturn NULL;\n }\n\n /* seek to block and read it */\n if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)),\n\t\t MSPACK_SYS_SEEK_START))\n {\n\tself->error = MSPACK_ERR_SEEK;\n\tsys->free(buf);\n\treturn NULL;\n }\n if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) {\n\tself->error = MSPACK_ERR_READ;\n\tsys->free(buf);\n\treturn NULL;\n }\n\n /* check the signature. Is is PMGL or PMGI? */\n if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) &&\n\t ((buf[3] == 0x4C) || (buf[3] == 0x49))))\n {\n\tself->error = MSPACK_ERR_SEEK;\n\tsys->free(buf);\n\treturn NULL;\n }\n\n /* all OK. Store chunk in cache and return it */\n return chm->chunk_cache[chunk_num] = buf;\n}", "label_name": "CWE-193", "label": 67} +{"code": "static int bmp_getint32(jas_stream_t *in, int_fast32_t *val)\n{\n\tint n;\n\tuint_fast32_t v;\n\tint c;\n\tfor (n = 4, v = 0;;) {\n\t\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t\tv |= (c << 24);\n\t\tif (--n <= 0) {\n\t\t\tbreak;\n\t\t}\n\t\tv >>= 8;\n\t}\n\tif (val) {\n\t\t*val = v;\n\t}\n\treturn 0;\n}", "label_name": "CWE-476", "label": 46} +{"code": "static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 4, &tmp))\n\t\treturn -1;\n\t*val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) &\n\t 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp);\n\treturn 0;\n}", "label_name": "CWE-190", "label": 19} +{"code": "static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 4, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n}", "label_name": "CWE-190", "label": 19} +{"code": "static void sycc444_to_rgb(opj_image_t *img)\n{\n\tint *d0, *d1, *d2, *r, *g, *b;\n\tconst int *y, *cb, *cr;\n\tunsigned int maxw, maxh, max, i;\n\tint offset, upb;\n\n\tupb = (int)img->comps[0].prec;\n\toffset = 1<<(upb - 1); upb = (1<comps[0].w; maxh = (unsigned int)img->comps[0].h;\n\tmax = maxw * maxh;\n\n\ty = img->comps[0].data;\n\tcb = img->comps[1].data;\n\tcr = img->comps[2].data;\n\n\td0 = r = (int*)malloc(sizeof(int) * (size_t)max);\n\td1 = g = (int*)malloc(sizeof(int) * (size_t)max);\n\td2 = b = (int*)malloc(sizeof(int) * (size_t)max);\n\n\tif(r == NULL || g == NULL || b == NULL) goto fails;\n\n\tfor(i = 0U; i < max; ++i)\n\t{\n\t\tsycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);\n\t\t++y; ++cb; ++cr; ++r; ++g; ++b;\n\t}\n\tfree(img->comps[0].data); img->comps[0].data = d0;\n\tfree(img->comps[1].data); img->comps[1].data = d1;\n\tfree(img->comps[2].data); img->comps[2].data = d2;\n\treturn;\n\nfails:\n\tif(r) free(r);\n\tif(g) free(g);\n\tif(b) free(b);\n\n}/* sycc444_to_rgb() */", "label_name": "CWE-125", "label": 47} +{"code": "parse_range(char *str, size_t file_sz, int *nranges)\n{\n\tstatic struct range\t ranges[MAX_RANGES];\n\tint\t\t\t i = 0;\n\tchar\t\t\t*p, *q;\n\n\t/* Extract range unit */\n\tif ((p = strchr(str, '=')) == NULL)\n\t\treturn (NULL);\n\n\t*p++ = '\\0';\n\t/* Check if it's a bytes range spec */\n\tif (strcmp(str, \"bytes\") != 0)\n\t\treturn (NULL);\n\n\twhile ((q = strchr(p, ',')) != NULL) {\n\t\t*q++ = '\\0';\n\n\t\t/* Extract start and end positions */\n\t\tif (parse_range_spec(p, file_sz, &ranges[i]) == 0)\n\t\t\tcontinue;\n\n\t\ti++;\n\t\tif (i == MAX_RANGES)\n\t\t\treturn (NULL);\n\n\t\tp = q;\n\t}\n\n\tif (parse_range_spec(p, file_sz, &ranges[i]) != 0)\n\t\ti++;\n\n\t*nranges = i;\n\treturn (i ? ranges : NULL);\n}", "label_name": "CWE-770", "label": 37} +{"code": "name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {\n\tint name_end = -1;\n\tint j = *idx;\n\tint ptr_count = 0;\n#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)\n#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)\n#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)\n\n\tchar *cp = name_out;\n\tconst char *const end = name_out + name_out_len;\n\n\t/* Normally, names are a series of length prefixed strings terminated */\n\t/* with a length of 0 (the lengths are u8's < 63). */\n\t/* However, the length can start with a pair of 1 bits and that */\n\t/* means that the next 14 bits are a pointer within the current */\n\t/* packet. */\n\n\tfor (;;) {\n\t\tu8 label_len;\n\t\tif (j >= length) return -1;\n\t\tGET8(label_len);\n\t\tif (!label_len) break;\n\t\tif (label_len & 0xc0) {\n\t\t\tu8 ptr_low;\n\t\t\tGET8(ptr_low);\n\t\t\tif (name_end < 0) name_end = j;\n\t\t\tj = (((int)label_len & 0x3f) << 8) + ptr_low;\n\t\t\t/* Make sure that the target offset is in-bounds. */\n\t\t\tif (j < 0 || j >= length) return -1;\n\t\t\t/* If we've jumped more times than there are characters in the\n\t\t\t * message, we must have a loop. */\n\t\t\tif (++ptr_count > length) return -1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (label_len > 63) return -1;\n\t\tif (cp != name_out) {\n\t\t\tif (cp + 1 >= end) return -1;\n\t\t\t*cp++ = '.';\n\t\t}\n\t\tif (cp + label_len >= end) return -1;\n\t\tmemcpy(cp, packet + j, label_len);\n\t\tcp += label_len;\n\t\tj += label_len;\n\t}\n\tif (cp >= end) return -1;\n\t*cp = '\\0';\n\tif (name_end < 0)\n\t\t*idx = j;\n\telse\n\t\t*idx = name_end;\n\treturn 0;\n err:\n\treturn -1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)\n{\n cJSON *current_element = NULL;\n\n if ((object == NULL) || (name == NULL))\n {\n return NULL;\n }\n\n current_element = object->child;\n if (case_sensitive)\n {\n while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))\n {\n current_element = current_element->next;\n }\n }\n else\n {\n while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))\n {\n current_element = current_element->next;\n }\n }\n\n return current_element;\n}", "label_name": "CWE-476", "label": 46} +{"code": "fname_match(\n regmatch_T\t*rmp,\n char_u\t*name,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match = NULL;\n char_u\t*p;\n\n if (name != NULL)\n {\n\t// Ignore case when 'fileignorecase' or the argument is set.\n\trmp->rm_ic = p_fic || ignore_case;\n\tif (vim_regexec(rmp, name, (colnr_T)0))\n\t match = name;\n\telse\n\t{\n\t // Replace $(HOME) with '~' and try matching again.\n\t p = home_replace_save(NULL, name);\n\t if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))\n\t\tmatch = name;\n\t vim_free(p);\n\t}\n }\n\n return match;\n}", "label_name": "CWE-476", "label": 46} +{"code": "buflist_match(\n regmatch_T\t*rmp,\n buf_T\t*buf,\n int\t\tignore_case) // when TRUE ignore case, when FALSE use 'fic'\n{\n char_u\t*match;\n\n // First try the short file name, then the long file name.\n match = fname_match(rmp, buf->b_sfname, ignore_case);\n if (match == NULL)\n\tmatch = fname_match(rmp, buf->b_ffname, ignore_case);\n\n return match;\n}", "label_name": "CWE-476", "label": 46} +{"code": "static VTermScreen *screen_new(VTerm *vt)\n{\n VTermState *state = vterm_obtain_state(vt);\n VTermScreen *screen;\n int rows, cols;\n\n if(!state)\n return NULL;\n\n screen = vterm_allocator_malloc(vt, sizeof(VTermScreen));\n\n vterm_get_size(vt, &rows, &cols);\n\n screen->vt = vt;\n screen->state = state;\n\n screen->damage_merge = VTERM_DAMAGE_CELL;\n screen->damaged.start_row = -1;\n screen->pending_scrollrect.start_row = -1;\n\n screen->rows = rows;\n screen->cols = cols;\n\n screen->callbacks = NULL;\n screen->cbdata = NULL;\n\n screen->buffers[0] = realloc_buffer(screen, NULL, rows, cols);\n\n screen->buffer = screen->buffers[0];\n\n screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * cols);\n\n vterm_state_set_callbacks(screen->state, &state_cbs, screen);\n\n return screen;\n}", "label_name": "CWE-476", "label": 46} +{"code": "cJSON *cJSON_CreateFloatArray( double *numbers, int count )\n{\n\tint i;\n\tcJSON *n = 0, *p = 0, *a = cJSON_CreateArray();\n\tfor ( i = 0; a && i < count; ++i ) {\n\t\tn = cJSON_CreateFloat( numbers[i] );\n\t\tif ( ! i )\n\t\t\ta->child = n;\n\t\telse\n\t\t\tsuffix_object( p, n );\n\t\tp = n;\n\t}\n\treturn a;\n}", "label_name": "CWE-120", "label": 44} +{"code": "void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )\n{\n\tcJSON_AddItemToArray( array, create_reference( item ) );\n}", "label_name": "CWE-120", "label": 44} +{"code": "cJSON *cJSON_CreateArray( void )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item )\n\t\titem->type = cJSON_Array;\n\treturn item;\n}", "label_name": "CWE-120", "label": 44} +{"code": "static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}", "label_name": "CWE-125", "label": 47} +{"code": "int ZEXPORT deflatePrime (strm, bits, value)\n z_streamp strm;\n int bits;\n int value;\n{\n deflate_state *s;\n int put;\n\n if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n s = strm->state;\n if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))\n return Z_BUF_ERROR;\n do {\n put = Buf_size - s->bi_valid;\n if (put > bits)\n put = bits;\n s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);\n s->bi_valid += put;\n _tr_flush_bits(s);\n value >>= put;\n bits -= put;\n } while (bits);\n return Z_OK;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {\n\tconst int nb10sz = 16;\n\tmemcpy (res, dbg_data, nb10sz);\n\tres->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);\n}", "label_name": "CWE-125", "label": 47} +{"code": "static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,\n const unsigned char *end )\n{\n int ret = 0;\n size_t n;\n\n if( ssl->conf->f_psk == NULL &&\n ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no pre-shared key\" ) );\n return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n }\n\n /*\n * Receive client pre-shared key identity name\n */\n if( *p + 2 > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n n = ( (*p)[0] << 8 ) | (*p)[1];\n *p += 2;\n\n if( n < 1 || n > 65535 || *p + n > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->conf->f_psk != NULL )\n {\n if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n else\n {\n /* Identity is not a big secret since clients send it in the clear,\n * but treat it carefully anyway, just in case */\n if( n != ssl->conf->psk_identity_len ||\n mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )\n {\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n }\n\n if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )\n {\n MBEDTLS_SSL_DEBUG_BUF( 3, \"Unknown PSK identity\", *p, n );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );\n return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );\n }\n\n *p += n;\n\n return( 0 );\n}", "label_name": "CWE-190", "label": 19} +{"code": "build_config(char *prefix, struct server *server)\n{\n char *path = NULL;\n int path_size = strlen(prefix) + strlen(server->port) + 20;\n\n path = ss_malloc(path_size);\n snprintf(path, path_size, \"%s/.shadowsocks_%s.conf\", prefix, server->port);\n FILE *f = fopen(path, \"w+\");\n if (f == NULL) {\n if (verbose) {\n LOGE(\"unable to open config file\");\n }\n ss_free(path);\n return;\n }\n fprintf(f, \"{\\n\");\n fprintf(f, \"\\\"server_port\\\":%d,\\n\", atoi(server->port));\n fprintf(f, \"\\\"password\\\":\\\"%s\\\"\", server->password);\n if (server->fast_open[0]) fprintf(f, \",\\n\\\"fast_open\\\": %s\", server->fast_open);\n if (server->mode) fprintf(f, \",\\n\\\"mode\\\":\\\"%s\\\"\", server->mode);\n if (server->method) fprintf(f, \",\\n\\\"method\\\":\\\"%s\\\"\", server->method);\n if (server->plugin) fprintf(f, \",\\n\\\"plugin\\\":\\\"%s\\\"\", server->plugin);\n if (server->plugin_opts) fprintf(f, \",\\n\\\"plugin_opts\\\":\\\"%s\\\"\", server->plugin_opts);\n fprintf(f, \"\\n}\\n\");\n fclose(f);\n ss_free(path);\n}", "label_name": "CWE-78", "label": 6} +{"code": "char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n /*\n rfbLog(\"rfbProcessFileTransferReadBuffer(%dlen)\\n\", length);\n */\n if (length>0) {\n buffer=malloc((uint64_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n}", "label_name": "CWE-787", "label": 24} +{"code": "get_html_data (MAPI_Attr *a)\n{\n VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);\n\n int j;\n for (j = 0; j < a->num_values; j++)\n {\n\tbody[j] = XMALLOC(VarLenData, 1);\n\tbody[j]->len = a->values[j].len;\n\tbody[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);\n\tmemmove (body[j]->data, a->values[j].data.buf, body[j]->len);\n }\n return body;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static char *r_socket_http_answer (RSocket *s, int *code, int *rlen) {\n\tr_return_val_if_fail (s, NULL);\n\tconst char *p;\n\tint ret, len = 0, bufsz = 32768, delta = 0;\n\tchar *dn, *buf = calloc (1, bufsz + 32); // XXX: use r_buffer here\n\tif (!buf) {\n\t\treturn NULL;\n\t}\n\tchar *res = NULL;\n\tint olen = __socket_slurp (s, (ut8*)buf, bufsz);\n\tif ((dn = (char*)r_str_casestr (buf, \"\\n\\n\"))) {\n\t\tdelta += 2;\n\t} else if ((dn = (char*)r_str_casestr (buf, \"\\r\\n\\r\\n\"))) {\n\t\tdelta += 4;\n\t} else {\n\t\tgoto fail;\n\t}\n\n\tolen -= delta;\n\t*dn = 0; // chop headers\n\t/* Parse Len */\n\tp = r_str_casestr (buf, \"Content-Length: \");\n\tif (p) {\n\t\tlen = atoi (p + 16);\n\t} else {\n\t\tlen = olen - (dn - buf);\n\t}\n\tif (len > 0) {\n\t\tif (len > olen) {\n\t\t\tres = malloc (len + 2);\n\t\t\tmemcpy (res, dn + delta, olen);\n\t\t\tdo {\n\t\t\t\tret = r_socket_read_block (s, (ut8*) res + olen, len - olen);\n\t\t\t\tif (ret < 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tolen += ret;\n\t\t\t} while (olen < len);\n\t\t\tres[len] = 0;\n\t\t} else {\n\t\t\tres = malloc (len + 1);\n\t\t\tif (res) {\n\t\t\t\tmemcpy (res, dn + delta, len);\n\t\t\t\tres[len] = 0;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tres = NULL;\n\t}\nfail:\n\tfree (buf);\n// is 's' free'd? isn't this going to cause a double free?\n\tr_socket_close (s);\n\tif (rlen) {\n\t\t*rlen = len;\n\t}\n\treturn res;\n}", "label_name": "CWE-78", "label": 6} +{"code": "static pyc_object *get_list_object(RBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n = 0;\n\n\tn = get_ut32 (buffer, &error);\n\tif (n > ST32_MAX) {\n\t\teprintf (\"bad marshal data (list size out of range)\\n\");\n\t\treturn NULL;\n\t}\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tret = get_array_object_generic (buffer, n);\n\tif (ret) {\n\t\tret->type = TYPE_LIST;\n\t\treturn ret;\n\t}\n\treturn NULL;\n}", "label_name": "CWE-825", "label": 64} +{"code": "static cache_accel_t *read_cache_accel(RBuffer *cache_buf, cache_hdr_t *hdr, cache_map_t *maps) {\n\tif (!cache_buf || !hdr || !hdr->accelerateInfoSize || !hdr->accelerateInfoAddr) {\n\t\treturn NULL;\n\t}\n\n\tut64 offset = va2pa (hdr->accelerateInfoAddr, hdr->mappingCount, maps, cache_buf, 0, NULL, NULL);\n\tif (!offset) {\n\t\treturn NULL;\n\t}\n\n\tut64 size = sizeof (cache_accel_t);\n\tcache_accel_t *accel = R_NEW0 (cache_accel_t);\n\tif (!accel) {\n\t\treturn NULL;\n\t}\n\n\tif (r_buf_fread_at (cache_buf, offset, (ut8*) accel, \"16il\", 1) != size) {\n\t\tR_FREE (accel);\n\t\treturn NULL;\n\t}\n\n\taccel->imagesExtrasOffset += offset;\n\taccel->bottomUpListOffset += offset;\n\taccel->dylibTrieOffset += offset;\n\taccel->initializersOffset += offset;\n\taccel->dofSectionsOffset += offset;\n\taccel->reExportListOffset += offset;\n\taccel->depListOffset += offset;\n\taccel->rangeTableOffset += offset;\n\n\treturn accel;\n}", "label_name": "CWE-787", "label": 24} +{"code": "R_API RCmdAliasVal *r_cmd_alias_get(RCmd *cmd, const char *k) {\n\tr_return_val_if_fail (cmd && cmd->aliases && k, NULL);\n\treturn ht_pp_find(cmd->aliases, k, NULL);\n}", "label_name": "CWE-125", "label": 47} +{"code": "RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n\tif (!bin->entry_table) {\n\t\treturn NULL;\n\t}\n\tRList *entries = r_list_newf (free);\n\tif (!entries) {\n\t\treturn NULL;\n\t}\n\tRList *segments = r_bin_ne_get_segments (bin);\n\tif (!segments) {\n\t\tr_list_free (entries);\n\t\treturn NULL;\n\t}\n\tif (bin->ne_header->csEntryPoint) {\n\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\tif (!entry) {\n\t\t\tr_list_free (entries);\n\t\t\treturn NULL;\n\t\t}\n\t\tentry->bits = 16;\n\t\tut32 entry_cs = bin->ne_header->csEntryPoint;\n\t\tRBinSection *s = r_list_get_n (segments, entry_cs - 1);\n\t\tentry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);\n\n\t\tr_list_append (entries, entry);\n\t}\n\tint off = 0;\n\tsize_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset;\n\twhile (off < bin->ne_header->EntryTableLength) {\n\t\tif (tableat + off >= r_buf_size (bin->buf)) {\n\t\t\tbreak;\n\t\t}\n\t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n\t\tif (!bundle_length) {\n\t\t\tbreak;\n\t\t}\n\t\toff++;\n\t\tut8 bundle_type = *(ut8 *)(bin->entry_table + off);\n\t\toff++;\n\t\tint i;\n\t\tfor (i = 0; i < bundle_length; i++) {\n\t\t\tif (tableat + off + 4 >= r_buf_size (bin->buf)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinAddr *entry = R_NEW0 (RBinAddr);\n\t\t\tif (!entry) {\n\t\t\t\tr_list_free (entries);\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\toff++;\n\t\t\tif (!bundle_type) { // Skip\n\t\t\t\toff--;\n\t\t\t\tfree (entry);\n\t\t\t\tbreak;\n\t\t\t} else if (bundle_type == 0xff) { // moveable\n\t\t\t\toff += 2;\n\t\t\t\tut8 segnum = *(bin->entry_table + off);\n\t\t\t\toff++;\n\t\t\t\tut16 segoff = *(ut16 *)(bin->entry_table + off);\n\t\t\t\tif (segnum > 0) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n\t\t\t\t}\n\t\t\t} else { // Fixed\n\t\t\t\tif (bundle_type < bin->ne_header->SegCount) {\n\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset\n\t\t\t\t\t\t* bin->alignment + *(ut16 *)(bin->entry_table + off);\n\t\t\t\t}\n\t\t\t}\n\t\t\toff += 2;\n\t\t\tr_list_append (entries, entry);\n\t\t}\n\t}\n\tr_list_free (segments);\n\tbin->entries = entries;\n\treturn entries;\n}", "label_name": "CWE-125", "label": 47} +{"code": "static bool vtable_is_value_in_text_section(RVTableContext *context, ut64 curAddress, ut64 *value) {\n\t//value at the current address\n\tut64 curAddressValue;\n\tif (!context->read_addr (context->anal, curAddress, &curAddressValue)) {\n\t\treturn false;\n\t}\n\t//if the value is in text section\n\tbool ret = vtable_addr_in_text_section (context, curAddressValue);\n\tif (value) {\n\t\t*value = curAddressValue;\n\t}\n\treturn ret;\n}", "label_name": "CWE-824", "label": 65} +{"code": "BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content,\n int content_len)\n{\n Packet *p = NULL;\n int hlen = 20;\n int ttl = 64;\n uint8_t *pcontent;\n IPV4Hdr ip4h;\n\n p = SCCalloc(1, sizeof(*p) + default_packet_size);\n if (unlikely(p == NULL))\n return NULL;\n\n PACKET_INITIALIZE(p);\n\n gettimeofday(&p->ts, NULL);\n //p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p);\n ip4h.ip_verhl = 4 << 4;\n ip4h.ip_verhl |= hlen >> 2;\n ip4h.ip_len = htons(hlen + content_len);\n ip4h.ip_id = htons(id);\n ip4h.ip_off = htons(off);\n if (mf)\n ip4h.ip_off = htons(IP_MF | off);\n else\n ip4h.ip_off = htons(off);\n ip4h.ip_ttl = ttl;\n ip4h.ip_proto = IPPROTO_ICMP;\n\n ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */\n ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */\n\n /* copy content_len crap, we need full length */\n PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h));\n p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p);\n SET_IPV4_SRC_ADDR(p, &p->src);\n SET_IPV4_DST_ADDR(p, &p->dst);\n\n pcontent = SCCalloc(1, content_len);\n if (unlikely(pcontent == NULL))\n return NULL;\n memset(pcontent, content, content_len);\n PacketCopyDataOffset(p, hlen, pcontent, content_len);\n SET_PKT_LEN(p, hlen + content_len);\n SCFree(pcontent);\n\n p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen);\n\n /* Self test. */\n if (IPV4_GET_VER(p) != 4)\n goto error;\n if (IPV4_GET_HLEN(p) != hlen)\n goto error;\n if (IPV4_GET_IPLEN(p) != hlen + content_len)\n goto error;\n if (IPV4_GET_IPID(p) != id)\n goto error;\n if (IPV4_GET_IPOFFSET(p) != off)\n goto error;\n if (IPV4_GET_MF(p) != mf)\n goto error;\n if (IPV4_GET_IPTTL(p) != ttl)\n goto error;\n if (IPV4_GET_IPPROTO(p) != IPPROTO_ICMP)\n goto error;\n\n return p;\nerror:\n if (p != NULL)\n SCFree(p);\n return NULL;\n}", "label_name": "CWE-358", "label": 50} +{"code": "static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,\n\tunsigned int *pv)\n{\n\tunsigned int field_type;\n\tunsigned int value_count;\n\n\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n\n\tif(value_count!=1) return 0;\n\n\tif(field_type==3) { // SHORT (uint16)\n\t\t*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);\n\t\treturn 1;\n\t}\n\telse if(field_type==4) { // LONG (uint32)\n\t\t*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-125", "label": 47} +{"code": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n\t\tconst iw_byte *d, size_t d_len)\n{\n\tstruct iw_exif_state e;\n\tiw_uint32 ifd;\n\n\tif(d_len<8) return;\n\n\tiw_zeromem(&e,sizeof(struct iw_exif_state));\n\te.d = d;\n\te.d_len = d_len;\n\n\te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n\n\tifd = iw_get_ui32_e(&d[4],e.endian);\n\n\tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n}", "label_name": "CWE-125", "label": 47} +{"code": "static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n\tdouble *pv)\n{\n\tunsigned int field_type;\n\tunsigned int value_count;\n\tunsigned int value_pos;\n\tunsigned int numer, denom;\n\n\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n\n\tif(value_count!=1) return 0;\n\n\tif(field_type!=5) return 0; // 5=Rational (two uint32's)\n\n\t// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read\n\t// the location where it is stored.\n\n\tvalue_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n\tif(value_pos > e->d_len-8) return 0;\n\n\t// Read the actual value.\n\tnumer = iw_get_ui32_e(&e->d[value_pos ],e->endian);\n\tdenom = iw_get_ui32_e(&e->d[value_pos+4],e->endian);\n\tif(denom==0) return 0;\n\n\t*pv = ((double)numer)/denom;\n\treturn 1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "IW_IMPL(int) iw_get_input_density(struct iw_context *ctx,\n double *px, double *py, int *pcode)\n{\n\t*px = 1.0;\n\t*py = 1.0;\n\t*pcode = ctx->img1.density_code;\n\tif(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) {\n\t\t*px = ctx->img1.density_x;\n\t\t*py = ctx->img1.density_y;\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-369", "label": 60} +{"code": "get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n/* This version is for reading raw-word-format PPM files with any maxval */\n{\n ppm_source_ptr source = (ppm_source_ptr)sinfo;\n register JSAMPROW ptr;\n register U_CHAR *bufferptr;\n register JSAMPLE *rescale = source->rescale;\n JDIMENSION col;\n unsigned int maxval = source->maxval;\n\n if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n ptr = source->pub.buffer[0];\n bufferptr = source->iobuffer;\n for (col = cinfo->image_width; col > 0; col--) {\n register unsigned int temp;\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n }\n return 1;\n}", "label_name": "CWE-787", "label": 24} +{"code": "void imap_quote_string (char *dest, size_t dlen, const char *src)\n{\n static const char quote[] = \"\\\"\\\\\";\n char *pt;\n const char *s;\n\n pt = dest;\n s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr (quote, *s))\n {\n dlen -= 2;\n if (!dlen)\n\tbreak;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = 0;\n}", "label_name": "CWE-78", "label": 6} +{"code": "static void _imap_quote_string (char *dest, size_t dlen, const char *src,\n const char *to_quote)\n{\n char *pt;\n const char *s;\n\n pt = dest;\n s = src;\n\n *pt++ = '\"';\n /* save room for trailing quote-char */\n dlen -= 2;\n\n for (; *s && dlen; s++)\n {\n if (strchr (to_quote, *s))\n {\n dlen -= 2;\n if (!dlen)\n\tbreak;\n *pt++ = '\\\\';\n *pt++ = *s;\n }\n else\n {\n *pt++ = *s;\n dlen--;\n }\n }\n *pt++ = '\"';\n *pt = 0;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static int pop_sync_mailbox(struct Context *ctx, int *index_hint)\n{\n int i, j, ret = 0;\n char buf[LONG_STRING];\n struct PopData *pop_data = (struct PopData *) ctx->data;\n struct Progress progress;\n#ifdef USE_HCACHE\n header_cache_t *hc = NULL;\n#endif\n\n pop_data->check_time = 0;\n\n while (true)\n {\n if (pop_reconnect(ctx) < 0)\n return -1;\n\n mutt_progress_init(&progress, _(\"Marking messages deleted...\"),\n MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);\n\n#ifdef USE_HCACHE\n hc = pop_hcache_open(pop_data, ctx->path);\n#endif\n\n for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)\n {\n if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)\n {\n j++;\n if (!ctx->quiet)\n mutt_progress_update(&progress, j, -1);\n snprintf(buf, sizeof(buf), \"DELE %d\\r\\n\", ctx->hdrs[i]->refno);\n ret = pop_query(pop_data, buf, sizeof(buf));\n if (ret == 0)\n {\n mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data);\n#ifdef USE_HCACHE\n mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));\n#endif\n }\n }\n\n#ifdef USE_HCACHE\n if (ctx->hdrs[i]->changed)\n {\n mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),\n ctx->hdrs[i], 0);\n }\n#endif\n }\n\n#ifdef USE_HCACHE\n mutt_hcache_close(hc);\n#endif\n\n if (ret == 0)\n {\n mutt_str_strfcpy(buf, \"QUIT\\r\\n\", sizeof(buf));\n ret = pop_query(pop_data, buf, sizeof(buf));\n }\n\n if (ret == 0)\n {\n pop_data->clear_cache = true;\n pop_clear_cache(pop_data);\n pop_data->status = POP_DISCONNECTED;\n return 0;\n }\n\n if (ret == -2)\n {\n mutt_error(\"%s\", pop_data->err_msg);\n return -1;\n }\n }\n}", "label_name": "CWE-22", "label": 2} +{"code": "int imap_subscribe(char *path, bool subscribe)\n{\n struct ImapData *idata = NULL;\n char buf[LONG_STRING];\n char mbox[LONG_STRING];\n char errstr[STRING];\n struct Buffer err, token;\n struct ImapMbox mx;\n\n if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox)\n {\n mutt_error(_(\"Bad mailbox name\"));\n return -1;\n }\n idata = imap_conn_find(&(mx.account), 0);\n if (!idata)\n goto fail;\n\n imap_fix_path(idata, mx.mbox, buf, sizeof(buf));\n if (!*buf)\n mutt_str_strfcpy(buf, \"INBOX\", sizeof(buf));\n\n if (ImapCheckSubscribed)\n {\n mutt_buffer_init(&token);\n mutt_buffer_init(&err);\n err.data = errstr;\n err.dsize = sizeof(errstr);\n snprintf(mbox, sizeof(mbox), \"%smailboxes \\\"%s\\\"\", subscribe ? \"\" : \"un\", path);\n if (mutt_parse_rc_line(mbox, &token, &err))\n mutt_debug(1, \"Error adding subscribed mailbox: %s\\n\", errstr);\n FREE(&token.data);\n }\n\n if (subscribe)\n mutt_message(_(\"Subscribing to %s...\"), buf);\n else\n mutt_message(_(\"Unsubscribing from %s...\"), buf);\n imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);\n\n snprintf(buf, sizeof(buf), \"%sSUBSCRIBE %s\", subscribe ? \"\" : \"UN\", mbox);\n\n if (imap_exec(idata, buf, 0) < 0)\n goto fail;\n\n imap_unmunge_mbox_name(idata, mx.mbox);\n if (subscribe)\n mutt_message(_(\"Subscribed to %s\"), mx.mbox);\n else\n mutt_message(_(\"Unsubscribed from %s\"), mx.mbox);\n FREE(&mx.mbox);\n return 0;\n\nfail:\n FREE(&mx.mbox);\n return -1;\n}", "label_name": "CWE-78", "label": 6} +{"code": "ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return true;\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return true;\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}", "label_name": "CWE-476", "label": 46} +{"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-787", "label": 24} +{"code": "process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n{\n\tUNUSED(size);\n\tint indexw;\n\tint indexh;\n\tint code;\n\tint collen;\n\tint replen;\n\tint color;\n\tint x;\n\tint revcode;\n\tuint8 * last_line;\n\tuint8 * this_line;\n\tuint8 * org_in;\n\tuint8 * org_out;\n\n\torg_in = in;\n\torg_out = out;\n\tlast_line = 0;\n\tindexh = 0;\n\twhile (indexh < height)\n\t{\n\t\tout = (org_out + width * height * 4) - ((indexh + 1) * width * 4);\n\t\tcolor = 0;\n\t\tthis_line = out;\n\t\tindexw = 0;\n\t\tif (last_line == 0)\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor = CVAL(in);\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = CVAL(in);\n\t\t\t\t\tif (x & 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\tcolor = -x;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tcolor = x;\n\t\t\t\t\t}\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tindexh++;\n\t\tlast_line = this_line;\n\t}\n\treturn (int) (in - org_in);\n}", "label_name": "CWE-787", "label": 24} +{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-191", "label": 55} +{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-191", "label": 55} +{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-787", "label": 24} +{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-125", "label": 47} +{"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "CWE-787", "label": 24} +{"code": "process_bitmap_updates(STREAM s)\n{\n\tuint16 num_updates;\n\tuint16 left, top, right, bottom, width, height;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tuint8 *data, *bmpdata;\n\tint i;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\n\tin_uint16_le(s, num_updates);\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t{\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n\t\txfree(bmpdata);\n\t}\n}", "label_name": "CWE-190", "label": 19} +{"code": "_PyMemoTable_ResizeTable(PyMemoTable *self, Py_ssize_t min_size)\n{\n PyMemoEntry *oldtable = NULL;\n PyMemoEntry *oldentry, *newentry;\n Py_ssize_t new_size = MT_MINSIZE;\n Py_ssize_t to_process;\n\n assert(min_size > 0);\n\n /* Find the smallest valid table size >= min_size. */\n while (new_size < min_size && new_size > 0)\n new_size <<= 1;\n if (new_size <= 0) {\n PyErr_NoMemory();\n return -1;\n }\n /* new_size needs to be a power of two. */\n assert((new_size & (new_size - 1)) == 0);\n\n /* Allocate new table. */\n oldtable = self->mt_table;\n self->mt_table = PyMem_NEW(PyMemoEntry, new_size);\n if (self->mt_table == NULL) {\n self->mt_table = oldtable;\n PyErr_NoMemory();\n return -1;\n }\n self->mt_allocated = new_size;\n self->mt_mask = new_size - 1;\n memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size);\n\n /* Copy entries from the old table. */\n to_process = self->mt_used;\n for (oldentry = oldtable; to_process > 0; oldentry++) {\n if (oldentry->me_key != NULL) {\n to_process--;\n /* newentry is a pointer to a chunk of the new\n mt_table, so we're setting the key:value pair\n in-place. */\n newentry = _PyMemoTable_Lookup(self, oldentry->me_key);\n newentry->me_key = oldentry->me_key;\n newentry->me_value = oldentry->me_value;\n }\n }\n\n /* Deallocate the old table. */\n PyMem_FREE(oldtable);\n return 0;\n}", "label_name": "CWE-190", "label": 19} +{"code": "PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value)\n{\n PyMemoEntry *entry;\n\n assert(key != NULL);\n\n entry = _PyMemoTable_Lookup(self, key);\n if (entry->me_key != NULL) {\n entry->me_value = value;\n return 0;\n }\n Py_INCREF(key);\n entry->me_key = key;\n entry->me_value = value;\n self->mt_used++;\n\n /* If we added a key, we can safely resize. Otherwise just return!\n * If used >= 2/3 size, adjust size. Normally, this quaduples the size.\n *\n * Quadrupling the size improves average table sparseness\n * (reducing collisions) at the cost of some memory. It also halves\n * the number of expensive resize operations in a growing memo table.\n *\n * Very large memo tables (over 50K items) use doubling instead.\n * This may help applications with severe memory constraints.\n */\n if (!(self->mt_used * 3 >= (self->mt_mask + 1) * 2))\n return 0;\n return _PyMemoTable_ResizeTable(self,\n (self->mt_used > 50000 ? 2 : 4) * self->mt_used);\n}", "label_name": "CWE-190", "label": 19} +{"code": "Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, int\n end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!value) {\n PyErr_SetString(PyExc_ValueError,\n \"field value is required for Assign\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = Assign_kind;\n p->v.Assign.targets = targets;\n p->v.Assign.value = value;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label_name": "CWE-125", "label": 47} +{"code": "AsyncFunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq\n * decorator_list, expr_ty returns, int lineno, int col_offset,\n int end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!name) {\n PyErr_SetString(PyExc_ValueError,\n \"field name is required for AsyncFunctionDef\");\n return NULL;\n }\n if (!args) {\n PyErr_SetString(PyExc_ValueError,\n \"field args is required for AsyncFunctionDef\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = AsyncFunctionDef_kind;\n p->v.AsyncFunctionDef.name = name;\n p->v.AsyncFunctionDef.args = args;\n p->v.AsyncFunctionDef.body = body;\n p->v.AsyncFunctionDef.decorator_list = decorator_list;\n p->v.AsyncFunctionDef.returns = returns;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label_name": "CWE-125", "label": 47} +{"code": "validate_commit_metadata (GVariant *commit_data,\n const char *ref,\n const char *required_metadata,\n gboolean require_xa_metadata,\n GError **error)\n{\n g_autoptr(GVariant) commit_metadata = NULL;\n const char *xa_metadata = NULL;\n\n commit_metadata = g_variant_get_child_value (commit_data, 0);\n\n if (commit_metadata != NULL)\n g_variant_lookup (commit_metadata, \"xa.metadata\", \"&s\", &xa_metadata);\n\n if ((xa_metadata == NULL && require_xa_metadata) ||\n (xa_metadata != NULL && g_strcmp0 (required_metadata, xa_metadata) != 0))\n {\n g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,\n _(\"Commit metadata for %s not matching expected metadata\"), ref);\n return FALSE;\n }\n\n return TRUE;\n}", "label_name": "CWE-276", "label": 45} +{"code": "mark_op_resolved (FlatpakTransactionOperation *op,\n const char *commit,\n GFile *sideload_path,\n GBytes *metadata,\n GBytes *old_metadata)\n{\n g_debug (\"marking op %s:%s resolved to %s\", kind_to_str (op->kind), flatpak_decomposed_get_ref (op->ref), commit ? commit : \"-\");\n\n g_assert (op != NULL);\n\n g_assert (commit != NULL);\n\n op->resolved = TRUE;\n\n if (op->resolved_commit != commit)\n {\n g_free (op->resolved_commit); /* This is already set if we retry resolving to get a token, so free first */\n op->resolved_commit = g_strdup (commit);\n }\n\n if (sideload_path)\n op->resolved_sideload_path = g_object_ref (sideload_path);\n\n if (metadata)\n {\n g_autoptr(GKeyFile) metakey = g_key_file_new ();\n if (g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))\n {\n op->resolved_metadata = g_bytes_ref (metadata);\n op->resolved_metakey = g_steal_pointer (&metakey);\n }\n else\n g_message (\"Warning: Failed to parse metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n }\n if (old_metadata)\n {\n g_autoptr(GKeyFile) metakey = g_key_file_new ();\n if (g_key_file_load_from_bytes (metakey, old_metadata, G_KEY_FILE_NONE, NULL))\n {\n op->resolved_old_metadata = g_bytes_ref (old_metadata);\n op->resolved_old_metakey = g_steal_pointer (&metakey);\n }\n else\n g_message (\"Warning: Failed to parse old metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n }\n}", "label_name": "CWE-276", "label": 45} +{"code": "TEE_Result syscall_cryp_obj_populate(unsigned long obj,\n\t\t\tstruct utee_attribute *usr_attrs,\n\t\t\tunsigned long attr_count)\n{\n\tTEE_Result res;\n\tstruct tee_ta_session *sess;\n\tstruct tee_obj *o;\n\tconst struct tee_cryp_obj_type_props *type_props;\n\tTEE_Attribute *attrs = NULL;\n\n\tres = tee_ta_get_current_session(&sess);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\tres = tee_obj_get(to_user_ta_ctx(sess->ctx),\n\t\t\t tee_svc_uref_to_vaddr(obj), &o);\n\tif (res != TEE_SUCCESS)\n\t\treturn res;\n\n\t/* Must be a transient object */\n\tif ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\t/* Must not be initialized already */\n\tif ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\n\ttype_props = tee_svc_find_type_props(o->info.objectType);\n\tif (!type_props)\n\t\treturn TEE_ERROR_NOT_IMPLEMENTED;\n\n\tattrs = malloc(sizeof(TEE_Attribute) * attr_count);\n\tif (!attrs)\n\t\treturn TEE_ERROR_OUT_OF_MEMORY;\n\tres = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,\n\t\t\t attrs);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;\n\n\tres = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,\n\t\t\t\t attrs, attr_count);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;\n\n\tres = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);\n\tif (res == TEE_SUCCESS)\n\t\to->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;\n\nout:\n\tfree(attrs);\n\treturn res;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static int do_i2c_mw(struct cmd_tbl *cmdtp, int flag, int argc,\n\t\t char *const argv[])\n{\n\tuint\tchip;\n\tulong\taddr;\n\tint\talen;\n\tuchar\tbyte;\n\tint\tcount;\n\tint ret;\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tstruct udevice *dev;\n#endif\n\n\tif ((argc < 4) || (argc > 5))\n\t\treturn CMD_RET_USAGE;\n\n\t/*\n\t * Chip is always specified.\n\t */\n\tchip = hextoul(argv[1], NULL);\n\n\t/*\n\t * Address is always specified.\n\t */\n\taddr = hextoul(argv[2], NULL);\n\talen = get_alen(argv[2], DEFAULT_ADDR_LEN);\n\tif (alen > 3)\n\t\treturn CMD_RET_USAGE;\n\n#if CONFIG_IS_ENABLED(DM_I2C)\n\tret = i2c_get_cur_bus_chip(chip, &dev);\n\tif (!ret && alen != -1)\n\t\tret = i2c_set_chip_offset_len(dev, alen);\n\tif (ret)\n\t\treturn i2c_report_err(ret, I2C_ERR_WRITE);\n#endif\n\t/*\n\t * Value to write is always specified.\n\t */\n\tbyte = hextoul(argv[3], NULL);\n\n\t/*\n\t * Optional count\n\t */\n\tif (argc == 5)\n\t\tcount = hextoul(argv[4], NULL);\n\telse\n\t\tcount = 1;\n\n\twhile (count-- > 0) {\n#if CONFIG_IS_ENABLED(DM_I2C)\n\t\tret = dm_i2c_write(dev, addr++, &byte, 1);\n#else\n\t\tret = i2c_write(chip, addr++, alen, &byte, 1);\n#endif\n\t\tif (ret)\n\t\t\treturn i2c_report_err(ret, I2C_ERR_WRITE);\n\t\t/*\n\t\t * Wait for the write to complete. The write can take\n\t\t * up to 10mSec (we allow a little more time).\n\t\t */\n/*\n * No write delay with FRAM devices.\n */\n#if !defined(CONFIG_SYS_I2C_FRAM)\n\t\tudelay(11000);\n#endif\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-787", "label": 24} +{"code": "SWFInput_readSBits(SWFInput input, int number)\n{\n\tint num = SWFInput_readBits(input, number);\n\n\tif ( num & (1<<(number-1)) )\n\t\treturn num - (1<metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1;\n\n\t*in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn 0;\n}", "label_name": "CWE-125", "label": 47} +{"code": "uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0;\n\n\tif (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1;\n\n\t*in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn 0;\n}", "label_name": "CWE-787", "label": 24} +{"code": "uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return NULL;\n\n\tuint32_t *MP4buffer = NULL;\n\tif (index < mp4->indexcount && mp4->mediafp)\n\t{\n\t\tMP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]);\n\n\t\tif (MP4buffer)\n\t\t{\n\t\t\tLONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);\n\t\t\tfread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp);\n\t\t\treturn MP4buffer;\n\t\t}\n\t}\n\treturn NULL;\n}", "label_name": "CWE-787", "label": 24} +{"code": "processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {\n const char *textStart, *textEnd;\n const char *next;\n enum XML_Error result;\n OPEN_INTERNAL_ENTITY *openEntity;\n\n if (parser->m_freeInternalEntities) {\n openEntity = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity->next;\n } else {\n openEntity\n = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));\n if (! openEntity)\n return XML_ERROR_NO_MEMORY;\n }\n entity->open = XML_TRUE;\n entity->processed = 0;\n openEntity->next = parser->m_openInternalEntities;\n parser->m_openInternalEntities = openEntity;\n openEntity->entity = entity;\n openEntity->startTagLevel = parser->m_tagLevel;\n openEntity->betweenDecl = betweenDecl;\n openEntity->internalEventPtr = NULL;\n openEntity->internalEventEndPtr = NULL;\n textStart = (char *)entity->textPtr;\n textEnd = (char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n next = textStart;\n\n#ifdef XML_DTD\n if (entity->is_param) {\n int tok\n = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);\n result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,\n tok, next, &next, XML_FALSE);\n } else\n#endif /* XML_DTD */\n result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,\n textStart, textEnd, &next, XML_FALSE);\n\n if (result == XML_ERROR_NONE) {\n if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {\n entity->processed = (int)(next - textStart);\n parser->m_processor = internalEntityProcessor;\n } else {\n entity->open = XML_FALSE;\n parser->m_openInternalEntities = openEntity->next;\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n }\n }\n return result;\n}", "label_name": "CWE-125", "label": 47} +{"code": "processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {\n const char *textStart, *textEnd;\n const char *next;\n enum XML_Error result;\n OPEN_INTERNAL_ENTITY *openEntity;\n\n if (parser->m_freeInternalEntities) {\n openEntity = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity->next;\n } else {\n openEntity\n = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));\n if (! openEntity)\n return XML_ERROR_NO_MEMORY;\n }\n entity->open = XML_TRUE;\n entity->processed = 0;\n openEntity->next = parser->m_openInternalEntities;\n parser->m_openInternalEntities = openEntity;\n openEntity->entity = entity;\n openEntity->startTagLevel = parser->m_tagLevel;\n openEntity->betweenDecl = betweenDecl;\n openEntity->internalEventPtr = NULL;\n openEntity->internalEventEndPtr = NULL;\n textStart = (char *)entity->textPtr;\n textEnd = (char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n next = textStart;\n\n#ifdef XML_DTD\n if (entity->is_param) {\n int tok\n = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);\n result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,\n tok, next, &next, XML_FALSE);\n } else\n#endif /* XML_DTD */\n result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,\n textStart, textEnd, &next, XML_FALSE);\n\n if (result == XML_ERROR_NONE) {\n if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {\n entity->processed = (int)(next - textStart);\n parser->m_processor = internalEntityProcessor;\n } else {\n entity->open = XML_FALSE;\n parser->m_openInternalEntities = openEntity->next;\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n }\n }\n return result;\n}", "label_name": "CWE-776", "label": 62} +{"code": "vips_tracked_malloc( size_t size )\n{\n void *buf;\n\n\tvips_tracked_init(); \n\n\t/* Need an extra sizeof(size_t) bytes to track \n\t * size of this block. Ask for an extra 16 to make sure we don't break\n\t * alignment rules.\n\t */\n\tsize += 16;\n\n if( !(buf = g_try_malloc( size )) ) {\n#ifdef DEBUG\n\t\tg_assert_not_reached();\n#endif /*DEBUG*/\n\n\t\tvips_error( \"vips_tracked\", \n\t\t\t_( \"out of memory --- size == %dMB\" ), \n\t\t\t(int) (size / (1024.0 * 1024.0)) );\n\t\tg_warning( _( \"out of memory --- size == %dMB\" ), \n\t\t\t(int) (size / (1024.0 * 1024.0)) );\n\n return( NULL );\n\t}\n\n\tg_mutex_lock( vips_tracked_mutex );\n\n\t*((size_t *)buf) = size;\n\tbuf = (void *) ((char *)buf + 16);\n\n\tvips_tracked_mem += size;\n\tif( vips_tracked_mem > vips_tracked_mem_highwater ) \n\t\tvips_tracked_mem_highwater = vips_tracked_mem;\n\tvips_tracked_allocs += 1;\n\n#ifdef DEBUG_VERBOSE\n\tprintf( \"vips_tracked_malloc: %p, %zd bytes\\n\", buf, size ); \n#endif /*DEBUG_VERBOSE*/\n\n\tg_mutex_unlock( vips_tracked_mutex );\n\n\tVIPS_GATE_MALLOC( size ); \n\n return( buf );\n}", "label_name": "CWE-908", "label": 48} +{"code": "completion_glob_pattern (string)\n char *string;\n{\n register int c;\n char *send;\n int open;\n\n DECLARE_MBSTATE;\n\n open = 0;\n send = string + strlen (string);\n\n while (c = *string++)\n {\n switch (c)\n\t{\n\tcase '?':\n\tcase '*':\n\t return (1);\n\n\tcase '[':\n\t open++;\n\t continue;\n\n\tcase ']':\n\t if (open)\n\t return (1);\n\t continue;\n\n\tcase '+':\n\tcase '@':\n\tcase '!':\n\t if (*string == '(')\t/*)*/\n\t return (1);\n\t continue;\n\n\tcase '\\\\':\n\t if (*string++ == 0)\n\t return (0);\n\t}\n\n /* Advance one fewer byte than an entire multibyte character to\n\t account for the auto-increment in the loop above. */\n#ifdef HANDLE_MULTIBYTE\n string--;\n ADVANCE_CHAR_P (string, send - string);\n string++;\n#else\n ADVANCE_CHAR_P (string, send - string);\n#endif\n }\n return (0);\n}", "label_name": "CWE-273", "label": 97} +{"code": "unquoted_glob_pattern_p (string)\n register char *string;\n{\n register int c;\n char *send;\n int open, bsquote;\n\n DECLARE_MBSTATE;\n\n open = bsquote = 0;\n send = string + strlen (string);\n\n while (c = *string++)\n {\n switch (c)\n\t{\n\tcase '?':\n\tcase '*':\n\t return (1);\n\n\tcase '[':\n\t open++;\n\t continue;\n\n\tcase ']':\n\t if (open)\n\t return (1);\n\t continue;\n\n\tcase '+':\n\tcase '@':\n\tcase '!':\n\t if (*string == '(')\t/*)*/\n\t return (1);\n\t continue;\n\n\t/* A pattern can't end with a backslash, but a backslash in the pattern\n\t can be removed by the matching engine, so we have to run it through\n\t globbing. */\n\tcase '\\\\':\n\t if (*string != '\\0' && *string != '/')\n\t {\n\t bsquote = 1;\n\t string++;\n\t continue;\n\t }\n\t else if (*string == 0)\n\t return (0);\n\t \t \n\tcase CTLESC:\n\t if (*string++ == '\\0')\n\t return (0);\n\t}\n\n /* Advance one fewer byte than an entire multibyte character to\n\t account for the auto-increment in the loop above. */\n#ifdef HANDLE_MULTIBYTE\n string--;\n ADVANCE_CHAR_P (string, send - string);\n string++;\n#else\n ADVANCE_CHAR_P (string, send - string);\n#endif\n }\n\n return ((bsquote && posix_glob_backslash) ? 2 : 0);\n}", "label_name": "CWE-273", "label": 97} +{"code": "pci_emul_add_capability(struct pci_vdev *dev, u_char *capdata, int caplen)\n{\n\tint i, capoff, reallen;\n\tuint16_t sts;\n\n\tassert(caplen > 0);\n\n\treallen = roundup2(caplen, 4);\t\t/* dword aligned */\n\n\tsts = pci_get_cfgdata16(dev, PCIR_STATUS);\n\tif ((sts & PCIM_STATUS_CAPPRESENT) == 0)\n\t\tcapoff = CAP_START_OFFSET;\n\telse\n\t\tcapoff = dev->capend + 1;\n\n\t/* Check if we have enough space */\n\tif (capoff + reallen > PCI_REGMAX + 1)\n\t\treturn -1;\n\n\t/* Set the previous capability pointer */\n\tif ((sts & PCIM_STATUS_CAPPRESENT) == 0) {\n\t\tpci_set_cfgdata8(dev, PCIR_CAP_PTR, capoff);\n\t\tpci_set_cfgdata16(dev, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT);\n\t} else\n\t\tpci_set_cfgdata8(dev, dev->prevcap + 1, capoff);\n\n\t/* Copy the capability */\n\tfor (i = 0; i < caplen; i++)\n\t\tpci_set_cfgdata8(dev, capoff + i, capdata[i]);\n\n\t/* Set the next capability pointer */\n\tpci_set_cfgdata8(dev, capoff + 1, 0);\n\n\tdev->prevcap = capoff;\n\tdev->capend = capoff + reallen - 1;\n\treturn 0;\n}", "label_name": "CWE-617", "label": 51} +{"code": "modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n{\n\tint error;\n\tstruct inout_port iop;\n\tstruct mem_range mr;\n\n\tif (is_pci_gvt(dev)) {\n\t\t/* GVT device is the only one who traps the pci bar access and\n\t\t * intercepts the corresponding contents in kernel. It needs\n\t\t * register pci resource only, but no need to register the\n\t\t * region.\n\t\t *\n\t\t * FIXME: This is a short term solution. This patch will be\n\t\t * obsoleted with the migration of using OVMF to do bar\n\t\t * addressing and generate ACPI PCI resource from using\n\t\t * acrn-dm.\n\t\t */\n\t\tprintf(\"modify_bar_registration: bypass for pci-gvt\\n\");\n\t\treturn;\n\t}\n\tswitch (dev->bar[idx].type) {\n\tcase PCIBAR_IO:\n\t\tbzero(&iop, sizeof(struct inout_port));\n\t\tiop.name = dev->name;\n\t\tiop.port = dev->bar[idx].addr;\n\t\tiop.size = dev->bar[idx].size;\n\t\tif (registration) {\n\t\t\tiop.flags = IOPORT_F_INOUT;\n\t\t\tiop.handler = pci_emul_io_handler;\n\t\t\tiop.arg = dev;\n\t\t\terror = register_inout(&iop);\n\t\t} else\n\t\t\terror = unregister_inout(&iop);\n\t\tbreak;\n\tcase PCIBAR_MEM32:\n\tcase PCIBAR_MEM64:\n\t\tbzero(&mr, sizeof(struct mem_range));\n\t\tmr.name = dev->name;\n\t\tmr.base = dev->bar[idx].addr;\n\t\tmr.size = dev->bar[idx].size;\n\t\tif (registration) {\n\t\t\tmr.flags = MEM_F_RW;\n\t\t\tmr.handler = pci_emul_mem_handler;\n\t\t\tmr.arg1 = dev;\n\t\t\tmr.arg2 = idx;\n\t\t\terror = register_mem(&mr);\n\t\t} else\n\t\t\terror = unregister_mem(&mr);\n\t\tbreak;\n\tdefault:\n\t\terror = EINVAL;\n\t\tbreak;\n\t}\n\tassert(error == 0);\n}", "label_name": "CWE-617", "label": 51} +{"code": "pci_emul_add_msicap(struct pci_vdev *dev, int msgnum)\n{\n\tstruct msicap msicap;\n\n\tpci_populate_msicap(&msicap, msgnum, 0);\n\n\treturn pci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n}", "label_name": "CWE-617", "label": 51} +{"code": "pci_get_cfgdata32(struct pci_vdev *dev, int offset)\n{\n\tassert(offset <= (PCI_REGMAX - 3) && (offset & 3) == 0);\n\treturn (*(uint32_t *)(dev->cfgdata + offset));\n}", "label_name": "CWE-617", "label": 51} +{"code": "string_object_to_c_ast(const char *s, PyObject *filename, int start,\n PyCompilerFlags *flags, int feature_version,\n PyArena *arena)\n{\n mod_ty mod;\n PyCompilerFlags localflags;\n perrdetail err;\n int iflags = PARSER_FLAGS(flags);\n\n node *n = Ta3Parser_ParseStringObject(s, filename,\n &_Ta3Parser_Grammar, start, &err,\n &iflags);\n if (flags == NULL) {\n localflags.cf_flags = 0;\n flags = &localflags;\n }\n if (n) {\n flags->cf_flags |= iflags & PyCF_MASK;\n mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena);\n Ta3Node_Free(n);\n }\n else {\n err_input(&err);\n mod = NULL;\n }\n err_free(&err);\n return mod;\n}", "label_name": "CWE-125", "label": 47} +{"code": "tok_new(void)\n{\n struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(\n sizeof(struct tok_state));\n if (tok == NULL)\n return NULL;\n tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;\n tok->done = E_OK;\n tok->fp = NULL;\n tok->input = NULL;\n tok->tabsize = TABSIZE;\n tok->indent = 0;\n tok->indstack[0] = 0;\n\n tok->atbol = 1;\n tok->pendin = 0;\n tok->prompt = tok->nextprompt = NULL;\n tok->lineno = 0;\n tok->level = 0;\n tok->altwarning = 1;\n tok->alterror = 1;\n tok->alttabsize = 1;\n tok->altindstack[0] = 0;\n tok->decoding_state = STATE_INIT;\n tok->decoding_erred = 0;\n tok->read_coding_spec = 0;\n tok->enc = NULL;\n tok->encoding = NULL;\n tok->cont_line = 0;\n#ifndef PGEN\n tok->filename = NULL;\n tok->decoding_readline = NULL;\n tok->decoding_buffer = NULL;\n#endif\n\n tok->async_def = 0;\n tok->async_def_indent = 0;\n tok->async_def_nl = 0;\n\n return tok;\n}", "label_name": "CWE-125", "label": 47} +{"code": "fp_setreadl(struct tok_state *tok, const char* enc)\n{\n PyObject *readline, *io, *stream;\n _Py_IDENTIFIER(open);\n _Py_IDENTIFIER(readline);\n int fd;\n long pos;\n\n fd = fileno(tok->fp);\n /* Due to buffering the file offset for fd can be different from the file\n * position of tok->fp. If tok->fp was opened in text mode on Windows,\n * its file position counts CRLF as one char and can't be directly mapped\n * to the file offset for fd. Instead we step back one byte and read to\n * the end of line.*/\n pos = ftell(tok->fp);\n if (pos == -1 ||\n lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) {\n PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL);\n return 0;\n }\n\n io = PyImport_ImportModuleNoBlock(\"io\");\n if (io == NULL)\n return 0;\n\n stream = _PyObject_CallMethodId(io, &PyId_open, \"isisOOO\",\n fd, \"r\", -1, enc, Py_None, Py_None, Py_False);\n Py_DECREF(io);\n if (stream == NULL)\n return 0;\n\n readline = _PyObject_GetAttrId(stream, &PyId_readline);\n Py_DECREF(stream);\n if (readline == NULL)\n return 0;\n Py_XSETREF(tok->decoding_readline, readline);\n\n if (pos > 0) {\n PyObject *bufobj = PyObject_CallObject(readline, NULL);\n if (bufobj == NULL)\n return 0;\n Py_DECREF(bufobj);\n }\n\n return 1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "indenterror(struct tok_state *tok)\n{\n if (tok->alterror) {\n tok->done = E_TABSPACE;\n tok->cur = tok->inp;\n return 1;\n }\n if (tok->altwarning) {\n#ifdef PGEN\n PySys_WriteStderr(\"inconsistent use of tabs and spaces \"\n \"in indentation\\n\");\n#else\n PySys_FormatStderr(\"%U: inconsistent use of tabs and spaces \"\n \"in indentation\\n\", tok->filename);\n#endif\n tok->altwarning = 0;\n }\n return 0;\n}", "label_name": "CWE-125", "label": 47} +{"code": "static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields)\n{\n PyObject *fnames, *result;\n int i;\n fnames = PyTuple_New(num_fields);\n if (!fnames) return NULL;\n for (i = 0; i < num_fields; i++) {\n PyObject *field = PyUnicode_FromString(fields[i]);\n if (!field) {\n Py_DECREF(fnames);\n return NULL;\n }\n PyTuple_SET_ITEM(fnames, i, field);\n }\n result = PyObject_CallFunction((PyObject*)&PyType_Type, \"s(O){sOss}\",\n type, base, \"_fields\", fnames, \"__module__\", \"_ast3\");\n Py_DECREF(fnames);\n return (PyTypeObject*)result;\n}", "label_name": "CWE-125", "label": 47} +{"code": "ast2obj_keyword(void* _o)\n{\n keyword_ty o = (keyword_ty)_o;\n PyObject *result = NULL, *value = NULL;\n if (!o) {\n Py_INCREF(Py_None);\n return Py_None;\n }\n\n result = PyType_GenericNew(keyword_type, NULL, NULL);\n if (!result) return NULL;\n value = ast2obj_identifier(o->arg);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_arg, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->value);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_value, value) == -1)\n goto failed;\n Py_DECREF(value);\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label_name": "CWE-125", "label": 47} +{"code": "obj2ast_keyword(PyObject* obj, keyword_ty* out, PyArena* arena)\n{\n PyObject* tmp = NULL;\n identifier arg;\n expr_ty value;\n\n if (exists_not_none(obj, &PyId_arg)) {\n int res;\n tmp = _PyObject_GetAttrId(obj, &PyId_arg);\n if (tmp == NULL) goto failed;\n res = obj2ast_identifier(tmp, &arg, arena);\n if (res != 0) goto failed;\n Py_CLEAR(tmp);\n } else {\n arg = NULL;\n }\n if (_PyObject_HasAttrId(obj, &PyId_value)) {\n int res;\n tmp = _PyObject_GetAttrId(obj, &PyId_value);\n if (tmp == NULL) goto failed;\n res = obj2ast_expr(tmp, &value, arena);\n if (res != 0) goto failed;\n Py_CLEAR(tmp);\n } else {\n PyErr_SetString(PyExc_TypeError, \"required field \\\"value\\\" missing from keyword\");\n return 1;\n }\n *out = keyword(arg, value, arena);\n return 0;\nfailed:\n Py_XDECREF(tmp);\n return 1;\n}", "label_name": "CWE-125", "label": 47} +{"code": "static int exists_not_none(PyObject *obj, _Py_Identifier *id)\n{\n int isnone;\n PyObject *attr = _PyObject_GetAttrId(obj, id);\n if (!attr) {\n PyErr_Clear();\n return 0;\n }\n isnone = attr == Py_None;\n Py_DECREF(attr);\n return !isnone;\n}", "label_name": "CWE-125", "label": 47} +{"code": "ast2obj_slice(void* _o)\n{\n slice_ty o = (slice_ty)_o;\n PyObject *result = NULL, *value = NULL;\n if (!o) {\n Py_INCREF(Py_None);\n return Py_None;\n }\n\n switch (o->kind) {\n case Slice_kind:\n result = PyType_GenericNew(Slice_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_expr(o->v.Slice.lower);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_lower, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->v.Slice.upper);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_upper, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->v.Slice.step);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_step, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n case ExtSlice_kind:\n result = PyType_GenericNew(ExtSlice_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_list(o->v.ExtSlice.dims, ast2obj_slice);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_dims, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n case Index_kind:\n result = PyType_GenericNew(Index_type, NULL, NULL);\n if (!result) goto failed;\n value = ast2obj_expr(o->v.Index.value);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_value, value) == -1)\n goto failed;\n Py_DECREF(value);\n break;\n }\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label_name": "CWE-125", "label": 47} +{"code": "ast_for_decorator(struct compiling *c, const node *n)\n{\n /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */\n expr_ty d = NULL;\n expr_ty name_expr;\n\n REQ(n, decorator);\n REQ(CHILD(n, 0), AT);\n REQ(RCHILD(n, -1), NEWLINE);\n\n name_expr = ast_for_dotted_name(c, CHILD(n, 1));\n if (!name_expr)\n return NULL;\n\n if (NCH(n) == 3) { /* No arguments */\n d = name_expr;\n name_expr = NULL;\n }\n else if (NCH(n) == 5) { /* Call with no arguments */\n d = Call(name_expr, NULL, NULL, LINENO(n),\n n->n_col_offset, c->c_arena);\n if (!d)\n return NULL;\n name_expr = NULL;\n }\n else {\n d = ast_for_call(c, CHILD(n, 3), name_expr);\n if (!d)\n return NULL;\n name_expr = NULL;\n }\n\n return d;\n}", "label_name": "CWE-125", "label": 47} +{"code": "FstringParser_Finish(FstringParser *state, struct compiling *c,\n const node *n)\n{\n asdl_seq *seq;\n\n FstringParser_check_invariants(state);\n\n /* If we're just a constant string with no expressions, return\n that. */\n if(state->expr_list.size == 0) {\n if (!state->last_str) {\n /* Create a zero length string. */\n state->last_str = PyUnicode_FromStringAndSize(NULL, 0);\n if (!state->last_str)\n goto error;\n }\n return make_str_node_and_del(&state->last_str, c, n);\n }\n\n /* Create a Str node out of last_str, if needed. It will be the\n last node in our expression list. */\n if (state->last_str) {\n expr_ty str = make_str_node_and_del(&state->last_str, c, n);\n if (!str || ExprList_Append(&state->expr_list, str) < 0)\n goto error;\n }\n /* This has already been freed. */\n assert(state->last_str == NULL);\n\n seq = ExprList_Finish(&state->expr_list, c->c_arena);\n if (!seq)\n goto error;\n\n /* If there's only one expression, return it. Otherwise, we need\n to join them together. */\n if (seq->size == 1)\n return seq->elements[0];\n\n return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena);\n\nerror:\n FstringParser_Dealloc(state);\n return NULL;\n}", "label_name": "CWE-125", "label": 47} +{"code": "decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s,\n size_t len)\n{\n return PyBytes_DecodeEscape(s, len, NULL, 0, NULL);\n}", "label_name": "CWE-125", "label": 47} +{"code": "add_mibfile(const char* tmpstr, const char* d_name, FILE *ip )\n{\n FILE *fp;\n char token[MAXTOKEN], token2[MAXTOKEN];\n\n /*\n * which module is this \n */\n if ((fp = fopen(tmpstr, \"r\")) == NULL) {\n snmp_log_perror(tmpstr);\n return 1;\n }\n DEBUGMSGTL((\"parse-mibs\", \"Checking file: %s...\\n\",\n tmpstr));\n mibLine = 1;\n File = tmpstr;\n if (get_token(fp, token, MAXTOKEN) != LABEL) {\n\t fclose(fp);\n\t return 1;\n }\n /*\n * simple test for this being a MIB \n */\n if (get_token(fp, token2, MAXTOKEN) == DEFINITIONS) {\n new_module(token, tmpstr);\n if (ip)\n fprintf(ip, \"%s %s\\n\", token, d_name);\n fclose(fp);\n return 0;\n } else {\n fclose(fp);\n return 1;\n }\n}", "label_name": "CWE-59", "label": 36} +{"code": "pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)\n{\n\tInitializeCriticalSection(mutex);\n\treturn 0;\n}", "label_name": "CWE-125", "label": 47} +{"code": "static inline void init_keys(at91_aes_key_size_t *key_size,\n\t\t\t unsigned int *cipher_key,\n\t\t\t unsigned int *cmac_key,\n\t\t\t unsigned int *iv)\n{\n#if defined(CONFIG_AES_KEY_SIZE_128)\n\t*key_size = AT91_AES_KEY_SIZE_128;\n#elif defined(CONFIG_AES_KEY_SIZE_192)\n\t*key_size = AT91_AES_KEY_SIZE_192;\n#elif defined(CONFIG_AES_KEY_SIZE_256)\n\t*key_size = AT91_AES_KEY_SIZE_256;\n#else\n#error \"bad AES key size\"\n#endif\n\n\tiv[0]\t\t= CONFIG_AES_IV_WORD0;\n\tiv[1]\t\t= CONFIG_AES_IV_WORD1;\n\tiv[2]\t\t= CONFIG_AES_IV_WORD2;\n\tiv[3]\t\t= CONFIG_AES_IV_WORD3;\n\n\tcipher_key[0]\t= CONFIG_AES_CIPHER_KEY_WORD0;\n\tcmac_key[0]\t= CONFIG_AES_CMAC_KEY_WORD0;\n\tcipher_key[1]\t= CONFIG_AES_CIPHER_KEY_WORD1;\n\tcmac_key[1]\t= CONFIG_AES_CMAC_KEY_WORD1;\n\tcipher_key[2]\t= CONFIG_AES_CIPHER_KEY_WORD2;\n\tcmac_key[2]\t= CONFIG_AES_CMAC_KEY_WORD2;\n\tcipher_key[3]\t= CONFIG_AES_CIPHER_KEY_WORD3;\n\tcmac_key[3]\t= CONFIG_AES_CMAC_KEY_WORD3;\n\n#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)\n\tcipher_key[4]\t= CONFIG_AES_CIPHER_KEY_WORD4;\n\tcmac_key[4]\t= CONFIG_AES_CMAC_KEY_WORD4;\n\tcipher_key[5]\t= CONFIG_AES_CIPHER_KEY_WORD5;\n\tcmac_key[5]\t= CONFIG_AES_CMAC_KEY_WORD5;\n#endif\n\n#if defined(CONFIG_AES_KEY_SIZE_256)\n\tcipher_key[6]\t= CONFIG_AES_CIPHER_KEY_WORD6;\n\tcmac_key[6]\t= CONFIG_AES_CMAC_KEY_WORD6;\n\tcipher_key[7]\t= CONFIG_AES_CIPHER_KEY_WORD7;\n\tcmac_key[7]\t= CONFIG_AES_CMAC_KEY_WORD7;\n#endif\n}", "label_name": "CWE-212", "label": 66} +{"code": "sysLocation_handler(snmp_varbind_t *varbind, uint32_t *oid)\n{\n snmp_api_set_string(varbind, oid, \"\");\n}", "label_name": "CWE-125", "label": 47} +{"code": "snmp_api_set_oid(snmp_varbind_t *varbind, uint32_t *oid, uint32_t *ret_oid)\n{\n\n snmp_api_replace_oid(varbind, oid);\n varbind->value_type = BER_DATA_TYPE_OID;\n varbind->value.oid = ret_oid;\n}", "label_name": "CWE-125", "label": 47} +{"code": "snmp_ber_decode_string_len_buffer(unsigned char *buf, uint32_t *buff_len, const char **str, uint32_t *length)\n{\n uint8_t type, i, length_bytes;\n\n buf = snmp_ber_decode_type(buf, buff_len, &type);\n\n if(buf == NULL || type != BER_DATA_TYPE_OCTET_STRING) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return NULL;\n }\n\n if((*buf & 0x80) == 0) {\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n } else {\n\n length_bytes = (uint8_t)(*buf++ & 0x7F);\n (*buff_len)--;\n if(length_bytes > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return NULL;\n }\n\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n for(i = 1; i < length_bytes; ++i) {\n *length <<= 8;\n *length |= *buf++;\n (*buff_len)--;\n }\n }\n\n *str = (const char *)buf;\n *buff_len -= *length;\n\n return buf + *length;\n}", "label_name": "CWE-125", "label": 47} +{"code": "snmp_ber_encode_unsigned_integer(unsigned char *out, uint32_t *out_len, uint8_t type, uint32_t number)\n{\n uint32_t original_out_len;\n\n original_out_len = *out_len;\n do {\n (*out_len)++;\n *out-- = (uint8_t)(number & 0xFF);\n number >>= 8;\n } while(number);\n\n out = snmp_ber_encode_length(out, out_len, ((*out_len - original_out_len) & 0xFF));\n out = snmp_ber_encode_type(out, out_len, type);\n\n return out;\n}", "label_name": "CWE-125", "label": 47} +{"code": "snmp_ber_decode_type(unsigned char *buff, uint32_t *buff_len, uint8_t *type)\n{\n if(*buff_len == 0) {\n return NULL;\n }\n\n *type = *buff++;\n (*buff_len)--;\n\n return buff;\n}", "label_name": "CWE-125", "label": 47} +{"code": "snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)\n{\n static snmp_header_t header;\n static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];\n static uint32_t varbind_length = SNMP_MAX_NR_VALUES;\n\n buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);\n if(buff == NULL) {\n return NULL;\n }\n\n if(header.version != SNMP_VERSION_1) {\n if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) {\n LOG_ERR(\"Request with invalid community\\n\");\n return NULL;\n }\n }\n\n /*\n * Now handle the SNMP requests depending on their type\n */\n switch(header.pdu_type) {\n case SNMP_DATA_TYPE_PDU_GET_REQUEST:\n if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {\n return NULL;\n }\n break;\n\n case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:\n if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {\n return NULL;\n }\n break;\n\n case SNMP_DATA_TYPE_PDU_GET_BULK:\n if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {\n return NULL;\n }\n break;\n\n default:\n LOG_ERR(\"Invalid request type\");\n return NULL;\n }\n\n header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;\n out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);\n\n return ++out;\n}", "label_name": "CWE-125", "label": 47} +{"code": "snmp_mib_add(snmp_mib_resource_t *new_resource)\n{\n snmp_mib_resource_t *resource;\n\n for(resource = list_head(snmp_mib);\n resource; resource = resource->next) {\n\n if(snmp_oid_cmp_oid(resource->oid, new_resource->oid) > 0) {\n break;\n }\n }\n if(resource == NULL) {\n list_add(snmp_mib, new_resource);\n } else {\n list_insert(snmp_mib, new_resource, resource);\n }\n\n#if LOG_LEVEL == LOG_LEVEL_DBG\n /*\n * We print the entire resource table\n */\n LOG_DBG(\"Table after insert.\\n\");\n for(resource = list_head(snmp_mib);\n resource; resource = resource->next) {\n\n snmp_oid_print(resource->oid);\n }\n#endif /* LOG_LEVEL == LOG_LEVEL_DBG */\n}", "label_name": "CWE-125", "label": 47} +{"code": "static pj_status_t pjsip_auth_verify( const pjsip_authorization_hdr *hdr,\n\t\t\t\t const pj_str_t *method,\n\t\t\t\t const pjsip_cred_info *cred_info )\n{\n if (pj_stricmp(&hdr->scheme, &pjsip_DIGEST_STR) == 0) {\n\tchar digest_buf[PJSIP_MD5STRLEN];\n\tpj_str_t digest;\n\tconst pjsip_digest_credential *dig = &hdr->credential.digest;\n\n\t/* Check that username and realm match. \n\t * These checks should have been performed before entering this\n\t * function.\n\t */\n\tPJ_ASSERT_RETURN(pj_strcmp(&dig->username, &cred_info->username) == 0,\n\t\t\t PJ_EINVALIDOP);\n\tPJ_ASSERT_RETURN(pj_strcmp(&dig->realm, &cred_info->realm) == 0,\n\t\t\t PJ_EINVALIDOP);\n\n\t/* Prepare for our digest calculation. */\n\tdigest.ptr = digest_buf;\n\tdigest.slen = PJSIP_MD5STRLEN;\n\n\t/* Create digest for comparison. */\n\tpjsip_auth_create_digest(&digest, \n\t\t\t\t &hdr->credential.digest.nonce,\n\t\t\t\t &hdr->credential.digest.nc, \n\t\t\t\t &hdr->credential.digest.cnonce,\n\t\t\t\t &hdr->credential.digest.qop,\n\t\t\t\t &hdr->credential.digest.uri,\n\t\t\t\t &cred_info->realm,\n\t\t\t\t cred_info, \n\t\t\t\t method );\n\n\t/* Compare digest. */\n\treturn (pj_stricmp(&digest, &hdr->credential.digest.response) == 0) ?\n\t PJ_SUCCESS : PJSIP_EAUTHINVALIDDIGEST;\n\n } else {\n\tpj_assert(!\"Unsupported authentication scheme\");\n\treturn PJSIP_EINVALIDAUTHSCHEME;\n }\n}", "label_name": "CWE-120", "label": 44} +{"code": "static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len)\n{\n char *p = buf;\n char *end = buf+len;\n unsigned i;\n int printed;\n\n /* check length for the \"m=\" line. */\n if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) {\n\treturn -1;\n }\n *p++ = 'm';\t /* m= */\n *p++ = '=';\n pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen);\n p += m->desc.media.slen;\n *p++ = ' ';\n printed = pj_utoa(m->desc.port, p);\n p += printed;\n if (m->desc.port_count > 1) {\n\t*p++ = '/';\n\tprinted = pj_utoa(m->desc.port_count, p);\n\tp += printed;\n }\n *p++ = ' ';\n pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen);\n p += m->desc.transport.slen;\n for (i=0; idesc.fmt_count; ++i) {\n\t*p++ = ' ';\n\tpj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen);\n\tp += m->desc.fmt[i].slen;\n }\n *p++ = '\\r';\n *p++ = '\\n';\n\n /* print connection info, if present. */\n if (m->conn) {\n\tprinted = print_connection_info(m->conn, p, (int)(end-p));\n\tif (printed < 0) {\n\t return -1;\n\t}\n\tp += printed;\n }\n \n /* print optional bandwidth info. */\n for (i=0; ibandw_count; ++i) {\n\tprinted = (int)print_bandw(m->bandw[i], p, end-p);\n\tif (printed < 0) {\n\t return -1;\n\t}\n\tp += printed;\n }\n\n /* print attributes. */\n for (i=0; iattr_count; ++i) {\n\tprinted = (int)print_attr(m->attr[i], p, end-p);\n\tif (printed < 0) {\n\t return -1;\n\t}\n\tp += printed;\n }\n\n return (int)(p-buf);\n}", "label_name": "CWE-120", "label": 44} +{"code": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_pli(\n\t\t\t\t\tpjmedia_rtcp_session *session, \n\t\t\t\t\tvoid *buf,\n\t\t\t\t\tpj_size_t *length)\n{\n pjmedia_rtcp_common *hdr;\n unsigned len;\n\n PJ_ASSERT_RETURN(session && buf && length, PJ_EINVAL);\n\n len = 12;\n if (len > *length)\n\treturn PJ_ETOOSMALL;\n\n /* Build RTCP-FB PLI header */\n hdr = (pjmedia_rtcp_common*)buf;\n pj_memcpy(hdr, &session->rtcp_rr_pkt.common, sizeof(*hdr));\n hdr->pt = RTCP_PSFB;\n hdr->count = 1; /* FMT = 1 */\n hdr->length = pj_htons((pj_uint16_t)(len/4 - 1));\n\n /* Finally */\n *length = len;\n\n return PJ_SUCCESS;\n}", "label_name": "CWE-125", "label": 47} +{"code": "char *compose_path(ctrl_t *ctrl, char *path)\n{\n\tstruct stat st;\n\tstatic char rpath[PATH_MAX];\n\tchar *name, *ptr;\n\tchar dir[PATH_MAX] = { 0 };\n\n\tstrlcpy(dir, ctrl->cwd, sizeof(dir));\n\tDBG(\"Compose path from cwd: %s, arg: %s\", ctrl->cwd, path ?: \"\");\n\tif (!path || !strlen(path))\n\t\tgoto check;\n\n\tif (path) {\n\t\tif (path[0] != '/') {\n\t\t\tif (dir[strlen(dir) - 1] != '/')\n\t\t\t\tstrlcat(dir, \"/\", sizeof(dir));\n\t\t}\n\t\tstrlcat(dir, path, sizeof(dir));\n\t}\n\ncheck:\n\twhile ((ptr = strstr(dir, \"//\")))\n\t\tmemmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);\n\n\tif (!chrooted) {\n\t\tsize_t len = strlen(home);\n\n\t\tDBG(\"Server path from CWD: %s\", dir);\n\t\tif (len > 0 && home[len - 1] == '/')\n\t\t\tlen--;\n\t\tmemmove(dir + len, dir, strlen(dir) + 1);\n\t\tmemcpy(dir, home, len);\n\t\tDBG(\"Resulting non-chroot path: %s\", dir);\n\t}\n\n\t/*\n\t * Handle directories slightly differently, since dirname() on a\n\t * directory returns the parent directory. So, just squash ..\n\t */\n\tif (!stat(dir, &st) && S_ISDIR(st.st_mode)) {\n\t\tif (!realpath(dir, rpath))\n\t\t\treturn NULL;\n\t} else {\n\t\t/*\n\t\t * Check realpath() of directory containing the file, a\n\t\t * STOR may want to save a new file. Then append the\n\t\t * file and return it.\n\t\t */\n\t\tname = basename(path);\n\t\tptr = dirname(dir);\n\n\t\tmemset(rpath, 0, sizeof(rpath));\n\t\tif (!realpath(ptr, rpath)) {\n\t\t\tINFO(\"Failed realpath(%s): %m\", ptr);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (rpath[1] != 0)\n\t\t\tstrlcat(rpath, \"/\", sizeof(rpath));\n\t\tstrlcat(rpath, name, sizeof(rpath));\n\t}\n\n\tif (!chrooted && strncmp(dir, home, strlen(home))) {\n\t\tDBG(\"Failed non-chroot dir:%s vs home:%s\", dir, home);\n\t\treturn NULL;\n\t}\n\n\treturn rpath;\n}", "label_name": "CWE-22", "label": 2} +{"code": "static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,\n Jsi_Value **ret, Jsi_Func *funcPtr)\n{\n if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj))\n return Jsi_LogError(\"expected array object\");\n const char *jstr = \"\";\n int argc, curlen;\n Jsi_DString dStr = {};\n\n curlen = Jsi_ObjGetLength(interp, _this->d.obj);\n if (curlen == 0) {\n goto bail;\n }\n\n if (Jsi_ValueGetLength(interp, args) >= 1) {\n Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0);\n if (sc != NULL)\n jstr = Jsi_ValueToString(interp, sc, NULL);\n }\n \n if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {\n goto bail;\n }\n int i;\n for (i = 0; i < argc; ++i) {\n const char *cp;\n Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i);\n if (!ov) {\n /* TODO: are NULL args ok? */ \n continue;\n cp = \"\";\n } else\n cp = Jsi_ValueToString(interp, ov, NULL);\n if (i && jstr[0])\n Jsi_DSAppend(&dStr, jstr, NULL);\n Jsi_DSAppend(&dStr, cp, NULL);\n }\n \n Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr));\n Jsi_DSFree(&dStr);\n return JSI_OK;\nbail:\n Jsi_ValueMakeStringDup(interp, ret, \"\");\n return JSI_OK; \n}", "label_name": "CWE-190", "label": 19} +{"code": "const char *jsi_GetHomeDir(Jsi_Interp *interp) {\n const char *str = NULL;\n if (interp->homeDir)\n return interp->homeDir;\n#ifdef __WIN32\n str = getenv(\"USERPROFILE\"); /* TODO: windows home dir. */\n#else\n \n if ((str = getenv(\"HOME\")) == NULL) {\n struct passwd pwd, *pw;\n char buf[20000];\n if (getpwuid_r(getuid(), &pwd, buf, sizeof(buf), &pw) == 0 && pw->pw_dir) \n str = pw->pw_dir;\n }\n#endif\n if (!str) {\n Jsi_LogBug(\"no home dir\");\n str = \"/\";\n }\n#ifdef JSI_LITE_ONLY\n return str;\n#else\n return (interp->homeDir = Jsi_KeyAdd(interp, str));\n#endif\n}", "label_name": "CWE-120", "label": 44} +{"code": "static void mdbEvalSetColumn(MyDbEvalContext *p, int iCol, Jsi_DString *dStr) {\n //Jsi_Interp *interp = p->jdb->interp;\n char nbuf[200];\n MysqlPrep *prep = p->prep;\n SqlFieldResults *field = prep->fieldResult+iCol;\n Jsi_Interp *interp = p->jdb->interp;\n if (field->isnull)\n return;\n \n switch(field->jsiTypeMap) {\n case JSI_OPTION_STRING: {\n int bytes = field->len;\n const char *zBlob = field->buffer.vstring;\n \n if( !zBlob ) {\n const char *nv = p->jdb->optPtr->nullvalue;\n Jsi_DSAppend(dStr, nv?nv:\"null\", NULL);\n return;\n }\n Jsi_DSAppendLen(dStr, zBlob, bytes);\n return;\n }\n case JSI_OPTION_BOOL: {\n snprintf(nbuf, sizeof(nbuf), \"%s\", field->buffer.vchar?\"true\":\"false\");\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case JSI_OPTION_INT64: {\n snprintf(nbuf, sizeof(nbuf), \"%lld\", field->buffer.vlonglong);\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n //case JSI_OPTION_TIME_T:\n case JSI_OPTION_TIME_D:\n case JSI_OPTION_TIME_W: {\n Jsi_Number jtime = mdbMyTimeToJS(&field->buffer.timestamp);\n Jsi_NumberToString(interp, jtime, nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case JSI_OPTION_DOUBLE: {\n Jsi_NumberToString(interp, field->buffer.vdouble, nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n default:\n Jsi_LogWarn(\"unknown type: %d\", field->jsiTypeMap);\n \n }\n}", "label_name": "CWE-120", "label": 44} +{"code": "static void dbEvalSetColumn(DbEvalContext *p, int iCol, Jsi_DString *dStr) {\n Jsi_Interp *interp = p->jdb->interp;\n char nbuf[200];\n\n sqlite3_stmt *pStmt = p->pPreStmt->pStmt;\n\n switch( sqlite3_column_type(pStmt, iCol) ) {\n case SQLITE_BLOB: {\n int bytes = sqlite3_column_bytes(pStmt, iCol);\n const char *zBlob = (char*)sqlite3_column_blob(pStmt, iCol);\n if( !zBlob ) {\n return;\n }\n Jsi_DSAppendLen(dStr, zBlob, bytes);\n return;\n }\n case SQLITE_INTEGER: {\n sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);\n if (v==0 || v==1) {\n const char *dectyp = sqlite3_column_decltype(pStmt, iCol);\n if (dectyp && !Jsi_Strncasecmp(dectyp,\"bool\", 4)) {\n Jsi_DSAppend(dStr, (v?\"true\":\"false\"), NULL);\n return;\n }\n }\n#ifdef __WIN32\n snprintf(nbuf, sizeof(nbuf), \"%\" PRId64, (Jsi_Wide)v);\n#else\n snprintf(nbuf, sizeof(nbuf), \"%lld\", v);\n#endif\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case SQLITE_FLOAT: {\n Jsi_NumberToString(interp, sqlite3_column_double(pStmt, iCol), nbuf, sizeof(nbuf));\n Jsi_DSAppend(dStr, nbuf, NULL);\n return;\n }\n case SQLITE_NULL: {\n return;\n }\n }\n const char *str = (char*)sqlite3_column_text(pStmt, iCol );\n if (!str)\n str = p->jdb->optPtr->nullvalue;\n Jsi_DSAppend(dStr, str?str:\"\", NULL);\n}", "label_name": "CWE-120", "label": 44} +{"code": "jsi_wsGetHeaders(jsi_wsPss *pss, struct lws *wsi, Jsi_DString* dStr, int lens[], int hmax)\n{\n int n = 0, i = 0, nlen;\n char buf[1000];\n const char *cp;\n while ((cp = (char*)lws_token_to_string((enum lws_token_indexes)n))) {\n int len = lws_hdr_copy(wsi, buf, sizeof(buf), ( enum lws_token_indexes)n);\n n++;\n if (i>=(n*2+2)) break;\n if (len<=0) continue;\n buf[sizeof(buf)-1] = 0;\n if (!buf[0]) continue;\n nlen = Jsi_Strlen(cp);\n if (nlen>0 && cp[nlen-1]==' ') nlen--;\n if (nlen>0 && cp[nlen-1]==':') nlen--;\n Jsi_DSAppendLen(dStr, cp, nlen);\n Jsi_DSAppend(dStr, \"=\", buf, \"\\n\", NULL);\n if (lens) {\n lens[i++] = nlen;\n lens[i++] = Jsi_Strlen(buf);\n }\n }\n //printf(\"HEE: %d = %s\\n\", pss->wid, Jsi_DSValue(dStr) );\n return i;\n}", "label_name": "CWE-120", "label": 44} +{"code": "static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {\n __Pyx_RefNannyDeclarations\n __Pyx_RefNannySetupContext(\"__Pyx_InitCachedConstants\", 0);\n\n /* \"clickhouse_driver/varint.pyx\":4\n * \n * \n * def write_varint(Py_ssize_t number, buf): # <<<<<<<<<<<<<<\n * \"\"\"\n * Writes integer of variable length using LEB128.\n */\n __pyx_tuple_ = PyTuple_Pack(5, __pyx_n_s_number, __pyx_n_s_buf, __pyx_n_s_i, __pyx_n_s_towrite, __pyx_n_s_num_buf); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 4, __pyx_L1_error)\n __Pyx_GOTREF(__pyx_tuple_);\n __Pyx_GIVEREF(__pyx_tuple_);\n __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_clickhouse_driver_varint_pyx, __pyx_n_s_write_varint, 4, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 4, __pyx_L1_error)\n\n /* \"clickhouse_driver/varint.pyx\":29\n * \n * \n * def read_varint(f): # <<<<<<<<<<<<<<\n * \"\"\"\n * Reads integer of variable length using LEB128.\n */\n __pyx_tuple__3 = PyTuple_Pack(5, __pyx_n_s_f, __pyx_n_s_shift, __pyx_n_s_result, __pyx_n_s_i, __pyx_n_s_read_one); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 29, __pyx_L1_error)\n __Pyx_GOTREF(__pyx_tuple__3);\n __Pyx_GIVEREF(__pyx_tuple__3);\n __pyx_codeobj__4 = (PyObject*)__Pyx_PyCode_New(1, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__3, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_clickhouse_driver_varint_pyx, __pyx_n_s_read_varint, 29, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__4)) __PYX_ERR(0, 29, __pyx_L1_error)\n __Pyx_RefNannyFinishContext();\n return 0;\n __pyx_L1_error:;\n __Pyx_RefNannyFinishContext();\n return -1;\n}", "label_name": "CWE-120", "label": 44} +{"code": "setup_secureChannel(void) {\n TestingPolicy(&dummyPolicy, dummyCertificate, &fCalled, &keySizes);\n UA_SecureChannel_init(&testChannel, &UA_ConnectionConfig_default);\n UA_SecureChannel_setSecurityPolicy(&testChannel, &dummyPolicy, &dummyCertificate);\n\n testingConnection = createDummyConnection(65535, &sentData);\n UA_Connection_attachSecureChannel(&testingConnection, &testChannel);\n testChannel.connection = &testingConnection;\n\n testChannel.state = UA_SECURECHANNELSTATE_OPEN;\n}", "label_name": "CWE-770", "label": 37} +{"code": "NOEXPORT int parse_socket_error(CLI *c, const char *text) {\n switch(get_last_socket_error()) {\n /* http://tangentsoft.net/wskfaq/articles/bsd-compatibility.html */\n case 0: /* close on read, or close on write on WIN32 */\n#ifndef USE_WIN32\n case EPIPE: /* close on write on Unix */\n#endif\n case S_ECONNABORTED:\n s_log(LOG_INFO, \"%s: Socket is closed\", text);\n return 0;\n case S_EINTR:\n s_log(LOG_DEBUG, \"%s: Interrupted by a signal: retrying\", text);\n return 1;\n case S_EWOULDBLOCK:\n s_log(LOG_NOTICE, \"%s: Would block: retrying\", text);\n s_poll_sleep(1, 0); /* Microsoft bug KB177346 */\n return 1;\n#if S_EAGAIN!=S_EWOULDBLOCK\n case S_EAGAIN:\n s_log(LOG_DEBUG,\n \"%s: Temporary lack of resources: retrying\", text);\n return 1;\n#endif\n#ifdef USE_WIN32\n case S_ECONNRESET:\n /* dying \"exec\" processes on Win32 cause reset instead of close */\n if(c->opt->exec_name) {\n s_log(LOG_INFO, \"%s: Socket is closed (exec)\", text);\n return 0;\n }\n /* fall through */\n#endif\n default:\n sockerror(text);\n throw_exception(c, 1);\n return -1; /* some C compilers require a return value */\n }\n}", "label_name": "CWE-295", "label": 52} +{"code": "int options_parse(CONF_TYPE type) {\n SERVICE_OPTIONS *section;\n\n options_defaults();\n section=&new_service_options;\n if(options_file(configuration_file, type, §ion))\n return 1;\n if(init_section(1, §ion))\n return 1;\n\n s_log(LOG_NOTICE, \"Configuration successful\");\n return 0;\n}", "label_name": "CWE-295", "label": 52} +{"code": "void main_init() { /* one-time initialization */\n#ifdef USE_SYSTEMD\n int i;\n\n systemd_fds=sd_listen_fds(1);\n if(systemd_fds<0)\n fatal(\"systemd initialization failed\");\n listen_fds_start=SD_LISTEN_FDS_START;\n /* set non-blocking mode on systemd file descriptors */\n for(i=0; i0)\n s_log(LOG_INFO, \"Systemd socket activation: %d descriptors received\",\n systemd_fds);\n}", "label_name": "CWE-295", "label": 52} +{"code": "NOEXPORT unsigned __stdcall daemon_thread(void *arg) {\n (void)arg; /* squash the unused parameter warning */\n\n tls_alloc(NULL, NULL, \"main\"); /* new thread-local storage */\n main_init();\n SetEvent(main_initialized); /* unlock the GUI thread */\n /* get a valid configuration */\n while(main_configure(cmdline.config_file, NULL)) {\n if(cmdline.config_file && *cmdline.config_file=='-')\n cmdline.config_file=NULL; /* don't retry commandline switches */\n unbind_ports(); /* in case initialization failed after bind_ports() */\n log_flush(LOG_MODE_ERROR); /* otherwise logs are buffered */\n PostMessage(hwnd, WM_INVALID_CONFIG, 0, 0); /* display error */\n WaitForSingleObject(config_ready, INFINITE);\n }\n PostMessage(hwnd, WM_VALID_CONFIG, 0, 0);\n\n /* start the main loop */\n daemon_loop();\n main_cleanup();\n _endthreadex(0); /* SIGNAL_TERMINATE received */\n return 0;\n}", "label_name": "CWE-295", "label": 52} +{"code": "NOEXPORT void tray_update(const int num) {\n NOTIFYICONDATA nid;\n static ICON_TYPE previous_icon=ICON_NONE;\n ICON_TYPE current_icon;\n LPTSTR tip;\n\n if(!global_options.option.taskbar) { /* currently disabled */\n tray_delete(); /* remove the taskbark icon if exists */\n return;\n }\n if(!tray_menu_handle) /* initialize taskbar */\n tray_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_TRAYMENU));\n if(!tray_menu_handle) {\n ioerror(\"LoadMenu\");\n return;\n }\n if(cmdline.service)\n EnableMenuItem(tray_menu_handle, IDM_EDIT_CONFIG, MF_GRAYED);\n\n ZeroMemory(&nid, sizeof nid);\n nid.cbSize=sizeof nid;\n nid.uID=1; /* application-defined icon ID */\n nid.uFlags=NIF_MESSAGE|NIF_TIP;\n nid.uCallbackMessage=WM_SYSTRAY; /* notification message */\n nid.hWnd=hwnd; /* window to receive notifications */\n if(num<0) {\n tip=str_tprintf(TEXT(\"Server is down\"));\n current_icon=ICON_ERROR;\n } else if(num>0) {\n tip=str_tprintf(TEXT(\"%d active session(s)\"), num);\n current_icon=ICON_ACTIVE;\n } else {\n tip=str_tprintf(TEXT(\"Server is idle\"));\n current_icon=ICON_IDLE;\n }\n _tcsncpy(nid.szTip, tip, 63);\n nid.szTip[63]=TEXT('\\0');\n str_free(tip);\n nid.hIcon=global_options.icon[current_icon];\n if(current_icon!=previous_icon) {\n nid.uFlags|=NIF_ICON;\n previous_icon=current_icon;\n }\n if(Shell_NotifyIcon(NIM_MODIFY, &nid)) /* modify tooltip */\n return; /* OK: taskbar icon exists */\n /* tooltip update failed - try to create the icon */\n nid.uFlags|=NIF_ICON;\n Shell_NotifyIcon(NIM_ADD, &nid);\n}", "label_name": "CWE-295", "label": 52} +{"code": "jpeg_error_handler(j_common_ptr)\n{\n return;\n}", "label_name": "CWE-476", "label": 46} +{"code": "void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,\n\ti64 pos)\n{\n\ti64 pixmap_version;\n\ti64 pack_size;\n\ti64 plane_bytes;\n\ti64 n;\n\n\tde_dbg(c, \"additional PixMap header fields, at %d\", (int)pos);\n\tde_dbg_indent(c, 1);\n\n\tpixmap_version = dbuf_getu16be(f, pos+0);\n\tde_dbg(c, \"pixmap version: %d\", (int)pixmap_version);\n\n\tbi->packing_type = dbuf_getu16be(f, pos+2);\n\tde_dbg(c, \"packing type: %d\", (int)bi->packing_type);\n\n\tpack_size = dbuf_getu32be(f, pos+4);\n\tde_dbg(c, \"pixel data length: %d\", (int)pack_size);\n\n\tbi->hdpi = pict_read_fixed(f, pos+8);\n\tbi->vdpi = pict_read_fixed(f, pos+12);\n\tde_dbg(c, \"dpi: %.2f\"DE_CHAR_TIMES\"%.2f\", bi->hdpi, bi->vdpi);\n\n\tbi->pixeltype = dbuf_getu16be(f, pos+16);\n\tbi->pixelsize = dbuf_getu16be(f, pos+18);\n\tbi->cmpcount = dbuf_getu16be(f, pos+20);\n\tbi->cmpsize = dbuf_getu16be(f, pos+22);\n\tde_dbg(c, \"pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d\",\n\t\t(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);\n\n\tbi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;\n\tif(bi->pdwidth < bi->npwidth) {\n\t\tbi->pdwidth = bi->npwidth;\n\t}\n\n\tplane_bytes = dbuf_getu32be(f, pos+24);\n\tde_dbg(c, \"plane bytes: %d\", (int)plane_bytes);\n\n\tbi->pmTable = (u32)dbuf_getu32be(f, pos+28);\n\tde_dbg(c, \"pmTable: 0x%08x\", (unsigned int)bi->pmTable);\n\n\tn = dbuf_getu32be(f, pos+32);\n\tde_dbg(c, \"pmReserved: 0x%08x\", (unsigned int)n);\n\n\tde_dbg_indent(c, -1);\n}", "label_name": "CWE-369", "label": 60} +{"code": "void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint32_t enc_len,\n char *public_shares,\n unsigned _t, unsigned _n) {\n LOG_INFO(__FUNCTION__);\n\n INIT_ERROR_STATE\n\n CHECK_STATE(encrypted_dkg_secret);\n CHECK_STATE(public_shares);\n CHECK_STATE(_t <= _n && _n > 0)\n\n SAFE_CHAR_BUF(decrypted_dkg_secret, DKG_MAX_SEALED_LEN);\n\n int status = AES_decrypt(encrypted_dkg_secret, enc_len, decrypted_dkg_secret,\n DKG_MAX_SEALED_LEN);\n\n CHECK_STATUS2(\"aes decrypt data - encrypted_dkg_secret failed with status %d\");\n\n status = calc_public_shares(decrypted_dkg_secret, public_shares, _t) != 0;\n CHECK_STATUS(\"t does not match polynomial in db\");\n\n SET_SUCCESS\n\n clean:\n ;\n LOG_INFO(\"SGX call completed\");\n}", "label_name": "CWE-787", "label": 24} +{"code": "void mobi_buffer_move(MOBIBuffer *buf, const int offset, const size_t len) {\n size_t aoffset = (size_t) abs(offset);\n unsigned char *source = buf->data + buf->offset;\n if (offset >= 0) {\n if (buf->offset + aoffset + len > buf->maxlen) {\n debug_print(\"%s\", \"End of buffer\\n\");\n buf->error = MOBI_BUFFER_END;\n return;\n }\n source += aoffset;\n } else {\n if (buf->offset < aoffset) {\n debug_print(\"%s\", \"End of buffer\\n\");\n buf->error = MOBI_BUFFER_END;\n return;\n }\n source -= aoffset;\n }\n memmove(buf->data + buf->offset, source, len);\n buf->offset += len;\n}", "label_name": "CWE-787", "label": 24} +{"code": "int audio_level_json(struct list *levell,\n\t\t const char *userid_self, const char *clientid_self,\n\t\t char **json_str, char **anon_str)\n{\n\tstruct json_object *jobj;\n\tstruct json_object *jarr;\n\tchar uid_anon[ANON_ID_LEN];\n\tchar cid_anon[ANON_CLIENT_LEN];\n\tstruct mbuf *pmb = NULL;\n\tint err = 0;\n\tstruct le *le;\n\n\tif (!levell || !json_str)\n\t\treturn EINVAL;\n\t\n\tjobj = jzon_alloc_object();\n\tif (!jobj)\n\t\treturn ENOMEM;\n\n\tjarr = jzon_alloc_array();\n\tif (!jarr) {\n\t\terr = ENOMEM;\n\t\tgoto out;\n\t}\n\n\tif (anon_str) {\n\t\tpmb = mbuf_alloc(512);\n\t\tmbuf_printf(pmb, \"%zu levels: \", list_count(levell));\n\t}\n\t\n\tLIST_FOREACH(levell, le) {\n\t\tstruct audio_level *a = le->data;\n\t\tstruct json_object *ja;\n\t\tconst char *userid = a->userid;\n\t\tconst char *clientid = a->clientid;\n\n\t\tif (a->is_self) {\n\t\t\tif (userid_self)\n\t\t\t\tuserid = userid_self;\n\t\t\tif (clientid_self)\n\t\t\t\tclientid = clientid_self;\n\t\t}\n\n\t\tja = jzon_alloc_object();\n\t\tif (ja) {\n\t\t\tjzon_add_str(ja, \"userid\", userid);\n\t\t\tjzon_add_str(ja, \"clientid\", clientid);\n\t\t\tjzon_add_int(ja, \"audio_level\",\n\t\t\t\t (int32_t)a->aulevel_smooth);\n\t\t\tjzon_add_int(ja, \"audio_level_now\",\n\t\t\t\t (int32_t)a->aulevel);\n\t\t}\n\t\tjson_object_array_add(jarr, ja);\n\n\t\t/* add to info string */\n\t\tif (pmb) {\n\t\t\tanon_id(uid_anon, userid);\n\t\t\tanon_client(cid_anon, clientid);\n\t\t\tmbuf_printf(pmb, \"{[%s.%s] audio_level: %d/%d}\",\n\t\t\t\t uid_anon, cid_anon,\n\t\t\t\t a->aulevel_smooth, a->aulevel);\n\t\t\tif (le != levell->tail)\n\t\t\t\tmbuf_printf(pmb, \",\");\n\t\t}\t\t\n\t}\n\tjson_object_object_add(jobj, \"audio_levels\", jarr);\n\n\tif (pmb) {\n\t\tpmb->pos = 0;\n\t\tmbuf_strdup(pmb, anon_str, pmb->end);\n\t\tmem_deref(pmb);\n\t}\n\n\tjzon_encode(json_str, jobj);\n out:\t\n\tmem_deref(jobj);\n\n\treturn err;\n}", "label_name": "CWE-134", "label": 54} +{"code": "def _inject_file_into_fs(fs, path, contents):\n absolute_path = os.path.join(fs, path.lstrip('/'))\n parent_dir = os.path.dirname(absolute_path)\n utils.execute('mkdir', '-p', parent_dir, run_as_root=True)\n utils.execute('tee', absolute_path, process_input=contents,\n run_as_root=True)", "label_name": "CWE-22", "label": 2} +{"code": " def set(self, key, value, serialize=True, timeout=0):\n \"\"\"\n Set a key/value pair in memcache\n\n :param key: key\n :param value: value\n :param serialize: if True, value is pickled before sending to memcache\n :param timeout: ttl in memcache\n \"\"\"\n key = md5hash(key)\n if timeout > 0:\n timeout += time.time()\n flags = 0\n if serialize:\n value = pickle.dumps(value, PICKLE_PROTOCOL)\n flags |= PICKLE_FLAG\n for (server, fp, sock) in self._get_conns(key):\n try:\n sock.sendall('set %s %d %d %s noreply\\r\\n%s\\r\\n' % \\\n (key, flags, timeout, len(value), value))\n self._return_conn(server, fp, sock)\n return\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 14} +{"code": " def get_multi(self, keys, server_key):\n \"\"\"\n Gets multiple values from memcache for the given keys.\n\n :param keys: keys for values to be retrieved from memcache\n :param servery_key: key to use in determining which server in the ring\n is used\n :returns: list of values\n \"\"\"\n server_key = md5hash(server_key)\n keys = [md5hash(key) for key in keys]\n for (server, fp, sock) in self._get_conns(server_key):\n try:\n sock.sendall('get %s\\r\\n' % ' '.join(keys))\n line = fp.readline().strip().split()\n responses = {}\n while line[0].upper() != 'END':\n if line[0].upper() == 'VALUE':\n size = int(line[3])\n value = fp.read(size)\n if int(line[2]) & PICKLE_FLAG:\n value = pickle.loads(value)\n responses[line[1]] = value\n fp.readline()\n line = fp.readline().strip().split()\n values = []\n for key in keys:\n if key in responses:\n values.append(responses[key])\n else:\n values.append(None)\n self._return_conn(server, fp, sock)\n return values\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 14} +{"code": " def get(self, key):\n \"\"\"\n Gets the object specified by key. It will also unpickle the object\n before returning if it is pickled in memcache.\n\n :param key: key\n :returns: value of the key in memcache\n \"\"\"\n key = md5hash(key)\n value = None\n for (server, fp, sock) in self._get_conns(key):\n try:\n sock.sendall('get %s\\r\\n' % key)\n line = fp.readline().strip().split()\n while line[0].upper() != 'END':\n if line[0].upper() == 'VALUE' and line[1] == key:\n size = int(line[3])\n value = fp.read(size)\n if int(line[2]) & PICKLE_FLAG:\n value = pickle.loads(value)\n fp.readline()\n line = fp.readline().strip().split()\n self._return_conn(server, fp, sock)\n return value\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 14} +{"code": " def set_multi(self, mapping, server_key, serialize=True, timeout=0):\n \"\"\"\n Sets multiple key/value pairs in memcache.\n\n :param mapping: dictonary of keys and values to be set in memcache\n :param servery_key: key to use in determining which server in the ring\n is used\n :param serialize: if True, value is pickled before sending to memcache\n :param timeout: ttl for memcache\n \"\"\"\n server_key = md5hash(server_key)\n if timeout > 0:\n timeout += time.time()\n msg = ''\n for key, value in mapping.iteritems():\n key = md5hash(key)\n flags = 0\n if serialize:\n value = pickle.dumps(value, PICKLE_PROTOCOL)\n flags |= PICKLE_FLAG\n msg += ('set %s %d %d %s noreply\\r\\n%s\\r\\n' %\n (key, flags, timeout, len(value), value))\n for (server, fp, sock) in self._get_conns(server_key):\n try:\n sock.sendall(msg)\n self._return_conn(server, fp, sock)\n return\n except Exception, e:\n self._exception_occurred(server, e)", "label_name": "CWE-94", "label": 14} +{"code": "def is_safe_url(url, host=None):\n \"\"\"\n Return ``True`` if the url is a safe redirection (i.e. it doesn't point to\n a different host and uses a safe scheme).\n\n Always returns ``False`` on an empty url.\n \"\"\"\n if url is not None:\n url = url.strip()\n if not url:\n return False\n # Chrome treats \\ completely as /\n url = url.replace('\\\\', '/')\n # Chrome considers any URL with more than two slashes to be absolute, but\n # urlparse is not so flexible. Treat any url with three slashes as unsafe.\n if url.startswith('///'):\n return False\n url_info = urlparse(url)\n # Forbid URLs like http:///example.com - with a scheme, but without a hostname.\n # In that URL, example.com is not the hostname but, a path component. However,\n # Chrome will still consider example.com to be the hostname, so we must not\n # allow this syntax.\n if not url_info.netloc and url_info.scheme:\n return False\n # Forbid URLs that start with control characters. Some browsers (like\n # Chrome) ignore quite a few control characters at the start of a\n # URL and might consider the URL as scheme relative.\n if unicodedata.category(url[0])[0] == 'C':\n return False\n return ((not url_info.netloc or url_info.netloc == host) and\n (not url_info.scheme or url_info.scheme in ['http', 'https']))", "label_name": "CWE-79", "label": 1} +{"code": " def load(self):\n\n if len(self.tile) != 1 or self.tile[0][0] != \"iptc\":\n return ImageFile.ImageFile.load(self)\n\n type, tile, box = self.tile[0]\n\n encoding, offset = tile\n\n self.fp.seek(offset)\n\n # Copy image data to temporary file\n outfile = tempfile.mktemp()\n o = open(outfile, \"wb\")\n if encoding == \"raw\":\n # To simplify access to the extracted file,\n # prepend a PPM header\n o.write(\"P5\\n%d %d\\n255\\n\" % self.size)\n while True:\n type, size = self.field()\n if type != (8, 10):\n break\n while size > 0:\n s = self.fp.read(min(size, 8192))\n if not s:\n break\n o.write(s)\n size = size - len(s)\n o.close()\n\n try:\n try:\n # fast\n self.im = Image.core.open_ppm(outfile)\n except:\n # slightly slower\n im = Image.open(outfile)\n im.load()\n self.im = im.im\n finally:\n try: os.unlink(outfile)\n except: pass", "label_name": "CWE-59", "label": 36} +{"code": "def subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (undo).'\n ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())", "label_name": "CWE-79", "label": 1} +{"code": " def fetch_file(self, in_path, out_path):\n ''' fetch a file from chroot to local '''\n\n in_path = self._normalize_path(in_path, self.get_jail_path())\n vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.jail)\n\n self._copy_file(in_path, out_path)", "label_name": "CWE-59", "label": 36} +{"code": " def _normalize_path(self, path, prefix):\n if not path.startswith(os.path.sep):\n path = os.path.join(os.path.sep, path)\n normpath = os.path.normpath(path)\n return os.path.join(prefix, normpath[1:])", "label_name": "CWE-59", "label": 36} +{"code": " def put_file(self, in_path, out_path):\n ''' transfer a file from local to zone '''\n\n out_path = self._normalize_path(out_path, self.get_zone_path())\n vvv(\"PUT %s TO %s\" % (in_path, out_path), host=self.zone)\n\n self._copy_file(in_path, out_path)", "label_name": "CWE-59", "label": 36} +{"code": " def fetch_file(self, in_path, out_path):\n ''' fetch a file from zone to local '''\n\n in_path = self._normalize_path(in_path, self.get_zone_path())\n vvv(\"FETCH %s TO %s\" % (in_path, out_path), host=self.zone)\n\n self._copy_file(in_path, out_path)", "label_name": "CWE-59", "label": 36} +{"code": "def _websocket_mask_python(mask, data):\n \"\"\"Websocket masking function.\n\n `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n Returns a `bytes` object of the same length as `data` with the mask applied\n as specified in section 5.3 of RFC 6455.\n\n This pure-python implementation may be replaced by an optimized version when available.\n \"\"\"\n mask = array.array(\"B\", mask)\n unmasked = array.array(\"B\", data)\n for i in xrange(len(data)):\n unmasked[i] = unmasked[i] ^ mask[i % 4]\n if hasattr(unmasked, 'tobytes'):\n # tostring was deprecated in py32. It hasn't been removed,\n # but since we turn on deprecation warnings in our tests\n # we need to use the right one.\n return unmasked.tobytes()\n else:\n return unmasked.tostring()", "label_name": "CWE-203", "label": 38} +{"code": " def GET(self, path, queries=()):\n return self._request('GET', path, queries)", "label_name": "CWE-295", "label": 52} +{"code": "def checkin(pickledata):\n config = pickle.loads(bz2.decompress(base64.urlsafe_b64decode(pickledata)))\n r, message = read_host_config(SESSION, config)\n if r is not None:\n return message + 'checked in successful'\n else:\n return message + 'error checking in'", "label_name": "CWE-94", "label": 14} +{"code": "def class_instances_from_soap_enveloped_saml_thingies(text, modules):\n \"\"\"Parses a SOAP enveloped header and body SAML thing and returns the\n thing as a dictionary class instance.\n\n :param text: The SOAP object as XML\n :param modules: modules representing xsd schemas\n :return: The body and headers as class instances\n \"\"\"\n try:\n envelope = ElementTree.fromstring(text)\n except Exception as exc:\n raise XmlParseError(\"%s\" % exc)\n\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n env = {\"header\": [], \"body\": None}\n\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n env[\"body\"] = instanciate_class(part[0], modules)\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n env[\"header\"].append(instanciate_class(item, modules))\n\n return env", "label_name": "CWE-611", "label": 13} +{"code": " def prop_sentences_stats(self, type, vId = None):\n return {\n 'get_data' : \"SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC\",\n 'all_networks' : \"SELECT networks.* FROM networks ORDER BY id\",\n 'get_preview' : \"SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = '%s'\" % (vId),\n 'id_networks' : \"SELECT networks.* FROM networks WHERE id = '%s'\" % (vId),\n 'get_requests' : \"SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id \",\n 'get_sessions' : \"SELECT COUNT(*) AS Total FROM networks\",\n 'get_clicks' : \"SELECT COUNT(*) AS Total FROM clicks\",\n 'get_online' : \"SELECT COUNT(*) AS Total FROM victims WHERE status = '%s'\" % ('online')\n }.get(type, False)", "label_name": "CWE-89", "label": 0} +{"code": " def prop_sentences_stats(self, type, vId = None):\n return {\n 'get_data' : \"SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC\",\n 'all_networks' : \"SELECT networks.* FROM networks ORDER BY id\",\n 'get_preview' : \"SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = '%s'\" % (vId),\n 'id_networks' : \"SELECT networks.* FROM networks WHERE id = '%s'\" % (vId),\n 'get_requests' : \"SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id \",\n 'get_sessions' : \"SELECT COUNT(*) AS Total FROM networks\",\n 'get_clicks' : \"SELECT COUNT(*) AS Total FROM clicks\",\n 'get_online' : \"SELECT COUNT(*) AS Total FROM victims WHERE status = '%s'\" % ('online')\n }.get(type, False)", "label_name": "CWE-79", "label": 1} +{"code": "def home_get_preview():\n vId = request.form['vId']\n d = db.sentences_stats('get_preview', vId)\n n = db.sentences_stats('id_networks', vId)\n return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});", "label_name": "CWE-89", "label": 0} +{"code": " def load(self, stream):\n '''read vault steam and return python object'''\n return yaml.load(self.vault.decrypt(stream))", "label_name": "CWE-94", "label": 14} +{"code": " def make_homeserver(self, reactor, clock):\n hs = self.setup_test_homeserver(\n http_client=None, homeserver_to_use=GenericWorkerServer\n )\n return hs", "label_name": "CWE-601", "label": 11} +{"code": " def make_homeserver(self, reactor, clock):\n # we mock out the keyring so as to skip the authentication check on the\n # federation API call.\n mock_keyring = Mock(spec=[\"verify_json_for_server\"])\n mock_keyring.verify_json_for_server.return_value = defer.succeed(True)\n\n # we mock out the federation client too\n mock_federation_client = Mock(spec=[\"put_json\"])\n mock_federation_client.put_json.return_value = defer.succeed((200, \"OK\"))\n\n # the tests assume that we are starting at unix time 1000\n reactor.pump((1000,))\n\n hs = self.setup_test_homeserver(\n notifier=Mock(),\n http_client=mock_federation_client,\n keyring=mock_keyring,\n replication_streams={},\n )\n\n return hs", "label_name": "CWE-601", "label": 11} +{"code": " def prepare(self, reactor, clock, homeserver):\n # make a second homeserver, configured to use the first one as a key notary\n self.http_client2 = Mock()\n config = default_config(name=\"keyclient\")\n config[\"trusted_key_servers\"] = [\n {\n \"server_name\": self.hs.hostname,\n \"verify_keys\": {\n \"ed25519:%s\"\n % (\n self.hs_signing_key.version,\n ): signedjson.key.encode_verify_key_base64(\n self.hs_signing_key.verify_key\n )\n },\n }\n ]\n self.hs2 = self.setup_test_homeserver(\n http_client=self.http_client2, config=config\n )\n\n # wire up outbound POST /key/v2/query requests from hs2 so that they\n # will be forwarded to hs1\n async def post_json(destination, path, data):\n self.assertEqual(destination, self.hs.hostname)\n self.assertEqual(\n path, \"/_matrix/key/v2/query\",\n )\n\n channel = FakeChannel(self.site, self.reactor)\n req = SynapseRequest(channel)\n req.content = BytesIO(encode_canonical_json(data))\n\n req.requestReceived(\n b\"POST\", path.encode(\"utf-8\"), b\"1.1\",\n )\n channel.await_result()\n self.assertEqual(channel.code, 200)\n resp = channel.json_body\n return resp\n\n self.http_client2.post_json.side_effect = post_json", "label_name": "CWE-601", "label": 11} +{"code": " def testInputPreProcessFormats(self):\n input_str = 'input1=/path/file.txt[ab3];input2=file2'\n input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'\n input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)\n input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(\n input_expr_str)\n self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3'))\n self.assertTrue(input_dict['input2'] == ('file2', None))\n print(input_expr_dict['input3'])\n self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2]))\n self.assertAllClose(input_expr_dict['input4'], [4, 5])\n self.assertTrue(len(input_dict) == 2)\n self.assertTrue(len(input_expr_dict) == 2)", "label_name": "CWE-94", "label": 14} +{"code": " def testRunCommandInvalidInputKeyError(self, use_tfrt):\n self.parser = saved_model_cli.create_parser()\n base_path = test.test_src_dir_path(SAVED_MODEL_PATH)\n args = self.parser.parse_args([\n 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def',\n 'regress_x2_to_y3', '--input_exprs', 'x2=np.ones((3,1))'\n ] + (['--use_tfrt'] if use_tfrt else []))\n with self.assertRaises(ValueError):\n saved_model_cli.run(args)", "label_name": "CWE-94", "label": 14} +{"code": " def test_str(self):\n code = LoginCode(user=self.user, code='foo', timestamp=datetime(2018, 7, 1))\n self.assertEqual(str(code), 'test_user - 2018-07-01 00:00:00')", "label_name": "CWE-312", "label": 71} +{"code": " def test_request_login_code(self):\n response = self.client.post('/accounts/login/', {\n 'username': self.user.username,\n 'next': '/private/',\n })\n\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response['Location'], '/accounts/login/code/')\n\n login_code = LoginCode.objects.filter(user=self.user).first()\n\n self.assertIsNotNone(login_code)\n self.assertEqual(login_code.next, '/private/')\n self.assertEqual(len(mail.outbox), 1)\n self.assertIn(\n 'http://testserver/accounts/login/code/?code={}'.format(login_code.code),\n mail.outbox[0].body,\n )", "label_name": "CWE-312", "label": 71} +{"code": " def test_received_preq_completed_connection_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = True\n preq.connection_close = True\n inst.received(b\"GET / HTTP/1.1\\n\\n\" + b\"a\" * 50000)\n self.assertEqual(inst.request, None)\n self.assertEqual(inst.server.tasks, [])", "label_name": "CWE-444", "label": 41} +{"code": " def test_bad_host_header(self):\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n to_send = \"GET / HTTP/1.0\\n\" \" Host: 0\\n\\n\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))", "label_name": "CWE-444", "label": 41} +{"code": " def test_before_start_response_http_11(self):\n to_send = \"GET /before_start_response HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()), [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"]\n )\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label_name": "CWE-444", "label": 41} +{"code": " def test_filelike_shortcl_http11(self):\n to_send = \"GET /filelike_shortcl HTTP/1.1\\n\\n\"\n to_send = tobytes(to_send)\n\n self.connect()\n\n for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)", "label_name": "CWE-444", "label": 41} +{"code": " def test_request_body_too_large_with_no_cl_http11_connclose(self):\n body = \"a\" * self.toobig\n to_send = \"GET / HTTP/1.1\\nConnection: close\\n\\n\"\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed 0)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "label_name": "CWE-444", "label": 41} +{"code": " def test_keepalive_http11_explicit(self):\n # Explicitly set keep-alive\n data = \"Default: Keep me alive\"\n s = tobytes(\n \"GET / HTTP/1.1\\n\"\n \"Connection: keep-alive\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"\n \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertTrue(response.getheader(\"connection\") != \"close\")", "label_name": "CWE-444", "label": 41} +{"code": " def testSimpleGET(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nFirstName: mickey\nlastname: Mouse\ncontent-length: 7\n\nHello.\n\"\"\"\n parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,\n {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"7\",},\n )\n self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")\n self.assertEqual(parser.proxy_scheme, \"\")\n self.assertEqual(parser.proxy_netloc, \"\")\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\\n\")", "label_name": "CWE-444", "label": 41} +{"code": " def test_parse_header_connection_close(self):\n data = b\"GET /foobar HTTP/1.1\\nConnection: close\\n\\n\"\n self.parser.parse_header(data)\n self.assertEqual(self.parser.connection_close, True)", "label_name": "CWE-444", "label": 41} +{"code": " def test_received_bad_host_header(self):\n from waitress.utilities import BadRequest\n\n data = b\"\"\"\\\nHTTP/1.0 GET /foobar\n Host: foo\n\n\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 33)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.error.__class__, BadRequest)", "label_name": "CWE-444", "label": 41} +{"code": " def test_received_no_doublecr(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 21)\n self.assertFalse(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", "label_name": "CWE-444", "label": 41} +{"code": " def testSpoofedHeadersDropped(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nx-auth_user: bob\ncontent-length: 7\n\nHello.\n\"\"\"\n self.feed(data)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {\"CONTENT_LENGTH\": \"7\",})", "label_name": "CWE-444", "label": 41} +{"code": " def test_parse_header_gardenpath(self):\n data = b\"\"\"\\\nGET /foobar HTTP/8.4\nfoo: bar\"\"\"\n self.parser.parse_header(data)\n self.assertEqual(self.parser.first_line, b\"GET /foobar HTTP/8.4\")\n self.assertEqual(self.parser.headers[\"FOO\"], \"bar\")", "label_name": "CWE-444", "label": 41} +{"code": " def test_received_control_line_finished_all_chunks_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n result = inst.received(b\"0;discard\\n\")\n self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.all_chunks_received, True)\n self.assertEqual(result, 10)\n self.assertEqual(inst.completed, False)", "label_name": "CWE-444", "label": 41} +{"code": " def rpn(self, irc, msg, args):\n \"\"\"\n\n Returns the value of an RPN expression.\n \"\"\"\n stack = []\n for arg in args:\n try:\n x = complex(arg)\n if x == abs(x):\n x = abs(x)\n stack.append(x)\n except ValueError: # Not a float.\n if arg in self._mathSafeEnv:\n f = self._mathSafeEnv[arg]\n if callable(f):\n called = False\n arguments = []\n while not called and stack:\n arguments.append(stack.pop())\n try:\n stack.append(f(*arguments))\n called = True\n except TypeError:\n pass\n if not called:\n irc.error(_('Not enough arguments for %s') % arg)\n return\n else:\n stack.append(f)\n elif arg in self._rpnEnv:\n self._rpnEnv[arg](stack)\n else:\n arg2 = stack.pop()\n arg1 = stack.pop()\n s = '%s%s%s' % (arg1, arg, arg2)\n try:\n stack.append(eval(s, self._mathSafeEnv, self._mathSafeEnv))\n except SyntaxError:\n irc.error(format(_('%q is not a defined function.'),\n arg))\n return\n if len(stack) == 1:\n irc.reply(str(self._complexToString(complex(stack[0]))))\n else:\n s = ', '.join(map(self._complexToString, list(map(complex, stack))))\n irc.reply(_('Stack: [%s]') % s)", "label_name": "CWE-94", "label": 14} +{"code": " def _sqrt(x):\n if isinstance(x, complex) or x < 0:\n return cmath.sqrt(x)\n else:\n return math.sqrt(x)", "label_name": "CWE-94", "label": 14} +{"code": " def icalc(self, irc, msg, args, text):\n \"\"\"\n\n This is the same as the calc command except that it allows integer\n math, and can thus cause the bot to suck up CPU. Hence it requires\n the 'trusted' capability to use.\n \"\"\"\n if self._calc_match_forbidden_chars.match(text):\n # Note: this is important to keep this to forbid usage of\n # __builtins__\n irc.error(_('There\\'s really no reason why you should have '\n 'underscores or brackets in your mathematical '\n 'expression. Please remove them.'))\n return\n # This removes spaces, too, but we'll leave the removal of _[] for\n # safety's sake.\n text = self._calc_remover(text)\n if 'lambda' in text:\n irc.error(_('You can\\'t use lambda in this command.'))\n return\n text = text.replace('lambda', '')\n try:\n self.log.info('evaluating %q from %s', text, msg.prefix)\n irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))\n except OverflowError:\n maxFloat = math.ldexp(0.9999999999999999, 1024)\n irc.error(_('The answer exceeded %s or so.') % maxFloat)\n except TypeError:\n irc.error(_('Something in there wasn\\'t a valid number.'))\n except NameError as e:\n irc.error(_('%s is not a defined function.') % str(e).split()[1])\n except Exception as e:\n irc.error(utils.exnToString(e))", "label_name": "CWE-94", "label": 14} +{"code": "def insensitive_exact(field: Term, value: str) -> Criterion:\n return Upper(field).eq(Upper(f\"{value}\"))", "label_name": "CWE-89", "label": 0} +{"code": "def insensitive_ends_with(field: Term, value: str) -> Criterion:\n return Upper(field).like(Upper(f\"%{value}\"))", "label_name": "CWE-89", "label": 0} +{"code": "def google_remote_app():\n if \"google\" not in oauth.remote_apps:\n oauth.remote_app(\n \"google\",\n base_url=\"https://www.google.com/accounts/\",\n authorize_url=\"https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent\",\n request_token_url=None,\n request_token_params={\n \"scope\": \"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile\"\n },\n access_token_url=\"https://accounts.google.com/o/oauth2/token\",\n access_token_method=\"POST\",\n consumer_key=settings.GOOGLE_CLIENT_ID,\n consumer_secret=settings.GOOGLE_CLIENT_SECRET,\n )\n\n return oauth.google", "label_name": "CWE-601", "label": 11} +{"code": "def login():\n callback = url_for(\".callback\", _external=True)\n next_path = request.args.get(\n \"next\", url_for(\"redash.index\", org_slug=session.get(\"org_slug\"))\n )\n logger.debug(\"Callback url: %s\", callback)\n logger.debug(\"Next is: %s\", next_path)\n return google_remote_app().authorize(callback=callback, state=next_path)", "label_name": "CWE-601", "label": 11} +{"code": "def is_private_address(url):\n hostname = urlparse(url).hostname\n ip_address = socket.gethostbyname(hostname)\n return ipaddress.ip_address(text_type(ip_address)).is_private", "label_name": "CWE-918", "label": 16} +{"code": "def env() -> Environment:\n from openapi_python_client import utils\n\n TEMPLATE_FILTERS = {\"snakecase\": utils.snake_case, \"spinalcase\": utils.spinal_case}\n env = Environment(loader=PackageLoader(\"openapi_python_client\"), trim_blocks=True, lstrip_blocks=True)\n env.filters.update(TEMPLATE_FILTERS)\n return env", "label_name": "CWE-22", "label": 2} +{"code": " def get_type_string(self) -> str:\n \"\"\" Get a string representation of type that should be used when declaring this property \"\"\"\n if self.required:\n return self._type_string\n return f\"Optional[{self._type_string}]\"", "label_name": "CWE-94", "label": 14} +{"code": "def group_title(value: str) -> str:\n value = re.sub(r\"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)\", lambda m: m.group(1).title() + m.group(2), value.strip())\n value = re.sub(r\"(^|[ _-])([A-Z])\", lambda m: m.group(1) + m.group(2).lower(), value)\n return value", "label_name": "CWE-94", "label": 14} +{"code": "def escape_text(text: EscapableEntity) -> str:\n \"\"\"Escape HTML text\n\n We only strip some tags and allow some simple tags\n such as

    , or to be part of the string.\n This is useful for messages where we want to keep formatting\n options. (Formerly known as 'permissive_attrencode')\n\n Args:\n text:\n\n Examples:\n\n >>> escape_text(\"Hello this is dog!\")\n 'Hello this is dog!'\n\n This is lame.\n\n >>> escape_text(\"Hello this is dog!\")\n 'Hello this <a href=>is dog!'\n\n Returns:\n\n \"\"\"\n if isinstance(text, HTML):\n return text.__html__()\n\n text = escape_attribute(text)\n text = _UNESCAPER_TEXT.sub(r'<\\1\\2>', text)\n for a_href in _A_HREF.finditer(text):\n text = text.replace(a_href.group(0), u\"\" % _QUOTE.sub(u\"\\\"\", a_href.group(1)))\n return text.replace(u\"&nbsp;\", u\" \")", "label_name": "CWE-79", "label": 1} +{"code": "def task_remove(request, task_id):\n \"\"\"\n remove task by task_id\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n try:\n # delete job from DjangoJob\n task = Task.objects.get(id=task_id)\n clients = clients_of_task(task)\n for client in clients:\n job_id = get_job_id(client, task)\n DjangoJob.objects.filter(name=job_id).delete()\n # delete task\n Task.objects.filter(id=task_id).delete()\n return JsonResponse({'result': '1'})\n except:\n return JsonResponse({'result': '0'})", "label_name": "CWE-78", "label": 6} +{"code": "def load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs):\n \"\"\"\n This is the image 'Preview' tab for the right-hand panel.\n \"\"\"\n context = {}\n\n # the index of a field within a well\n index = getIntOrDefault(request, \"index\", 0)\n\n manager = BaseContainer(conn, **{str(c_type): long(c_id)})\n if share_id:\n context[\"share\"] = BaseShare(conn, share_id)\n if c_type == \"well\":\n manager.image = manager.well.getImage(index)\n\n allRdefs = manager.image.getAllRenderingDefs()\n rdefs = {}\n rdefId = manager.image.getRenderingDefId()\n # remove duplicates per user\n for r in allRdefs:\n ownerId = r[\"owner\"][\"id\"]\n r[\"current\"] = r[\"id\"] == rdefId\n # if duplicate rdefs for user, pick one with highest ID\n if ownerId not in rdefs or rdefs[ownerId][\"id\"] < r[\"id\"]:\n rdefs[ownerId] = r\n rdefs = rdefs.values()\n # format into rdef strings,\n # E.g. {c: '1|3118:35825$FF0000,2|2086:18975$FFFF00', m: 'c'}\n rdefQueries = []\n for r in rdefs:\n chs = []\n for i, c in enumerate(r[\"c\"]):\n act = \"-\"\n if c[\"active\"]:\n act = \"\"\n color = c[\"lut\"] if \"lut\" in c else c[\"color\"]\n reverse = \"r\" if c[\"inverted\"] else \"-r\"\n chs.append(\n \"%s%s|%s:%s%s$%s\" % (act, i + 1, c[\"start\"], c[\"end\"], reverse, color)\n )\n rdefQueries.append(\n {\n \"id\": r[\"id\"],\n \"owner\": r[\"owner\"],\n \"c\": \",\".join(chs),\n \"m\": r[\"model\"] == \"greyscale\" and \"g\" or \"c\",\n }\n )\n max_w, max_h = conn.getMaxPlaneSize()\n size_x = manager.image.getSizeX()\n size_y = manager.image.getSizeY()\n\n context[\"tiledImage\"] = (size_x * size_y) > (max_w * max_h)\n context[\"manager\"] = manager\n context[\"rdefsJson\"] = json.dumps(rdefQueries)\n context[\"rdefs\"] = rdefs\n context[\"template\"] = \"webclient/annotations/metadata_preview.html\"\n return context", "label_name": "CWE-79", "label": 1} +{"code": "\tdef decompile(self):\n\t\tself.writeln(\"** Decompiling APK...\", clr.OKBLUE)\n\t\twith ZipFile(self.file) as zipped:\n\t\t\ttry:\n\t\t\t\tdex = self.tempdir + \"/\" + self.apk.package + \".dex\"\n\t\t\t\twith open(dex, \"wb\") as classes:\n\t\t\t\t\tclasses.write(zipped.read(\"classes.dex\"))\n\t\t\texcept Exception as e:\n\t\t\t\tsys.exit(self.writeln(str(e), clr.WARNING))\n\t\tdec = \"%s %s -d %s --deobf\" % (self.jadx, dex, self.tempdir)\n\t\tos.system(dec)\n\t\treturn self.tempdir", "label_name": "CWE-78", "label": 6} +{"code": " def test_it_works_with_explicit_external_host(self, app, monkeypatch):\n with app.test_request_context():\n monkeypatch.setattr('flask.request.host_url', 'http://example.com')\n result = _validate_redirect_url('http://works.com',\n _external_host='works.com')\n assert result is True\n monkeypatch.undo()", "label_name": "CWE-601", "label": 11} +{"code": " def __init__(self, sourceName: str):\n self.sourceName = sourceName\n self.type = \"file\"\n self.content = None", "label_name": "CWE-78", "label": 6} +{"code": " def relative(self, relativePath) -> FileInputSource:\n return FileInputSource(os.path.join(self.directory(), relativePath))", "label_name": "CWE-22", "label": 2} +{"code": "def command_dispatch(request):\n \"\"\"\n Xtheme command dispatch view.\n\n :param request: A request\n :type request: django.http.HttpRequest\n :return: A response\n :rtype: django.http.HttpResponse\n \"\"\"\n command = request.POST.get(\"command\")\n if command:\n response = handle_command(request, command)\n if response:\n return response\n raise Problem(\"Error! Unknown command: `%r`\" % command)", "label_name": "CWE-79", "label": 1} +{"code": "def view_configuration():\n read_column = calibre_db.session.query(db.Custom_Columns)\\\n .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all()\n restrict_columns = calibre_db.session.query(db.Custom_Columns)\\\n .filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all()\n languages = calibre_db.speaking_language()\n translations = [LC('en')] + babel.list_translations()\n return render_title_template(\"config_view_edit.html\", conf=config, readColumns=read_column,\n restrictColumns=restrict_columns,\n languages=languages,\n translations=translations,\n title=_(u\"UI Configuration\"), page=\"uiconfig\")", "label_name": "CWE-918", "label": 16} +{"code": "def edit_user(user_id):\n content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User\n if not content or (not config.config_anonbrowse and content.name == \"Guest\"):\n flash(_(u\"User not found\"), category=\"error\")\n return redirect(url_for('admin.admin'))\n languages = calibre_db.speaking_language(return_all_languages=True)\n translations = babel.list_translations() + [LC('en')]\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n if request.method == \"POST\":\n to_save = request.form.to_dict()\n resp = _handle_edit_user(to_save, content, languages, translations, kobo_support)\n if resp:\n return resp\n return render_title_template(\"user_edit.html\",\n translations=translations,\n languages=languages,\n new_user=0,\n content=content,\n config=config,\n registered_oauth=oauth_check,\n mail_configured=config.get_mail_server_configured(),\n kobo_support=kobo_support,\n title=_(u\"Edit User %(nick)s\", nick=content.name),\n page=\"edituser\")", "label_name": "CWE-918", "label": 16} +{"code": " def get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False,\n config_read_column=False, *join):", "label_name": "CWE-918", "label": 16} +{"code": " def setup_db(cls, config_calibre_dir, app_db_path):\n cls.dispose()\n\n if not config_calibre_dir:\n cls.config.invalidate()\n return False\n\n dbpath = os.path.join(config_calibre_dir, \"metadata.db\")\n if not os.path.exists(dbpath):\n cls.config.invalidate()\n return False\n\n try:\n cls.engine = create_engine('sqlite://',\n echo=False,\n isolation_level=\"SERIALIZABLE\",\n connect_args={'check_same_thread': False},\n poolclass=StaticPool)\n with cls.engine.begin() as connection:\n connection.execute(text(\"attach database '{}' as calibre;\".format(dbpath)))\n connection.execute(text(\"attach database '{}' as app_settings;\".format(app_db_path)))\n\n conn = cls.engine.connect()\n # conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302\n except Exception as ex:\n cls.config.invalidate(ex)\n return False\n\n cls.config.db_configured = True\n\n if not cc_classes:\n try:\n cc = conn.execute(text(\"SELECT id, datatype FROM custom_columns\"))\n cls.setup_db_cc_classes(cc)\n except OperationalError as e:\n log.error_or_exception(e)\n\n cls.session_factory = scoped_session(sessionmaker(autocommit=False,\n autoflush=True,\n bind=cls.engine))\n for inst in cls.instances:\n inst.initSession()\n\n cls._init = True\n return True", "label_name": "CWE-918", "label": 16} +{"code": "def edit_book_series_index(series_index, book):\n # Add default series_index to book\n modif_date = False\n series_index = series_index or '1'\n if not series_index.replace('.', '', 1).isdigit():\n flash(_(\"%(seriesindex)s is not a valid number, skipping\", seriesindex=series_index), category=\"warning\")\n return False\n if str(book.series_index) != series_index:\n book.series_index = series_index\n modif_date = True\n return modif_date", "label_name": "CWE-918", "label": 16} +{"code": "def table_xchange_author_title():\n vals = request.get_json().get('xchange')\n if vals:\n for val in vals:\n modif_date = False\n book = calibre_db.get_book(val)\n authors = book.title\n book.authors = calibre_db.order_authors([book])\n author_names = []\n for authr in book.authors:\n author_names.append(authr.name.replace('|', ','))\n\n title_change = handle_title_on_edit(book, \" \".join(author_names))\n input_authors, authorchange, renamed = handle_author_on_edit(book, authors)\n if authorchange or title_change:\n edited_books_id = book.id\n modif_date = True\n\n if config.config_use_google_drive:\n gdriveutils.updateGdriveCalibreFromLocal()\n\n if edited_books_id:\n helper.update_dir_structure(edited_books_id, config.config_calibre_dir, input_authors[0],\n renamed_author=renamed)\n if modif_date:\n book.last_modified = datetime.utcnow()\n try:\n calibre_db.session.commit()\n except (OperationalError, IntegrityError) as e:\n calibre_db.session.rollback()\n log.error_or_exception(\"Database error: %s\", e)\n return json.dumps({'success': False})\n\n if config.config_use_google_drive:\n gdriveutils.updateGdriveCalibreFromLocal()\n return json.dumps({'success': True})\n return \"\"", "label_name": "CWE-918", "label": 16} +{"code": "def merge_list_book():\n vals = request.get_json().get('Merge_books')\n to_file = list()\n if vals:\n # load all formats from target book\n to_book = calibre_db.get_book(vals[0])\n vals.pop(0)\n if to_book:\n for file in to_book.data:\n to_file.append(file.format)\n to_name = helper.get_valid_filename(to_book.title, chars=96) + ' - ' + \\\n helper.get_valid_filename(to_book.authors[0].name, chars=96)\n for book_id in vals:\n from_book = calibre_db.get_book(book_id)\n if from_book:\n for element in from_book.data:\n if element.format not in to_file:\n # create new data entry with: book_id, book_format, uncompressed_size, name\n filepath_new = os.path.normpath(os.path.join(config.config_calibre_dir,\n to_book.path,\n to_name + \".\" + element.format.lower()))\n filepath_old = os.path.normpath(os.path.join(config.config_calibre_dir,\n from_book.path,\n element.name + \".\" + element.format.lower()))\n copyfile(filepath_old, filepath_new)\n to_book.data.append(db.Data(to_book.id,\n element.format,\n element.uncompressed_size,\n to_name))\n delete_book_from_table(from_book.id,\"\", True)\n return json.dumps({'success': True})\n return \"\"", "label_name": "CWE-918", "label": 16} +{"code": "def table_get_custom_enum(c_id):\n ret = list()\n cc = (calibre_db.session.query(db.Custom_Columns)\n .filter(db.Custom_Columns.id == c_id)\n .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none())\n ret.append({'value': \"\", 'text': \"\"})\n for idx, en in enumerate(cc.get_display_dict()['enum_values']):\n ret.append({'value': en, 'text': en})\n return json.dumps(ret)", "label_name": "CWE-918", "label": 16} +{"code": "def render_edit_book(book_id):\n cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()\n book = calibre_db.get_filtered_book(book_id, allow_show_archived=True)\n if not book:\n flash(_(u\"Oops! Selected book title is unavailable. File does not exist or is not accessible\"), category=\"error\")\n return redirect(url_for(\"web.index\"))\n\n for lang in book.languages:\n lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code)\n\n book.authors = calibre_db.order_authors([book])\n\n author_names = []\n for authr in book.authors:\n author_names.append(authr.name.replace('|', ','))\n\n # Option for showing convertbook button\n valid_source_formats=list()\n allowed_conversion_formats = list()\n kepub_possible=None\n if config.config_converterpath:\n for file in book.data:\n if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM:\n valid_source_formats.append(file.format.lower())\n if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]:\n kepub_possible = True\n if not config.config_converterpath:\n valid_source_formats.append('epub')\n\n # Determine what formats don't already exist\n if config.config_converterpath:\n allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:]\n for file in book.data:\n if file.format.lower() in allowed_conversion_formats:\n allowed_conversion_formats.remove(file.format.lower())\n if kepub_possible:\n allowed_conversion_formats.append('kepub')\n return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc,\n title=_(u\"edit metadata\"), page=\"editbook\",\n conversion_formats=allowed_conversion_formats,\n config=config,\n source_formats=valid_source_formats)", "label_name": "CWE-918", "label": 16} +{"code": "def update_dir_structure_gdrive(book_id, first_author, renamed_author):\n book = calibre_db.get_book(book_id)\n\n authordir = book.path.split('/')[0]\n titledir = book.path.split('/')[1]\n new_authordir = rename_all_authors(first_author, renamed_author, gdrive=True)\n new_titledir = get_valid_filename(book.title, chars=96) + u\" (\" + str(book_id) + u\")\"\n\n if titledir != new_titledir:\n gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), titledir)\n if gFile:\n gd.moveGdriveFileRemote(gFile, new_titledir)\n book.path = book.path.split('/')[0] + u'/' + new_titledir\n gd.updateDatabaseOnEdit(gFile['id'], book.path) # only child folder affected\n else:\n return _(u'File %(file)s not found on Google Drive', file=book.path) # file not found\n\n if authordir != new_authordir and authordir not in renamed_author:\n gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), new_titledir)\n if gFile:\n gd.moveGdriveFolderRemote(gFile, new_authordir)\n book.path = new_authordir + u'/' + book.path.split('/')[1]\n gd.updateDatabaseOnEdit(gFile['id'], book.path)\n else:\n return _(u'File %(file)s not found on Google Drive', file=authordir) # file not found\n\n # change location in database to new author/title path\n book.path = os.path.join(new_authordir, new_titledir).replace('\\\\', '/')\n return rename_files_on_change(first_author, renamed_author, book, gdrive=True)", "label_name": "CWE-918", "label": 16} +{"code": "def uniq(inpt):\n output = []\n inpt = [ \" \".join(inp.split()) for inp in inpt]\n for x in inpt:\n if x not in output:\n output.append(x)\n return output", "label_name": "CWE-918", "label": 16} +{"code": "def check_unrar(unrarLocation):\n if not unrarLocation:\n return\n\n if not os.path.exists(unrarLocation):\n return _('Unrar binary file not found')\n\n try:\n unrarLocation = [unrarLocation]\n value = process_wait(unrarLocation, pattern='UNRAR (.*) freeware')\n if value:\n version = value.group(1)\n log.debug(\"unrar version %s\", version)\n\n except (OSError, UnicodeDecodeError) as err:\n log.error_or_exception(err)\n return _('Error excecuting UnRar')", "label_name": "CWE-918", "label": 16} +{"code": "def rename_all_authors(first_author, renamed_author, calibre_path=\"\", localbook=None, gdrive=False):\n # Create new_author_dir from parameter or from database\n # Create new title_dir from database and add id\n if first_author:\n new_authordir = get_valid_filename(first_author, chars=96)\n for r in renamed_author:\n new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()\n old_author_dir = get_valid_filename(r, chars=96)\n new_author_rename_dir = get_valid_filename(new_author.name, chars=96)\n if gdrive:\n gFile = gd.getFileFromEbooksFolder(None, old_author_dir)\n if gFile:\n gd.moveGdriveFolderRemote(gFile, new_author_rename_dir)\n else:\n if os.path.isdir(os.path.join(calibre_path, old_author_dir)):\n try:\n old_author_path = os.path.join(calibre_path, old_author_dir)\n new_author_path = os.path.join(calibre_path, new_author_rename_dir)\n shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path))\n except (OSError) as ex:\n log.error(\"Rename author from: %s to %s: %s\", old_author_path, new_author_path, ex)\n log.debug(ex, exc_info=True)\n return _(\"Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s\",\n src=old_author_path, dest=new_author_path, error=str(ex))\n else:\n new_authordir = get_valid_filename(localbook.authors[0].name, chars=96)\n return new_authordir", "label_name": "CWE-918", "label": 16} +{"code": "def feed_category(book_id):\n off = request.args.get(\"offset\") or 0\n entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,\n db.Books,\n db.Books.tags.any(db.Tags.id == book_id),\n [db.Books.timestamp.desc()])\n return render_xml_template('feed.xml', entries=entries, pagination=pagination)", "label_name": "CWE-918", "label": 16} +{"code": "def feed_unread_books():\n off = request.args.get(\"offset\") or 0\n result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True)\n return render_xml_template('feed.xml', entries=result, pagination=pagination)", "label_name": "CWE-918", "label": 16} +{"code": "def render_hot_books(page, order):\n if current_user.check_visibility(constants.SIDEBAR_HOT):\n if order[1] not in ['hotasc', 'hotdesc']:\n # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+\n #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or\n # order[0][0].compare(func.count(ub.Downloads.book_id).asc())):\n order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc'\n if current_user.show_detail_random():\n random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \\\n .order_by(func.random()).limit(config.config_random_books)\n else:\n random = false()\n off = int(int(config.config_books_per_page) * (page - 1))\n all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\\\n .order_by(*order[0]).group_by(ub.Downloads.book_id)\n hot_books = all_books.offset(off).limit(config.config_books_per_page)\n entries = list()\n for book in hot_books:\n downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter(\n db.Books.id == book.Downloads.book_id).first()\n if downloadBook:\n entries.append(downloadBook)\n else:\n ub.delete_download(book.Downloads.book_id)\n numBooks = entries.__len__()\n pagination = Pagination(page, config.config_books_per_page, numBooks)\n return render_title_template('index.html', random=random, entries=entries, pagination=pagination,\n title=_(u\"Hot Books (Most Downloaded)\"), page=\"hot\", order=order[1])\n else:\n abort(404)", "label_name": "CWE-918", "label": 16} +{"code": "def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs):\n for extension in include_extension_inputs:\n q = q.filter(db.Books.data.any(db.Data.format == extension))\n for extension in exclude_extension_inputs:\n q = q.filter(not_(db.Books.data.any(db.Data.format == extension)))\n return q", "label_name": "CWE-918", "label": 16} +{"code": "def logout():\n if current_user is not None and current_user.is_authenticated:\n ub.delete_user_session(current_user.id, flask_session.get('_id',\"\"))\n logout_user()\n if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):\n logout_oauth_user()\n log.debug(u\"User logged out\")\n return redirect(url_for('web.login'))", "label_name": "CWE-918", "label": 16} +{"code": "def profile():\n languages = calibre_db.speaking_language()\n translations = babel.list_translations() + [LC('en')]\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n if feature_support['oauth'] and config.config_login_type == 2:\n oauth_status = get_oauth_status()\n local_oauth_check = oauth_check\n else:\n oauth_status = None\n local_oauth_check = {}\n\n if request.method == \"POST\":\n change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)\n return render_title_template(\"user_edit.html\",\n translations=translations,\n profile=1,\n languages=languages,\n content=current_user,\n kobo_support=kobo_support,\n title=_(u\"%(name)s's profile\", name=current_user.name),\n page=\"me\",\n registered_oauth=local_oauth_check,\n oauth_status=oauth_status)", "label_name": "CWE-918", "label": 16} +{"code": "def set_bookmark(book_id, book_format):\n bookmark_key = request.form[\"bookmark\"]\n ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id),\n ub.Bookmark.book_id == book_id,\n ub.Bookmark.format == book_format)).delete()\n if not bookmark_key:\n ub.session_commit()\n return \"\", 204\n\n lbookmark = ub.Bookmark(user_id=current_user.id,\n book_id=book_id,\n format=book_format,\n bookmark_key=bookmark_key)\n ub.session.merge(lbookmark)\n ub.session_commit(\"Bookmark for user {} in book {} created\".format(current_user.id, book_id))\n return \"\", 201", "label_name": "CWE-918", "label": 16} +{"code": " def test_more_custom_templates(self):\n \"\"\"\n Test custom templates and metadata\n Template is relative to collection-specific dir\n Add custom metadata and test its presence in custom search page\n \"\"\"\n custom_search = os.path.join(self.root_dir, COLLECTIONS, 'test',\n 'templates', 'search.html')\n\n # add metadata\n main(['metadata', 'test', '--set', 'some=value'])\n\n with open(custom_search, 'w+b') as fh:\n fh.write(b'overriden search page: ')\n fh.write(b'{{ metadata | tojson }}\\n')\n\n # force clear of jinja env cache to reload\n self.app.rewriterapp.jinja_env.jinja_env.cache = {}\n\n resp = self.testapp.get('/test/')\n resp.charset = 'utf-8'\n assert resp.status_int == 200\n assert resp.content_type == 'text/html'\n assert 'overriden search page: ' in resp.text\n print(resp.text)\n assert '\"some\":\"value\"' in resp.text, resp.text", "label_name": "CWE-79", "label": 1} +{"code": "def test_unicorn_render_kwarg():\n token = Token(\n TokenType.TEXT,\n \"unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'\",\n )\n unicorn_node = unicorn(None, token)\n context = {}\n actual = unicorn_node.render(context)\n\n assert \"->tested!<-\" in actual", "label_name": "CWE-79", "label": 1} +{"code": "def create(request, topic_id):\n topic = get_object_or_404(\n Topic.objects.for_access(request.user),\n pk=topic_id)\n form = NotificationCreationForm(\n user=request.user,\n topic=topic,\n data=request.POST)\n\n if form.is_valid():\n form.save()\n else:\n messages.error(request, utils.render_form_errors(form))\n\n return redirect(request.POST.get('next', topic.get_absolute_url()))", "label_name": "CWE-601", "label": 11} +{"code": "def custom_logout(request, **kwargs):\n if not request.user.is_authenticated:\n return redirect(request.GET.get('next', reverse(settings.LOGIN_URL)))\n\n if request.method == 'POST':\n return _logout_view(request, **kwargs)\n\n return render(request, 'spirit/user/auth/logout.html')", "label_name": "CWE-601", "label": 11} +{"code": "def test_remote_static(app):\n \"\"\"Test endpoint that serves files as a logged user\"\"\"\n # GIVEN a file on disk\n file = \"../demo/ACC5963A1_lanes_1234_star_sorted_sj_filtered_sorted.bed.gz\"\n\n # GIVEN a running demo app\n with app.test_client() as client:\n # GIVEN that user is logged in\n client.get(url_for(\"auto_login\"))\n with client.session_transaction() as session:\n # GIVEN that resource file exists in user session\n session[\"igv_tracks\"] = [file]\n\n # THEN the resource should be available to the user\n resp = client.get(\n url_for(\n \"alignviewers.remote_static\",\n file=file,\n )\n )\n assert resp.status_code == 200", "label_name": "CWE-918", "label": 16} +{"code": "def validate_and_sanitize_search_inputs(fn, instance, args, kwargs):\n\tkwargs.update(dict(zip(fn.__code__.co_varnames, args)))\n\tsanitize_searchfield(kwargs['searchfield'])\n\tkwargs['start'] = cint(kwargs['start'])\n\tkwargs['page_len'] = cint(kwargs['page_len'])\n\n\tif kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']):\n\t\treturn []\n\n\treturn fn(**kwargs)", "label_name": "CWE-79", "label": 1} +{"code": "def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:\n if isinstance(typ, new.BoolDefinition):\n return old.BaseType(\"bool\")\n if isinstance(typ, new.AddressDefinition):\n return old.BaseType(\"address\")\n if isinstance(typ, new.InterfaceDefinition):\n return old.InterfaceType(typ._id)\n if isinstance(typ, new.BytesMDefinition):\n m = typ._length # type: ignore\n return old.BaseType(f\"bytes{m}\")\n if isinstance(typ, new.BytesArrayDefinition):\n return old.ByteArrayType(typ.length)\n if isinstance(typ, new.StringDefinition):\n return old.StringType(typ.length)\n if isinstance(typ, new.DecimalDefinition):\n return old.BaseType(\"decimal\")\n if isinstance(typ, new.SignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"int\" + str(bits))\n if isinstance(typ, new.UnsignedIntegerAbstractType):\n bits = typ._bits # type: ignore\n return old.BaseType(\"uint\" + str(bits))\n if isinstance(typ, new.ArrayDefinition):\n return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.DynamicArrayDefinition):\n return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)\n if isinstance(typ, new.TupleDefinition):\n return old.TupleType(typ.value_type)\n if isinstance(typ, new.StructDefinition):\n return old.StructType(\n {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id\n )\n raise InvalidType(f\"unknown type {typ}\")", "label_name": "CWE-190", "label": 19} +{"code": " def __call__(self, request):\n file_fields = request.POST.getlist(\"s3file\")\n for field_name in file_fields:\n paths = request.POST.getlist(field_name)\n request.FILES.setlist(field_name, list(self.get_files_from_storage(paths)))\n\n if local_dev and request.path == \"/__s3_mock__/\":\n return views.S3MockView.as_view()(request)\n\n return self.get_response(request)", "label_name": "CWE-22", "label": 2} +{"code": " def test_process_request(self, rf):\n uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"\n\n storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"", "label_name": "CWE-22", "label": 2} +{"code": " public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {\n \n Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);\n String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);\n Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);\n \n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n if (err != null) {\n err.printStackTrace(pw);\n } else {\n pw.println(\"(none)\");\n }\n pw.flush();\n \n // If we are here there was no error servlet, so show the default error page\n String output = Launcher.RESOURCES.getString(\"WinstoneResponse.ErrorPage\",\n new String[] { sc + \"\", (msg == null ? \"\" : msg), sw.toString(),\n Launcher.RESOURCES.getString(\"ServerVersion\"),\n \"\" + new Date() });\n response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);\n Writer out = response.getWriter();\n out.write(output);\n out.flush();\n }", "label_name": "CWE-79", "label": 1} +{"code": " private boolean exractAndLoad(ArrayList errors, String version, String customPath, String resourcePath) {\n URL resource = classLoader.getResource(resourcePath);\n if( resource !=null ) {\n \n String libName = name + \"-\" + getBitModel();\n if( version !=null) {\n libName += \"-\" + version;\n }\n \n if( customPath!=null ) {\n // Try to extract it to the custom path...\n File target = file(customPath, map(libName));\n if( extract(errors, resource, target) ) {\n if( load(errors, target) ) {\n return true;\n }\n }\n }\n \n // Fall back to extracting to the tmp dir\n customPath = System.getProperty(\"java.io.tmpdir\");\n File target = file(customPath, map(libName));\n if( extract(errors, resource, target) ) {\n if( load(errors, target) ) {\n return true;\n }\n }\n }\n return false;\n }", "label_name": "CWE-94", "label": 14} +{"code": " private String getMimeType(ParsedUri pParsedUri) {\n if (pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()) != null) {\n return \"text/javascript\";\n } else {\n String mimeType = pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue());\n if (mimeType != null) {\n return mimeType;\n }\n mimeType = configuration.get(ConfigKey.MIME_TYPE);\n return mimeType != null ? mimeType : ConfigKey.MIME_TYPE.getDefaultValue();\n }\n }", "label_name": "CWE-79", "label": 1} +{"code": " public void testCallbackPost() throws URISyntaxException, IOException, java.text.ParseException {\n HttpExchange exchange = prepareExchange(\"http://localhost:8080/jolokia?callback=data\",\n \"Content-Type\",\"text/plain; charset=UTF-8\",\n \"Origin\",null\n );\n\n // Simple GET method\n prepareMemoryPostReadRequest(exchange);\n Headers header = new Headers();\n ByteArrayOutputStream out = prepareResponse(handler, exchange, header);\n\n handler.doHandle(exchange);\n\n assertEquals(header.getFirst(\"content-type\"),\"text/javascript; charset=utf-8\");\n String result = out.toString(\"utf-8\");\n assertTrue(result.endsWith(\"});\"));\n assertTrue(result.startsWith(\"data({\"));\n assertTrue(result.contains(\"\\\"used\\\"\"));\n\n assertEquals(header.getFirst(\"Cache-Control\"),\"no-cache\");\n assertEquals(header.getFirst(\"Pragma\"),\"no-cache\");\n SimpleDateFormat rfc1123Format = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss zzz\", Locale.US);\n rfc1123Format.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n String expires = header.getFirst(\"Expires\");\n String date = header.getFirst(\"Date\");\n\n Date parsedExpires = rfc1123Format.parse(expires);\n Date parsedDate = rfc1123Format.parse(date);\n assertTrue(parsedExpires.before(parsedDate) || parsedExpires.equals(parsedDate));\n Date now = new Date();\n assertTrue(parsedExpires.before(now) || parsedExpires.equals(now));\n }", "label_name": "CWE-79", "label": 1} +{"code": " private File tempFile() throws IOException {\n String newpostfix;\n String diskFilename = getDiskFilename();\n if (diskFilename != null) {\n newpostfix = '_' + diskFilename;\n } else {\n newpostfix = getPostfix();\n }\n File tmpFile;\n if (getBaseDirectory() == null) {\n // create a temporary file\n tmpFile = File.createTempFile(getPrefix(), newpostfix);\n } else {\n tmpFile = File.createTempFile(getPrefix(), newpostfix, new File(\n getBaseDirectory()));\n }\n if (deleteOnExit()) {\n // See https://github.com/netty/netty/issues/10351\n DeleteFileOnExitHook.add(tmpFile.getPath());\n }\n return tmpFile;\n }", "label_name": "CWE-379", "label": 83} +{"code": " public void testRenameTo() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n tmpFile.deleteOnExit();\n final int totalByteCount = 4096;\n byte[] bytes = new byte[totalByteCount];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n ByteBuf content = Unpooled.wrappedBuffer(bytes);\n test.setContent(content);\n boolean succ = test.renameTo(tmpFile);\n assertTrue(succ);\n FileInputStream fis = new FileInputStream(tmpFile);\n try {\n byte[] buf = new byte[totalByteCount];\n int count = 0;\n int offset = 0;\n int size = totalByteCount;\n while ((count = fis.read(buf, offset, size)) > 0) {\n offset += count;\n size -= count;\n if (offset >= totalByteCount || size <= 0) {\n break;\n }\n }\n assertArrayEquals(bytes, buf);\n assertEquals(0, fis.available());\n } finally {\n fis.close();\n }\n } finally {\n //release the ByteBuf in AbstractMemoryHttpData\n test.delete();\n }\n }", "label_name": "CWE-378", "label": 80} +{"code": " public static void beforeClass() throws IOException {\n final Random r = new Random();\n for (int i = 0; i < BYTES.length; i++) {\n BYTES[i] = (byte) r.nextInt(255);\n }\n\n tmp = File.createTempFile(\"netty-traffic\", \".tmp\");\n tmp.deleteOnExit();\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(tmp);\n out.write(BYTES);\n out.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n // ignore\n }\n }\n }\n }", "label_name": "CWE-379", "label": 83} +{"code": " public static File createTempFile(String prefix, String suffix, File directory) throws IOException {\n if (javaVersion() >= 7) {\n if (directory == null) {\n return Files.createTempFile(prefix, suffix).toFile();\n }\n return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();\n }\n if (directory == null) {\n return File.createTempFile(prefix, suffix);\n }\n File file = File.createTempFile(prefix, suffix, directory);\n // Try to adjust the perms, if this fails there is not much else we can do...\n file.setReadable(false, false);\n file.setReadable(true, true);\n return file;\n }", "label_name": "CWE-378", "label": 80} +{"code": " protected boolean evaluate(InputSource inputSource)\n {\n try\n {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n DocumentBuilder dbuilder = factory.newDocumentBuilder();\n Document doc = dbuilder.parse(inputSource);\n\n //An XPath expression could return a true or false value instead of a node.\n //eval() is a better way to determine the boolean value of the exp.\n //For compliance with legacy behavior where selecting an empty node returns true,\n //selectNodeIterator is attempted in case of a failure.\n\n CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();\n XObject result = cachedXPathAPI.eval(doc, xpath);\n if (result.bool())\n return true;\n else\n {\n NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);\n return (iterator.nextNode() != null);\n }\n\n }\n catch (Throwable e)\n {\n return false;\n }\n }", "label_name": "CWE-611", "label": 13} +{"code": " public byte[] toByteArray()\n {\n\t\t/* index || secretKeySeed || secretKeyPRF || publicSeed || root */\n int n = params.getDigestSize();\n int indexSize = (params.getHeight() + 7) / 8;\n int secretKeySize = n;\n int secretKeyPRFSize = n;\n int publicSeedSize = n;\n int rootSize = n;\n int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;\n byte[] out = new byte[totalSize];\n int position = 0;\n\t\t/* copy index */\n byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);\n XMSSUtil.copyBytesAtOffset(out, indexBytes, position);\n position += indexSize;\n\t\t/* copy secretKeySeed */\n XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);\n position += secretKeySize;\n\t\t/* copy secretKeyPRF */\n XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);\n position += secretKeyPRFSize;\n\t\t/* copy publicSeed */\n XMSSUtil.copyBytesAtOffset(out, publicSeed, position);\n position += publicSeedSize;\n\t\t/* copy root */\n XMSSUtil.copyBytesAtOffset(out, root, position);\n\t\t/* concatenate bdsState */\n byte[] bdsStateOut = null;\n try\n {\n bdsStateOut = XMSSUtil.serialize(bdsState);\n }\n catch (IOException e)\n {\n e.printStackTrace();\n throw new RuntimeException(\"error serializing bds state\");\n }\n return Arrays.concatenate(out, bdsStateOut);\n }", "label_name": "CWE-502", "label": 15} +{"code": " public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters\n .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssPrivateKey.getIndex())\n .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssPrivateKey.getPublicSeed())\n .withRoot(xmssPrivateKey.getRoot());\n\n if (xmssPrivateKey.getBdsState() != null)\n {\n keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }", "label_name": "CWE-470", "label": 84} +{"code": " protected BigInteger[] derDecode(\n byte[] encoding)\n throws IOException\n {\n ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);\n ASN1InputStream aIn = new ASN1InputStream(bIn);\n ASN1Sequence s = (ASN1Sequence)aIn.readObject();\n\n BigInteger[] sig = new BigInteger[2];\n\n sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();\n sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();\n\n return sig;\n }", "label_name": "CWE-347", "label": 25} +{"code": " protected String getExecutionPreamble()\n {\n if ( getWorkingDirectoryAsString() == null )\n {\n return null;\n }\n\n String dir = getWorkingDirectoryAsString();\n StringBuilder sb = new StringBuilder();\n sb.append( \"cd \" );\n\n sb.append( unifyQuotes( dir ) );\n sb.append( \" && \" );\n\n return sb.toString();\n }", "label_name": "CWE-78", "label": 6} +{"code": " public void testPreserveSingleQuotesOnArgument()\n {\n Shell sh = newShell();\n\n sh.setWorkingDirectory( \"/usr/bin\" );\n sh.setExecutable( \"chmod\" );\n\n String[] args = { \"\\'some arg with spaces\\'\" };\n\n List shellCommandLine = sh.getShellCommandLine( args );\n\n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n assertTrue( cli.endsWith( args[0] ) );\n }", "label_name": "CWE-78", "label": 6} +{"code": "\tpublic byte[] decrypt(final JWEHeader header,\n\t\t\t final Base64URL encryptedKey,\n\t\t\t final Base64URL iv,\n\t\t\t final Base64URL cipherText,\n\t\t\t final Base64URL authTag)\n\t\tthrows JOSEException {\n\n\t\tfinal JWEAlgorithm alg = header.getAlgorithm();\n\t\tfinal ECDH.AlgorithmMode algMode = ECDH.resolveAlgorithmMode(alg);\n\n\t\tcritPolicy.ensureHeaderPasses(header);\n\n\t\t// Get ephemeral EC key\n\t\tECKey ephemeralKey = header.getEphemeralPublicKey();\n\n\t\tif (ephemeralKey == null) {\n\t\t\tthrow new JOSEException(\"Missing ephemeral public EC key \\\"epk\\\" JWE header parameter\");\n\t\t}\n\n\t\tECPublicKey ephemeralPublicKey = ephemeralKey.toECPublicKey();\n\t\t\n\t\t// Curve check\n\t\tECDH.ensurePointOnCurve(ephemeralPublicKey, getPrivateKey());\n\n\t\t// Derive 'Z'\n\t\tSecretKey Z = ECDH.deriveSharedSecret(\n\t\t\tephemeralPublicKey,\n\t\t\tprivateKey,\n\t\t\tgetJCAContext().getKeyEncryptionProvider());\n\n\t\t// Derive shared key via concat KDF\n\t\tgetConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat\n\t\tSecretKey sharedKey = ECDH.deriveSharedKey(header, Z, getConcatKDF());\n\n\t\tfinal SecretKey cek;\n\n\t\tif (algMode.equals(ECDH.AlgorithmMode.DIRECT)) {\n\t\t\tcek = sharedKey;\n\t\t} else if (algMode.equals(ECDH.AlgorithmMode.KW)) {\n\t\t\tif (encryptedKey == null) {\n\t\t\t\tthrow new JOSEException(\"Missing JWE encrypted key\");\n\t\t\t}\n\t\t\tcek = AESKW.unwrapCEK(sharedKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider());\n\t\t} else {\n\t\t\tthrow new JOSEException(\"Unexpected JWE ECDH algorithm mode: \" + algMode);\n\t\t}\n\n\t\treturn ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext());\n\t}", "label_name": "CWE-347", "label": 25} +{"code": "\tpublic static byte[] decryptWithConcatKDF(final JWEHeader header,\n\t\t\t\t\t\t final SecretKey secretKey,\n\t\t\t\t\t\t final Base64URL encryptedKey,\n\t\t\t\t\t\t final Base64URL iv,\n\t\t\t\t\t\t final Base64URL cipherText,\n\t\t\t\t\t\t final Base64URL authTag,\n\t\t\t\t\t\t final Provider ceProvider,\n\t\t\t\t\t\t final Provider macProvider)\n\t\tthrows JOSEException {\n\n\t\tbyte[] epu = null;\n\n\t\tif (header.getCustomParam(\"epu\") instanceof String) {\n\n\t\t\tepu = new Base64URL((String)header.getCustomParam(\"epu\")).decode();\n\t\t}\n\n\t\tbyte[] epv = null;\n\n\t\tif (header.getCustomParam(\"epv\") instanceof String) {\n\n\t\t\tepv = new Base64URL((String)header.getCustomParam(\"epv\")).decode();\n\t\t}\n\n\t\tSecretKey cekAlt = LegacyConcatKDF.generateCEK(secretKey, header.getEncryptionMethod(), epu, epv);\n\n\t\tfinal byte[] plainText = AESCBC.decrypt(cekAlt, iv.decode(), cipherText.decode(), ceProvider);\n\n\t\tSecretKey cik = LegacyConcatKDF.generateCIK(secretKey, header.getEncryptionMethod(), epu, epv);\n\n\t\tString macInput = header.toBase64URL().toString() + \".\" +\n\t\t\tencryptedKey.toString() + \".\" +\n\t\t\tiv.toString() + \".\" +\n\t\t\tcipherText.toString();\n\n\t\tbyte[] mac = HMAC.compute(cik, macInput.getBytes(), macProvider);\n\n\t\tif (! ConstantTimeUtils.areEqual(authTag.decode(), mac)) {\n\n\t\t\tthrow new JOSEException(\"HMAC integrity check failed\");\n\t\t}\n\n\t\treturn plainText;\n\t}", "label_name": "CWE-354", "label": 82} +{"code": " protected DispatchHandler getDispatchHandler() {\n if (dispatchHandler == null) {\n dispatchHandler = new DispatchHandler();\n }\n\n return dispatchHandler;\n }", "label_name": "CWE-611", "label": 13} +{"code": " public void setFeature(String name, boolean value) throws SAXException {\n getXMLReader().setFeature(name, value);\n }", "label_name": "CWE-611", "label": 13} +{"code": " public void removeHandler(String path) {\n getDispatchHandler().removeHandler(path);\n }", "label_name": "CWE-611", "label": 13} +{"code": " public Document read(InputStream in, String systemId)\n throws DocumentException {\n InputSource source = new InputSource(in);\n source.setSystemId(systemId);\n if (this.encoding != null) {\n source.setEncoding(this.encoding);\n }\n\n return read(source);\n }", "label_name": "CWE-611", "label": 13} +{"code": " public void setIncludeExternalDTDDeclarations(boolean include) {\n this.includeExternalDTDDeclarations = include;\n }", "label_name": "CWE-611", "label": 13} +{"code": " public EntityResolver getEntityResolver() {\n return entityResolver;\n }", "label_name": "CWE-611", "label": 13} +{"code": " public SAXReader(boolean validating) {\n this.validating = validating;\n }", "label_name": "CWE-611", "label": 13} +{"code": " public void setXMLReaderClassName(String xmlReaderClassName)\n throws SAXException {\n setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName));\n }", "label_name": "CWE-611", "label": 13} +{"code": " private String getLocalePrefix(FacesContext context) {\n\n String localePrefix = null;\n \n localePrefix = context.getExternalContext().getRequestParameterMap().get(\"loc\");\n \n if(localePrefix != null){\n return localePrefix;\n }\n \n String appBundleName = context.getApplication().getMessageBundle();\n if (null != appBundleName) {\n \t\n Locale locale = null;\n if (context.getViewRoot() != null) {\n locale = context.getViewRoot().getLocale();\n } else {\n locale = context.getApplication().getViewHandler().calculateLocale(context);\n }\n \n try {\n ResourceBundle appBundle =\n ResourceBundle.getBundle(appBundleName,\n locale,\n Util.getCurrentLoader(ResourceManager.class));\n localePrefix =\n appBundle\n .getString(ResourceHandler.LOCALE_PREFIX);\n } catch (MissingResourceException mre) { \n if (LOGGER.isLoggable(Level.FINEST)) {\n LOGGER.log(Level.FINEST, \"Ignoring missing resource\", mre);\n }\n }\n }\n return localePrefix;\n\n }", "label_name": "CWE-22", "label": 2} +{"code": " public static void main(String[] args) {\n\n // Will serve all static file are under \"/public\" in classpath if the route isn't consumed by others routes.\n staticFileLocation(\"/public\");\n\n get(\"/hello\", (request, response) -> {\n return \"Hello World!\";\n });\n }", "label_name": "CWE-22", "label": 2} +{"code": " void rawUnicode() {\n // 2- and 3-byte UTF-8\n final PathAndQuery res1 = PathAndQuery.parse(\"/\\u00A2?\\u20AC\"); // \u00a2 and \u20ac\n assertThat(res1).isNotNull();\n assertThat(res1.path()).isEqualTo(\"/%C2%A2\");\n assertThat(res1.query()).isEqualTo(\"%E2%82%AC\");\n\n // 4-byte UTF-8\n final PathAndQuery res2 = PathAndQuery.parse(\"/\\uD800\\uDF48\"); // \ud800\udf48\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/%F0%90%8D%88\");\n assertThat(res2.query()).isNull();\n\n // 5- and 6-byte forms are only theoretically possible, so we won't test them here.\n }", "label_name": "CWE-22", "label": 2} +{"code": " void doubleDots() {\n assertThat(PathAndQuery.parse(\"/..\")).isNull();\n assertThat(PathAndQuery.parse(\"/../\")).isNull();\n assertThat(PathAndQuery.parse(\"/../foo\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/..\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/../\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/../bar\")).isNull();\n\n // Escaped\n assertThat(PathAndQuery.parse(\"/.%2e\")).isNull();\n assertThat(PathAndQuery.parse(\"/%2E./\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/.%2e\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/%2E./\")).isNull();\n\n // Not the double dots we are looking for.\n final PathAndQuery res = PathAndQuery.parse(\"/..a\");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/..a\");\n final PathAndQuery res2 = PathAndQuery.parse(\"/a..\");\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/a..\");\n }", "label_name": "CWE-22", "label": 2} +{"code": " void controlChars() {\n assertThat(PathAndQuery.parse(\"/\\0\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\nb\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\u007fb\")).isNull();\n\n // Escaped\n assertThat(PathAndQuery.parse(\"/%00\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%09b\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%0ab\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%0db\")).isNull();\n assertThat(PathAndQuery.parse(\"/a%7fb\")).isNull();\n\n // With query string\n assertThat(PathAndQuery.parse(\"/\\0?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\tb?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\nb?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\rb?c\")).isNull();\n assertThat(PathAndQuery.parse(\"/a\\u007fb?c\")).isNull();\n\n // With query string with control chars\n assertThat(PathAndQuery.parse(\"/?\\0\")).isNull();\n assertThat(PathAndQuery.parse(\"/?%00\")).isNull();\n assertThat(PathAndQuery.parse(\"/?a\\u007fb\")).isNull();\n assertThat(PathAndQuery.parse(\"/?a%7Fb\")).isNull();\n // However, 0x0A, 0x0D, 0x09 should be accepted in a query string.\n assertThat(PathAndQuery.parse(\"/?a\\tb\").query()).isEqualTo(\"a%09b\");\n assertThat(PathAndQuery.parse(\"/?a\\nb\").query()).isEqualTo(\"a%0Ab\");\n assertThat(PathAndQuery.parse(\"/?a\\rb\").query()).isEqualTo(\"a%0Db\");\n assertThat(PathAndQuery.parse(\"/?a%09b\").query()).isEqualTo(\"a%09b\");\n assertThat(PathAndQuery.parse(\"/?a%0Ab\").query()).isEqualTo(\"a%0Ab\");\n assertThat(PathAndQuery.parse(\"/?a%0Db\").query()).isEqualTo(\"a%0Db\");\n }", "label_name": "CWE-22", "label": 2} +{"code": " void space() {\n final PathAndQuery res = PathAndQuery.parse(\"/ ? \");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/%20\");\n assertThat(res.query()).isEqualTo(\"+\");\n\n final PathAndQuery res2 = PathAndQuery.parse(\"/%20?%20\");\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/%20\");\n assertThat(res2.query()).isEqualTo(\"+\");\n }", "label_name": "CWE-22", "label": 2} +{"code": "\t public String getHeader(String name) {\n\t //logger.info(\"Ineader .. parameter .......\");\n\t String value = super.getHeader(name);\n\t if (value == null)\n\t return null;\n\t //logger.info(\"Ineader RequestWrapper ........... value ....\");\n\t return cleanXSS(value);\n\t }", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {\n\t\t\n\t\t\n\t\t\n\t\treturn this.displayCategory(friendlyUrl,ref,model,request,response,locale);\n\t}", "label_name": "CWE-79", "label": 1} +{"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tencryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label_name": "CWE-125", "label": 47} +{"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tencryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label_name": "CWE-787", "label": 24} +{"code": "\tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n\t\t\tbyte[] ciphertext, int ciphertextOffset, int length)\n\t\t\tthrows ShortBufferException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the plaintext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (space < 16 || length > (space - 16))\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t\tint result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset);\n\t\t\tcipher.doFinal(ciphertext, ciphertextOffset + result);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, length);\n\t\tghash.pad(ad != null ? ad.length : 0, length);\n\t\tghash.finish(ciphertext, ciphertextOffset + length, 16);\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\tciphertext[ciphertextOffset + length + index] ^= hashKey[index];\n\t\treturn length + 16;\n\t}", "label_name": "CWE-125", "label": 47} +{"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the ciphertext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, dataLen);\n\t\tghash.pad(ad != null ? ad.length : 0, dataLen);\n\t\tghash.finish(iv, 0, 16);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\ttry {\n\t\t\tint result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);\n\t\t\tcipher.doFinal(plaintext, plaintextOffset + result);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\treturn dataLen;\n\t}", "label_name": "CWE-125", "label": 47} +{"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the ciphertext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tpoly.update(ciphertext, ciphertextOffset, dataLen);\n\t\tfinish(ad, dataLen);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\tencrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);\n\t\treturn dataLen;\n\t}", "label_name": "CWE-787", "label": 24} +{"code": " static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) {\n Ruby runtime = context.getRuntime();\n XmlSchema xmlSchema = (XmlSchema) NokogiriService.XML_SCHEMA_ALLOCATOR.allocate(runtime, klazz);\n xmlSchema.setInstanceVariable(\"@errors\", runtime.newEmptyArray());\n\n try {\n SchemaErrorHandler error_handler = new SchemaErrorHandler(context.getRuntime(), (RubyArray)xmlSchema.getInstanceVariable(\"@errors\"));\n Schema schema = xmlSchema.getSchema(source, context.getRuntime().getCurrentDirectory(), context.getRuntime().getInstanceConfig().getScriptFileName(), error_handler);\n xmlSchema.setValidator(schema.newValidator());\n return xmlSchema;\n } catch (SAXException ex) {\n throw context.getRuntime().newRuntimeError(\"Could not parse document: \" + ex.getMessage());\n }\n }", "label_name": "CWE-611", "label": 13} +{"code": " public DefaultFileSystemResourceLoader() {\n this.baseDirPath = Optional.empty();\n }", "label_name": "CWE-22", "label": 2} +{"code": " protected List readPropertySourceListFromFiles(String files) {\n List propertySources = new ArrayList<>();\n Collection propertySourceLoaders = getPropertySourceLoaders();\n Optional> filePathList = Optional.ofNullable(files)\n .filter(value -> !value.isEmpty())\n .map(value -> value.split(FILE_SEPARATOR))\n .map(Arrays::asList)\n .map(Collections::unmodifiableList);\n\n filePathList.ifPresent(list -> {\n if (!list.isEmpty()) {\n int order = AbstractPropertySourceLoader.DEFAULT_POSITION + 50;\n for (String filePath: list) {\n if (!propertySourceLoaders.isEmpty()) {\n String extension = NameUtils.extension(filePath);\n String fileName = NameUtils.filename(filePath);\n Optional propertySourceLoader = Optional.ofNullable(loaderByFormatMap.get(extension));\n if (propertySourceLoader.isPresent()) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Reading property sources from loader: {}\", propertySourceLoader);\n }\n Optional> properties = readPropertiesFromLoader(fileName, filePath, propertySourceLoader.get());\n if (properties.isPresent()) {\n propertySources.add(PropertySource.of(filePath, properties.get(), order));\n }\n order++;\n } else {\n throw new ConfigurationException(\"Unsupported properties file format: \" + fileName);\n }\n }\n }\n }\n });\n return propertySources;\n }", "label_name": "CWE-22", "label": 2} +{"code": "\tpublic ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, \n\t\t\tGitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, \n\t\t\tWicketServlet wicketServlet, WebSocketManager webSocketManager, \n\t\t\tAttachmentUploadServlet attachmentUploadServlet, ServletContainer jerseyServlet) {\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.shiroFilter = shiroFilter;\n this.gitFilter = gitFilter;\n\t\tthis.preReceiveServlet = preReceiveServlet;\n\t\tthis.postReceiveServlet = postReceiveServlet;\n\t\tthis.wicketServlet = wicketServlet;\n\t\tthis.webSocketManager = webSocketManager;\n\t\tthis.jerseyServlet = jerseyServlet;\n\t\tthis.attachmentUploadServlet = attachmentUploadServlet;\n\t}", "label_name": "CWE-502", "label": 15} +{"code": " public Operation.OperationResult executeFixedCostOperation(\n final MessageFrame frame, final EVM evm) {\n Bytes shiftAmount = frame.popStackItem();\n if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {\n frame.popStackItem();\n frame.pushStackItem(UInt256.ZERO);\n } else {\n final int shiftAmountInt = shiftAmount.toInt();\n final Bytes value = leftPad(frame.popStackItem());\n\n if (shiftAmountInt >= 256) {\n frame.pushStackItem(UInt256.ZERO);\n } else {\n frame.pushStackItem(value.shiftLeft(shiftAmountInt));\n }\n }\n return successResponse;\n }", "label_name": "CWE-681", "label": 59} +{"code": " public HtmlElement content(String body) {\n return content(new TextElement(body));\n }", "label_name": "CWE-79", "label": 1} +{"code": " private String attributeToString(Object attribute) {\n if (attribute == null) {\n return null;\n }\n\n if (attribute instanceof Number) {\n return attribute.toString();\n } else if (attribute instanceof String) {\n return (String) attribute;\n } else if (attribute instanceof Element) {\n return ((Element) attribute).getTextContent();\n } else {\n logger.warn(\"This library currently doesn't handle attributes of type [\" + attribute.getClass() + \"]\");\n }\n\n return null;\n }", "label_name": "CWE-611", "label": 13} +{"code": " protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {\n String secret = getSecret();\n Key key = new SecretKeySpec(Decoders.BASE64.decode(secret), getSignatureAlgorithm().getJcaName());\n \n Jwt jwt = Jwts.parser().\n setSigningKey(key).\n parse((String) token.getPrincipal());\n Map principal = getPrincipal(jwt);\n return new SimpleAuthenticationInfo(principal, ((String) token.getCredentials()).toCharArray(), getName());\n }", "label_name": "CWE-347", "label": 25} +{"code": " private String getSkinResourcePath(String resource)\n {\n String skinFolder = getSkinFolder();\n String resourcePath = skinFolder + resource;\n\n // Prevent inclusion of templates from other directories\n Path normalizedResource = Paths.get(resourcePath).normalize();\n // Protect against directory attacks.\n if (!normalizedResource.startsWith(skinFolder)) {\n LOGGER.warn(\"Direct access to skin file [{}] refused. Possible break-in attempt!\", normalizedResource);\n return null;\n }\n\n return resourcePath;\n }", "label_name": "CWE-22", "label": 2} +{"code": " public int addWorkUnit(WorkUnit workUnit, long fileModificationTimeInMillis, long fileSize) {\n workUnitList.add(workUnit);\n if (fileModificationTimeInMillis < oldestFileModificationTime) {\n oldestFileModificationTime = fileModificationTimeInMillis;\n }\n if (fileModificationTimeInMillis > youngestFileModificationTime) {\n youngestFileModificationTime = fileModificationTimeInMillis;\n }\n totalFileSize += fileSize;\n return size();\n }", "label_name": "CWE-502", "label": 15} +{"code": " void setPaths(final String s) {\n try {\n final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes(\"8859_1\")));\n this.paths = (WorkBundle) ois.readObject();\n } catch (Exception e) {\n logger.error(\"Cannot deserialize WorkBundle using {} bytes\", s.length(), e);\n throw new IllegalArgumentException(\"Cannot deserialize WorkBundle\");\n }\n }", "label_name": "CWE-502", "label": 15} +{"code": " public static Object deserialize(final String s) {\n ObjectInputStream ois = null;\n try {\n ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes(\"8859_1\")));\n return ois.readObject();\n } catch (Exception e) {\n logger.error(\"Cannot deserialize payload using \" + (s == null ? -1 : s.length()) + \" bytes\", e);\n throw new IllegalArgumentException(\"Cannot deserialize payload\");\n } finally {\n if (ois != null) {\n try {\n ois.close();\n } catch (IOException ignore) {\n // empty catch block\n }\n }\n }\n }", "label_name": "CWE-502", "label": 15} +{"code": " private static void writeBaloFile(HttpURLConnection conn, Path baloPath, String fullModuleName,\n long resContentLength) {\n try (InputStream inputStream = conn.getInputStream();\n FileOutputStream outputStream = new FileOutputStream(baloPath.toString())) {\n writeAndHandleProgress(inputStream, outputStream, resContentLength / 1024, fullModuleName);\n } catch (IOException e) {\n createError(\"error occurred copying the balo file: \" + e.getMessage());\n }\n }", "label_name": "CWE-306", "label": 79} +{"code": "\tprotected List findEfficiencyStatements(IdentityRef identity) {\n\t\tList efficiencyStatements = new ArrayList<>();\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"select statement from effstatement as statement\")\n\t\t .append(\" where statement.identity.key=:identityKey\");\n\n\t\tList statements = dbInstance.getCurrentEntityManager()\n\t\t\t\t.createQuery(sb.toString(), UserEfficiencyStatementImpl.class)\n\t\t\t\t.setParameter(\"identityKey\", identity.getKey())\n\t\t\t\t.getResultList();\n\t\tfor(UserEfficiencyStatementImpl statement:statements) {\n\t\t\tif(StringHelper.containsNonWhitespace(statement.getStatementXml())) {\n\t\t\t\tEfficiencyStatement s = (EfficiencyStatement)xstream.fromXML(statement.getStatementXml());\n\t\t\t\tefficiencyStatements.add(s);\n\t\t\t}\n\t\t}\n\t\treturn efficiencyStatements;\n\t}", "label_name": "CWE-91", "label": 78} +{"code": "\tpublic Controller getMediaController(UserRequest ureq, WindowControl wControl, Media media, MediaRenderingHints hints) {\n\t\tString statementXml = media.getContent();\n\t\tEfficiencyStatement statement = null;\n\t\tif(StringHelper.containsNonWhitespace(statementXml)) {\n\t\t\ttry {\n\t\t\t\tstatement = (EfficiencyStatement)myXStream.fromXML(statementXml);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"Cannot load efficiency statement from artefact\", e);\n\t\t\t}\n\t\t}\n\t\tCertificateAndEfficiencyStatementController ctrl = new CertificateAndEfficiencyStatementController(wControl, ureq, statement);\n\t\tctrl.disableMediaCollector();\n\t\treturn ctrl;\n\t}", "label_name": "CWE-91", "label": 78} +{"code": "\tpublic void testUpdateMapper_serializade() {\n\t\t//create a mapper\n\t\tString mapperId = UUID.randomUUID().toString();\n\t\tString sessionId = UUID.randomUUID().toString().substring(0, 32);\n\t\tPersistentMapper sMapper = new PersistentMapper(\"mapper-to-persist-bis\");\n\t\tPersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1);\n\t\tAssert.assertNotNull(pMapper);\n\t\tdbInstance.commitAndCloseSession();\n\t\t\n\t\t//load the mapper\n\t\tPersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);\n\t\tAssert.assertNotNull(loadedMapper);\n\t\tObject objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;\n\t\tAssert.assertEquals(\"mapper-to-persist-bis\", sMapperReloaded.getKey());\n\t\t\n\t\t//update\n\t\tPersistentMapper sMapper2 = new PersistentMapper(\"mapper-to-update\");\n\t\tboolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, -1);\n\t\tAssert.assertTrue(updated);\n\t\tdbInstance.commitAndCloseSession();\n\t\t\n\t\t//load the updated mapper\n\t\tPersistedMapper loadedMapper2 = mapperDao.loadByMapperId(mapperId);\n\t\tAssert.assertNotNull(loadedMapper2);\n\t\tObject objReloaded2 = XStreamHelper.createXStreamInstance().fromXML(loadedMapper2.getXmlConfiguration());\n\t\tAssert.assertTrue(objReloaded2 instanceof PersistentMapper);\n\t\tPersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2;\n\t\tAssert.assertEquals(\"mapper-to-update\", sMapperReloaded2.getKey());\n\t}", "label_name": "CWE-91", "label": 78} +{"code": "\tprotected static RootSearcher searchRootDirectory(Path fPath)\n\tthrows IOException {\n\t\tRootSearcher rootSearcher = new RootSearcher();\n\t\tFiles.walkFileTree(fPath, rootSearcher);\n\t\treturn rootSearcher;\n\t}", "label_name": "CWE-22", "label": 2} +{"code": "\tpublic static ResourceEvaluation evaluate(File file, String filename) {\n\t\tResourceEvaluation eval = new ResourceEvaluation();\n\t\ttry {\n\t\t\tImsManifestFileFilter visitor = new ImsManifestFileFilter();\n\t\t\tPath fPath = PathUtils.visit(file, filename, visitor);\n\t\t\tif(visitor.isValid()) {\n\t\t\t\tPath realManifestPath = visitor.getManifestPath();\n\t\t\t\tPath manifestPath = fPath.resolve(realManifestPath);\n\t\t\t\t\n\t\t\t\tRootSearcher rootSearcher = new RootSearcher();\n\t\t\t\tFiles.walkFileTree(fPath, rootSearcher);\n\t\t\t\tif(rootSearcher.foundRoot()) {\n\t\t\t\t\tmanifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);\n\t\t\t\t} else {\n\t\t\t\t\tmanifestPath = fPath.resolve(IMS_MANIFEST);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDocument doc = IMSLoader.loadIMSDocument(manifestPath);\n\t\t\t\tif(validateImsManifest(doc)) {\n\t\t\t\t\teval.setValid(true);\n\t\t\t\t} else {\n\t\t\t\t\teval.setValid(false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\teval.setValid(false);\n\t\t\t}\n\t\t\tPathUtils.closeSubsequentFS(fPath);\n\t\t} catch (IOException | IllegalArgumentException e) {\n\t\t\tlog.error(\"\", e);\n\t\t\teval.setValid(false);\n\t\t}\n\t\treturn eval;\n\t}", "label_name": "CWE-22", "label": 2} +{"code": "\tprotected Response attachToPost(Message mess, String filename, InputStream file, HttpServletRequest request) {\n\t\tIdentity identity = getIdentity(request);\n\t\tif(identity == null) {\n\t\t\treturn Response.serverError().status(Status.UNAUTHORIZED).build();\n\t\t} else if (!identity.equalsByPersistableKey(mess.getCreator())) {\n\t\t\tif(mess.getModifier() == null || !identity.equalsByPersistableKey(mess.getModifier())) {\n\t\t\t\treturn Response.serverError().status(Status.UNAUTHORIZED).build();\n\t\t\t}\n\t\t}\n\n\t\tVFSContainer container = fom.getMessageContainer(mess.getForum().getKey(), mess.getKey());\n\t\tVFSItem item = container.resolve(filename);\n\t\tVFSLeaf attachment = null;\n\t\tif(item == null) {\n\t\t\tattachment = container.createChildLeaf(filename);\n\t\t} else {\n\t\t\tfilename = VFSManager.rename(container, filename);\n\t\t\tif(filename == null) {\n\t\t\t\treturn Response.serverError().status(Status.NOT_ACCEPTABLE).build();\n\t\t\t}\n\t\t\tattachment = container.createChildLeaf(filename);\n\t\t}\n\t\t\n\n\t\ttry(OutputStream out = attachment.getOutputStream(false)) {\n\t\t\tIOUtils.copy(file, out);\n\t\t} catch (IOException e) {\n\t\t\treturn Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();\n\t\t} finally {\n\t\t\tFileUtils.closeSafely(file);\n\t\t}\n\t\treturn Response.ok().build();\n\t}", "label_name": "CWE-22", "label": 2} +{"code": " private void ensureCorrectTheme(Intent data) {\n String oldListLayout = data.getStringExtra(SettingsActivity.SP_FEED_LIST_LAYOUT);\n String newListLayout = mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT,\"0\");\n\n if (ThemeChooser.themeRequiresRestartOfUI() || !newListLayout.equals(oldListLayout)) {\n NewsReaderListActivity.this.recreate();\n } else if (data.hasExtra(SettingsActivity.CACHE_CLEARED)) {\n resetUiAndStartSync();\n }\n }", "label_name": "CWE-829", "label": 86} +{"code": " public static DocumentBuilderFactory getNsAwareDocumentBuilderFactory() throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(true);\n setFeature(dbf, \"http://apache.org/xml/features/disallow-doctype-decl\");\n return dbf;\n }", "label_name": "CWE-611", "label": 13} +{"code": " public void testFormat() throws Exception {\n assertEquals(\" c\", format(\"c\", 1).replaceAll(\"[\\r\\n]\", \"\"));\n assertEquals(\" c\", format(\"c\", 3).replaceAll(\"[\\r\\n]\", \"\"));\n assertEquals(\"c\", format(\"c\", -21));\n\n assertThrows(IllegalArgumentException.class, () -> format(\"c\", 0));\n\n // check if the XXE protection is enabled\n String xxeAttack = \"\\n\" + \" \\n\" + \" ]>\" + \"&xxe;\";\n assertEquals(xxeAttack, format(xxeAttack, 1));\n\n // wrongly formatted XML\n assertEquals(\"c\", format(\"c\", 1));\n }", "label_name": "CWE-611", "label": 13} +{"code": "\tpublic CommandExecutionResult createBinary(String code, String full, boolean compact) {\n\t\tfinal Player player = new PlayerBinary(full, getSkinParam(), ruler, compactByDefault);\n\t\tplayers.put(code, player);\n\t\treturn CommandExecutionResult.ok();\n\t}", "label_name": "CWE-918", "label": 16} +{"code": "\tpublic static boolean isTransparent(HColor back) {\n\t\tif (back == TRANSPARENT) {\n\t\t\treturn true;\n\t\t}\n\t\tif (back instanceof HColorBackground && ((HColorBackground) back).getBack() == TRANSPARENT) {\n\t\t\treturn true;\n\t\t}\n\t\tif (back instanceof HColorSimple && ((HColorSimple) back).isTransparent()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "label_name": "CWE-918", "label": 16} +{"code": "\tprotected void doGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException\n\t{\n // GAE can't serve dot prefixed folders\n String uri = request.getRequestURI().replace(\"/.\", \"/\");\n\n if (uri.toLowerCase().contains(\".json\"))\n {\n \tresponse.setContentType(\"application/json\");\n }\n\n // Serve whatever was requested from .well-known\n try (InputStream in = getServletContext().getResourceAsStream(uri))\n {\n if (in == null)\n {\n \tresponse.sendError(404);\n return;\n }\n \n byte[] buffer = new byte[8192];\n int count;\n\n while ((count = in.read(buffer)) > 0)\n {\n \tresponse.getOutputStream().write(buffer, 0, count);\n }\n \n response.getOutputStream().flush();\n response.getOutputStream().close();\n }\n }", "label_name": "CWE-22", "label": 2} +{"code": " callback: (request: PublishRequest, response: PublishResponse) => void;", "label_name": "CWE-770", "label": 37} +{"code": "\tprivate void initializeVelocity() {\n\t\tif (velocityEngine == null) {\n\t\t\tvelocityEngine = new VelocityEngine();\n\t\t\t\n\t\t\tProperties props = new Properties();\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG, \"startup_wizard_vel.log\");\n\t\t\t// Linux requires setting logging properties to initialize Velocity Context.\n\t\t\tprops.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,\n\t\t\t \"org.apache.velocity.runtime.log.CommonsLogLogChute\");\n\t\t\tprops.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, \"initial_wizard_velocity\");\n\t\t\t\n\t\t\t// so the vm pages can import the header/footer\n\t\t\tprops.setProperty(RuntimeConstants.RESOURCE_LOADER, \"class\");\n\t\t\tprops.setProperty(\"class.resource.loader.description\", \"Velocity Classpath Resource Loader\");\n\t\t\tprops.setProperty(\"class.resource.loader.class\",\n\t\t\t \"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader\");\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvelocityEngine.init(props);\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tlog.error(\"velocity init failed, because: \" + e);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-22", "label": 2} +{"code": " public void getLogFile(@PathVariable(\"filename\") String fileName, HttpServletResponse response) throws Exception {\n InputStream inputStream = null;\n try {\n \t//Validate/Sanitize user input filename using a standard library, prevent from path traversal \n String logFileName = getFilePath() + File.separator + FilenameUtils.getName(fileName);\n File fileToDownload = new File(logFileName);\n inputStream = new FileInputStream(fileToDownload);\n response.setContentType(\"application/force-download\");\n response.setHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n IOUtils.copy(inputStream, response.getOutputStream());\n response.flushBuffer();\n } catch (Exception e) {\n logger.debug(\"Request could not be completed at this moment. Please try again.\");\n logger.debug(e.getStackTrace().toString());\n throw e;\n } finally {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException e) {\n logger.debug(e.getStackTrace().toString());\n throw e;\n }\n }\n }\n\n }", "label_name": "CWE-22", "label": 2} +{"code": "void CClient::EchoMessage(const CMessage& Message) {\n CMessage EchoedMessage = Message;\n for (CClient* pClient : GetClients()) {\n if (pClient->HasEchoMessage() ||\n (pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||\n pClient->HasSelfMessage()))) {\n EchoedMessage.SetNick(GetNickMask());\n pClient->PutClient(EchoedMessage);\n }\n }\n}", "label_name": "CWE-476", "label": 46} +{"code": "BOOL nego_read_request(rdpNego* nego, wStream* s)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;\n\n\tif (!tpkt_read_header(s, &length))\n\t\treturn FALSE;\n\n\tif (!tpdu_read_connection_request(s, &li, length))\n\t\treturn FALSE;\n\n\tif (li != Stream_GetRemainingLength(s) + 6)\n\t{\n\t\tWLog_ERR(TAG, \"Incorrect TPDU length indicator.\");\n\t\treturn FALSE;\n\t}\n\n\tif (!nego_read_request_token_or_cookie(nego, s))\n\t{\n\t\tWLog_ERR(TAG, \"Failed to parse routing token or cookie.\");\n\t\treturn FALSE;\n\t}\n\n\tif (Stream_GetRemainingLength(s) >= 8)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */\n\n\t\tif (type != TYPE_RDP_NEG_REQ)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Incorrect negotiation request type %\" PRIu8 \"\", type);\n\t\t\treturn FALSE;\n\t\t}\n\n\t\tnego_process_negotiation_request(nego, s);\n\t}\n\n\treturn tpkt_ensure_stream_consumed(s, length);\n}", "label_name": "CWE-125", "label": 47} +{"code": "NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId,\n size_t* pcbAvPairListRemaining)\n{\n\tsize_t cbAvPair = cbAvPairList;\n\tNTLM_AV_PAIR* pAvPair = pAvPairList;\n\n\tif (!ntlm_av_pair_check(pAvPair, cbAvPair))\n\t\tpAvPair = NULL;\n\n\twhile (pAvPair)\n\t{\n\t\tUINT16 id = ntlm_av_pair_get_id(pAvPair);\n\n\t\tif (id == AvId)\n\t\t\tbreak;\n\t\tif (id == MsvAvEOL)\n\t\t{\n\t\t\tpAvPair = NULL;\n\t\t\tbreak;\n\t\t}\n\n\t\tpAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);\n\t}\n\n\tif (!pAvPair)\n\t\tcbAvPair = 0;\n\tif (pcbAvPairListRemaining)\n\t\t*pcbAvPairListRemaining = cbAvPair;\n\n\treturn pAvPair;\n}", "label_name": "CWE-125", "label": 47} +{"code": "Variant HHVM_METHOD(XMLReader, expand,\n const Variant& basenode /* = null */) {\n auto* data = Native::data(this_);\n req::ptr doc;\n xmlDocPtr docp = nullptr;\n SYNC_VM_REGS_SCOPED();\n\n if (!basenode.isNull()) {\n auto dombasenode = Native::data(basenode.toObject());\n doc = dombasenode->doc();\n docp = doc->docp();\n if (docp == nullptr) {\n raise_warning(\"Invalid State Error\");\n return false;\n }\n }\n\n if (data->m_ptr) {\n xmlNodePtr node = xmlTextReaderExpand(data->m_ptr);\n if (node == nullptr) {\n raise_warning(\"An Error Occurred while expanding\");\n return false;\n } else {\n xmlNodePtr nodec = xmlDocCopyNode(node, docp, 1);\n if (nodec == nullptr) {\n raise_notice(\"Cannot expand this node type\");\n return false;\n } else {\n return php_dom_create_object(nodec, doc);\n }\n }\n }\n\n raise_warning(\"Load Data before trying to read\");\n return false;\n}", "label_name": "CWE-22", "label": 2} +{"code": "void do_change_user(int afdt_fd) {\n std::string uname;\n lwp_read(afdt_fd, uname);\n if (!uname.length()) return;\n\n auto buf = PasswdBuffer{};\n struct passwd *pw;\n if (getpwnam_r(uname.c_str(), &buf.ent, buf.data.get(), buf.size, &pw)) {\n // TODO(alexeyt) should we log something and/or fail to start?\n return;\n }\n if (!pw) {\n // TODO(alexeyt) should we log something and/or fail to start?\n return;\n }\n\n if (pw->pw_gid) {\n initgroups(pw->pw_name, pw->pw_gid);\n setgid(pw->pw_gid);\n }\n if (pw->pw_uid) {\n setuid(pw->pw_uid);\n }\n}", "label_name": "CWE-22", "label": 2} +{"code": "bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n assertx(m_len != -1);\n if (whence == SEEK_CUR) {\n if (offset > 0 && offset < bufferedLen()) {\n setReadPosition(getReadPosition() + offset);\n setPosition(getPosition() + offset);\n return true;\n }\n offset += getPosition();\n whence = SEEK_SET;\n }\n\n // invalidate the current buffer\n setWritePosition(0);\n setReadPosition(0);\n if (whence == SEEK_SET) {\n m_cursor = offset;\n } else {\n assertx(whence == SEEK_END);\n m_cursor = m_len + offset;\n }\n setPosition(m_cursor);\n return true;\n}", "label_name": "CWE-787", "label": 24} +{"code": " int size() const {\n return m_str ? m_str->size() : 0;\n }", "label_name": "CWE-787", "label": 24} +{"code": "Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n const String& key,\n const String& iv) {\n auto pm = get_valid_mcrypt_resource(td);\n if (!pm) {\n return false;\n }\n\n int max_key_size = mcrypt_enc_get_key_size(pm->m_td);\n int iv_size = mcrypt_enc_get_iv_size(pm->m_td);\n\n if (key.empty()) {\n raise_warning(\"Key size is 0\");\n }\n\n unsigned char *key_s = (unsigned char *)malloc(key.size());\n memset(key_s, 0, key.size());\n\n unsigned char *iv_s = (unsigned char *)malloc(iv_size + 1);\n memset(iv_s, 0, iv_size + 1);\n\n int key_size;\n if (key.size() > max_key_size) {\n raise_warning(\"Key size too large; supplied length: %d, max: %d\",\n key.size(), max_key_size);\n key_size = max_key_size;\n } else {\n key_size = key.size();\n }\n memcpy(key_s, key.data(), key.size());\n\n if (iv.size() != iv_size) {\n raise_warning(\"Iv size incorrect; supplied length: %d, needed: %d\",\n iv.size(), iv_size);\n }\n memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n\n mcrypt_generic_deinit(pm->m_td);\n int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);\n\n /* If this function fails, close the mcrypt module to prevent crashes\n * when further functions want to access this resource */\n if (result < 0) {\n pm->close();\n switch (result) {\n case -3:\n raise_warning(\"Key length incorrect\");\n break;\n case -4:\n raise_warning(\"Memory allocation error\");\n break;\n case -1:\n default:\n raise_warning(\"Unknown error\");\n break;\n }\n } else {\n pm->m_init = true;\n }\n\n free(iv_s);\n free(key_s);\n return result;\n}", "label_name": "CWE-787", "label": 24} +{"code": "TypedValue HHVM_FUNCTION(substr_compare,\n const String& main_str,\n const String& str,\n int offset,\n int length /* = INT_MAX */,\n bool case_insensitivity /* = false */) {\n int s1_len = main_str.size();\n int s2_len = str.size();\n\n if (length <= 0) {\n raise_warning(\"The length must be greater than zero\");\n return make_tv(false);\n }\n\n if (offset < 0) {\n offset = s1_len + offset;\n if (offset < 0) offset = 0;\n }\n\n if (offset >= s1_len) {\n raise_warning(\"The start position cannot exceed initial string length\");\n return make_tv(false);\n }\n\n int cmp_len = s1_len - offset;\n if (cmp_len < s2_len) cmp_len = s2_len;\n if (cmp_len > length) cmp_len = length;\n\n const char *s1 = main_str.data();\n if (case_insensitivity) {\n return tvReturn(bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len));\n }\n return tvReturn(string_ncmp(s1 + offset, str.data(), cmp_len));\n}", "label_name": "CWE-787", "label": 24} +{"code": "static bool extractFileTo(zip* zip, const std::string &file, std::string& to,\n char* buf, size_t len) {\n auto sep = file.rfind('/');\n if (sep != std::string::npos) {\n auto path = to + file.substr(0, sep);\n if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {\n return false;\n }\n\n if (sep == file.length() - 1) {\n return true;\n }\n }\n\n to.append(file);\n struct zip_stat zipStat;\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto zipFile = zip_fopen_index(zip, zipStat.index, 0);\n FAIL_IF_INVALID_PTR(zipFile);\n\n auto outFile = fopen(to.c_str(), \"wb\");\n if (outFile == nullptr) {\n zip_fclose(zipFile);\n return false;\n }\n\n for (auto n = zip_fread(zipFile, buf, len); n != 0;\n n = zip_fread(zipFile, buf, len)) {\n if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {\n zip_fclose(zipFile);\n fclose(outFile);\n remove(to.c_str());\n return false;\n }\n }\n\n zip_fclose(zipFile);\n if (fclose(outFile) != 0) {\n return false;\n }\n\n return true;\n}", "label_name": "CWE-22", "label": 2} +{"code": "static String HHVM_FUNCTION(bcadd, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n if (scale < 0) scale = BCG(bc_precision);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_add(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n return ret;\n}", "label_name": "CWE-190", "label": 19} +{"code": "static String HHVM_FUNCTION(bcmul, const String& left, const String& right,\n int64_t scale /* = -1 */) {\n if (scale < 0) scale = BCG(bc_precision);\n bc_num first, second, result;\n bc_init_num(&first);\n bc_init_num(&second);\n bc_init_num(&result);\n php_str2num(&first, (char*)left.data());\n php_str2num(&second, (char*)right.data());\n bc_multiply(first, second, &result, scale);\n if (result->n_scale > scale) {\n result->n_scale = scale;\n }\n String ret(bc_num2str(result), AttachString);\n bc_free_num(&first);\n bc_free_num(&second);\n bc_free_num(&result);\n return ret;\n}", "label_name": "CWE-190", "label": 19} +{"code": "jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend)\n{\n\tjas_matrix_t *matrix;\n\tassert(xstart <= xend && ystart <= yend);\n\tif (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {\n\t\treturn 0;\n\t}\n\tmatrix->xstart_ = xstart;\n\tmatrix->ystart_ = ystart;\n\tmatrix->xend_ = xend;\n\tmatrix->yend_ = yend;\n\treturn matrix;\n}", "label_name": "CWE-190", "label": 19} +{"code": "jas_matrix_t *jas_matrix_create(int numrows, int numcols)\n{\n\tjas_matrix_t *matrix;\n\tint i;\n\tsize_t size;\n\n\tmatrix = 0;\n\n\tif (numrows < 0 || numcols < 0) {\n\t\tgoto error;\n\t}\n\n\tif (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {\n\t\tgoto error;\n\t}\n\tmatrix->flags_ = 0;\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\tmatrix->rows_ = 0;\n\tmatrix->maxrows_ = numrows;\n\tmatrix->data_ = 0;\n\tmatrix->datasize_ = 0;\n\n\t// matrix->datasize_ = numrows * numcols;\n\tif (!jas_safe_size_mul(numrows, numcols, &size)) {\n\t\tgoto error;\n\t}\n\tmatrix->datasize_ = size;\n\n\tif (matrix->maxrows_ > 0) {\n\t\tif (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,\n\t\t sizeof(jas_seqent_t *)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (matrix->datasize_ > 0) {\n\t\tif (!(matrix->data_ = jas_alloc2(matrix->datasize_,\n\t\t sizeof(jas_seqent_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[i * matrix->numcols_];\n\t}\n\n\tfor (i = 0; i < matrix->datasize_; ++i) {\n\t\tmatrix->data_[i] = 0;\n\t}\n\n\tmatrix->xstart_ = 0;\n\tmatrix->ystart_ = 0;\n\tmatrix->xend_ = matrix->numcols_;\n\tmatrix->yend_ = matrix->numrows_;\n\n\treturn matrix;\n\nerror:\n\tif (matrix) {\n\t\tjas_matrix_destroy(matrix);\n\t}\n\treturn 0;\n}", "label_name": "CWE-190", "label": 19} +{"code": "check_owner_password_V4(std::string& user_password,\n std::string const& owner_password,\n QPDF::EncryptionData const& data)\n{\n // Algorithm 3.7 from the PDF 1.7 Reference Manual\n\n unsigned char key[OU_key_bytes_V4];\n compute_O_rc4_key(user_password, owner_password, data, key);\n unsigned char O_data[key_bytes];\n memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);\n iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, true);\n std::string new_user_password =\n std::string(reinterpret_cast(O_data), key_bytes);\n bool result = false;\n if (check_user_password(new_user_password, data))\n {\n result = true;\n user_password = new_user_password;\n }\n return result;\n}", "label_name": "CWE-125", "label": 47} +{"code": "Pl_Count::write(unsigned char* buf, size_t len)\n{\n if (len)\n {\n\tthis->m->count += QIntC::to_offset(len);\n\tgetNext()->write(buf, len);\n\tthis->m->last_char = buf[len - 1];\n }\n}", "label_name": "CWE-787", "label": 24} +{"code": "AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)\n{\n AP4_UI32 predefined;\n stream.ReadUI32(predefined);\n stream.ReadUI32(m_HandlerType);\n stream.ReadUI32(m_Reserved[0]);\n stream.ReadUI32(m_Reserved[1]);\n stream.ReadUI32(m_Reserved[2]);\n \n // read the name unless it is empty\n int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n if (name_size == 0) return;\n char* name = new char[name_size+1];\n stream.Read(name, name_size);\n name[name_size] = '\\0'; // force a null termination\n // handle a special case: the Quicktime files have a pascal\n // string here, but ISO MP4 files have a C string.\n // we try to detect a pascal encoding and correct it.\n if (name[0] == name_size-1) {\n m_HandlerName = name+1;\n } else {\n m_HandlerName = name;\n }\n delete[] name;\n}", "label_name": "CWE-476", "label": 46} +{"code": "R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;\n\tattr->size = offset;\n\treturn attr;\n}", "label_name": "CWE-788", "label": 87} +{"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-805", "label": 63} +{"code": "static int lookup1_values(int entries, int dim)\n{\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n assert(pow((float) r+1, dim) > entries);\n assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above\n return r;\n}", "label_name": "CWE-908", "label": 48} +{"code": "static float *get_window(vorb *f, int len)\n{\n len <<= 1;\n if (len == f->blocksize_0) return f->window[0];\n if (len == f->blocksize_1) return f->window[1];\n assert(0);\n return NULL;\n}", "label_name": "CWE-787", "label": 24} +{"code": "static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)\n{\n int dy = y1 - y0;\n int adx = x1 - x0;\n int ady = abs(dy);\n int base;\n int x=x0,y=y0;\n int err = 0;\n int sy;\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {\n if (dy < 0) {\n base = -integer_divide_table[ady][adx];\n sy = base-1;\n } else {\n base = integer_divide_table[ady][adx];\n sy = base+1;\n }\n } else {\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n }\n#else\n base = dy / adx;\n if (dy < 0)\n sy = base - 1;\n else\n sy = base+1;\n#endif\n ady -= abs(base) * adx;\n if (x1 > n) x1 = n;\n if (x < x1) {\n LINE_OP(output[x], inverse_db_table[y]);\n for (++x; x < x1; ++x) {\n err += ady;\n if (err >= adx) {\n err -= adx;\n y += sy;\n } else\n y += base;\n LINE_OP(output[x], inverse_db_table[y]);\n }\n }\n}", "label_name": "CWE-787", "label": 24} +{"code": "static NO_INLINE JsVar *jspGetNamedFieldInParents(JsVar *object, const char* name, bool returnName) {\n // Now look in prototypes\n JsVar * child = jspeiFindChildFromStringInParents(object, name);\n\n /* Check for builtins via separate function\n * This way we save on RAM for built-ins because everything comes out of program code */\n if (!child) {\n child = jswFindBuiltInFunction(object, name);\n }\n\n /* We didn't get here if we found a child in the object itself, so\n * if we're here then we probably have the wrong name - so for example\n * with `a.b = c;` could end up setting `a.prototype.b` (bug #360)\n *\n * Also we might have got a built-in, which wouldn't have a name on it\n * anyway - so in both cases, strip the name if it is there, and create\n * a new name that references the object we actually requested the\n * member from..\n */\n if (child && returnName) {\n // Get rid of existing name\n if (jsvIsName(child)) {\n JsVar *t = jsvGetValueOfName(child);\n jsvUnLock(child);\n child = t;\n }\n // create a new name\n JsVar *nameVar = jsvNewFromString(name);\n JsVar *newChild = jsvCreateNewChild(object, nameVar, child);\n jsvUnLock2(nameVar, child);\n child = newChild;\n }\n\n // If not found and is the prototype, create it\n if (!child) {\n if (jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) {\n // prototype is supposed to be an object\n JsVar *proto = jsvNewObject();\n // make sure it has a 'constructor' variable that points to the object it was part of\n jsvObjectSetChild(proto, JSPARSE_CONSTRUCTOR_VAR, object);\n child = jsvAddNamedChild(object, proto, JSPARSE_PROTOTYPE_VAR);\n jspEnsureIsPrototype(object, child);\n jsvUnLock(proto);\n } else if (strcmp(name, JSPARSE_INHERITS_VAR)==0) {\n const char *objName = jswGetBasicObjectName(object);\n if (objName) {\n child = jspNewPrototype(objName);\n }\n }\n }\n\n return child;\n}", "label_name": "CWE-787", "label": 24} +{"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-22", "label": 2} +{"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-22", "label": 2} +{"code": "void test_base64_decode(void)\n{\n char buffer[16];\n int len = mutt_b64_decode(buffer, encoded);\n if (!TEST_CHECK(len == sizeof(clear) - 1))\n {\n TEST_MSG(\"Expected: %zu\", sizeof(clear) - 1);\n TEST_MSG(\"Actual : %zu\", len);\n }\n buffer[len] = '\\0';\n if (!TEST_CHECK(strcmp(buffer, clear) == 0))\n {\n TEST_MSG(\"Expected: %s\", clear);\n TEST_MSG(\"Actual : %s\", buffer);\n }\n}", "label_name": "CWE-120", "label": 44} +{"code": "inline void AveragePool(const uint8* input_data, const Dims<4>& input_dims,\n int stride_width, int stride_height, int pad_width,\n int pad_height, int filter_width, int filter_height,\n int32 output_activation_min,\n int32 output_activation_max, uint8* output_data,\n const Dims<4>& output_dims) {\n tflite::PoolParams params;\n params.stride_height = stride_height;\n params.stride_width = stride_width;\n params.filter_height = filter_height;\n params.filter_width = filter_width;\n params.padding_values.height = pad_height;\n params.padding_values.width = pad_width;\n params.quantized_activation_min = output_activation_min;\n params.quantized_activation_max = output_activation_max;\n AveragePool(params, DimsToShape(input_dims), input_data,\n DimsToShape(output_dims), output_data);\n}", "label_name": "CWE-835", "label": 42} +{"code": "void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride,\n int pad_width, int pad_height, int filter_width,\n int filter_height, float* output_data,\n const Dims<4>& output_dims) {\n AveragePool(input_data, input_dims, stride, stride, pad_width, pad_height,\n filter_width, filter_height, output_data, output_dims);\n}", "label_name": "CWE-835", "label": 42} +{"code": " void AddBatchOffsets(Tensor* indices, const Tensor& params) {\n int64_t batch_size = 1; // The size of all batch dimensions.\n for (int idx = 0; idx < batch_dims_; ++idx) {\n batch_size *= params.dim_size(idx);\n }\n\n auto indices_flat = indices->flat();\n int64_t const index_inner_size = indices->NumElements() / batch_size;\n int64_t const batch_offset = params.dim_size(batch_dims_);\n for (int64_t batch_idx = 0, dest_idx = 0; batch_idx < batch_size;\n ++batch_idx) {\n for (int64_t idx = 0; idx < index_inner_size; ++idx) {\n indices_flat(dest_idx++) += batch_offset * batch_idx;\n }\n }\n }", "label_name": "CWE-369", "label": 60} +{"code": "StatusOr SpecializeType(const AttrSlice& attrs,\n const OpDef& op_def) {\n FullTypeDef ft;\n ft.set_type_id(TFT_PRODUCT);\n\n for (int i = 0; i < op_def.output_arg_size(); i++) {\n auto* t = ft.add_args();\n\n *t = op_def.output_arg(i).experimental_full_type();\n\n // Resolve dependent types. The convention for op registrations is to use\n // attributes as type variables.\n // See https://www.tensorflow.org/guide/create_op#type_polymorphism.\n // Once the op signature can be defined entirely in FullType, this\n // convention can be deprecated.\n //\n // Note: While this code performs some basic verifications, it generally\n // assumes consistent op defs and attributes. If more complete\n // verifications are needed, they should be done by separately, and in a\n // way that can be reused for type inference.\n for (int j = 0; j < t->args_size(); j++) {\n auto* arg = t->mutable_args(i);\n if (arg->type_id() == TFT_VAR) {\n const auto* attr = attrs.Find(arg->s());\n DCHECK(attr != nullptr);\n if (attr->value_case() == AttrValue::kList) {\n const auto& attr_list = attr->list();\n arg->set_type_id(TFT_PRODUCT);\n for (int i = 0; i < attr_list.type_size(); i++) {\n map_dtype_to_tensor(attr_list.type(i), arg->add_args());\n }\n\n } else if (attr->value_case() == AttrValue::kType) {\n map_dtype_to_tensor(attr->type(), arg);\n\n } else {\n return Status(error::UNIMPLEMENTED,\n absl::StrCat(\"unknown attribute type\",\n attrs.DebugString(), \" key=\", arg->s()));\n }\n\n arg->clear_s();\n }\n }\n }\n\n return ft;\n}", "label_name": "CWE-476", "label": 46} +{"code": "bool ConstantFolding::SimplifyReshape(const GraphProperties& properties,\n bool use_shape_info, NodeDef* node) {\n if (!use_shape_info || node->attr().count(\"T\") == 0 ||\n !IsSimplifiableReshape(*node, properties)) {\n return false;\n }\n DataType output_type = node->attr().at(\"T\").type();\n node->set_op(\"Identity\");\n EraseRegularNodeAttributes(node);\n (*node->mutable_attr())[\"T\"].set_type(output_type);\n *node->mutable_input(1) = AsControlDependency(node->input(1));\n return true;\n}", "label_name": "CWE-617", "label": 51} +{"code": "Status InferenceContext::Multiply(DimensionHandle first,\n DimensionOrConstant second,\n DimensionHandle* out) {\n const int64_t first_value = Value(first);\n const int64_t second_value = Value(second);\n // Special cases.\n if (first_value == 0) {\n *out = first;\n } else if (second_value == 0) {\n *out = MakeDim(second);\n } else if (first_value == 1) {\n *out = MakeDim(second);\n } else if (second_value == 1) {\n *out = first;\n } else if (first_value == kUnknownDim || second_value == kUnknownDim) {\n *out = UnknownDim();\n } else {\n // Invariant: Both values are known and greater than 1.\n const int64_t product = first_value * second_value;\n if (product < 0) {\n return errors::InvalidArgument(\n \"Negative dimension size caused by overflow when multiplying \",\n first_value, \" and \", second_value);\n }\n *out = MakeDim(product);\n }\n return Status::OK();\n}", "label_name": "CWE-190", "label": 19} +{"code": " friend bool operator==(const TensorKey& t1, const TensorKey& t2) {\n if (t1.dtype() != t2.dtype() || t1.shape() != t2.shape()) {\n return false;\n }\n if (DataTypeCanUseMemcpy(t1.dtype())) {\n return t1.tensor_data() == t2.tensor_data();\n }\n if (t1.dtype() == DT_STRING) {\n const auto s1 = t1.unaligned_flat();\n const auto s2 = t2.unaligned_flat();\n for (int64_t i = 0, n = t1.NumElements(); i < n; ++i) {\n if (TF_PREDICT_FALSE(s1(i) != s2(i))) {\n return false;\n }\n }\n return true;\n }\n return false;\n }", "label_name": "CWE-120", "label": 44} +{"code": "__global__ void UnsortedSegmentCustomKernel(const Index input_outer_dim_size,\n const Index inner_dim_size,\n const Index output_outer_dim_size,\n const Index* segment_ids,\n const T* input, T* output) {\n const Index input_total_size = input_outer_dim_size * inner_dim_size;\n const Index output_total_size = output_outer_dim_size * inner_dim_size;\n for (int input_index : GpuGridRangeX(input_total_size)) {\n const Index input_segment_index = input_index / inner_dim_size;\n const Index segment_offset = input_index % inner_dim_size;\n const Index output_segment_index = segment_ids[input_segment_index];\n if (output_segment_index < 0 || output_segment_index >= output_total_size) {\n continue;\n }\n const Index output_index =\n output_segment_index * inner_dim_size + segment_offset;\n KernelReductionFunctor()(output + output_index, ldg(input + input_index));\n }\n}", "label_name": "CWE-681", "label": 59} +{"code": "TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n int max_index = -1;\n const int segment_id_size = segment_ids->dims->data[0];\n if (segment_id_size > 0) {\n max_index = segment_ids->data.i32[segment_id_size - 1];\n }\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;\n for (int i = 1; i < data_rank; ++i) {\n output_shape->data[i] = data->dims->data[i];\n }\n return context->ResizeTensor(context, output, output_shape);\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* data =\n reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 1);\n\n TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt16);\n output->type = kTfLiteInt32;\n if (data->out_float) {\n output->type = kTfLiteFloat32;\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(2);\n int num_frames = 0;\n if (input->dims->data[0] >= data->state->window.size) {\n num_frames = (input->dims->data[0] - data->state->window.size) /\n data->state->window.step / data->frame_stride +\n 1;\n }\n output_size->data[0] = num_frames;\n output_size->data[1] = data->state->filterbank.num_channels *\n (1 + data->left_context + data->right_context);\n\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 47} +{"code": " TfLiteRegistration CopyOpRegistration() {\n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // Set output size to input size\n const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n return context->ResizeTensor(context, tensor1, newSize);\n };\n\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n CallReporting* call_reporting =\n static_cast(node->builtin_data);\n // Copy input data to output data.\n const TfLiteTensor* a0 = GetInput(context, node, 0);\n TfLiteTensor* a1 = GetOutput(context, node, 0);\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n a1->data.f[i] = a0->data.f[i];\n }\n call_reporting->Record();\n return kTfLiteOk;\n };\n return reg;\n }", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus PrepareHashtableSize(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputResourceIdTensor);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);\n\n TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);\n TF_LITE_ENSURE(context, output_tensor != nullptr);\n TF_LITE_ENSURE_EQ(context, output_tensor->type, kTfLiteInt64);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n outputSize->data[0] = 1;\n return context->ResizeTensor(context, output_tensor, outputSize);\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,\n TfLiteNode* node) {\n OpData* data = reinterpret_cast(node->user_data);\n\n // Make sure that the input is in uint8_t with at least 1 data entry.\n const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);\n if (input->type != kTfLiteUInt8) return kTfLiteError;\n if (NumElements(input->dims) == 0) return kTfLiteError;\n\n // Allocate a temporary buffer with the same size of input for sorting.\n TF_LITE_ENSURE_STATUS(context->RequestScratchBufferInArena(\n context, sizeof(uint8_t) * NumElements(input->dims),\n &data->sorting_buffer));\n // We can interleave scratch / persistent buffer allocation.\n data->invoke_count = reinterpret_cast(\n context->AllocatePersistentBuffer(context, sizeof(int)));\n *data->invoke_count = 0;\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus LogSoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) {\n LogSoftmaxOpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, output->params.scale, 16.0 / 256);\n static const double kBeta = 1.0;\n if (input->type == kTfLiteUInt8) {\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 255);\n data->params.table = data->f_table;\n optimized_ops::PopulateSoftmaxLookupTable(&data->params,\n input->params.scale, kBeta);\n data->params.zero_point = output->params.zero_point;\n data->params.scale = output->params.scale;\n }\n if (input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 127);\n static const int kScaledDiffIntegerBits = 5;\n tflite::PreprocessLogSoftmaxScalingExp(\n kBeta, input->params.scale, kScaledDiffIntegerBits,\n &data->input_multiplier, &data->input_left_shift,\n &data->reverse_scaling_divisor, &data->reverse_scaling_right_shift);\n data->reverse_scaling_right_shift *= -1;\n data->diff_min =\n -1.0 * tflite::CalculateInputRadius(kScaledDiffIntegerBits,\n data->input_left_shift);\n }\n }\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Relu6Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n size_t elements = input->bytes / sizeof(float);\n const float* in = GetTensorData(input);\n const float* in_end = in + elements;\n float* out = GetTensorData(output);\n for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f);\n return kTfLiteOk;\n } break;\n case kTfLiteUInt8:\n QuantizedReluX(0.0f, 6.0f, input, output, data);\n return kTfLiteOk;\n case kTfLiteInt8: {\n QuantizedReluX(0.0f, 6.0f, input, output, data);\n return kTfLiteOk;\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context,\n \"Only float32, uint8 and int8 are supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus ReluPrepare(TfLiteContext* context, TfLiteNode* node) {\n ReluOpData* data = reinterpret_cast(node->user_data);\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n if (input->type == kTfLiteInt8 || input->type == kTfLiteUInt8) {\n double real_multiplier = input->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Relu1Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n optimized_ops::Relu1(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output),\n GetTensorData(output));\n return kTfLiteOk;\n } break;\n case kTfLiteUInt8: {\n QuantizedReluX(-1.0f, 1.0f, input, output, data);\n return kTfLiteOk;\n } break;\n case kTfLiteInt8: {\n QuantizedReluX(-1, 1, input, output, data);\n return kTfLiteOk;\n } break;\n default:\n TF_LITE_KERNEL_LOG(context,\n \"Only float32, uint8, int8 supported \"\n \"currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus ReluEval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const ReluOpData* data = reinterpret_cast(node->user_data);\n switch (input->type) {\n case kTfLiteFloat32: {\n optimized_ops::Relu(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n } break;\n // TODO(renjieliu): We may revisit the quantization calculation logic,\n // the unbounded upper limit is actually hard to quantize.\n case kTfLiteUInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n case kTfLiteInt8: {\n QuantizedReluX(0.0f, std::numeric_limits::infinity(),\n input, output, data);\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context, \"Only float32 & int8/uint8 is supported currently, got %s.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) {\n EvalAdd(context, node, params, data, input1, input2, output);\n } else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_OK(context,\n EvalAddQuantized(context, node, params, data,\n input1, input2, output));\n } else {\n TF_LITE_UNSUPPORTED_TYPE(context, output->type, \"Add\");\n }\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n // TODO(b/137042749): TFLite infrastructure (converter, delegate) doesn't\n // fully support 0-output ops yet. Currently it works if we manually crfat\n // a TFLite graph that contains variable ops. Note:\n // * The TFLite Converter need to be changed to be able to produce an op\n // with 0 output.\n // * The delegation code need to be changed to handle 0 output ops. However\n // everything still works fine when variable ops aren't used.\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n if (input->type != kTfLiteFloat32) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, \"Ceil\");\n }\n\n optimized_ops::Ceil(GetTensorShape(input), GetTensorData(input),\n GetTensorShape(output), GetTensorData(output));\n\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n if (!is_supported_type(input->type)) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);\n }\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TfLiteTensor* output = GetOutput(context, node, 0);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n if (!is_supported_type(input->type)) {\n TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);\n }\n return context->ResizeTensor(context, output,\n TfLiteIntArrayCopy(input->dims));\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* lookup = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);\n TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);\n\n const TfLiteTensor* value = GetInput(context, node, 1);\n TF_LITE_ENSURE(context, NumDimensions(value) >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, 0);\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));\n\n outputSize->data[0] = SizeOfDimension(lookup, 0);\n outputSize->data[1] = SizeOfDimension(value, 1);\n for (int i = 2; i < NumDimensions(value); i++) {\n outputSize->data[i] = SizeOfDimension(value, i);\n }\n return context->ResizeTensor(context, output, outputSize);\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // Check for supported activation types.\n auto* params =\n reinterpret_cast(node->builtin_data);\n const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const bool is_quantized =\n ((filter->type == kTfLiteUInt8) || (filter->type == kTfLiteInt8));\n const bool is_hybrid = is_quantized && (input->type == kTfLiteFloat32);\n const bool is_pie = kernel_type == kLegacyPie;\n\n // Pie and hybrid path supports all kinds of fused activations, otherwise only\n // clipping activations are supported.\n if (!is_pie && !is_hybrid) {\n TF_LITE_ENSURE(context, params->activation == kTfLiteActNone ||\n params->activation == kTfLiteActRelu ||\n params->activation == kTfLiteActReluN1To1 ||\n params->activation == kTfLiteActRelu6);\n }\n return PrepareImpl(context, node);\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = input->dims->data[1];\n output_size->data[2] = input->dims->data[2];\n output_size->data[3] = input->dims->data[3];\n\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteIntArray* input_dims = input->dims;\n int input_dims_size = input_dims->size;\n TF_LITE_ENSURE(context, input_dims_size >= 2);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(input_dims_size);\n for (int i = 0; i < input_dims_size; i++) {\n output_shape->data[i] = input_dims->data[i];\n }\n\n // Resize the output tensor to the same size as the input tensor.\n output->type = input->type;\n TF_LITE_ENSURE_OK(context,\n context->ResizeTensor(context, output, output_shape));\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);\n const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);\n\n const bool requires_broadcast = !HaveSameShapes(input1, input2);\n\n TfLiteIntArray* output_size = nullptr;\n if (requires_broadcast) {\n TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(\n context, input1, input2, &output_size));\n } else {\n output_size = TfLiteIntArrayCopy(input1->dims);\n }\n\n if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||\n output->type == kTfLiteInt16) {\n TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(\n context, params->activation, output, &data->output_activation_min,\n &data->output_activation_max));\n double real_multiplier =\n input1->params.scale * input2->params.scale / output->params.scale;\n QuantizeMultiplier(real_multiplier, &data->output_multiplier,\n &data->output_shift);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output = GetOutput(context, node, 0);\n const TfLiteTensor* input = GetInput(context, node, 0);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n int batches = input->dims->data[0];\n int height = input->dims->data[1];\n int width = input->dims->data[2];\n int channels_out = input->dims->data[3];\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n params->filter_height, params->filter_width, padding, &out_height,\n &out_width);\n\n if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {\n if (pool_type == kAverage || pool_type == kMax) {\n TFLITE_DCHECK_LE(std::abs(input->params.scale - output->params.scale),\n 1.0e-6);\n TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point);\n }\n if (pool_type == kL2) {\n // We currently don't have a quantized implementation of L2Pool\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = batches;\n output_size->data[1] = out_height;\n output_size->data[2] = out_width;\n output_size->data[3] = channels_out;\n return context->ResizeTensor(context, output, output_size);\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* start = GetInput(context, node, kStartTensor);\n const TfLiteTensor* limit = GetInput(context, node, kLimitTensor);\n const TfLiteTensor* delta = GetInput(context, node, kDeltaTensor);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeOutput(context, start, limit, delta, output));\n }\n\n switch (output->type) {\n case kTfLiteInt32: {\n EvalImpl(start, delta, output);\n break;\n }\n case kTfLiteFloat32: {\n EvalImpl(start, delta, output);\n break;\n }\n default: {\n context->ReportError(context, \"Unsupported data type: %d\", output->type);\n return kTfLiteError;\n }\n }\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n Subgraph* subgraph = reinterpret_cast(context->impl_);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n int resource_id = input_resource_id_tensor->data.i32[0];\n auto& resources = subgraph->resources();\n auto* variable = resource::GetResourceVariable(&resources, resource_id);\n TF_LITE_ENSURE(context, variable != nullptr);\n\n TfLiteTensor* variable_tensor = variable->GetTensor();\n TfLiteTensor* output = GetOutput(context, node, kOutputValue);\n\n TF_LITE_ENSURE_TYPES_EQ(context, variable_tensor->type, output->type);\n TF_LITE_ENSURE_OK(\n context, context->ResizeTensor(\n context, output, TfLiteIntArrayCopy(variable_tensor->dims)));\n memcpy(output->data.raw, variable_tensor->data.raw, output->bytes);\n\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, node->inputs->size, 1);\n TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);\n\n const TfLiteTensor* input_resource_id_tensor =\n GetInput(context, node, kInputVariableId);\n TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);\n\n TfLiteTensor* output = GetOutput(context, node, kOutputValue);\n SetTensorToDynamic(output);\n\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus EvalLogic(TfLiteContext* context, TfLiteNode* node,\n OpContext* op_context, T init_value,\n T reducer(const T current, const T in)) {\n int64_t num_axis = NumElements(op_context->axis);\n TfLiteTensor* temp_index = GetTemporary(context, node, /*index=*/0);\n TfLiteTensor* resolved_axis = GetTemporary(context, node, /*index=*/1);\n // Resize the output tensor if the output tensor is dynamic.\n if (IsDynamicTensor(op_context->output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTempAxis(context, op_context, resolved_axis));\n TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, op_context));\n }\n if (op_context->input->type == kTfLiteUInt8 ||\n op_context->input->type == kTfLiteInt8) {\n TF_LITE_ENSURE_EQ(context, op_context->input->params.scale,\n op_context->output->params.scale);\n TF_LITE_ENSURE_EQ(context, op_context->input->params.zero_point,\n op_context->output->params.zero_point);\n }\n TF_LITE_ENSURE(\n context,\n reference_ops::ReduceGeneric(\n GetTensorData(op_context->input), op_context->input->dims->data,\n op_context->input->dims->size, GetTensorData(op_context->output),\n op_context->output->dims->data, op_context->output->dims->size,\n GetTensorData(op_context->axis), num_axis,\n op_context->params->keep_dims, GetTensorData(temp_index),\n GetTensorData(resolved_axis), init_value, reducer));\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n TfLiteIntArray* output_shape = GetOutputShape(context, node);\n std::unique_ptr\n scoped_output_shape(output_shape, TfLiteIntArrayFree);\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n // Tensorflow's Reshape allows one of the shape components to have the\n // special -1 value, meaning it will be calculated automatically based on the\n // input. Here we calculate what that dimension should be so that the number\n // of output elements in the same as the number of input elements.\n int num_input_elements = NumElements(input);\n\n int num_output_elements = 1;\n int stretch_dim = -1;\n for (int i = 0; i < output_shape->size; ++i) {\n int value = output_shape->data[i];\n if (value == -1) {\n TF_LITE_ENSURE_EQ(context, stretch_dim, -1);\n stretch_dim = i;\n } else {\n num_output_elements *= value;\n }\n }\n if (stretch_dim != -1) {\n output_shape->data[stretch_dim] = num_input_elements / num_output_elements;\n num_output_elements *= output_shape->data[stretch_dim];\n }\n\n TF_LITE_ENSURE_EQ(context, num_input_elements, num_output_elements);\n return context->ResizeTensor(context, output, scoped_output_shape.release());\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus ReverseSequenceHelper(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* seq_lengths_tensor =\n GetInput(context, node, kSeqLengthsTensor);\n switch (seq_lengths_tensor->type) {\n case kTfLiteInt32: {\n return ReverseSequenceImpl(context, node);\n }\n case kTfLiteInt64: {\n return ReverseSequenceImpl(context, node);\n }\n default: {\n context->ReportError(\n context,\n \"Seq_lengths type '%s' is not supported by reverse_sequence.\",\n TfLiteTypeGetName(seq_lengths_tensor->type));\n return kTfLiteError;\n }\n }\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n const TfLiteTensor* fft_length = GetInput(context, node, kFftLengthTensor);\n const int32_t* fft_length_data = GetTensorData(fft_length);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (output->type != kTfLiteComplex64) {\n context->ReportError(context,\n \"Type '%s' for output is not supported by rfft2d.\",\n TfLiteTypeGetName(output->type));\n return kTfLiteError;\n }\n\n // Resize the output tensor if the fft_length tensor is not constant.\n // Otherwise, check if the output shape is correct.\n if (!IsConstantTensor(fft_length)) {\n TF_LITE_ENSURE_STATUS(ResizeOutputandTemporaryTensors(context, node));\n } else {\n int num_dims_output = NumDimensions(output);\n const RuntimeShape output_shape = GetTensorShape(output);\n TF_LITE_ENSURE_EQ(context, num_dims_output, NumDimensions(input));\n TF_LITE_ENSURE(context, num_dims_output >= 2);\n TF_LITE_ENSURE_EQ(context, output_shape.Dims(num_dims_output - 2),\n fft_length_data[0]);\n TF_LITE_ENSURE_EQ(context, output_shape.Dims(num_dims_output - 1),\n fft_length_data[1] / 2 + 1);\n }\n\n return Rfft2dHelper(context, node);\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);\n const TfLiteTensor* segment_ids =\n GetInput(context, node, kInputSegmentIdsTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context,\n ResizeOutputTensor(context, data, segment_ids, output));\n }\n\n#define TF_LITE_SEGMENT_SUM(dtype) \\\n reference_ops::SegmentSum( \\\n GetTensorShape(data), GetTensorData(data), \\\n GetTensorShape(segment_ids), GetTensorData(segment_ids), \\\n GetTensorShape(output), GetTensorData(output));\n switch (data->type) {\n case kTfLiteInt32:\n TF_LITE_SEGMENT_SUM(int32_t);\n break;\n case kTfLiteFloat32:\n TF_LITE_SEGMENT_SUM(float);\n break;\n default:\n context->ReportError(context,\n \"Currently SegmentSum doesn't support type: %s\",\n TfLiteTypeGetName(data->type));\n return kTfLiteError;\n }\n#undef TF_LITE_SEGMENT_SUM\n return kTfLiteOk;\n}", "label_name": "CWE-125", "label": 47} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n TF_LITE_ENSURE_TYPES_EQ(context, GetInput(context, node, 0)->type,\n kTfLiteString);\n TF_LITE_ENSURE_TYPES_EQ(context, GetOutput(context, node, 0)->type,\n kTfLiteString);\n return kTfLiteOk;\n}", "label_name": "CWE-787", "label": 24} +{"code": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* cond_tensor =\n GetInput(context, node, kInputConditionTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n if (cond_tensor->type != kTfLiteBool) {\n context->ReportError(context,\n \"Condition tensor must be of type bool, but saw '%s'.\",\n TfLiteTypeGetName(cond_tensor->type));\n return kTfLiteError;\n }\n\n // As output will be a 2D tensor of indices, use int64 to be consistent with\n // tensorflow.\n output->type = kTfLiteInt64;\n\n // Exit early if cond is a non-const tensor. Set output tensor to dynamic so\n // output size can be determined in Eval.\n if (!IsConstantTensor(cond_tensor)) {\n SetTensorToDynamic(output);\n return kTfLiteOk;\n }\n return ResizeOutputTensor(context, cond_tensor, output);\n}", "label_name": "CWE-125", "label": 47} +{"code": " void CalculateOutputIndexRowSplit(\n const RowPartitionTensor& row_split,\n const vector& parent_output_index,\n INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size,\n vector* result) {\n INDEX_TYPE row_split_size = row_split.size();\n if (row_split_size > 0) {\n result->reserve(row_split(row_split_size - 1));\n }\n for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) {\n INDEX_TYPE row_length = row_split(i + 1) - row_split(i);\n INDEX_TYPE real_length = std::min(output_size, row_length);\n INDEX_TYPE parent_output_index_current = parent_output_index[i];\n\n if (parent_output_index_current == -1) {\n real_length = 0;\n }\n for (INDEX_TYPE j = 0; j < real_length; ++j) {\n result->push_back(parent_output_index_current);\n parent_output_index_current += output_index_multiplier;\n }\n for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) {\n result->push_back(-1);\n }\n }\n if (row_split_size > 0) {\n DCHECK_EQ(result->size(), row_split(row_split_size - 1));\n }\n }", "label_name": "CWE-131", "label": 88} +{"code": " void ValidateInputTensors(OpKernelContext* ctx, const Tensor& in0,\n const Tensor& in1) override {\n OP_REQUIRES(\n ctx, in0.dims() >= 2,\n errors::InvalidArgument(\"In[0] ndims must be >= 2: \", in0.dims()));\n\n OP_REQUIRES(\n ctx, in1.dims() >= 2,\n errors::InvalidArgument(\"In[0] ndims must be >= 2: \", in1.dims()));\n }", "label_name": "CWE-125", "label": 47} +{"code": "template void testFeatTable(const T & table, const char * testName)\n{\n FeatureMap testFeatureMap;\n dummyFace.replace_table(TtfUtil::Tag::Feat, &table, sizeof(T));\n gr_face * face = gr_make_face_with_ops(&dummyFace, &face_handle::ops, gr_face_dumbRendering);\n if (!face) throw std::runtime_error(\"failed to load font\");\n bool readStatus = testFeatureMap.readFeats(*face);\n testAssert(\"readFeats\", readStatus);\n fprintf(stderr, testName, NULL);\n testAssertEqual(\"test num features %hu,%hu\\n\", testFeatureMap.numFeats(), table.m_header.m_numFeat);\n\n for (size_t i = 0; i < sizeof(table.m_defs) / sizeof(FeatDefn); i++)\n {\n const FeatureRef * ref = testFeatureMap.findFeatureRef(table.m_defs[i].m_featId);\n testAssert(\"test feat\\n\", ref);\n testAssertEqual(\"test feat settings %hu %hu\\n\", ref->getNumSettings(), table.m_defs[i].m_numFeatSettings);\n testAssertEqual(\"test feat label %hu %hu\\n\", ref->getNameId(), table.m_defs[i].m_label);\n size_t settingsIndex = (table.m_defs[i].m_settingsOffset - sizeof(FeatHeader)\n - (sizeof(FeatDefn) * table.m_header.m_numFeat)) / sizeof(FeatSetting);\n for (size_t j = 0; j < table.m_defs[i].m_numFeatSettings; j++)\n {\n testAssertEqual(\"setting label %hu %hu\\n\", ref->getSettingName(j),\n table.m_settings[settingsIndex+j].m_label);\n }\n }\n gr_face_destroy(face);\n}", "label_name": "CWE-476", "label": 46} +{"code": "folly::Optional EncryptedReadRecordLayer::read(\n folly::IOBufQueue& buf) {\n auto decryptedBuf = getDecryptedBuf(buf);\n if (!decryptedBuf) {\n return folly::none;\n }\n\n TLSMessage msg;\n // Iterate over the buffers while trying to find\n // the first non-zero octet. This is much faster than\n // first iterating and then trimming.\n auto currentBuf = decryptedBuf->get();\n bool nonZeroFound = false;\n do {\n currentBuf = currentBuf->prev();\n size_t i = currentBuf->length();\n while (i > 0 && !nonZeroFound) {\n nonZeroFound = (currentBuf->data()[i - 1] != 0);\n i--;\n }\n if (nonZeroFound) {\n msg.type = static_cast(currentBuf->data()[i]);\n }\n currentBuf->trimEnd(currentBuf->length() - i);\n } while (!nonZeroFound && currentBuf != decryptedBuf->get());\n if (!nonZeroFound) {\n throw std::runtime_error(\"No content type found\");\n }\n msg.fragment = std::move(*decryptedBuf);\n\n switch (msg.type) {\n case ContentType::handshake:\n case ContentType::alert:\n case ContentType::application_data:\n break;\n default:\n throw std::runtime_error(folly::to(\n \"received encrypted content type \",\n static_cast(msg.type)));\n }\n\n if (!msg.fragment || msg.fragment->empty()) {\n if (msg.type == ContentType::application_data) {\n msg.fragment = folly::IOBuf::create(0);\n } else {\n throw std::runtime_error(\"received empty fragment\");\n }\n }\n\n return msg;\n}", "label_name": "CWE-770", "label": 37} +{"code": "Envoy::Ssl::ClientValidationStatus DefaultCertValidator::verifyCertificate(\n X509* cert, const std::vector& verify_san_list,\n const std::vector>&\n subject_alt_name_matchers) {\n Envoy::Ssl::ClientValidationStatus validated = Envoy::Ssl::ClientValidationStatus::NotValidated;\n\n if (!verify_san_list.empty()) {\n if (!verifySubjectAltName(cert, verify_san_list)) {\n stats_.fail_verify_san_.inc();\n return Envoy::Ssl::ClientValidationStatus::Failed;\n }\n validated = Envoy::Ssl::ClientValidationStatus::Validated;\n }\n\n if (!subject_alt_name_matchers.empty()) {\n if (!matchSubjectAltName(cert, subject_alt_name_matchers)) {\n stats_.fail_verify_san_.inc();\n return Envoy::Ssl::ClientValidationStatus::Failed;\n }\n validated = Envoy::Ssl::ClientValidationStatus::Validated;\n }\n\n if (!verify_certificate_hash_list_.empty() || !verify_certificate_spki_list_.empty()) {\n const bool valid_certificate_hash =\n !verify_certificate_hash_list_.empty() &&\n verifyCertificateHashList(cert, verify_certificate_hash_list_);\n const bool valid_certificate_spki =\n !verify_certificate_spki_list_.empty() &&\n verifyCertificateSpkiList(cert, verify_certificate_spki_list_);\n\n if (!valid_certificate_hash && !valid_certificate_spki) {\n stats_.fail_verify_cert_hash_.inc();\n return Envoy::Ssl::ClientValidationStatus::Failed;\n }\n\n validated = Envoy::Ssl::ClientValidationStatus::Validated;\n }\n\n return validated;\n}", "label_name": "CWE-295", "label": 52} +{"code": "bool SPIFFEValidator::matchSubjectAltName(X509& leaf_cert) {\n bssl::UniquePtr san_names(static_cast(\n X509_get_ext_d2i(&leaf_cert, NID_subject_alt_name, nullptr, nullptr)));\n // We must not have san_names == nullptr here because this function is called after the\n // SPIFFE cert validation algorithm succeeded, which requires exactly one URI SAN in the leaf\n // cert.\n ASSERT(san_names != nullptr,\n \"san_names should have at least one name after SPIFFE cert validation\");\n\n // Only match against URI SAN since SPIFFE specification does not restrict values in other SAN\n // types. See the discussion: https://github.com/envoyproxy/envoy/issues/15392\n for (const GENERAL_NAME* general_name : san_names.get()) {\n if (general_name->type == GEN_URI) {\n const std::string san = Utility::generalNameAsString(general_name);\n for (const auto& config_san_matcher : subject_alt_name_matchers_) {\n if (config_san_matcher.match(san)) {\n return true;\n }\n }\n }\n }\n return false;\n}", "label_name": "CWE-295", "label": 52} +{"code": "TEST_P(SslSocketTest, GetUriWithUriSan) {\n const std::string client_ctx_yaml = R\"EOF(\n common_tls_context:\n tls_certificates:\n certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem\"\n)EOF\";\n\n const std::string server_ctx_yaml = R\"EOF(\n common_tls_context:\n tls_certificates:\n certificate_chain:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/unittest_cert.pem\"\n private_key:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/unittest_key.pem\"\n validation_context:\n trusted_ca:\n filename: \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem\"\n match_subject_alt_names:\n exact: \"spiffe://lyft.com/test-team\"\n)EOF\";\n\n TestUtilOptions test_options(client_ctx_yaml, server_ctx_yaml, true, GetParam());\n testUtil(test_options.setExpectedClientCertUri(\"spiffe://lyft.com/test-team\")\n .setExpectedSerialNumber(TEST_SAN_URI_CERT_SERIAL));\n}", "label_name": "CWE-295", "label": 52} +{"code": " inline int check(int itemSize, int nItems=1, bool wait=true)\n {\n if (ptr + itemSize * nItems > end) {\n if (ptr + itemSize > end)\n return overrun(itemSize, nItems, wait);\n\n nItems = (end - ptr) / itemSize;\n }\n return nItems;\n }", "label_name": "CWE-787", "label": 24} +{"code": " inline void skip(int bytes) {\n while (bytes > 0) {\n int n = check(1, bytes);\n ptr += n;\n bytes -= n;\n }\n }", "label_name": "CWE-787", "label": 24} +{"code": " int overrun(int itemSize, int nItems, bool wait) { throw EndOfStream(); }", "label_name": "CWE-787", "label": 24} +{"code": "int ZlibOutStream::length()\n{\n return offset + ptr - start;\n}", "label_name": "CWE-787", "label": 24} +{"code": " bool read(ReadonlyBytes buffer)\n {\n auto fields_size = sizeof(CentralDirectoryRecord) - (sizeof(u8*) * 3);\n if (buffer.size() < fields_size)\n return false;\n if (memcmp(buffer.data(), central_directory_record_signature, sizeof(central_directory_record_signature)) != 0)\n return false;\n memcpy(reinterpret_cast(&made_by_version), buffer.data() + sizeof(central_directory_record_signature), fields_size);\n name = buffer.data() + sizeof(central_directory_record_signature) + fields_size;\n extra_data = name + name_length;\n comment = extra_data + extra_data_length;\n return true;\n }", "label_name": "CWE-120", "label": 44} +{"code": "bool PackLinuxElf32::calls_crt1(Elf32_Rel const *rel, int sz)\n{\n if (!dynsym || !dynstr) {\n return false;\n }\n for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf32_Rel)), ++rel, ++relnum) {\n unsigned const symnum = get_te32(&rel->r_info) >> 8;\n char const *const symnam = get_dynsym_name(symnum, relnum);\n if (0==strcmp(symnam, \"__libc_start_main\") // glibc\n || 0==strcmp(symnam, \"__libc_init\") // Android\n || 0==strcmp(symnam, \"__uClibc_main\")\n || 0==strcmp(symnam, \"__uClibc_start_main\"))\n return true;\n }\n return false;\n}", "label_name": "CWE-190", "label": 19} +{"code": "int64_t LineBasedFrameDecoder::findEndOfLine(IOBufQueue& buf) {\n Cursor c(buf.front());\n for (uint32_t i = 0; i < maxLength_ && i < buf.chainLength(); i++) {\n auto b = c.read();\n if (b == '\\n' && terminatorType_ != TerminatorType::CARRIAGENEWLINE) {\n return i;\n } else if (terminatorType_ != TerminatorType::NEWLINE &&\n b == '\\r' && !c.isAtEnd() && c.read() == '\\n') {\n return i;\n }\n }\n\n return -1;\n}", "label_name": "CWE-787", "label": 24} +{"code": "snmp_process_data(void)\n{\n static unsigned char packet[SNMP_MAX_PACKET_SIZE];\n unsigned char *packet_end;\n static uint32_t packet_len;\n\n packet_end = packet + sizeof(packet) - 1;\n packet_len = 0;\n\n LOG_DBG(\"receiving UDP datagram from [\");\n LOG_DBG_6ADDR(&UIP_IP_BUF->srcipaddr);\n LOG_DBG_(\"]:%u\", uip_ntohs(UIP_UDP_BUF->srcport));\n LOG_DBG_(\" Length: %u\\n\", uip_datalen());\n\n /*\n * Handle the request\n */\n if((packet_end = snmp_engine(uip_appdata, uip_datalen(), packet_end, &packet_len)) == NULL) {\n LOG_DBG(\"Error while handling the request\\n\");\n } else {\n LOG_DBG(\"Sending response\\n\");\n /*\n * Send the response\n */\n uip_udp_packet_sendto(snmp_udp_conn, packet_end, packet_len, &UIP_IP_BUF->srcipaddr, UIP_UDP_BUF->srcport);\n }\n}", "label_name": "CWE-125", "label": 47} +{"code": "int LibarchivePlugin::extractionFlags() const\n{\n int result = ARCHIVE_EXTRACT_TIME;\n result |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;\n\n // TODO: Don't use arksettings here\n /*if ( ArkSettings::preservePerms() )\n {\n result &= ARCHIVE_EXTRACT_PERM;\n }\n\n if ( !ArkSettings::extractOverwrite() )\n {\n result &= ARCHIVE_EXTRACT_NO_OVERWRITE;\n }*/\n\n return result;\n}", "label_name": "CWE-59", "label": 36} +{"code": "void MainWindow::showUpgradePrompt()\n{\n if (Settings.checkUpgradeAutomatic()) {\n showStatusMessage(\"Checking for upgrade...\");\n QNetworkRequest request(QUrl(\"https://check.shotcut.org/version.json\"));\n QSslConfiguration sslConfig = request.sslConfiguration();\n sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);\n request.setSslConfiguration(sslConfig);\n m_network.get(request);\n } else {\n m_network.setStrictTransportSecurityEnabled(false);\n QAction* action = new QAction(tr(\"Click here to check for a new version of Shotcut.\"), 0);\n connect(action, SIGNAL(triggered(bool)), SLOT(on_actionUpgrade_triggered()));\n showStatusMessage(action, 15 /* seconds */);\n }\n}", "label_name": "CWE-295", "label": 52} +{"code": "bool AES_GCM_EncryptContext::Encrypt(\n\tconst void *pPlaintextData, size_t cbPlaintextData,\n\tconst void *pIV,\n\tvoid *pEncryptedDataAndTag, uint32 *pcbEncryptedDataAndTag,\n\tconst void *pAdditionalAuthenticationData, size_t cbAuthenticationData\n) {\n unsigned long long pcbEncryptedDataAndTag_longlong = *pcbEncryptedDataAndTag;\n\n crypto_aead_aes256gcm_encrypt_afternm(\n\t\tstatic_cast( pEncryptedDataAndTag ), &pcbEncryptedDataAndTag_longlong,\n\t\tstatic_cast( pPlaintextData ), cbPlaintextData,\n\t\tstatic_cast(pAdditionalAuthenticationData), cbAuthenticationData,\n\t\tnullptr,\n\t\tstatic_cast( pIV ),\n\t\tstatic_cast( m_ctx )\n\t);\n\n *pcbEncryptedDataAndTag = pcbEncryptedDataAndTag_longlong;\n\n return true;\n}", "label_name": "CWE-787", "label": 24} +{"code": "Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)\r\n{\r\n auto* zei = entries.getUnchecked (index);\r\n\r\n #if JUCE_WINDOWS\r\n auto entryPath = zei->entry.filename;\r\n #else\r\n auto entryPath = zei->entry.filename.replaceCharacter ('\\\\', '/');\r\n #endif\r\n\r\n if (entryPath.isEmpty())\r\n return Result::ok();\r\n\r\n auto targetFile = targetDirectory.getChildFile (entryPath);\r\n\r\n if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\\\'))\r\n return targetFile.createDirectory(); // (entry is a directory, not a file)\r\n\r\n std::unique_ptr in (createStreamForEntry (index));\r\n\r\n if (in == nullptr)\r\n return Result::fail (\"Failed to open the zip file for reading\");\r\n\r\n if (targetFile.exists())\r\n {\r\n if (! shouldOverwriteFiles)\r\n return Result::ok();\r\n\r\n if (! targetFile.deleteFile())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n }\r\n\r\n if (! targetFile.getParentDirectory().createDirectory())\r\n return Result::fail (\"Failed to create target folder: \" + targetFile.getParentDirectory().getFullPathName());\r\n\r\n if (zei->entry.isSymbolicLink)\r\n {\r\n String originalFilePath (in->readEntireStreamAsString()\r\n .replaceCharacter (L'/', File::getSeparatorChar()));\r\n\r\n if (! File::createSymbolicLink (targetFile, originalFilePath, true))\r\n return Result::fail (\"Failed to create symbolic link: \" + originalFilePath);\r\n }\r\n else\r\n {\r\n FileOutputStream out (targetFile);\r\n\r\n if (out.failedToOpen())\r\n return Result::fail (\"Failed to write to target file: \" + targetFile.getFullPathName());\r\n\r\n out << *in;\r\n }\r\n\r\n targetFile.setCreationTime (zei->entry.fileTime);\r\n targetFile.setLastModificationTime (zei->entry.fileTime);\r\n targetFile.setLastAccessTime (zei->entry.fileTime);\r\n\r\n return Result::ok();\r\n}\r", "label_name": "CWE-59", "label": 36} +{"code": "std::string RestAuthHandler::generateJwt(std::string const& username,\n std::string const& password) {\n AuthenticationFeature* af = AuthenticationFeature::instance();\n TRI_ASSERT(af != nullptr);\n return fuerte::jwt::generateUserToken(af->tokenCache().jwtSecret(), username, _validFor);\n}", "label_name": "CWE-613", "label": 7} +{"code": "RestAuthHandler::RestAuthHandler(application_features::ApplicationServer& server,\n GeneralRequest* request, GeneralResponse* response)\n : RestVocbaseBaseHandler(server, request, response),\n _validFor(60 * 60 * 24 * 30) {}", "label_name": "CWE-613", "label": 7} +{"code": "string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {\n CHECK_STATE(errStatus);\n CHECK_STATE(err_string);\n CHECK_STATE(_key);\n auto keyArray = make_shared>(BUF_LEN, 0);\n auto encryptedKey = make_shared>(BUF_LEN, 0);\n\n vector errMsg(BUF_LEN, 0);\n\n strncpy(keyArray->data(), _key, BUF_LEN);\n *errStatus = 0;\n unsigned int encryptedLen = 0;\n\n sgx_status_t status = trustedEncryptKeyAES(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(), &encryptedLen);\n\n HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());\n\n SAFE_CHAR_BUF(resultBuf, 2 * BUF_LEN + 1);\n\n carray2Hex(encryptedKey->data(), encryptedLen, resultBuf, 2 * BUF_LEN + 1);\n\n return string(resultBuf);\n}", "label_name": "CWE-787", "label": 24} +{"code": "shared_ptr > check_and_set_SEK(const string &SEK) {\n\n vector decr_key(BUF_LEN, 0);\n vector errMsg(BUF_LEN, 0);\n int err_status = 0;\n\n auto encrypted_SEK = make_shared < vector < uint8_t >> (BUF_LEN, 0);\n\n uint32_t l = 0;\n\n sgx_status_t status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l,\n SEK.c_str());\n\n encrypted_SEK->resize(l);\n\n HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());\n\n validate_SEK();\n\n return encrypted_SEK;\n}", "label_name": "CWE-787", "label": 24} +{"code": "TEST_CASE_METHOD(TestFixture, \"DKG AES encrypted secret shares test\", \"[dkg-aes-encr-sshares]\") {\n vector errMsg(BUF_LEN, 0);\n vector result(BUF_LEN, 0);\n\n int errStatus = 0;\n uint32_t encLen = 0;\n\n vector encryptedDKGSecret(BUF_LEN, 0);\n PRINT_SRC_LINE\n auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n\n uint64_t enc_len = encLen;\n\n PRINT_SRC_LINE\n status = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), enc_len);\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n\n vector encrPRDHKey(BUF_LEN, 0);\n\n string pub_keyB = SAMPLE_PUBLIC_KEY_B;\n\n vector s_shareG2(BUF_LEN, 0);\n PRINT_SRC_LINE\n status = trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &encLen,\n result.data(),\n s_shareG2.data(),\n (char *) pub_keyB.data(), 2, 2, 1);\n\n REQUIRE(status == SGX_SUCCESS);\n REQUIRE(errStatus == SGX_SUCCESS);\n}", "label_name": "CWE-787", "label": 24} +{"code": "RawTile KakaduImage::getRegion( int seq, int ang, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h )\n{\n // Scale up our output bit depth to the nearest factor of 8\n unsigned int obpc = bpc;\n if( bpc <= 16 && bpc > 8 ) obpc = 16;\n else if( bpc <= 8 ) obpc = 8;\n\n#ifdef DEBUG\n Timer timer;\n timer.start();\n#endif\n\n RawTile rawtile( 0, res, seq, ang, w, h, channels, obpc );\n\n if( obpc == 16 ) rawtile.data = new unsigned short[w*h*channels];\n else if( obpc == 8 ) rawtile.data = new unsigned char[w*h*channels];\n else throw file_error( \"Kakadu :: Unsupported number of bits\" );\n\n rawtile.dataLength = w*h*channels*(obpc/8);\n rawtile.filename = getImagePath();\n rawtile.timestamp = timestamp;\n\n process( res, layers, x, y, w, h, rawtile.data );\n\n#ifdef DEBUG\n logfile << \"Kakadu :: getRegion() :: \" << timer.getTime() << \" microseconds\" << endl;\n#endif\n\n return rawtile;\n\n}", "label_name": "CWE-190", "label": 19} +{"code": " bool CheckRegion(int nPos, int nSize)\n {\n return (nPos >= 0 && nPos + nSize >= nPos && nPos + nSize <= m_nLen);\n }", "label_name": "CWE-787", "label": 24} +{"code": "int32_t CxImage::GetSize()\r\n{\r\n\treturn head.biSize + head.biSizeImage + GetPaletteSize();\r\n}\r", "label_name": "CWE-770", "label": 37} +{"code": "void DCR_CLASS dcr_parse_riff(DCRAW* p)\r\n{\r\n\tunsigned i, size, end;\r\n\tchar tag[4], date[64], month[64];\r\n\tstatic const char mon[12][4] =\r\n\t{ \"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\" };\r\n\tstruct tm t;\r\n\r\n\tp->order = 0x4949;\r\n\tdcr_fread(p->obj_, tag, 4, 1);\r\n\tsize = dcr_get4(p);\r\n\tend = dcr_ftell(p->obj_) + size;\r\n\tif (!memcmp(tag,\"RIFF\",4) || !memcmp(tag,\"LIST\",4)) {\r\n\t\tdcr_get4(p);\r\n\t\twhile (dcr_ftell(p->obj_)+7 < (long)end)\r\n\t\t\tdcr_parse_riff(p);\r\n\t} else if (!memcmp(tag,\"nctg\",4)) {\r\n\t\twhile (dcr_ftell(p->obj_)+7 < (long)end) {\r\n\t\t\ti = dcr_get2(p);\r\n\t\t\tsize = dcr_get2(p);\r\n\t\t\tif ((i+1) >> 1 == 10 && size == 20)\r\n\t\t\t\tdcr_get_timestamp(p,0);\r\n\t\t\telse dcr_fseek(p->obj_, size, SEEK_CUR);\r\n\t\t}\r\n\t} else if (!memcmp(tag,\"IDIT\",4) && size < 64) {\r\n\t\tdcr_fread(p->obj_, date, 64, 1);\r\n\t\tdate[size] = 0;\r\n\t\tmemset (&t, 0, sizeof t);\r\n\t\tif (sscanf (date, \"%*s %s %d %d:%d:%d %d\", month, &t.tm_mday,\r\n\t\t\t&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {\r\n\t\t\tfor (i=0; i < 12 && strcasecmp(mon[i],month); i++);\r\n\t\t\tt.tm_mon = i;\r\n\t\t\tt.tm_year -= 1900;\r\n\t\t\tif (mktime(&t) > 0)\r\n\t\t\t\tp->timestamp = mktime(&t);\r\n\t\t}\r\n\t} else\r\n\t\tdcr_fseek(p->obj_, size, SEEK_CUR);\r\n}\r", "label_name": "CWE-770", "label": 37} +{"code": " def quote_column_name(name) #:nodoc:\n %Q(\"#{name}\")\n end", "label_name": "CWE-89", "label": 0} +{"code": " def _call(env)\n unless ALLOWED_VERBS.include? env[\"REQUEST_METHOD\"]\n return fail(405, \"Method Not Allowed\")\n end\n\n path_info = Utils.unescape(env[\"PATH_INFO\"])\n parts = path_info.split SEPS\n\n parts.inject(0) do |depth, part|\n case part\n when '', '.'\n depth\n when '..'\n return fail(404, \"Not Found\") if depth - 1 < 0\n depth - 1\n else\n depth + 1\n end\n end", "label_name": "CWE-22", "label": 2} +{"code": " it \"with Pathname command\" do\n cl = subject.build_command_line(Pathname.new(\"/usr/bin/ruby\"))\n expect(cl).to eq \"/usr/bin/ruby\"\n end", "label_name": "CWE-78", "label": 6} +{"code": " it \"without params\" do\n cl = subject.build_command_line(\"true\")\n expect(cl).to eq \"true\"\n end", "label_name": "CWE-78", "label": 6} +{"code": " it \"with params as empty Hash\" do\n cl = subject.build_command_line(\"true\", {})\n expect(cl).to eq \"true\"\n end", "label_name": "CWE-78", "label": 6} +{"code": " def media_type_mismatch?\n ! supplied_file_media_types.include?(calculated_media_type)\n end", "label_name": "CWE-79", "label": 1} +{"code": " def filename_extension\n File.extname(@name.to_s.downcase).sub(/^\\./, '').to_sym\n end", "label_name": "CWE-79", "label": 1} +{"code": " def show_tree\n Log.add_info(request, params.inspect)\n\n if !@login_user.nil? and @login_user.admin?(User::AUTH_FOLDER)\n\n @group_id = nil\n if !params[:thetisBoxSelKeeper].nil?\n @group_id = params[:thetisBoxSelKeeper].split(':').last\n elsif !params[:group_id].nil? and !params[:group_id].empty?\n @group_id = params[:group_id]\n end\n\n @folder_tree = Folder.get_tree_by_group_for_admin(@group_id || '0')\n else\n @folder_tree = Folder.get_tree_for(@login_user)\n end\n end", "label_name": "CWE-89", "label": 0} +{"code": " def wf_issue\n Log.add_info(request, params.inspect)\n\n begin\n @item = Item.find(params[:id])\n @workflow = @item.workflow\n rescue => evar\n Log.add_error(request, evar)\n end\n \n attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now})\n @workflow.update_attributes(attrs.permit(Workflow::PERMIT_BASE))\n\n @orders = @workflow.get_orders\n\n render(:partial => 'ajax_workflow', :layout => false)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def show\n if params[:action] == 'show'\n Log.add_info(request, params.inspect)\n end\n\n @mail_filter = MailFilter.find_by_id(params[:id])\n if @mail_filter.nil?\n render(:text => 'ERROR:' + t('msg.already_deleted', :name => MailFilter.model_name.human))\n return\n else\n if @mail_filter.mail_account.user_id != @login_user.id\n render(:text => 'ERROR:' + t('msg.need_to_be_owner'))\n return\n end\n end\n render(:action => 'show', :layout => (!request.xhr?))\n end", "label_name": "CWE-89", "label": 0} +{"code": " def check_import(mode, address_names) #, address_emails\n\n err_msgs = []\n\n # Existing Addresss\n unless self.id.nil? or self.id == 0 or self.id == ''\n if mode == 'add'\n err_msgs << I18n.t('address.import.dont_specify_id')\n else\n begin\n org_address = Address.find(self.id)\n rescue\n end\n if org_address.nil?\n err_msgs << I18n.t('address.import.not_found')\n end\n end\n end\n\n # Requierd\n if self.name.nil? or self.name.empty?\n err_msgs << Address.human_attribute_name('name') + I18n.t('msg.is_required')\n end\n\n # Groups\n unless self.groups.nil? or self.groups.empty?\n\n if (/^|([0-9]+|)+$/ =~ self.groups) == 0\n\n self.get_groups_a.each do |group_id|\n group = Group.find_by_id(group_id)\n if group.nil?\n err_msgs << I18n.t('address.import.not_valid_groups') + ': '+group_id.to_s\n break\n end\n end\n else\n err_msgs << I18n.t('address.import.invalid_groups_format')\n end\n end\n\n # Teams\n unless self.teams.nil? or self.teams.empty?\n\n if (/^|([0-9]+|)+$/ =~ self.teams) == 0\n\n self.get_teams_a.each do |team_id|\n team = Team.find_by_id(team_id)\n if team.nil?\n err_msgs << I18n.t('address.import.not_valid_teams') + ': '+team_id.to_s\n break\n end\n end\n\n else\n err_msgs << I18n.t('address.import.invalid_teams_format')\n end\n end\n\n return err_msgs\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.parse_csv_row(row, book, idxs, user)\n\n imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip)\n unless imp_id.nil? or imp_id.empty?\n org_address = Address.find_by_id(imp_id)\n end\n\n if org_address.nil?\n address = Address.new\n else\n address = org_address\n end\n\n address.id = imp_id\n attr_names = [\n :name,\n :name_ruby,\n :nickname,\n :screenname,\n :email1,\n :email2,\n :email3,\n :postalcode,\n :address,\n :tel1_note,\n :tel1,\n :tel2_note,\n :tel2,\n :tel3_note,\n :tel3,\n :fax,\n :url,\n :organization,\n :title,\n :memo,\n :xorder,\n :groups,\n :teams\n ]\n attr_names.each_with_index do |attr_name, idx|\n row_idx = idxs[idx+1]\n break if row_idx.nil?\n\n val = (row[row_idx].nil?)?(nil):(row[row_idx].strip)\n address.send(attr_name.to_s + '=', val)\n end\n if (address.groups == Address::EXP_IMP_FOR_ALL) \\\n or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?)\n address.groups = nil\n address.teams = nil\n address.owner_id = 0\n elsif !address.groups.blank? or !address.teams.blank?\n address.owner_id = 0\n else\n address.owner_id = user.id\n end\n\n return address\n end", "label_name": "CWE-89", "label": 0} +{"code": " def rename\n Log.add_info(request, params.inspect)\n\n @folder = Folder.find(params[:id])\n\n unless Folder.check_user_auth(@folder.id, @login_user, 'w', true)\n flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')\n render(:partial => 'ajax_folder_name', :layout => false)\n return\n end\n\n unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?\n @folder.name = params[:thetisBoxEdit]\n @folder.save\n end\n render(:partial => 'ajax_folder_name', :layout => false)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def wf_issue\n Log.add_info(request, params.inspect)\n\n begin\n @item = Item.find(params[:id])\n @workflow = @item.workflow\n rescue => evar\n Log.add_error(request, evar)\n end\n \n attrs = ActionController::Parameters.new({status: Workflow::STATUS_ACTIVE, issued_at: Time.now})\n @workflow.update_attributes(attrs.permit(Workflow::PERMIT_BASE))\n\n @orders = @workflow.get_orders\n\n render(:partial => 'ajax_workflow', :layout => false)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def set_workflow\n Log.add_info(request, params.inspect)\n\n @item = Item.find(params[:id])\n\n orders_hash = params.dup\n orders_hash.reject! { |key, value|\n key.index(/order-/) != 0\n }\n orders_hash.sort_by { |key, value|\n key.split('-').last.to_i\n }\n\n orders = []\n orders_hash.each do |key, value|\n\n orders << '|' + value.split(',').join('|') + '|'\n end\n @item.workflow.update_attribute(:users, orders.join(','))\n\n render(:partial => 'ajax_item_workflow', :layout => false)\n\n rescue => evar\n Log.add_error(request, evar)\n\n render(:partial => 'ajax_item_workflow', :layout => false)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def search\n Log.add_info(request, params.inspect)\n\n unless params[:select_sorting].nil? or params[:select_sorting].empty?\n sort_a = params[:select_sorting].split(' ')\n params[:sort_col] = sort_a.first\n params[:sort_type] = sort_a.last\n end\n\n list\n\n if params[:keyword].nil? or params[:keyword].empty?\n if params[:from_action].nil? or params[:from_action] == 'bbs'\n render(:action => 'bbs')\n else\n render(:action => 'list')\n end\n end\n end", "label_name": "CWE-89", "label": 0} +{"code": " def on_moved\n Log.add_info(request, params.inspect)\n\n location_id = params[:id]\n\n if location_id.nil? or location_id.empty?\n location = Location.get_for(@login_user)\n if location.nil?\n location = Location.new\n location.user_id = @login_user.id\n end\n else\n begin\n location = Location.find(location_id)\n rescue\n end\n end\n\n unless location.nil?\n group_id = params[:group_id]\n group_id = nil if group_id.empty?\n attrs = ActionController::Parameters.new({group_id: group_id, x: params[:x], y: params[:y]})\n location.update_attributes(attrs.permit(Location::PERMIT_BASE))\n end\n\n render(:text => (location.nil?)?'':location.id.to_s)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def check_member\n\n return if params[:id].nil? or params[:id].empty? or @login_user.nil?\n\n if Item.find(params[:id]).user_id != @login_user.id\n Log.add_check(request, '[check_member]'+request.to_s)\n\n flash[:notice] = t('team.need_to_be_member')\n redirect_to(:controller => 'desktop', :action => 'show')\n end\n end", "label_name": "CWE-89", "label": 0} +{"code": " def create_title\n\n titles = User.get_config_titles\n titles = [] if titles.nil?\n titles << t('user.new_title')\n User.save_config_titles titles\n\n render(:partial => 'ajax_title', :layout => false)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def add_to_group\n Log.add_info(request, params.inspect)\n\n if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?\n render(:partial => 'ajax_groups', :layout => false)\n return\n end\n\n group_id = params[:thetisBoxSelKeeper].split(':').last\n unless group_id == '0' # '0' for ROOT\n begin\n group = Group.find(group_id)\n rescue => evar\n Log.add_error(request, evar)\n ensure\n if group.nil?\n render(:partial => 'ajax_groups', :layout => false)\n return\n end\n end\n end\n\n begin\n @user = User.find(params[:user_id])\n rescue => evar\n Log.add_error(request, evar)\n end\n\n unless @user.nil?\n\n is_modified = false\n\n # Change, not simply Add\n unless params[:current_id] == nil or params[:current_id].empty?\n if @user.exclude_from(params[:current_id])\n is_modified = true\n end\n end\n\n is_modified = true if @user.add_to(group_id)\n\n if is_modified == true\n# @user.update_attribute(:groups, @user.groups)\n @user.save!\n\n if @user.id == @login_user.id\n @login_user = @user\n end\n end\n end\n\n render(:partial => 'ajax_groups', :layout => false)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def check_owner\n return if params[:id].nil? or params[:id].empty? or @login_user.nil?\n\n begin\n owner_id = Workflow.find(params[:id]).user_id\n rescue\n owner_id = -1\n end\n if !@login_user.admin?(User::AUTH_WORKFLOW) and owner_id != @login_user.id\n Log.add_check(request, '[check_owner]'+request.to_s)\n\n flash[:notice] = t('msg.need_to_be_owner')\n redirect_to(:controller => 'desktop', :action => 'show')\n end\n end", "label_name": "CWE-89", "label": 0} +{"code": " def copy\n Log.add_info(request, params.inspect)\n\n return unless request.post?\n\n tmpl_id = params[:thetisBoxSelKeeper].split(':').last\n tmpl_item = Item.find(tmpl_id)\n\n item = tmpl_item.copy(@login_user.id, @login_user.get_my_folder.id)\n if item.public != false\n item.update_attribute(:public, false)\n end\n\n redirect_to(:controller => 'items', :action => 'edit', :id => item.id)\n\n rescue => evar\n Log.add_error(request, evar)\n\n redirect_to(:controller => 'items', :action => 'new')\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_comment_of(item_id, user_id)\n\n SqlHelper.validate_token([item_id, user_id])\n begin\n comment = Comment.where(\"(user_id=#{user_id}) and (item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')\").first\n rescue => evar\n Log.add_error(nil, evar)\n end\n\n return comment\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_tree_by_group_for_admin(group_id)\n\n SqlHelper.validate_token([group_id])\n\n folder_tree = {}\n tree_id = '0'\n\n if group_id.to_s == '0'\n sql = 'select distinct * from folders'\n\n where = \" where (parent_id = #{tree_id})\"\n where << \" and ((xtype is null) or not(xtype = '#{XTYPE_GROUP}' or xtype = '#{XTYPE_USER}'))\"\n\n order_by = ' order by xorder ASC, id ASC'\n else\n sql = 'select distinct Folder.* from folders Folder, users User'\n\n where = \" where (Folder.parent_id = #{tree_id})\"\n where << ' and ('\n where << \"(Folder.xtype = '#{XTYPE_GROUP}' and Folder.owner_id = #{group_id})\"\n where << ' or '\n where << \"(Folder.xtype = '#{XTYPE_USER}' and Folder.owner_id = User.id and #{SqlHelper.get_sql_like(['User.groups'], \"|#{group_id}|\")})\"\n where << ' )'\n\n order_by = ' order by Folder.xorder ASC, Folder.id ASC'\n end\n\n sql << where + order_by\n\n folder_tree[tree_id] = Folder.find_by_sql(sql)\n\n folder_tree[tree_id].each do |folder|\n folder_tree = Folder.get_tree(folder_tree, nil, folder, true)\n end\n\n return Folder.sort_tree(folder_tree)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_tree(folder_tree, conditions, parent, admin)\n\n if parent.instance_of?(Folder)\n tree_id = parent.id.to_s\n else\n tree_id = parent.to_s\n parent = nil\n if tree_id != '0'\n begin\n parent = Folder.find(tree_id)\n rescue\n end\n return folder_tree if parent.nil?\n end\n end\n\n group_obj_cache = {}\n folder_tree[tree_id] = []\n if !parent.nil? and (parent.xtype == Folder::XTYPE_GROUP)\n Group.get_childs(parent.owner_id, false, true).each do |group|\n group_obj_cache[group.id] = group\n con = Marshal.load(Marshal.dump(conditions)) unless conditions.nil?\n if con.nil?\n con = ''\n else\n con << ' and '\n end\n con << \"(xtype='#{Folder::XTYPE_GROUP}') and (owner_id=#{group.id})\"\n begin\n group_folder = Folder.where(con).first\n rescue => evar\n Log.add_error(nil, evar)\n end\n unless group_folder.nil?\n folder_tree[tree_id] << group_folder\n end\n end\n end\n\n con = Marshal.load(Marshal.dump(conditions)) unless conditions.nil?\n if con.nil?\n con = ''\n else\n con << ' and '\n end\n con << \"parent_id=#{tree_id}\"\n folder_tree[tree_id] += Folder.where(con).order('xorder ASC, id ASC').to_a\n\n delete_ary = []\n\n folder_tree[tree_id].each do |folder|\n\n if !admin and (folder.xtype == Folder::XTYPE_SYSTEM)\n delete_ary << folder\n next\n end\n\n if (tree_id == '0') and (folder.xtype == Folder::XTYPE_GROUP)\n group = Group.find_with_cache(folder.owner_id, group_obj_cache)\n unless group.nil?\n if group.parent_id != 0\n delete_ary << folder\n next\n end\n end\n end\n\n folder_tree = Folder.get_tree(folder_tree, conditions, folder, admin)\n end\n\n folder_tree[tree_id] -= delete_ary\n\n return folder_tree\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_for_group(group_id)\n\n SqlHelper.validate_token([group_id])\n if group_id.nil?\n con = 'group_id is null'\n else\n con = \"group_id=#{group_id}\"\n end\n\n Location.do_expire(con)\n\n return Location.where(con).to_a\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_for(group_id, include_parents=false, enabled=nil)\n\n SqlHelper.validate_token([group_id])\n\n con = []\n #con << \"(disabled=#{!enabled})\" unless enabled.nil?\n\n if include_parents\n group_con = '(group_id is null)'\n\n unless group_id.nil? or group_id.to_s == '0'\n group_obj_cache = {}\n group = Group.find_with_cache(group_id, group_obj_cache)\n group_ids = group.get_parents(false, group_obj_cache)\n group_ids << group_id\n group_con << \" or (group_id in (#{group_ids.join(',')}))\"\n end\n\n con << '(' + group_con + ')'\n else\n con << \"(group_id=#{group_id})\"\n end\n\n order_by = 'order by xorder ASC, id ASC'\n #order_by = 'order by disabled ASC, xorder ASC, id ASC'\n\n sql = 'select * from official_titles where ' + con.join(' and ') + ' ' + order_by\n\n return OfficialTitle.find_by_sql(sql)\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_for(user_id, fiscal_year=nil)\n\n SqlHelper.validate_token([user_id, fiscal_year])\n\n begin\n con = []\n con << \"(user_id=#{user_id})\"\n if fiscal_year.nil?\n return PaidHoliday.where(con).order('year ASC').to_a\n else\n con << \"(year=#{fiscal_year})\"\n return PaidHoliday.where(con.join(' and ')).first\n end\n rescue\n end\n return nil\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.save_value(user_id, category, key, value)\n\n SqlHelper.validate_token([user_id, category, key])\n\n con = []\n con << \"(user_id=#{user_id})\"\n con << \"(category='#{category}')\"\n con << \"(xkey='#{key}')\"\n\n setting = Setting.where(con.join(' and ')).first\n\n if value.nil?\n unless setting.nil?\n setting.destroy\n end\n else\n if setting.nil?\n setting = Setting.new\n setting.user_id = user_id\n setting.category = category\n setting.xkey = key\n setting.xvalue = value\n setting.save!\n else\n setting.update_attribute(:xvalue, value)\n end\n end\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_value(user_id, category, key)\n\n SqlHelper.validate_token([user_id, category, key])\n\n con = []\n con << \"(user_id=#{user_id})\"\n con << \"(category='#{category}')\"\n con << \"(xkey='#{key}')\"\n\n setting = Setting.where(con.join(' and ')).first\n\n return setting.xvalue unless setting.nil?\n\n return nil\n end", "label_name": "CWE-89", "label": 0} +{"code": " def self.get_by_email(mail_addr, user, book=Address::BOOK_BOTH)\n\n SqlHelper.validate_token([mail_addr])\n\n email_con = []\n email_con.push(\"(email1='#{mail_addr}')\")\n email_con.push(\"(email2='#{mail_addr}')\")\n email_con.push(\"(email3='#{mail_addr}')\")\n con = []\n con.push('('+email_con.join(' or ')+')')\n con.push(AddressbookHelper.get_scope_condition_for(user, book))\n\n return Address.where(con.join(' and ')).to_a\n end", "label_name": "CWE-89", "label": 0} +{"code": " def clean_text(text)\n text.gsub(/[\\u0000-\\u0008\\u000b-\\u000c\\u000e-\\u001F\\u007f]/, \".\".freeze)\n end", "label_name": "CWE-94", "label": 14} +{"code": " def load_file(filename)\n Gem.load_yaml\n\n yaml_errors = [ArgumentError]\n yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError)\n\n return {} unless filename and File.exist? filename\n\n begin\n content = YAML.load(File.read(filename))\n unless content.kind_of? Hash\n warn \"Failed to load #{filename} because it doesn't contain valid YAML hash\"\n return {}\n end\n return content\n rescue *yaml_errors => e\n warn \"Failed to load #{filename}, #{e}\"\n rescue Errno::EACCES\n warn \"Failed to load #{filename} due to permissions problem.\"\n end\n\n {}\n end", "label_name": "CWE-502", "label": 15} +{"code": " def read_checksums gem\n Gem.load_yaml\n\n @checksums = gem.seek 'checksums.yaml.gz' do |entry|\n Zlib::GzipReader.wrap entry do |gz_io|\n YAML.load gz_io.read\n end\n end\n end", "label_name": "CWE-502", "label": 15} +{"code": " def extract_tar_gz io, destination_dir, pattern = \"*\" # :nodoc:\n open_tar_gz io do |tar|\n tar.each do |entry|\n next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH\n\n destination = install_location entry.full_name, destination_dir\n\n FileUtils.rm_rf destination\n\n mkdir_options = {}\n mkdir_options[:mode] = entry.header.mode if entry.directory?\n mkdir =\n if entry.directory? then\n destination\n else\n File.dirname destination\n end\n\n FileUtils.mkdir_p mkdir, mkdir_options\n\n File.open destination, 'wb' do |out|\n out.write entry.read\n FileUtils.chmod entry.header.mode, destination\n end if entry.file?\n\n File.symlink(entry.header.linkname, destination) if entry.symlink?\n\n verbose destination\n end\n end\n end", "label_name": "CWE-22", "label": 2} +{"code": " def install_location filename, destination_dir # :nodoc:\n raise Gem::Package::PathError.new(filename, destination_dir) if\n filename.start_with? '/'\n\n destination_dir = File.realpath destination_dir if\n File.respond_to? :realpath\n destination_dir = File.expand_path destination_dir\n\n destination = File.join destination_dir, filename\n destination = File.realpath destination if\n File.respond_to? :realpath\n destination = File.expand_path destination\n\n raise Gem::Package::PathError.new(destination, destination_dir) unless\n destination.start_with? destination_dir + '/'\n\n destination.untaint\n destination\n end", "label_name": "CWE-22", "label": 2} +{"code": " def find(uuid, options = {})\n if uuid.nil? || uuid.to_s.empty?\n raise NotFound, \"can't find a record with nil identifier\"\n end\n\n uri = uuid =~ /^http/ ? uuid : member_path(uuid)\n begin\n from_response API.get(uri, {}, options)\n rescue API::NotFound => e\n raise NotFound, e.description\n end\n end", "label_name": "CWE-918", "label": 16} +{"code": " def _extend_marshalling(options)\n @marshalling = !(options[:marshalling] === false) # HACK - TODO delegate to Factory\n extend Marshalling if @marshalling\n end", "label_name": "CWE-502", "label": 15} +{"code": " def _marshal(val, options)\n yield marshal?(options) ? Marshal.dump(val) : val\n end", "label_name": "CWE-502", "label": 15} +{"code": " def self.map_library_name(lib)\n # Mangle the library name to reflect the native library naming conventions\n lib = lib.to_s unless lib.kind_of?(String)\n lib = Library::LIBC if lib == 'c'\n\n if lib && File.basename(lib) == lib\n lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/\n r = Platform::IS_GNU ? \"\\\\.so($|\\\\.[1234567890]+)\" : \"\\\\.#{Platform::LIBSUFFIX}$\"\n lib += \".#{Platform::LIBSUFFIX}\" unless lib =~ /#{r}/\n end\n\n lib\n end", "label_name": "CWE-426", "label": 70} +{"code": " it 'removes existing content types' do\n subject.content_type :xls, 'application/vnd.ms-excel'\n subject.get :excel do\n 'some binary content'\n end\n get '/excel.json'\n expect(last_response.status).to eq(406)\n expect(last_response.body).to eq(\"The requested format 'txt' is not supported.\")\n end", "label_name": "CWE-79", "label": 1} +{"code": " def set_member_and_redirect(member)\n set_member member\n Member::ActivityLog.create(\n cur_site: @cur_site,\n cur_member: member,\n activity_type: \"login\",\n remote_addr: remote_addr,\n user_agent: request.user_agent)\n\n ref = URI::decode(params[:ref] || flash[:ref] || \"\")\n ref = redirect_url if ref.blank?\n flash.discard(:ref)\n\n redirect_to ref\n end", "label_name": "CWE-601", "label": 11} +{"code": " it 'should verify a standard RS256 token' do\n domain = 'example.org'\n sub = 'abc123'\n payload = {\n sub: sub,\n exp: future_timecode,\n iss: \"https://#{domain}/\",\n iat: past_timecode,\n aud: client_id,\n kid: jwks_kid\n }\n token = make_rs256_token(payload)\n verified_token = make_jwt_validator(opt_domain: domain).verify(token)\n expect(verified_token['sub']).to eq(sub)\n end", "label_name": "CWE-347", "label": 25} +{"code": " def initialize(attribute = nil, direction = nil)\n @attribute = attribute\n @direction = direction || :asc\n end", "label_name": "CWE-89", "label": 0} +{"code": " it \"should raise an error if the image fails an integrity check when downloaded\" do\n stub_request(:get, \"www.example.com/test.jpg\").to_return(body: File.read(file_path(\"test.jpg\")))\n\n expect(running {\n @instance.remote_image_url = \"http://www.example.com/test.jpg\"\n }).to raise_error(CarrierWave::IntegrityError)\n end", "label_name": "CWE-918", "label": 16} +{"code": " def updated_ajax\n @user = current_site.users.find(params[:user_id])\n render inline: @user.update(params.require(:password).permit!) ? \"\" : @user.errors.full_messages.join(', ')\n end", "label_name": "CWE-613", "label": 7} +{"code": " def mime_magic_content_type(new_file)\n content_type = nil\n\n File.open(new_file.path) do |fd|\n content_type = Marcel::MimeType.for(fd)\n end\n\n content_type\n end", "label_name": "CWE-79", "label": 1} +{"code": " def group_link(uniqueid, data)\n notification = t(\n \"notifications.group.#{data[:type]}\",\n name: data[:user],\n group_name: data[:group]\n )\n link = \"/groups/#{data[:group_id]}\"\n notification_link(uniqueid, link, notification)\n end", "label_name": "CWE-79", "label": 1} +{"code": " it \"should get a 200 with html for an authorized user\" do\n\n def @bus.is_admin_lookup\n proc { |_| true }\n end\n\n get \"/message-bus/_diagnostics\"\n last_response.status.must_equal 200\n end", "label_name": "CWE-22", "label": 2} +{"code": " it \"should return a 403 if a user attempts to get at the _diagnostics path\" do\n get \"/message-bus/_diagnostics\"\n last_response.status.must_equal 403\n end", "label_name": "CWE-22", "label": 2} +{"code": " def base_api_url\n computed_api_endpoint = \"https://#{get_data_center_from_api_key(self.api_key)}api.mailchimp.com\"\n raise Gibbon::GibbonError, \"SSRF attempt\" unless URI(computed_api_endpoint).host.include?(\"api.mailchimp.com\")\n\n \"#{self.api_endpoint || computed_api_endpoint}/3.0/\"\n end", "label_name": "CWE-918", "label": 16} +{"code": "func TestReadRequest_BadConnectHost(t *testing.T) {\n\tdata := []byte(\"CONNECT []%20%48%54%54%50%2f%31%2e%31%0a%4d%79%48%65%61%64%65%72%3a%20%31%32%33%0a%0a HTTP/1.0\\n\\n\")\n\tr, err := ReadRequest(bufio.NewReader(bytes.NewReader(data)))\n\tif err == nil {\n\t\tt.Fatal(\"Got unexpected request = %#v\", r)\n\t}\n}", "label_name": "CWE-444", "label": 41} +{"code": "func SearchUserByName(opt SearchOption) (us []*User, err error) {\n\topt.Keyword = FilterSQLInject(opt.Keyword)\n\tif len(opt.Keyword) == 0 {\n\t\treturn us, nil\n\t}\n\topt.Keyword = strings.ToLower(opt.Keyword)\n\n\tus = make([]*User, 0, opt.Limit)\n\terr = x.Limit(opt.Limit).Where(\"type=0\").And(\"lower_name like '%\" + opt.Keyword + \"%'\").Find(&us)\n\treturn us, err\n}", "label_name": "CWE-89", "label": 0} +{"code": "func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {\n\tbuffer := make([]byte, len(aad)+len(nonce)+len(ciphertext)+8)\n\tn := 0\n\tn += copy(buffer, aad)\n\tn += copy(buffer[n:], nonce)\n\tn += copy(buffer[n:], ciphertext)\n\tbinary.BigEndian.PutUint64(buffer[n:], uint64(len(aad)*8))\n\n\t// According to documentation, Write() on hash.Hash never fails.\n\thmac := hmac.New(ctx.hash, ctx.integrityKey)\n\t_, _ = hmac.Write(buffer)\n\n\treturn hmac.Sum(nil)[:ctx.authtagBytes]\n}", "label_name": "CWE-190", "label": 19} +{"code": "func main() {\n\tif len(os.Args) < 3 {\n\t\tfatal(usage)\n\t}\n\n\tcmd, filename := os.Args[1], os.Args[2]\n\n\tff := archiver.MatchingFormat(filename)\n\tif ff == nil {\n\t\tfatalf(\"%s: Unsupported file extension\", filename)\n\t}\n\n\tvar err error\n\tswitch cmd {\n\tcase \"make\":\n\t\tif len(os.Args) < 4 {\n\t\t\tfatal(usage)\n\t\t}\n\t\terr = ff.Make(filename, os.Args[3:])\n\tcase \"open\":\n\t\tdest := \"\"\n\t\tif len(os.Args) == 4 {\n\t\t\tdest = os.Args[3]\n\t\t} else if len(os.Args) > 4 {\n\t\t\tfatal(usage)\n\t\t}\n\t\terr = ff.Open(filename, dest)\n\tdefault:\n\t\tfatal(usage)\n\t}\n\tif err != nil {\n\t\tfatal(err)\n\t}\n}", "label_name": "CWE-22", "label": 2} +{"code": "func validateAndCreateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) {\n\tc.Data[\"Webhook\"] = w\n\n\tif c.HasError() {\n\t\tc.Success(orCtx.TmplNew)\n\t\treturn\n\t}\n\n\tfield, msg, ok := validateWebhook(c.User, c.Locale, w)\n\tif !ok {\n\t\tc.FormErr(field)\n\t\tc.RenderWithErr(msg, orCtx.TmplNew, nil)\n\t\treturn\n\t}\n\n\tif err := w.UpdateEvent(); err != nil {\n\t\tc.Error(err, \"update event\")\n\t\treturn\n\t} else if err := db.CreateWebhook(w); err != nil {\n\t\tc.Error(err, \"create webhook\")\n\t\treturn\n\t}\n\n\tc.Flash.Success(c.Tr(\"repo.settings.add_hook_success\"))\n\tc.Redirect(orCtx.Link + \"/settings/hooks\")\n}", "label_name": "CWE-918", "label": 16} +{"code": "func TestSkipUnknownTypeBinaryProtocol(t *testing.T) {\n\tvar m MyTestStruct\n\td := NewDeserializer()\n\tf := NewBinaryProtocolFactoryDefault()\n\td.Protocol = f.GetProtocol(d.Transport)\n\t// skip over a map with invalid key/value type and 1.7B entries\n\tdata := []byte(\"\\n\\x10\\rO\\t6\\x03\\n\\n\\n\\x10\\r\\n\\tslice\\x00\")\n\tstart := time.Now()\n\terr := d.Read(&m, data)\n\tif err == nil {\n\t\tt.Fatalf(\"Parsed invalid message correctly\")\n\t} else if !strings.Contains(err.Error(), \"unknown type\") {\n\t\tt.Fatalf(\"Failed for reason besides unknown type\")\n\t}\n\n\tif time.Now().Sub(start).Seconds() > 5 {\n\t\tt.Fatalf(\"It should not take seconds to parse a small message\")\n\t}\n}", "label_name": "CWE-770", "label": 37} +{"code": "\tappendMessage = func(targetOffset uint32) bool {\n\t\tfor _, f := range frags {\n\t\t\tif f.handshakeHeader.FragmentOffset == targetOffset {\n\t\t\t\tfragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength)\n\t\t\t\tif fragmentEnd != f.handshakeHeader.Length {\n\t\t\t\t\tif !appendMessage(fragmentEnd) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trawMessage = append(f.data, rawMessage...)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}", "label_name": "CWE-835", "label": 42} +{"code": "func (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\th.L.Warnln(\"It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.\")\n\th.L.Warnln(\"A client requested the default login & consent URL, environment variable OAUTH2_CONSENT_URL or OAUTH2_LOGIN_URL or both are probably not set.\")\n\n\tw.Write([]byte(`\n\n\n\tMisconfigured consent/login URL\n\n\n

    \n\tIt looks like you forgot to set the consent/login provider url, which can be set using the OAUTH2_CONSENT_URL and OAUTH2_LOGIN_URL\n\tenvironment variable.\n

    \n

    \n\tIf you are an administrator, please read \n\tthe guide to understand what you need to do. If you are a user, please contact the administrator.\n

    \n\n\n`))\n}", "label_name": "CWE-79", "label": 1} +{"code": "func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\th.L.Warnln(\"A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.\")\n\n\tfmt.Fprintf(w, `\n\n\n\tAn OAuth 2.0 Error Occurred\n\n\n

    \n\tThe OAuth2 request resulted in an error.\n

    \n
      \n\t
    • Error: %s
    • \n\t
    • Description: %s
    • \n\t
    • Hint: %s
    • \n\t
    • Debug: %s
    • \n
    \n

    \n\tYou are seeing this default error page because the administrator has not set a dedicated error URL (environment variable OAUTH2_ERROR_URL is not set). \n\tIf you are an administrator, please read the guide to understand what you\n\tneed to do. If you are a user, please contact the administrator.\n

    \n\n\n`, r.URL.Query().Get(\"error\"), r.URL.Query().Get(\"error_description\"), r.URL.Query().Get(\"error_hint\"), r.URL.Query().Get(\"error_debug\"))\n}", "label_name": "CWE-79", "label": 1} +{"code": "\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}", "label_name": "CWE-843", "label": 43} +{"code": "\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}", "label_name": "CWE-915", "label": 35} +{"code": "func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {\n\tpluginID := web.Params(c.Req)[\":pluginId\"]\n\tplugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID)\n\tif !exists {\n\t\tc.JsonApiErr(404, \"Plugin not found\", nil)\n\t\treturn\n\t}\n\n\trequestedFile := filepath.Clean(web.Params(c.Req)[\"*\"])\n\tpluginFilePath := filepath.Join(plugin.PluginDir, requestedFile)\n\n\tif !plugin.IncludedInSignature(requestedFile) {\n\t\ths.log.Warn(\"Access to requested plugin file will be forbidden in upcoming Grafana versions as the file \"+\n\t\t\t\"is not included in the plugin signature\", \"file\", requestedFile)\n\t}\n\n\t// It's safe to ignore gosec warning G304 since we already clean the requested file path and subsequently\n\t// use this with a prefix of the plugin's directory, which is set during plugin loading\n\t// nolint:gosec\n\tf, err := os.Open(pluginFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tc.JsonApiErr(404, \"Plugin file not found\", err)\n\t\t\treturn\n\t\t}\n\t\tc.JsonApiErr(500, \"Could not open plugin file\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := f.Close(); err != nil {\n\t\t\ths.log.Error(\"Failed to close file\", \"err\", err)\n\t\t}\n\t}()\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\tc.JsonApiErr(500, \"Plugin file exists but could not open\", err)\n\t\treturn\n\t}\n\n\tif hs.Cfg.Env == setting.Dev {\n\t\tc.Resp.Header().Set(\"Cache-Control\", \"max-age=0, must-revalidate, no-cache\")\n\t} else {\n\t\tc.Resp.Header().Set(\"Cache-Control\", \"public, max-age=3600\")\n\t}\n\n\thttp.ServeContent(c.Resp, c.Req, pluginFilePath, fi.ModTime(), f)\n}", "label_name": "CWE-22", "label": 2} +{"code": "func (x *GetWalletLedgerRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[45]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 7} +{"code": "func (*MatchState) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{31}\n}", "label_name": "CWE-613", "label": 7} +{"code": "func (x *ListGroupsRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[27]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 7} +{"code": "func (x *ListSubscriptionsRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[29]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 7} +{"code": "func (*MatchStateRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{32}\n}", "label_name": "CWE-613", "label": 7} +{"code": "func (x *LeaderboardRequest) ProtoReflect() protoreflect.Message {\n\tmi := &file_console_proto_msgTypes[25]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}", "label_name": "CWE-613", "label": 7} +{"code": "func (s *ConsoleServer) Authenticate(ctx context.Context, in *console.AuthenticateRequest) (*console.ConsoleSession, error) {\n\trole := console.UserRole_USER_ROLE_UNKNOWN\n\tvar uname string\n\tvar email string\n\tvar id uuid.UUID\n\tswitch in.Username {\n\tcase s.config.GetConsole().Username:\n\t\tif in.Password == s.config.GetConsole().Password {\n\t\t\trole = console.UserRole_USER_ROLE_ADMIN\n\t\t\tuname = in.Username\n\t\t\tid = uuid.Nil\n\t\t}\n\tdefault:\n\t\tvar err error\n\t\tid, uname, email, role, err = s.lookupConsoleUser(ctx, in.Username, in.Password)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif role == console.UserRole_USER_ROLE_UNKNOWN {\n\t\treturn nil, status.Error(codes.Unauthenticated, \"Invalid credentials.\")\n\t}\n\n\texp := time.Now().UTC().Add(time.Duration(s.config.GetConsole().TokenExpirySec) * time.Second).Unix()\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, &ConsoleTokenClaims{\n\t\tExpiresAt: exp,\n\t\tID: id.String(),\n\t\tUsername: uname,\n\t\tEmail: email,\n\t\tRole: role,\n\t\tCookie: s.cookie,\n\t})\n\tkey := []byte(s.config.GetConsole().SigningKey)\n\tsignedToken, _ := token.SignedString(key)\n\n\ts.consoleSessionCache.Add(id, exp, signedToken, 0, \"\")\n\treturn &console.ConsoleSession{Token: signedToken}, nil\n}", "label_name": "CWE-307", "label": 26} +{"code": "func AppList(c *gin.Context) {\n\n\t//service.MyService.Docker().DockerContainerCommit(\"test2\")\n\n\tindex := c.DefaultQuery(\"index\", \"1\")\n\tsize := c.DefaultQuery(\"size\", \"10000\")\n\tt := c.DefaultQuery(\"type\", \"rank\")\n\tcategoryId := c.DefaultQuery(\"category_id\", \"0\")\n\tkey := c.DefaultQuery(\"key\", \"\")\n\trecommend, list, community := service.MyService.OAPI().GetServerList(index, size, t, categoryId, key)\n\t// for i := 0; i < len(recommend); i++ {\n\t// \tct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion)\n\t// \tif ct != nil {\n\t// \t\trecommend[i].State = ct.State\n\t// \t}\n\t// }\n\t// for i := 0; i < len(list); i++ {\n\t// \tct, _ := service.MyService.Docker().DockerListByImage(list[i].Image, list[i].ImageVersion)\n\t// \tif ct != nil {\n\t// \t\tlist[i].State = ct.State\n\t// \t}\n\t// }\n\t// for i := 0; i < len(community); i++ {\n\t// \tct, _ := service.MyService.Docker().DockerListByImage(community[i].Image, community[i].ImageVersion)\n\t// \tif ct != nil {\n\t// \t\tcommunity[i].State = ct.State\n\t// \t}\n\t// }\n\tdata := make(map[string]interface{}, 3)\n\tdata[\"recommend\"] = recommend\n\tdata[\"list\"] = list\n\tdata[\"community\"] = community\n\n\tc.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})\n}", "label_name": "CWE-78", "label": 6} +{"code": " content: Buffer.concat(buffers),\n mimeType: resp.headers[\"content-type\"] || null,\n });\n });", "label_name": "CWE-918", "label": 16} +{"code": " _resolvePath(path = '.') {\n const clientPath = (() => {\n path = nodePath.normalize(path);\n if (nodePath.isAbsolute(path)) {\n return nodePath.join(path);\n } else {\n return nodePath.join(this.cwd, path);\n }\n })();\n\n const fsPath = (() => {\n const resolvedPath = nodePath.join(this.root, clientPath);\n return nodePath.resolve(nodePath.normalize(nodePath.join(resolvedPath)));\n })();\n\n return {\n clientPath,\n fsPath\n };\n }", "label_name": "CWE-22", "label": 2} +{"code": "function networkStats(ifaces, callback) {\n\n let ifacesArray = [];\n // fallback - if only callback is given\n if (util.isFunction(ifaces) && !callback) {\n callback = ifaces;\n ifacesArray = [getDefaultNetworkInterface()];\n } else {\n ifaces = ifaces || getDefaultNetworkInterface();\n ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');\n ifacesArray = ifaces.split('|');\n }\n\n return new Promise((resolve) => {\n process.nextTick(() => {\n\n const result = [];\n\n const workload = [];\n if (ifacesArray.length && ifacesArray[0].trim() === '*') {\n ifacesArray = [];\n networkInterfaces(false).then(allIFaces => {\n for (let iface of allIFaces) {\n ifacesArray.push(iface.iface);\n }\n networkStats(ifacesArray.join(',')).then(result => {\n if (callback) { callback(result); }\n resolve(result);\n });\n });\n } else {\n for (let iface of ifacesArray) {\n workload.push(networkStatsSingle(iface.trim()));\n }\n if (workload.length) {\n Promise.all(\n workload\n ).then(data => {\n if (callback) { callback(data); }\n resolve(data);\n });\n } else {\n if (callback) { callback(result); }\n resolve(result);\n }\n }\n });\n });\n}", "label_name": "CWE-78", "label": 6} +{"code": "function has(target, path) {\n \"use strict\";\n try {\n var test = reduce(target, path);\n if ( typeof test !== \"undefined\") {\n return true;\n }\n return false;\n } catch(ex) {\n console.error(ex);\n return;\n }\n}", "label_name": "CWE-915", "label": 35} +{"code": "\t\t([ key, value ]) => ({ [key]: exec.bind(null, value) }),\n\t),", "label_name": "CWE-78", "label": 6} +{"code": "\t\t([ key, value ]) => ({ [key]: list.bind(null, value) }),\n\t),", "label_name": "CWE-78", "label": 6} +{"code": " Object.keys(data).forEach((key) => {\n obj.add(deserializer(data[key], baseType) as T);\n });", "label_name": "CWE-915", "label": 35} +{"code": " schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propertyMetadata.type)};\n }\n\n schemaTypeOptions = cleanProps({...schemaTypeOptions, ...rawMongooseSchema});\n\n if (propertyMetadata.isCollection) {\n if (propertyMetadata.isArray) {\n schemaTypeOptions = [schemaTypeOptions];\n } else {\n // Can be a Map or a Set;\n // Mongoose implements only Map;\n if (propertyMetadata.collectionType !== Map) {\n throw new Error(`Invalid collection type. ${propertyMetadata.collectionName} is not supported.`);\n }\n\n schemaTypeOptions = {type: Map, of: schemaTypeOptions};\n }\n }\n\n return schemaTypeOptions;\n}", "label_name": "CWE-915", "label": 35} +{"code": " constructor({asset, message, onClick}: Params, element: HTMLElement) {\n super(message);\n this.asset = asset;\n this.message = message;\n this.isVisible = ko.observable(false);\n this.onClick = (_data, event) => onClick(message, event);\n\n this.dummyImageUrl = `data:image/svg+xml;utf8,`;\n\n this.imageUrl = ko.observable();\n\n this.isIdle = () => this.uploadProgress() === -1 && !this.asset.resource() && !this.message.isObfuscated();\n\n ko.computed(\n () => {\n if (this.isVisible() && asset.resource()) {\n this.assetRepository\n .load(asset.resource())\n .then(blob => {\n this.imageUrl(window.URL.createObjectURL(blob));\n })\n .catch(error => console.error(error));\n }\n },\n {disposeWhenNodeIsRemoved: element},\n );\n\n this.container = element;\n viewportObserver.onElementInViewport(this.container, () => this.isVisible(true));\n }", "label_name": "CWE-79", "label": 1} +{"code": "export async function loadFromGit(input: Input): Promise {\n try {\n return await new Promise((resolve, reject) => {\n exec(createCommand(input), { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => {\n if (error) {\n reject(error);\n } else {\n resolve(stdout);\n }\n });\n });\n } catch (error) {\n throw createLoadError(error);\n }\n}", "label_name": "CWE-78", "label": 6} +{"code": " switchToInvites: async () => {\n await this.waitAndClick('.e_InvTabB');\n await this.invitedUsersList.waitUntilLoaded();\n },", "label_name": "CWE-613", "label": 7} +{"code": "export function html(m, keyPath, ...args) {\n const html = str(m, keyPath, ...args);\n\n return html ? React.createElement('span', { dangerouslySetInnerHTML: { __html: html } }) : null;\n}", "label_name": "CWE-79", "label": 1} +{"code": " `${c.amount(d.value, d.name)}${day(d.date)}`,\n });\n}", "label_name": "CWE-79", "label": 1} +{"code": "export function initSidebar(): void {\n const errorCountEl = document.getElementById(\"error-count\");\n if (errorCountEl instanceof HTMLLIElement) {\n errorCount.subscribe((errorCount_val) => {\n errorCountEl.classList.toggle(\"hidden\", errorCount_val === 0);\n const span = errorCountEl.querySelector(\"span\");\n if (span) {\n span.innerHTML = `${errorCount_val}`;\n }\n });\n }\n\n const asideButton = document.getElementById(\"aside-button\");\n if (asideButton instanceof HTMLButtonElement) {\n asideButton.addEventListener(\"click\", () => {\n document.querySelector(\"aside\")?.classList.toggle(\"active\");\n asideButton.classList.toggle(\"active\");\n });\n }\n}", "label_name": "CWE-79", "label": 1} +{"code": "function text({ url, host }: Record<\"url\" | \"host\", string>) {\n return `Sign in to ${host}\\n${url}\\n\\n`\n}", "label_name": "CWE-79", "label": 1}