prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/*\n * Functions relative to short URLs: adding, editing, etc\n * (either proper short URLs (\"http://sho.rt/abc\") or \"keywords\" (the \"abc\" part)\n */", "\n/**\n * Add a new link in the DB, either with custom keyword, or find one\n *\n * The return array will contain at least the following keys:\n * status: string, 'success' or 'fail'\n * message: string, a descriptive localized message of what happened in any case\n * code: string, a short descriptivish and untranslated message describing what happened\n *\n * Depending on the operation, it will contain any of the following keys:\n * errorCode: string, a HTTP status code\n * url: array, the short URL creation information, with the following keys: 'keyword', 'url', 'title', 'date', 'ip'\n * title: string, the URL title\n * shorturl: string, the proper short URL in full (eg 'http://sho.rt/abc')\n * html: string, the HTML part used by the ajax to update the page display if any\n *\n * @param string $url URL to shorten\n * @param string $keyword optional \"keyword\"\n * @param string $title option title\n * @return array array with error/success state and short URL information\n */\nfunction yourls_add_new_link( $url, $keyword = '', $title = '' ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );\n if ( false !== $pre )\n return $pre;", " $url = yourls_sanitize_url( $url );\n if ( !$url || $url == 'http://' || $url == 'https://' ) {\n $return['status'] = 'fail';\n $return['code'] = 'error:nourl';\n $return['message'] = yourls__( 'Missing or malformed URL' );\n $return['errorCode'] = '400';\n return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );\n }", " // Prevent DB flood\n $ip = yourls_get_IP();\n yourls_check_IP_flood( $ip );", " // Prevent internal redirection loops: cannot shorten a shortened URL\n if( yourls_get_relative_url( $url ) ) {\n if( yourls_is_shorturl( $url ) ) {\n $return['status'] = 'fail';\n $return['code'] = 'error:noloop';\n $return['message'] = yourls__( 'URL is a short URL' );\n $return['errorCode'] = '400';\n return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );\n }\n }", " yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );", " $return = array();", " // duplicates allowed or new URL => store it\n if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_long_url_exists( $url ) ) ) {", " if( isset( $title ) && !empty( $title ) ) {\n $title = yourls_sanitize_title( $title );\n } else {\n $title = yourls_get_remote_title( $url );\n }\n $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );", " // Custom keyword provided\n if ( $keyword ) {", " yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );", " $keyword = yourls_sanitize_keyword( $keyword, true );\n $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );", " if ( !yourls_keyword_is_free( $keyword ) ) {\n // This shorturl either reserved or taken already\n $return['status'] = 'fail';\n $return['code'] = 'error:keyword';\n $return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );\n } else {\n // all clear, store !\n yourls_insert_link_in_db( $url, $keyword, $title );\n $return['url'] = array('keyword' => $keyword, 'url' => $url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );\n $return['status'] = 'success';\n $return['message'] = /* //translators: eg \"http://someurl/ added to DB\" */ yourls_s( '%s added to database', yourls_trim_long_string( $url ) );\n $return['title'] = $title;\n $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );\n $return['shorturl'] = yourls_link($keyword);\n }", " // Create random keyword\n } else {", " yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );", " $timestamp = date( 'Y-m-d H:i:s' );\n $id = yourls_get_next_decimal();\n $ok = false;\n do {\n $keyword = yourls_int2string( $id );\n $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );\n if ( yourls_keyword_is_free($keyword) ) {\n if (yourls_insert_link_in_db( $url, $keyword, $title )){\n // everything ok, populate needed vars\n $return['url'] = array('keyword' => $keyword, 'url' => $url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );\n $return['status'] = 'success';\n $return['message'] = /* //translators: eg \"http://someurl/ added to DB\" */ yourls_s( '%s added to database', yourls_trim_long_string( $url ) );\n $return['title'] = $title;\n $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );\n $return['shorturl'] = yourls_link($keyword);\n } else {\n // database error, couldnt store result\n $return['status'] = 'fail';\n $return['code'] = 'error:db';\n $return['message'] = yourls_s( 'Error saving url to database' );\n }\n $ok = true;\n }\n $id++;\n } while ( !$ok );\n @yourls_update_next_decimal( $id );\n }", " // URL was already stored\n } else {", " yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );", " $return['status'] = 'fail';\n $return['code'] = 'error:url';\n $return['url'] = array( 'keyword' => $url_exists->keyword, 'url' => $url, 'title' => $url_exists->title, 'date' => $url_exists->timestamp, 'ip' => $url_exists->ip, 'clicks' => $url_exists->clicks );\n $return['message'] = /* //translators: eg \"http://someurl/ already exists\" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $url ) );\n $return['title'] = $url_exists->title;\n $return['shorturl'] = yourls_link($url_exists->keyword);\n }", " yourls_do_action( 'post_add_new_link', $url, $keyword, $title, $return );", " $return['statusCode'] = 200; // regardless of result, this is still a valid request\n return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );\n}", "/**\n * Determine the allowed character set in short URLs\n *\n * @return string Acceptable charset for short URLS keywords\n */\nfunction yourls_get_shorturl_charset() {\n static $charset = null;\n if ( $charset !== null ) {\n return $charset;\n }", " if ( defined( 'YOURLS_URL_CONVERT' ) && in_array( YOURLS_URL_CONVERT, [ 62, 64 ] ) ) {\n $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n }\n else {\n // defined to 36, or wrongly defined\n $charset = '0123456789abcdefghijklmnopqrstuvwxyz';\n }", " return yourls_apply_filter( 'get_shorturl_charset', $charset );\n}", "/**\n * Is a URL a short URL? Accept either 'http://sho.rt/abc' or 'abc'\n *\n * @param string $shorturl short URL\n * @return bool true if registered short URL, false otherwise\n */\nfunction yourls_is_shorturl( $shorturl ) {\n // TODO: make sure this function evolves with the feature set.", " $is_short = false;", " // Is $shorturl a URL (http://sho.rt/abc) or a keyword (abc) ?\n if( yourls_get_protocol( $shorturl ) ) {\n $keyword = yourls_get_relative_url( $shorturl );\n } else {\n $keyword = $shorturl;\n }", " // Check if it's a valid && used keyword\n if( $keyword && $keyword == yourls_sanitize_keyword( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {\n $is_short = true;\n }", " return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );\n}", "/**\n * Check to see if a given keyword is reserved (ie reserved URL or an existing page). Returns bool\n *\n * @param string $keyword Short URL keyword\n * @return bool True if keyword reserved, false if free to be used\n */\nfunction yourls_keyword_is_reserved( $keyword ) {\n global $yourls_reserved_URL;\n $keyword = yourls_sanitize_keyword( $keyword );\n $reserved = false;", " if ( in_array( $keyword, $yourls_reserved_URL)\n or yourls_is_page($keyword)\n or is_dir( YOURLS_ABSPATH .\"/$keyword\" )\n )\n $reserved = true;", " return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );\n}", "/**\n * Delete a link in the DB\n *\n */\nfunction yourls_delete_link_by_keyword( $keyword ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_delete_link_by_keyword', null, $keyword );\n if ( null !== $pre ) {\n return $pre;\n }", " $table = YOURLS_DB_TABLE_URL;\n $keyword = yourls_sanitize_keyword($keyword);\n $delete = yourls_get_db()->fetchAffected(\"DELETE FROM `$table` WHERE `keyword` = :keyword\", array('keyword' => $keyword));\n yourls_do_action( 'delete_link', $keyword, $delete );\n return $delete;\n}", "/**\n * SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting\n *\n */\nfunction yourls_insert_link_in_db( $url, $keyword, $title = '' ) {\n $url = yourls_sanitize_url($url);\n $keyword = yourls_sanitize_keyword($keyword);\n $title = yourls_sanitize_title($title);\n $timestamp = date('Y-m-d H:i:s');\n $ip = yourls_get_IP();", " $table = YOURLS_DB_TABLE_URL;\n $binds = array(\n 'keyword' => $keyword,\n 'url' => $url,\n 'title' => $title,\n 'timestamp' => $timestamp,\n 'ip' => $ip,\n );\n $insert = yourls_get_db()->fetchAffected(\"INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES(:keyword, :url, :title, :timestamp, :ip, 0);\", $binds);", " yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );", " return (bool)$insert;\n}", "/**\n * Check if a long URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.\n *\n * This function supersedes function yourls_url_exists(), deprecated in 1.7.10, with a better naming.\n *\n * @since 1.7.10\n * @param string $url URL to check if already shortened\n * @return mixed NULL if does not already exist in DB, or object with URL information as properties (eg keyword, url, title, ...)\n */\nfunction yourls_long_url_exists( $url ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_url_exists', false, $url );\n if ( false !== $pre ) {\n return $pre;\n }", " $table = YOURLS_DB_TABLE_URL;\n $url = yourls_sanitize_url($url);\n $url_exists = yourls_get_db()->fetchObject(\"SELECT * FROM `$table` WHERE `url` = :url\", array('url'=>$url));", " if ($url_exists === false) {\n $url_exists = NULL;\n }", " return yourls_apply_filter( 'url_exists', $url_exists, $url );\n}", "/**\n * Edit a link\n *\n */\nfunction yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_edit_link', null, $keyword, $url, $keyword, $newkeyword, $title );\n if ( null !== $pre )\n return $pre;", " $ydb = yourls_get_db();", " $table = YOURLS_DB_TABLE_URL;\n $url = yourls_sanitize_url($url);\n $keyword = yourls_sanitize_keyword($keyword);\n $title = yourls_sanitize_title($title);\n $newkeyword = yourls_sanitize_keyword($newkeyword, true);", " $strip_url = stripslashes( $url );\n $strip_title = stripslashes( $title );", "\n if(!$url OR !$newkeyword) {\n $return['status'] = 'fail';\n $return['message'] = yourls__( 'Long URL or Short URL cannot be blank' );\n return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title );\n }", " $old_url = $ydb->fetchValue(\"SELECT `url` FROM `$table` WHERE `keyword` = :keyword\", array('keyword' => $keyword));", " // Check if new URL is not here already\n if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {\n $new_url_already_there = intval($ydb->fetchValue(\"SELECT COUNT(keyword) FROM `$table` WHERE `url` = :url;\", array('url' => $url)));\n } else {\n $new_url_already_there = false;\n }", " // Check if the new keyword is not here already\n if ( $newkeyword != $keyword ) {\n $keyword_is_ok = yourls_keyword_is_free( $newkeyword );\n } else {\n $keyword_is_ok = true;\n }", " yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );", " // All clear, update\n if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {\n $sql = \"UPDATE `$table` SET `url` = :url, `keyword` = :newkeyword, `title` = :title WHERE `keyword` = :keyword\";\n $binds = array('url' => $url, 'newkeyword' => $newkeyword, 'title' => $title, 'keyword' => $keyword);\n $update_url = $ydb->fetchAffected($sql, $binds);\n if( $update_url ) {", " $return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => yourls_link($newkeyword), 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'title' => $strip_title, 'display_title' => yourls_trim_long_string( $strip_title ) );", " $return['status'] = 'success';\n $return['message'] = yourls__( 'Link updated in database' );\n } else {\n $return['status'] = 'fail';", " $return['message'] = /* //translators: \"Error updating http://someurl/ (Shorturl: http://sho.rt/blah)\" */ yourls_s( 'Error updating %s (Short URL: %s)', yourls_trim_long_string( $strip_url ), $keyword ) ;", " }", " // Nope\n } else {\n $return['status'] = 'fail';\n $return['message'] = yourls__( 'URL or keyword already exists in database' );\n }", " return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );\n}", "/**\n * Update a title link (no checks for duplicates etc..)\n *\n */\nfunction yourls_edit_link_title( $keyword, $title ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_edit_link_title', null, $keyword, $title );\n if ( null !== $pre ) {\n return $pre;\n }", " $keyword = yourls_sanitize_keyword( $keyword );\n $title = yourls_sanitize_title( $title );", " $table = YOURLS_DB_TABLE_URL;\n $update = yourls_get_db()->fetchAffected(\"UPDATE `$table` SET `title` = :title WHERE `keyword` = :keyword;\", array('title' => $title, 'keyword' => $keyword));", " return $update;\n}", "/**\n * Check if keyword id is free (ie not already taken, and not reserved). Return bool.\n *\n * @param string $keyword short URL keyword\n * @return bool true if keyword is taken (ie there is a short URL for it), false otherwise\n */\nfunction yourls_keyword_is_free( $keyword ) {\n $free = true;\n if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword, false ) ) {\n $free = false;\n }", " return yourls_apply_filter( 'keyword_is_free', $free, $keyword );\n}", "/**\n * Check if a keyword matches a \"page\"\n *\n * @see https://github.com/YOURLS/YOURLS/wiki/Pages\n * @since 1.7.10\n * @param string $keyword Short URL $keyword\n * @return bool true if is page, false otherwise\n */\nfunction yourls_is_page($keyword) {\n return yourls_apply_filter( 'is_page', file_exists( YOURLS_PAGEDIR . \"/$keyword.php\" ) );\n}", "/**\n * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.\n *\n */\n/**\n * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.\n *\n * @param string $keyword short URL keyword\n * @param bool $use_cache optional, default true: do we want to use what is cached in memory, if any, or force a new SQL query\n * @return bool true if keyword is taken (ie there is a short URL for it), false otherwise\n */\nfunction yourls_keyword_is_taken( $keyword, $use_cache = true ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_keyword_is_taken', false, $keyword );\n if ( false !== $pre ) {\n return $pre;\n }", " $taken = false;\n // To check if a keyword is already associated with a short URL, we fetch all info matching that keyword. This\n // will save a query in case of a redirection in yourls-go.php because info will be cached\n if ( yourls_get_keyword_infos($keyword, $use_cache) ) {\n $taken = true;\n }", " return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );\n}", "/**\n * Return array of all information associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB\n *\n * Sincere apologies to native English speakers, we are aware that the plural of 'info' is actually 'info', not 'infos'.\n * This function yourls_get_keyword_infos() returns all information, while function yourls_get_keyword_info() (no 's') return only\n * one information. Blame YOURLS contributors whose mother tongue is not English :)\n *\n * @since 1.4\n * @param string $keyword Short URL keyword\n * @param bool $use_cache Default true, set to false to force fetching from DB\n * @return false|object false if not found, object with URL properties if found\n */\nfunction yourls_get_keyword_infos( $keyword, $use_cache = true ) {\n $ydb = yourls_get_db();\n $keyword = yourls_sanitize_keyword( $keyword );", " yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );", " if( $ydb->has_infos($keyword) && $use_cache === true ) {\n return yourls_apply_filter( 'get_keyword_infos', $ydb->get_infos($keyword), $keyword );\n }", " yourls_do_action( 'get_keyword_not_cached', $keyword );", " $table = YOURLS_DB_TABLE_URL;\n $infos = $ydb->fetchObject(\"SELECT * FROM `$table` WHERE `keyword` = :keyword\", array('keyword' => $keyword));", " if( $infos ) {\n $infos = (array)$infos;\n $ydb->set_infos($keyword, $infos);\n } else {\n // is NULL if not found\n $infos = false;\n $ydb->set_infos($keyword, false);\n }", " return yourls_apply_filter( 'get_keyword_infos', $infos, $keyword );\n}", "/**\n * Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_info( $keyword, $field, $notfound = false ) {", " // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );\n if ( false !== $pre )\n return $pre;", " $keyword = yourls_sanitize_keyword( $keyword );\n $infos = yourls_get_keyword_infos( $keyword );", " $return = $notfound;\n if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )\n $return = $infos[ $field ];", " return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound );\n}", "/**\n * Return title associated with keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_title( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'title', $notfound );\n}", "/**\n * Return long URL associated with keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_longurl( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'url', $notfound );\n}", "/**\n * Return number of clicks on a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_clicks( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'clicks', $notfound );\n}", "/**\n * Return IP that added a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_IP( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'ip', $notfound );\n}", "/**\n * Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_timestamp( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );\n}", "/**\n * Return array of stats for a given keyword\n *\n * This function supersedes function yourls_get_link_stats(), deprecated in 1.7.10, with a better naming.\n *\n * @since 1.7.10\n * @param string $shorturl short URL keyword\n * @return array stats\n */\nfunction yourls_get_keyword_stats( $shorturl ) {\n $table_url = YOURLS_DB_TABLE_URL;\n $shorturl = yourls_sanitize_keyword( $shorturl );", " $res = yourls_get_db()->fetchObject(\"SELECT * FROM `$table_url` WHERE `keyword` = :keyword\", array('keyword' => $shorturl));\n $return = array();", " if( !$res ) {\n // non existent link\n $return = array(\n 'statusCode' => 404,\n 'message' => 'Error: short URL not found',\n );\n } else {\n $return = array(\n 'statusCode' => 200,\n 'message' => 'success',\n 'link' => array(\n 'shorturl' => yourls_link($res->keyword),\n 'url' => $res->url,\n 'title' => $res->title,\n 'timestamp'=> $res->timestamp,\n 'ip' => $res->ip,\n 'clicks' => $res->clicks,\n )\n );\n }", " return yourls_apply_filter( 'get_link_stats', $return, $shorturl );\n}", "/**\n * Return array of keywords that redirect to the submitted long URL\n *\n * @since 1.7\n * @param string $longurl long url\n * @param string $order Optional SORT order (can be 'ASC' or 'DESC')\n * @return array array of keywords\n */\nfunction yourls_get_longurl_keywords( $longurl, $order = 'ASC' ) {\n $longurl = yourls_sanitize_url($longurl);\n $table = YOURLS_DB_TABLE_URL;\n $sql = \"SELECT `keyword` FROM `$table` WHERE `url` = :url\";", " if (in_array($order, array('ASC','DESC'))) {\n $sql .= \" ORDER BY `keyword` \".$order;\n }", " return yourls_apply_filter( 'get_longurl_keywords', yourls_get_db()->fetchCol($sql, array('url'=>$longurl)), $longurl );\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [343, 41], "buggy_code_start_loc": [304, 41], "filenames": ["includes/functions-shorturls.php", "tests/tests/shorturl/shorturl.php"], "fixing_code_end_loc": [347, 45], "fixing_code_start_loc": [303, 42], "message": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yourls:yourls:*:*:*:*:*:*:*:*", "matchCriteriaId": "6A2C8C7B-8D81-4333-8912-980436C67E17", "versionEndExcluding": "1.8.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "yourls es vulnerable a la Neutralizaci\u00f3n Inapropiada de la Entrada durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-3785", "lastModified": "2021-09-23T19:31:11.840", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-09-15T12:15:16.283", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b4085d13-54fa-4419-a2ce-1d780cc31638"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, "type": "CWE-79"}
281
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/*\n * Functions relative to short URLs: adding, editing, etc\n * (either proper short URLs (\"http://sho.rt/abc\") or \"keywords\" (the \"abc\" part)\n */", "\n/**\n * Add a new link in the DB, either with custom keyword, or find one\n *\n * The return array will contain at least the following keys:\n * status: string, 'success' or 'fail'\n * message: string, a descriptive localized message of what happened in any case\n * code: string, a short descriptivish and untranslated message describing what happened\n *\n * Depending on the operation, it will contain any of the following keys:\n * errorCode: string, a HTTP status code\n * url: array, the short URL creation information, with the following keys: 'keyword', 'url', 'title', 'date', 'ip'\n * title: string, the URL title\n * shorturl: string, the proper short URL in full (eg 'http://sho.rt/abc')\n * html: string, the HTML part used by the ajax to update the page display if any\n *\n * @param string $url URL to shorten\n * @param string $keyword optional \"keyword\"\n * @param string $title option title\n * @return array array with error/success state and short URL information\n */\nfunction yourls_add_new_link( $url, $keyword = '', $title = '' ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );\n if ( false !== $pre )\n return $pre;", " $url = yourls_sanitize_url( $url );\n if ( !$url || $url == 'http://' || $url == 'https://' ) {\n $return['status'] = 'fail';\n $return['code'] = 'error:nourl';\n $return['message'] = yourls__( 'Missing or malformed URL' );\n $return['errorCode'] = '400';\n return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );\n }", " // Prevent DB flood\n $ip = yourls_get_IP();\n yourls_check_IP_flood( $ip );", " // Prevent internal redirection loops: cannot shorten a shortened URL\n if( yourls_get_relative_url( $url ) ) {\n if( yourls_is_shorturl( $url ) ) {\n $return['status'] = 'fail';\n $return['code'] = 'error:noloop';\n $return['message'] = yourls__( 'URL is a short URL' );\n $return['errorCode'] = '400';\n return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );\n }\n }", " yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );", " $return = array();", " // duplicates allowed or new URL => store it\n if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_long_url_exists( $url ) ) ) {", " if( isset( $title ) && !empty( $title ) ) {\n $title = yourls_sanitize_title( $title );\n } else {\n $title = yourls_get_remote_title( $url );\n }\n $title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );", " // Custom keyword provided\n if ( $keyword ) {", " yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );", " $keyword = yourls_sanitize_keyword( $keyword, true );\n $keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );", " if ( !yourls_keyword_is_free( $keyword ) ) {\n // This shorturl either reserved or taken already\n $return['status'] = 'fail';\n $return['code'] = 'error:keyword';\n $return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );\n } else {\n // all clear, store !\n yourls_insert_link_in_db( $url, $keyword, $title );\n $return['url'] = array('keyword' => $keyword, 'url' => $url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );\n $return['status'] = 'success';\n $return['message'] = /* //translators: eg \"http://someurl/ added to DB\" */ yourls_s( '%s added to database', yourls_trim_long_string( $url ) );\n $return['title'] = $title;\n $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );\n $return['shorturl'] = yourls_link($keyword);\n }", " // Create random keyword\n } else {", " yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );", " $timestamp = date( 'Y-m-d H:i:s' );\n $id = yourls_get_next_decimal();\n $ok = false;\n do {\n $keyword = yourls_int2string( $id );\n $keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );\n if ( yourls_keyword_is_free($keyword) ) {\n if (yourls_insert_link_in_db( $url, $keyword, $title )){\n // everything ok, populate needed vars\n $return['url'] = array('keyword' => $keyword, 'url' => $url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );\n $return['status'] = 'success';\n $return['message'] = /* //translators: eg \"http://someurl/ added to DB\" */ yourls_s( '%s added to database', yourls_trim_long_string( $url ) );\n $return['title'] = $title;\n $return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );\n $return['shorturl'] = yourls_link($keyword);\n } else {\n // database error, couldnt store result\n $return['status'] = 'fail';\n $return['code'] = 'error:db';\n $return['message'] = yourls_s( 'Error saving url to database' );\n }\n $ok = true;\n }\n $id++;\n } while ( !$ok );\n @yourls_update_next_decimal( $id );\n }", " // URL was already stored\n } else {", " yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );", " $return['status'] = 'fail';\n $return['code'] = 'error:url';\n $return['url'] = array( 'keyword' => $url_exists->keyword, 'url' => $url, 'title' => $url_exists->title, 'date' => $url_exists->timestamp, 'ip' => $url_exists->ip, 'clicks' => $url_exists->clicks );\n $return['message'] = /* //translators: eg \"http://someurl/ already exists\" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $url ) );\n $return['title'] = $url_exists->title;\n $return['shorturl'] = yourls_link($url_exists->keyword);\n }", " yourls_do_action( 'post_add_new_link', $url, $keyword, $title, $return );", " $return['statusCode'] = 200; // regardless of result, this is still a valid request\n return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );\n}", "/**\n * Determine the allowed character set in short URLs\n *\n * @return string Acceptable charset for short URLS keywords\n */\nfunction yourls_get_shorturl_charset() {\n static $charset = null;\n if ( $charset !== null ) {\n return $charset;\n }", " if ( defined( 'YOURLS_URL_CONVERT' ) && in_array( YOURLS_URL_CONVERT, [ 62, 64 ] ) ) {\n $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n }\n else {\n // defined to 36, or wrongly defined\n $charset = '0123456789abcdefghijklmnopqrstuvwxyz';\n }", " return yourls_apply_filter( 'get_shorturl_charset', $charset );\n}", "/**\n * Is a URL a short URL? Accept either 'http://sho.rt/abc' or 'abc'\n *\n * @param string $shorturl short URL\n * @return bool true if registered short URL, false otherwise\n */\nfunction yourls_is_shorturl( $shorturl ) {\n // TODO: make sure this function evolves with the feature set.", " $is_short = false;", " // Is $shorturl a URL (http://sho.rt/abc) or a keyword (abc) ?\n if( yourls_get_protocol( $shorturl ) ) {\n $keyword = yourls_get_relative_url( $shorturl );\n } else {\n $keyword = $shorturl;\n }", " // Check if it's a valid && used keyword\n if( $keyword && $keyword == yourls_sanitize_keyword( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {\n $is_short = true;\n }", " return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );\n}", "/**\n * Check to see if a given keyword is reserved (ie reserved URL or an existing page). Returns bool\n *\n * @param string $keyword Short URL keyword\n * @return bool True if keyword reserved, false if free to be used\n */\nfunction yourls_keyword_is_reserved( $keyword ) {\n global $yourls_reserved_URL;\n $keyword = yourls_sanitize_keyword( $keyword );\n $reserved = false;", " if ( in_array( $keyword, $yourls_reserved_URL)\n or yourls_is_page($keyword)\n or is_dir( YOURLS_ABSPATH .\"/$keyword\" )\n )\n $reserved = true;", " return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );\n}", "/**\n * Delete a link in the DB\n *\n */\nfunction yourls_delete_link_by_keyword( $keyword ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_delete_link_by_keyword', null, $keyword );\n if ( null !== $pre ) {\n return $pre;\n }", " $table = YOURLS_DB_TABLE_URL;\n $keyword = yourls_sanitize_keyword($keyword);\n $delete = yourls_get_db()->fetchAffected(\"DELETE FROM `$table` WHERE `keyword` = :keyword\", array('keyword' => $keyword));\n yourls_do_action( 'delete_link', $keyword, $delete );\n return $delete;\n}", "/**\n * SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting\n *\n */\nfunction yourls_insert_link_in_db( $url, $keyword, $title = '' ) {\n $url = yourls_sanitize_url($url);\n $keyword = yourls_sanitize_keyword($keyword);\n $title = yourls_sanitize_title($title);\n $timestamp = date('Y-m-d H:i:s');\n $ip = yourls_get_IP();", " $table = YOURLS_DB_TABLE_URL;\n $binds = array(\n 'keyword' => $keyword,\n 'url' => $url,\n 'title' => $title,\n 'timestamp' => $timestamp,\n 'ip' => $ip,\n );\n $insert = yourls_get_db()->fetchAffected(\"INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES(:keyword, :url, :title, :timestamp, :ip, 0);\", $binds);", " yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );", " return (bool)$insert;\n}", "/**\n * Check if a long URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.\n *\n * This function supersedes function yourls_url_exists(), deprecated in 1.7.10, with a better naming.\n *\n * @since 1.7.10\n * @param string $url URL to check if already shortened\n * @return mixed NULL if does not already exist in DB, or object with URL information as properties (eg keyword, url, title, ...)\n */\nfunction yourls_long_url_exists( $url ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_url_exists', false, $url );\n if ( false !== $pre ) {\n return $pre;\n }", " $table = YOURLS_DB_TABLE_URL;\n $url = yourls_sanitize_url($url);\n $url_exists = yourls_get_db()->fetchObject(\"SELECT * FROM `$table` WHERE `url` = :url\", array('url'=>$url));", " if ($url_exists === false) {\n $url_exists = NULL;\n }", " return yourls_apply_filter( 'url_exists', $url_exists, $url );\n}", "/**\n * Edit a link\n *\n */\nfunction yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_edit_link', null, $keyword, $url, $keyword, $newkeyword, $title );\n if ( null !== $pre )\n return $pre;", " $ydb = yourls_get_db();", " $table = YOURLS_DB_TABLE_URL;\n $url = yourls_sanitize_url($url);\n $keyword = yourls_sanitize_keyword($keyword);\n $title = yourls_sanitize_title($title);\n $newkeyword = yourls_sanitize_keyword($newkeyword, true);", "", "\n if(!$url OR !$newkeyword) {\n $return['status'] = 'fail';\n $return['message'] = yourls__( 'Long URL or Short URL cannot be blank' );\n return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title );\n }", " $old_url = $ydb->fetchValue(\"SELECT `url` FROM `$table` WHERE `keyword` = :keyword\", array('keyword' => $keyword));", " // Check if new URL is not here already\n if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {\n $new_url_already_there = intval($ydb->fetchValue(\"SELECT COUNT(keyword) FROM `$table` WHERE `url` = :url;\", array('url' => $url)));\n } else {\n $new_url_already_there = false;\n }", " // Check if the new keyword is not here already\n if ( $newkeyword != $keyword ) {\n $keyword_is_ok = yourls_keyword_is_free( $newkeyword );\n } else {\n $keyword_is_ok = true;\n }", " yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );", " // All clear, update\n if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {\n $sql = \"UPDATE `$table` SET `url` = :url, `keyword` = :newkeyword, `title` = :title WHERE `keyword` = :keyword\";\n $binds = array('url' => $url, 'newkeyword' => $newkeyword, 'title' => $title, 'keyword' => $keyword);\n $update_url = $ydb->fetchAffected($sql, $binds);\n if( $update_url ) {", " $return['url'] = array( 'keyword' => $newkeyword,\n 'shorturl' => yourls_link($newkeyword),\n 'url' => yourls_esc_url($url),\n 'display_url' => yourls_esc_html(yourls_trim_long_string($url)),\n 'title' => yourls_esc_attr($title),\n 'display_title' => yourls_esc_html(yourls_trim_long_string( $title ))\n );", " $return['status'] = 'success';\n $return['message'] = yourls__( 'Link updated in database' );\n } else {\n $return['status'] = 'fail';", " $return['message'] = /* //translators: \"Error updating http://someurl/ (Shorturl: http://sho.rt/blah)\" */ yourls_s( 'Error updating %s (Short URL: %s)', yourls_esc_html(yourls_trim_long_string($url)), $keyword ) ;", " }", " // Nope\n } else {\n $return['status'] = 'fail';\n $return['message'] = yourls__( 'URL or keyword already exists in database' );\n }", " return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );\n}", "/**\n * Update a title link (no checks for duplicates etc..)\n *\n */\nfunction yourls_edit_link_title( $keyword, $title ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_edit_link_title', null, $keyword, $title );\n if ( null !== $pre ) {\n return $pre;\n }", " $keyword = yourls_sanitize_keyword( $keyword );\n $title = yourls_sanitize_title( $title );", " $table = YOURLS_DB_TABLE_URL;\n $update = yourls_get_db()->fetchAffected(\"UPDATE `$table` SET `title` = :title WHERE `keyword` = :keyword;\", array('title' => $title, 'keyword' => $keyword));", " return $update;\n}", "/**\n * Check if keyword id is free (ie not already taken, and not reserved). Return bool.\n *\n * @param string $keyword short URL keyword\n * @return bool true if keyword is taken (ie there is a short URL for it), false otherwise\n */\nfunction yourls_keyword_is_free( $keyword ) {\n $free = true;\n if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword, false ) ) {\n $free = false;\n }", " return yourls_apply_filter( 'keyword_is_free', $free, $keyword );\n}", "/**\n * Check if a keyword matches a \"page\"\n *\n * @see https://github.com/YOURLS/YOURLS/wiki/Pages\n * @since 1.7.10\n * @param string $keyword Short URL $keyword\n * @return bool true if is page, false otherwise\n */\nfunction yourls_is_page($keyword) {\n return yourls_apply_filter( 'is_page', file_exists( YOURLS_PAGEDIR . \"/$keyword.php\" ) );\n}", "/**\n * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.\n *\n */\n/**\n * Check if a keyword is taken (ie there is already a short URL with this id). Return bool.\n *\n * @param string $keyword short URL keyword\n * @param bool $use_cache optional, default true: do we want to use what is cached in memory, if any, or force a new SQL query\n * @return bool true if keyword is taken (ie there is a short URL for it), false otherwise\n */\nfunction yourls_keyword_is_taken( $keyword, $use_cache = true ) {\n // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_keyword_is_taken', false, $keyword );\n if ( false !== $pre ) {\n return $pre;\n }", " $taken = false;\n // To check if a keyword is already associated with a short URL, we fetch all info matching that keyword. This\n // will save a query in case of a redirection in yourls-go.php because info will be cached\n if ( yourls_get_keyword_infos($keyword, $use_cache) ) {\n $taken = true;\n }", " return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );\n}", "/**\n * Return array of all information associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB\n *\n * Sincere apologies to native English speakers, we are aware that the plural of 'info' is actually 'info', not 'infos'.\n * This function yourls_get_keyword_infos() returns all information, while function yourls_get_keyword_info() (no 's') return only\n * one information. Blame YOURLS contributors whose mother tongue is not English :)\n *\n * @since 1.4\n * @param string $keyword Short URL keyword\n * @param bool $use_cache Default true, set to false to force fetching from DB\n * @return false|object false if not found, object with URL properties if found\n */\nfunction yourls_get_keyword_infos( $keyword, $use_cache = true ) {\n $ydb = yourls_get_db();\n $keyword = yourls_sanitize_keyword( $keyword );", " yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );", " if( $ydb->has_infos($keyword) && $use_cache === true ) {\n return yourls_apply_filter( 'get_keyword_infos', $ydb->get_infos($keyword), $keyword );\n }", " yourls_do_action( 'get_keyword_not_cached', $keyword );", " $table = YOURLS_DB_TABLE_URL;\n $infos = $ydb->fetchObject(\"SELECT * FROM `$table` WHERE `keyword` = :keyword\", array('keyword' => $keyword));", " if( $infos ) {\n $infos = (array)$infos;\n $ydb->set_infos($keyword, $infos);\n } else {\n // is NULL if not found\n $infos = false;\n $ydb->set_infos($keyword, false);\n }", " return yourls_apply_filter( 'get_keyword_infos', $infos, $keyword );\n}", "/**\n * Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_info( $keyword, $field, $notfound = false ) {", " // Allow plugins to short-circuit the whole function\n $pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );\n if ( false !== $pre )\n return $pre;", " $keyword = yourls_sanitize_keyword( $keyword );\n $infos = yourls_get_keyword_infos( $keyword );", " $return = $notfound;\n if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )\n $return = $infos[ $field ];", " return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound );\n}", "/**\n * Return title associated with keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_title( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'title', $notfound );\n}", "/**\n * Return long URL associated with keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_longurl( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'url', $notfound );\n}", "/**\n * Return number of clicks on a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_clicks( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'clicks', $notfound );\n}", "/**\n * Return IP that added a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_IP( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'ip', $notfound );\n}", "/**\n * Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found\n *\n */\nfunction yourls_get_keyword_timestamp( $keyword, $notfound = false ) {\n return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );\n}", "/**\n * Return array of stats for a given keyword\n *\n * This function supersedes function yourls_get_link_stats(), deprecated in 1.7.10, with a better naming.\n *\n * @since 1.7.10\n * @param string $shorturl short URL keyword\n * @return array stats\n */\nfunction yourls_get_keyword_stats( $shorturl ) {\n $table_url = YOURLS_DB_TABLE_URL;\n $shorturl = yourls_sanitize_keyword( $shorturl );", " $res = yourls_get_db()->fetchObject(\"SELECT * FROM `$table_url` WHERE `keyword` = :keyword\", array('keyword' => $shorturl));\n $return = array();", " if( !$res ) {\n // non existent link\n $return = array(\n 'statusCode' => 404,\n 'message' => 'Error: short URL not found',\n );\n } else {\n $return = array(\n 'statusCode' => 200,\n 'message' => 'success',\n 'link' => array(\n 'shorturl' => yourls_link($res->keyword),\n 'url' => $res->url,\n 'title' => $res->title,\n 'timestamp'=> $res->timestamp,\n 'ip' => $res->ip,\n 'clicks' => $res->clicks,\n )\n );\n }", " return yourls_apply_filter( 'get_link_stats', $return, $shorturl );\n}", "/**\n * Return array of keywords that redirect to the submitted long URL\n *\n * @since 1.7\n * @param string $longurl long url\n * @param string $order Optional SORT order (can be 'ASC' or 'DESC')\n * @return array array of keywords\n */\nfunction yourls_get_longurl_keywords( $longurl, $order = 'ASC' ) {\n $longurl = yourls_sanitize_url($longurl);\n $table = YOURLS_DB_TABLE_URL;\n $sql = \"SELECT `keyword` FROM `$table` WHERE `url` = :url\";", " if (in_array($order, array('ASC','DESC'))) {\n $sql .= \" ORDER BY `keyword` \".$order;\n }", " return yourls_apply_filter( 'get_longurl_keywords', yourls_get_db()->fetchCol($sql, array('url'=>$longurl)), $longurl );\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [343, 41], "buggy_code_start_loc": [304, 41], "filenames": ["includes/functions-shorturls.php", "tests/tests/shorturl/shorturl.php"], "fixing_code_end_loc": [347, 45], "fixing_code_start_loc": [303, 42], "message": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yourls:yourls:*:*:*:*:*:*:*:*", "matchCriteriaId": "6A2C8C7B-8D81-4333-8912-980436C67E17", "versionEndExcluding": "1.8.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "yourls es vulnerable a la Neutralizaci\u00f3n Inapropiada de la Entrada durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-3785", "lastModified": "2021-09-23T19:31:11.840", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-09-15T12:15:16.283", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b4085d13-54fa-4419-a2ce-1d780cc31638"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, "type": "CWE-79"}
281
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Short URL tests\n *\n * @group shorturls\n * @since 0.1\n */", "class ShortURL_Tests extends PHPUnit\\Framework\\TestCase {", " public function test_reserved_keywords() {\n global $yourls_reserved_URL;\n $reserved = $yourls_reserved_URL[ array_rand( $yourls_reserved_URL, 1 ) ];\n $this->assertTrue( yourls_keyword_is_reserved( $reserved ) );\n $this->assertFalse( yourls_keyword_is_reserved( rand_str() ) );\n }", " public function test_free_keywords() {\n global $yourls_reserved_URL;\n $reserved = $yourls_reserved_URL[ array_rand( $yourls_reserved_URL, 1 ) ];\n $this->assertFalse( yourls_keyword_is_free( $reserved ) );\n $this->assertFalse( yourls_keyword_is_free( 'ozh' ) );\n $this->assertTrue( yourls_keyword_is_free( rand_str() ) );\n }", " public function test_url_exists() {\n $exists = yourls_long_url_exists( 'http://ozh.org/' );\n $this->assertEquals( 'ozh', $exists->keyword );\n $this->assertNull( yourls_long_url_exists( rand_str() ) );\n }", " public function test_add_url() {\n $keyword = rand_str();\n $title = rand_str();\n $url = 'http://' . rand_str();", " $newurl = yourls_add_new_link( $url, $keyword, $title );\n $this->assertEquals( 'success', $newurl['status'] );", " $fail = yourls_add_new_link( $url, $keyword, $title );", "", " $this->assertEquals( 'fail', $fail['status'] );\n $this->assertEquals( 'error:url', $fail['code'] );", " $fail = yourls_add_new_link( 'http://' . rand_str(), $keyword, $title );\n $this->assertEquals( 'fail', $fail['status'] );\n $this->assertEquals( 'error:keyword', $fail['code'] );", " $this->assertEquals( $title, yourls_get_keyword_title( $keyword ) );\n $this->assertEquals( $url, yourls_get_keyword_longurl( $keyword ) );\n $this->assertEquals( 0, yourls_get_keyword_clicks( $keyword ) );", " return $keyword;\n }", " /**\n * @depends test_add_url\n */\n public function test_edit_title( $original_keyword ) {\n $new_keyword = rand_str();\n $new_title = rand_str();\n $new_url = 'http://' . rand_str();", " $edit = yourls_edit_link_title( $original_keyword, $new_title );\n $this->assertEquals( 1, $edit );\n // purge cache\n $original = yourls_get_keyword_infos( $original_keyword, false );\n $this->assertEquals( $new_title, yourls_get_keyword_title( $original_keyword ) );", " return $original_keyword;\n }\n /**\n * @depends test_add_url\n */\n public function test_is_shorturl( $keyword ) {\n $this->assertFalse( yourls_is_shorturl( rand_str() ) );\n $this->assertTrue( yourls_is_shorturl( $keyword ) );\n $this->assertTrue( yourls_is_shorturl( yourls_link( $keyword ) ) );\n }", " /**\n * @depends test_add_url\n */\n public function test_update_hits( $keyword ) {\n // purge cache\n $cache = yourls_get_keyword_infos( $keyword, false );\n $this->assertEquals( 0, yourls_get_keyword_clicks( $keyword ) );", " $this->assertEquals( 1, yourls_update_clicks( $keyword ) );\n // purge cache\n yourls_get_keyword_infos( $keyword, false );\n $this->assertEquals( 1, yourls_get_keyword_clicks( $keyword ) );\n }", " public function test_log_hits_unknown() {\n $rand = rand_str();\n $this->assertEquals( 0, yourls_update_clicks( $rand ) );\n $this->assertEquals( 0, yourls_get_keyword_clicks( $rand ) );\n }", " /**\n * @depends test_edit_title\n */\n public function test_edit_url( $original_keyword ) {\n $new_keyword = rand_str();\n $new_title = rand_str();\n $new_url = 'http://' . rand_str();", " // purge cache\n $original = yourls_get_keyword_infos( $original_keyword, false );", " $edit = yourls_edit_link( $original['url'], $original_keyword, $new_keyword, $new_title );\n $this->assertEquals( $edit['url']['title'], $new_title );\n $this->assertEquals( $edit['url']['keyword'], $new_keyword );", " $edit = yourls_edit_link( $new_url, $new_keyword, $new_keyword, $new_title );\n $this->assertEquals( $edit['url']['url'], $new_url );", " return $new_keyword;\n }", " /**\n * @depends test_edit_url\n */\n public function test_delete_url( $keyword ) {\n $delete = yourls_delete_link_by_keyword( rand_str() );\n $this->assertEquals( 0, $delete );\n $delete = yourls_delete_link_by_keyword( $keyword );\n $this->assertEquals( 1, $delete );\n $this->assertFalse( yourls_is_shorturl( $keyword ) );\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [343, 41], "buggy_code_start_loc": [304, 41], "filenames": ["includes/functions-shorturls.php", "tests/tests/shorturl/shorturl.php"], "fixing_code_end_loc": [347, 45], "fixing_code_start_loc": [303, 42], "message": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yourls:yourls:*:*:*:*:*:*:*:*", "matchCriteriaId": "6A2C8C7B-8D81-4333-8912-980436C67E17", "versionEndExcluding": "1.8.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "yourls es vulnerable a la Neutralizaci\u00f3n Inapropiada de la Entrada durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-3785", "lastModified": "2021-09-23T19:31:11.840", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-09-15T12:15:16.283", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b4085d13-54fa-4419-a2ce-1d780cc31638"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, "type": "CWE-79"}
281
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Short URL tests\n *\n * @group shorturls\n * @since 0.1\n */", "class ShortURL_Tests extends PHPUnit\\Framework\\TestCase {", " public function test_reserved_keywords() {\n global $yourls_reserved_URL;\n $reserved = $yourls_reserved_URL[ array_rand( $yourls_reserved_URL, 1 ) ];\n $this->assertTrue( yourls_keyword_is_reserved( $reserved ) );\n $this->assertFalse( yourls_keyword_is_reserved( rand_str() ) );\n }", " public function test_free_keywords() {\n global $yourls_reserved_URL;\n $reserved = $yourls_reserved_URL[ array_rand( $yourls_reserved_URL, 1 ) ];\n $this->assertFalse( yourls_keyword_is_free( $reserved ) );\n $this->assertFalse( yourls_keyword_is_free( 'ozh' ) );\n $this->assertTrue( yourls_keyword_is_free( rand_str() ) );\n }", " public function test_url_exists() {\n $exists = yourls_long_url_exists( 'http://ozh.org/' );\n $this->assertEquals( 'ozh', $exists->keyword );\n $this->assertNull( yourls_long_url_exists( rand_str() ) );\n }", " public function test_add_url() {\n $keyword = rand_str();\n $title = rand_str();\n $url = 'http://' . rand_str();", " $newurl = yourls_add_new_link( $url, $keyword, $title );\n $this->assertEquals( 'success', $newurl['status'] );", " $fail = yourls_add_new_link( $url, $keyword, $title );", " $this->assertEquals( 'fail', $fail['status'] );", " $fail = yourls_add_new_link( $url, rand_str(), rand_str() );", " $this->assertEquals( 'fail', $fail['status'] );\n $this->assertEquals( 'error:url', $fail['code'] );", " $fail = yourls_add_new_link( 'http://' . rand_str(), $keyword, $title );\n $this->assertEquals( 'fail', $fail['status'] );\n $this->assertEquals( 'error:keyword', $fail['code'] );", " $this->assertEquals( $title, yourls_get_keyword_title( $keyword ) );\n $this->assertEquals( $url, yourls_get_keyword_longurl( $keyword ) );\n $this->assertEquals( 0, yourls_get_keyword_clicks( $keyword ) );", " return $keyword;\n }", " /**\n * @depends test_add_url\n */\n public function test_edit_title( $original_keyword ) {\n $new_keyword = rand_str();\n $new_title = rand_str();\n $new_url = 'http://' . rand_str();", " $edit = yourls_edit_link_title( $original_keyword, $new_title );\n $this->assertEquals( 1, $edit );\n // purge cache\n $original = yourls_get_keyword_infos( $original_keyword, false );\n $this->assertEquals( $new_title, yourls_get_keyword_title( $original_keyword ) );", " return $original_keyword;\n }\n /**\n * @depends test_add_url\n */\n public function test_is_shorturl( $keyword ) {\n $this->assertFalse( yourls_is_shorturl( rand_str() ) );\n $this->assertTrue( yourls_is_shorturl( $keyword ) );\n $this->assertTrue( yourls_is_shorturl( yourls_link( $keyword ) ) );\n }", " /**\n * @depends test_add_url\n */\n public function test_update_hits( $keyword ) {\n // purge cache\n $cache = yourls_get_keyword_infos( $keyword, false );\n $this->assertEquals( 0, yourls_get_keyword_clicks( $keyword ) );", " $this->assertEquals( 1, yourls_update_clicks( $keyword ) );\n // purge cache\n yourls_get_keyword_infos( $keyword, false );\n $this->assertEquals( 1, yourls_get_keyword_clicks( $keyword ) );\n }", " public function test_log_hits_unknown() {\n $rand = rand_str();\n $this->assertEquals( 0, yourls_update_clicks( $rand ) );\n $this->assertEquals( 0, yourls_get_keyword_clicks( $rand ) );\n }", " /**\n * @depends test_edit_title\n */\n public function test_edit_url( $original_keyword ) {\n $new_keyword = rand_str();\n $new_title = rand_str();\n $new_url = 'http://' . rand_str();", " // purge cache\n $original = yourls_get_keyword_infos( $original_keyword, false );", " $edit = yourls_edit_link( $original['url'], $original_keyword, $new_keyword, $new_title );\n $this->assertEquals( $edit['url']['title'], $new_title );\n $this->assertEquals( $edit['url']['keyword'], $new_keyword );", " $edit = yourls_edit_link( $new_url, $new_keyword, $new_keyword, $new_title );\n $this->assertEquals( $edit['url']['url'], $new_url );", " return $new_keyword;\n }", " /**\n * @depends test_edit_url\n */\n public function test_delete_url( $keyword ) {\n $delete = yourls_delete_link_by_keyword( rand_str() );\n $this->assertEquals( 0, $delete );\n $delete = yourls_delete_link_by_keyword( $keyword );\n $this->assertEquals( 1, $delete );\n $this->assertFalse( yourls_is_shorturl( $keyword ) );\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [343, 41], "buggy_code_start_loc": [304, 41], "filenames": ["includes/functions-shorturls.php", "tests/tests/shorturl/shorturl.php"], "fixing_code_end_loc": [347, 45], "fixing_code_start_loc": [303, 42], "message": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yourls:yourls:*:*:*:*:*:*:*:*", "matchCriteriaId": "6A2C8C7B-8D81-4333-8912-980436C67E17", "versionEndExcluding": "1.8.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "yourls is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "yourls es vulnerable a la Neutralizaci\u00f3n Inapropiada de la Entrada durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-3785", "lastModified": "2021-09-23T19:31:11.840", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-09-15T12:15:16.283", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b4085d13-54fa-4419-a2ce-1d780cc31638"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/yourls/yourls/commit/1d8e224ebabb8a4c75b97f026950ed710faab0ff"}, "type": "CWE-79"}
281
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * ---------------------------------------------------------------------\n *\n * GLPI - Gestionnaire Libre de Parc Informatique\n *\n * http://glpi-project.org\n *\n * @copyright 2015-2022 Teclib' and contributors.\n * @copyright 2003-2014 by the INDEPNET Development Team.\n * @licence https://www.gnu.org/licenses/gpl-3.0.html\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n *\n * ---------------------------------------------------------------------\n */", "use Glpi\\Application\\View\\TemplateRenderer;\nuse Glpi\\RichText\\RichText;\nuse Glpi\\Socket;\nuse Glpi\\Toolbox\\DataExport;\nuse Glpi\\Toolbox\\Sanitizer;", "/**\n * Search Class\n *\n * Generic class for Search Engine\n **/\nclass Search\n{\n /**\n * Default number of items displayed in global search\n * @var int\n * @see GLOBAL_SEARCH\n */\n const GLOBAL_DISPLAY_COUNT = 10;", " // EXPORT TYPE\n /**\n * The global search view (Search across many item types).\n * This is NOT the same as the AllAssets view which is just a special itemtype.\n * @var int\n */\n const GLOBAL_SEARCH = -1;", " /**\n * The standard view.\n * This includes the following sub-views:\n * - Table/List\n * - Map\n * - Browse\n * @var int\n */\n const HTML_OUTPUT = 0;", " /**\n * SYLK export format\n * @var int\n */\n const SYLK_OUTPUT = 1;", " /**\n * PDF export format (Landscape mode)\n * @var int\n */\n const PDF_OUTPUT_LANDSCAPE = 2;", " /**\n * CSV export format\n * @var int\n */\n const CSV_OUTPUT = 3;", " /**\n * PDF export format (Portrait mode)\n * @var int\n */\n const PDF_OUTPUT_PORTRAIT = 4;", " /**\n * Names list export format\n * @var int\n */\n const NAMES_OUTPUT = 5;", " /**\n * Placeholder for a <br> line break\n * @var string\n */\n const LBBR = '#LBBR#';", " /**\n * Placeholder for a <hr> line break\n * @var string\n */\n const LBHR = '#LBHR#';", " /**\n * Separator used to separate values of a same element in CONCAT MySQL function.\n *\n * @var string\n * @see LONGSEP\n */\n const SHORTSEP = '$#$';", " /**\n * Separator used to separate each element in GROUP_CONCAT MySQL function.\n *\n * @var string\n * @see SHORTSEP\n */\n const LONGSEP = '$$##$$';", " /**\n * Placeholder for a null value\n * @var string\n */\n const NULLVALUE = '__NULL__';", " /**\n * The output format for the search results\n * @var int\n */\n public static $output_type = self::HTML_OUTPUT;\n public static $search = [];", " /**\n * Display search engine for an type\n *\n * @param string $itemtype Item type to manage\n *\n * @return void\n **/\n public static function show($itemtype)\n {", " $params = self::manageParams($itemtype, $_GET);\n echo \"<div class='search_page row'>\";\n TemplateRenderer::getInstance()->display('layout/parts/saved_searches.html.twig', [\n 'itemtype' => $itemtype,\n ]);\n echo \"<div class='col search-container'>\";", " if (\n $itemtype == \"Ticket\"\n && $default = Glpi\\Dashboard\\Grid::getDefaultDashboardForMenu('mini_ticket', true)\n ) {\n $dashboard = new Glpi\\Dashboard\\Grid($default, 33, 2);\n $dashboard->show(true);\n }", " self::showGenericSearch($itemtype, $params);\n if ($params['as_map'] == 1) {\n self::showMap($itemtype, $params);\n } elseif ($params['browse'] == 1) {\n $itemtype::showBrowseView($itemtype, $params);\n } else {\n self::showList($itemtype, $params);\n }\n echo \"</div>\";\n echo \"</div>\";\n }", "\n /**\n * Display result table for search engine for an type\n *\n * @param class-string<CommonDBTM> $itemtype Item type to manage\n * @param array $params Search params passed to\n * prepareDatasForSearch function\n * @param array $forcedisplay Array of columns to display (default empty\n * = use display pref and search criteria)\n *\n * @return void\n **/\n public static function showList(\n $itemtype,\n $params,\n array $forcedisplay = []\n ) {\n $data = self::getDatas($itemtype, $params, $forcedisplay);", " switch ($data['display_type']) {\n case self::CSV_OUTPUT:\n case self::PDF_OUTPUT_LANDSCAPE:\n case self::PDF_OUTPUT_PORTRAIT:\n case self::SYLK_OUTPUT:\n case self::NAMES_OUTPUT:\n self::outputData($data);\n break;\n case self::GLOBAL_SEARCH:\n case self::HTML_OUTPUT:\n default:\n self::displayData($data);\n break;\n }\n }", " /**\n * Display result table for search engine for an type as a map\n *\n * @param class-string<CommonDBTM> $itemtype Item type to manage\n * @param array $params Search params passed to prepareDatasForSearch function\n *\n * @return void\n **/\n public static function showMap($itemtype, $params)\n {\n global $CFG_GLPI;", " if ($itemtype == 'Location') {\n $latitude = 21;\n $longitude = 20;\n } else if ($itemtype == 'Entity') {\n $latitude = 67;\n $longitude = 68;\n } else {\n $latitude = 998;\n $longitude = 999;\n }", " $params['criteria'][] = [\n 'link' => 'AND NOT',\n 'field' => $latitude,\n 'searchtype' => 'contains',\n 'value' => 'NULL'\n ];\n $params['criteria'][] = [\n 'link' => 'AND NOT',\n 'field' => $longitude,\n 'searchtype' => 'contains',\n 'value' => 'NULL'\n ];", " $data = self::getDatas($itemtype, $params);\n self::displayData($data);", " if ($data['data']['totalcount'] > 0) {\n $target = $data['search']['target'];\n $criteria = $data['search']['criteria'];\n array_pop($criteria);\n array_pop($criteria);\n $criteria[] = [\n 'link' => 'AND',\n 'field' => ($itemtype == 'Location' || $itemtype == 'Entity') ? 1 : (($itemtype == 'Ticket') ? 83 : 3),\n 'searchtype' => 'equals',\n 'value' => 'CURLOCATION'\n ];\n $globallinkto = Toolbox::append_params(\n [\n 'criteria' => Sanitizer::unsanitize($criteria),\n 'metacriteria' => Sanitizer::unsanitize($data['search']['metacriteria'])\n ],\n '&amp;'\n );\n $sort_params = Toolbox::append_params([\n 'sort' => $data['search']['sort'],\n 'order' => $data['search']['order']\n ], '&amp;');\n $parameters = \"as_map=0&amp;\" . $sort_params . '&amp;' .\n $globallinkto;", " if (strpos($target, '?') == false) {\n $fulltarget = $target . \"?\" . $parameters;\n } else {\n $fulltarget = $target . \"&\" . $parameters;\n }\n $typename = class_exists($itemtype) ? $itemtype::getTypeName($data['data']['totalcount']) : $itemtype;", " echo \"<div class='card border-top-0 rounded-0 search-as-map'>\";\n echo \"<div class='card-body px-0' id='map_container'>\";\n echo \"<small class='text-muted p-1'>\" . __('Search results for localized items only') . \"</small>\";\n $js = \"$(function() {\n var map = initMap($('#map_container'), 'map', 'full');\n _loadMap(map, '$itemtype');\n });", " var _loadMap = function(map_elt, itemtype) {\n L.AwesomeMarkers.Icon.prototype.options.prefix = 'far';\n var _micon = 'circle';", " var stdMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'blue'\n });", " var aMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'cadetblue'\n });", " var bMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'purple'\n });", " var cMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'darkpurple'\n });", " var dMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'red'\n });", " var eMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'darkred'\n });", "\n //retrieve geojson data\n map_elt.spin(true);\n $.ajax({\n dataType: 'json',\n method: 'POST',\n url: '{$CFG_GLPI['root_doc']}/ajax/map.php',\n data: {\n itemtype: itemtype,\n params: \" . json_encode($params) . \"\n }\n }).done(function(data) {\n var _points = data.points;\n var _markers = L.markerClusterGroup({\n iconCreateFunction: function(cluster) {\n var childCount = cluster.getChildCount();", " var markers = cluster.getAllChildMarkers();\n var n = 0;\n for (var i = 0; i < markers.length; i++) {\n n += markers[i].count;\n }", " var c = ' marker-cluster-';\n if (n < 10) {\n c += 'small';\n } else if (n < 100) {\n c += 'medium';\n } else {\n c += 'large';\n }", " return new L.DivIcon({ html: '<div><span>' + n + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });\n }\n });", " $.each(_points, function(index, point) {\n var _title = '<strong>' + point.title + '</strong><br/><a href=\\''+'$fulltarget'.replace(/CURLOCATION/, point.loc_id)+'\\'>\" . sprintf(__('%1$s %2$s'), 'COUNT', $typename) . \"'.replace(/COUNT/, point.count)+'</a>';\n if (point.types) {\n $.each(point.types, function(tindex, type) {\n _title += '<br/>\" . sprintf(__('%1$s %2$s'), 'COUNT', 'TYPE') . \"'.replace(/COUNT/, type.count).replace(/TYPE/, type.name);\n });\n }\n var _icon = stdMarker;\n if (point.count < 10) {\n _icon = stdMarker;\n } else if (point.count < 100) {\n _icon = aMarker;\n } else if (point.count < 1000) {\n _icon = bMarker;\n } else if (point.count < 5000) {\n _icon = cMarker;\n } else if (point.count < 10000) {\n _icon = dMarker;\n } else {\n _icon = eMarker;\n }\n var _marker = L.marker([point.lat, point.lng], { icon: _icon, title: point.title });\n _marker.count = point.count;\n _marker.bindPopup(_title);\n _markers.addLayer(_marker);\n });", " map_elt.addLayer(_markers);\n map_elt.fitBounds(\n _markers.getBounds(), {\n padding: [50, 50],\n maxZoom: 12\n }\n );\n }).fail(function (response) {\n var _data = response.responseJSON;\n var _message = '\" . __s('An error occurred loading data :(') . \"';\n if (_data.message) {\n _message = _data.message;\n }\n var fail_info = L.control();\n fail_info.onAdd = function (map) {\n this._div = L.DomUtil.create('div', 'fail_info');\n this._div.innerHTML = _message + '<br/><span id=\\'reload_data\\'><i class=\\'fa fa-sync\\'></i> \" . __s('Reload') . \"</span>';\n return this._div;\n };\n fail_info.addTo(map_elt);\n $('#reload_data').on('click', function() {\n $('.fail_info').remove();\n _loadMap(map_elt);\n });\n }).always(function() {\n //hide spinner\n map_elt.spin(false);\n });\n }", " \";\n echo Html::scriptBlock($js);\n echo \"</div>\"; // .card-body\n echo \"</div>\"; // .card\n }\n }", "\n /**\n * Get data based on search parameters\n *\n * @since 0.85\n *\n * @param class-string<CommonDBTM> $itemtype Item type to manage\n * @param array $params Search params passed to prepareDatasForSearch function\n * @param array $forcedisplay Array of columns to display (default empty = empty use display pref and search criteria)\n *\n * @return array The data\n **/\n public static function getDatas($itemtype, $params, array $forcedisplay = [])\n {", " $data = self::prepareDatasForSearch($itemtype, $params, $forcedisplay);\n self::constructSQL($data);\n self::constructData($data);", " return $data;\n }", "\n /**\n * Prepare search criteria to be used for a search\n *\n * @since 0.85\n *\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param array $params Array of parameters\n * may include sort, order, start, list_limit, deleted, criteria, metacriteria\n * @param array $forcedisplay Array of columns to display (default empty = empty use display pref and search criterias)\n *\n * @return array prepare to be used for a search (include criteria and others needed information)\n **/\n public static function prepareDatasForSearch($itemtype, array $params, array $forcedisplay = [])\n {\n global $CFG_GLPI;", " // Default values of parameters\n $p['criteria'] = [];\n $p['metacriteria'] = [];\n $p['sort'] = ['1'];\n $p['order'] = ['ASC'];\n $p['start'] = 0;//\n $p['is_deleted'] = 0;\n $p['export_all'] = 0;\n if (class_exists($itemtype)) {\n $p['target'] = $itemtype::getSearchURL();\n } else {\n $p['target'] = Toolbox::getItemTypeSearchURL($itemtype);\n }\n $p['display_type'] = self::HTML_OUTPUT;\n $p['showmassiveactions'] = true;\n $p['dont_flush'] = false;\n $p['show_pager'] = true;\n $p['show_footer'] = true;\n $p['no_sort'] = false;\n $p['list_limit'] = $_SESSION['glpilist_limit'];\n $p['massiveactionparams'] = [];", " foreach ($params as $key => $val) {\n switch ($key) {\n case 'order':\n if (!is_array($val)) {\n // Backward compatibility with GLPI < 10.0 links\n if (in_array($val, ['ASC', 'DESC'])) {\n $p[$key] = [$val];\n }\n break;\n }\n $p[$key] = $val;\n break;\n case 'sort':\n if (!is_array($val)) {\n // Backward compatibility with GLPI < 10.0 links\n $val = (int) $val;\n if ($val >= 0) {\n $p[$key] = [$val];\n }\n break;\n }\n $p[$key] = $val;\n break;\n case 'is_deleted':\n if ($val == 1) {\n $p[$key] = '1';\n }\n break;\n default:\n $p[$key] = $val;\n break;\n }\n }", " // Set display type for export if define\n if (isset($p['display_type'])) {\n // Limit to 10 element\n if ($p['display_type'] == self::GLOBAL_SEARCH) {\n $p['list_limit'] = self::GLOBAL_DISPLAY_COUNT;\n }\n }", " if ($p['export_all']) {\n $p['start'] = 0;\n }", " $data = [];\n $data['search'] = $p;\n $data['itemtype'] = $itemtype;", " // Instanciate an object to access method\n $data['item'] = null;", " if ($itemtype != AllAssets::getType()) {\n $data['item'] = getItemForItemtype($itemtype);\n }", " $data['display_type'] = $data['search']['display_type'];", " if (!$CFG_GLPI['allow_search_all']) {\n foreach ($p['criteria'] as $val) {\n if (isset($val['field']) && $val['field'] == 'all') {\n Html::displayRightError();\n }\n }\n }\n if (!$CFG_GLPI['allow_search_view']) {\n foreach ($p['criteria'] as $val) {\n if (isset($val['field']) && $val['field'] == 'view') {\n Html::displayRightError();\n }\n }\n }", " /// Get the items to display\n // Add searched items", " $forcetoview = false;\n if (is_array($forcedisplay) && count($forcedisplay)) {\n $forcetoview = true;\n }\n $data['search']['all_search'] = false;\n $data['search']['view_search'] = false;\n // If no research limit research to display item and compute number of item using simple request\n $data['search']['no_search'] = true;", " $data['toview'] = self::addDefaultToView($itemtype, $params);\n $data['meta_toview'] = [];\n if (!$forcetoview) {\n // Add items to display depending of personal prefs\n $displaypref = DisplayPreference::getForTypeUser($itemtype, Session::getLoginUserID());\n if (count($displaypref)) {\n foreach ($displaypref as $val) {\n array_push($data['toview'], $val);\n }\n }\n } else {\n $data['toview'] = array_merge($data['toview'], $forcedisplay);\n }", " if (count($p['criteria']) > 0) {\n // use a recursive closure to push searchoption when using nested criteria\n $parse_criteria = function ($criteria) use (&$parse_criteria, &$data) {\n foreach ($criteria as $criterion) {\n // recursive call\n if (isset($criterion['criteria'])) {\n $parse_criteria($criterion['criteria']);\n } else {\n // normal behavior\n if (\n isset($criterion['field'])\n && !in_array($criterion['field'], $data['toview'])\n ) {\n if (\n $criterion['field'] != 'all'\n && $criterion['field'] != 'view'\n && (!isset($criterion['meta'])\n || !$criterion['meta'])\n ) {\n array_push($data['toview'], $criterion['field']);\n } else if ($criterion['field'] == 'all') {\n $data['search']['all_search'] = true;\n } else if ($criterion['field'] == 'view') {\n $data['search']['view_search'] = true;\n }\n }", " if (\n isset($criterion['value'])\n && (strlen($criterion['value']) > 0)\n ) {\n $data['search']['no_search'] = false;\n }\n }\n }\n };", " // call the closure\n $parse_criteria($p['criteria']);\n }", " if (count($p['metacriteria'])) {\n $data['search']['no_search'] = false;\n }", " // Add order item\n $to_add_view = array_diff($p['sort'], $data['toview']);\n array_push($data['toview'], ...$to_add_view);", " // Special case for CommonITILObjects : put ID in front\n if (is_a($itemtype, CommonITILObject::class, true)) {\n array_unshift($data['toview'], 2);\n }", " $limitsearchopt = self::getCleanedOptions($itemtype);\n // Clean and reorder toview\n $tmpview = [];\n foreach ($data['toview'] as $val) {\n if (isset($limitsearchopt[$val]) && !in_array($val, $tmpview)) {\n $tmpview[] = $val;\n }\n }\n $data['toview'] = $tmpview;\n $data['tocompute'] = $data['toview'];", " // Force item to display\n if ($forcetoview) {\n foreach ($data['toview'] as $val) {\n if (!in_array($val, $data['tocompute'])) {\n array_push($data['tocompute'], $val);\n }\n }\n }", " return $data;\n }", "\n /**\n * Construct SQL request depending of search parameters\n *\n * Add to data array a field sql containing an array of requests :\n * search : request to get items limited to wanted ones\n * count : to count all items based on search criterias\n * may be an array a request : need to add counts\n * maybe empty : use search one to count\n *\n * @since 0.85\n *\n * @param array $data Array of search datas prepared to generate SQL\n *\n * @return void|false May return false if the search request data is invalid\n **/\n public static function constructSQL(array &$data)\n {\n global $DB, $CFG_GLPI;", " if (!isset($data['itemtype'])) {\n return false;\n }", " $data['sql']['count'] = [];\n $data['sql']['search'] = '';", " $searchopt = &self::getOptions($data['itemtype']);", " $blacklist_tables = [];\n $orig_table = self::getOrigTableName($data['itemtype']);\n if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {\n $itemtable = $CFG_GLPI['union_search_type'][$data['itemtype']];\n $blacklist_tables[] = $orig_table;\n } else {\n $itemtable = $orig_table;\n }", " // hack for AllAssets and ReservationItem\n if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {\n $entity_restrict = true;\n } else {\n $entity_restrict = $data['item']->isEntityAssign() && $data['item']->isField('entities_id');\n }", " // Construct the request", " //// 1 - SELECT\n // request currentuser for SQL supervision, not displayed\n $SELECT = \"SELECT DISTINCT `$itemtable`.`id` AS id, '\" . Toolbox::addslashes_deep($_SESSION['glpiname']) . \"' AS currentuser,\n \" . self::addDefaultSelect($data['itemtype']);", " // Add select for all toview item\n foreach ($data['toview'] as $val) {\n $SELECT .= self::addSelect($data['itemtype'], $val);\n }", " if (isset($data['search']['as_map']) && $data['search']['as_map'] == 1 && $data['itemtype'] != 'Entity') {\n $SELECT .= ' `glpi_locations`.`id` AS loc_id, ';\n }", " //// 2 - FROM AND LEFT JOIN\n // Set reference table\n $FROM = \" FROM `$itemtable`\";", " // Init already linked tables array in order not to link a table several times\n $already_link_tables = [];\n // Put reference table\n array_push($already_link_tables, $itemtable);", " // Add default join\n $COMMONLEFTJOIN = self::addDefaultJoin($data['itemtype'], $itemtable, $already_link_tables);\n $FROM .= $COMMONLEFTJOIN;", " // Add all table for toview items\n foreach ($data['tocompute'] as $val) {\n if (!in_array($searchopt[$val][\"table\"], $blacklist_tables)) {\n $FROM .= self::addLeftJoin(\n $data['itemtype'],\n $itemtable,\n $already_link_tables,\n $searchopt[$val][\"table\"],\n $searchopt[$val][\"linkfield\"],\n 0,\n 0,\n $searchopt[$val][\"joinparams\"],\n $searchopt[$val][\"field\"]\n );\n }\n }", " // Search all case :\n if ($data['search']['all_search']) {\n foreach ($searchopt as $key => $val) {\n // Do not search on Group Name\n if (is_array($val) && isset($val['table'])) {\n if (!in_array($searchopt[$key][\"table\"], $blacklist_tables)) {\n $FROM .= self::addLeftJoin(\n $data['itemtype'],\n $itemtable,\n $already_link_tables,\n $searchopt[$key][\"table\"],\n $searchopt[$key][\"linkfield\"],\n 0,\n 0,\n $searchopt[$key][\"joinparams\"],\n $searchopt[$key][\"field\"]\n );\n }\n }\n }\n }", " //// 3 - WHERE", " // default string\n $COMMONWHERE = self::addDefaultWhere($data['itemtype']);\n $first = empty($COMMONWHERE);", " // Add deleted if item have it\n if ($data['item'] && $data['item']->maybeDeleted()) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" \";\n $first = false;\n }\n $COMMONWHERE .= $LINK . \"`$itemtable`.`is_deleted` = \" . (int)$data['search']['is_deleted'] . \" \";\n }", " // Remove template items\n if ($data['item'] && $data['item']->maybeTemplate()) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" \";\n $first = false;\n }\n $COMMONWHERE .= $LINK . \"`$itemtable`.`is_template` = 0 \";\n }", " // Add Restrict to current entities\n if ($entity_restrict) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" \";\n $first = false;\n }", " if ($data['itemtype'] == 'Entity') {\n $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable);\n } else if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n // Will be replace below in Union/Recursivity Hack\n $COMMONWHERE .= $LINK . \" ENTITYRESTRICT \";\n } else {\n $COMMONWHERE .= getEntitiesRestrictRequest(\n $LINK,\n $itemtable,\n '',\n '',\n $data['item']->maybeRecursive() && $data['item']->isField('is_recursive')\n );\n }\n }\n $WHERE = \"\";\n $HAVING = \"\";", " // Add search conditions\n // If there is search items\n if (count($data['search']['criteria'])) {\n $WHERE = self::constructCriteriaSQL($data['search']['criteria'], $data, $searchopt);\n $HAVING = self::constructCriteriaSQL($data['search']['criteria'], $data, $searchopt, true);", " // if criteria (with meta flag) need additional join/from sql\n self::constructAdditionalSqlForMetacriteria($data['search']['criteria'], $SELECT, $FROM, $already_link_tables, $data);\n }", " //// 4 - ORDER\n $ORDER = \" ORDER BY `id` \";\n $sort_fields = [];\n $sort_count = count($data['search']['sort']);\n for ($i = 0; $i < $sort_count; $i++) {\n foreach ($data['tocompute'] as $val) {\n if ($data['search']['sort'][$i] == $val) {\n $sort_fields[] = [\n 'searchopt_id' => $data['search']['sort'][$i],\n 'order' => $data['search']['order'][$i] ?? null\n ];\n }\n }\n }\n if (count($sort_fields)) {\n $ORDER = self::addOrderBy($data['itemtype'], $sort_fields);\n }", " $SELECT = rtrim(trim($SELECT), ',');", " //// 7 - Manage GROUP BY\n $GROUPBY = \"\";\n // Meta Search / Search All / Count tickets\n $criteria_with_meta = array_filter($data['search']['criteria'], function ($criterion) {\n return isset($criterion['meta'])\n && $criterion['meta'];\n });\n if (\n (count($data['search']['metacriteria']))\n || count($criteria_with_meta)\n || !empty($HAVING)\n || $data['search']['all_search']\n ) {\n $GROUPBY = \" GROUP BY `$itemtable`.`id`\";\n }", " if (empty($GROUPBY)) {\n foreach ($data['toview'] as $val2) {\n if (!empty($GROUPBY)) {\n break;\n }\n if (isset($searchopt[$val2][\"forcegroupby\"])) {\n $GROUPBY = \" GROUP BY `$itemtable`.`id`\";\n }\n }\n }", " $LIMIT = \"\";\n $numrows = 0;\n //No search : count number of items using a simple count(ID) request and LIMIT search\n if ($data['search']['no_search']) {\n $LIMIT = \" LIMIT \" . (int)$data['search']['start'] . \", \" . (int)$data['search']['list_limit'];", " $count = \"count(DISTINCT `$itemtable`.`id`)\";\n // request currentuser for SQL supervision, not displayed\n $query_num = \"SELECT $count,\n '\" . Toolbox::addslashes_deep($_SESSION['glpiname']) . \"' AS currentuser\n FROM `$itemtable`\" .\n $COMMONLEFTJOIN;", " $first = true;", " if (!empty($COMMONWHERE)) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" WHERE \";\n $first = false;\n }\n $query_num .= $LINK . $COMMONWHERE;\n }\n // Union Search :\n if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n $tmpquery = $query_num;", " foreach ($CFG_GLPI[$CFG_GLPI[\"union_search_type\"][$data['itemtype']]] as $ctype) {\n $ctable = $ctype::getTable();\n if (\n ($citem = getItemForItemtype($ctype))\n && $citem->canView()\n ) {\n // State case\n if ($data['itemtype'] == AllAssets::getType()) {\n $query_num = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $tmpquery\n );\n $query_num = str_replace($data['itemtype'], $ctype, $query_num);\n $query_num .= \" AND `$ctable`.`id` IS NOT NULL \";", " // Add deleted if item have it\n if ($citem && $citem->maybeDeleted()) {\n $query_num .= \" AND `$ctable`.`is_deleted` = 0 \";\n }", " // Remove template items\n if ($citem && $citem->maybeTemplate()) {\n $query_num .= \" AND `$ctable`.`is_template` = 0 \";\n }\n } else {// Ref table case\n $reftable = $data['itemtype']::getTable();\n if ($data['item'] && $data['item']->maybeDeleted()) {\n $tmpquery = str_replace(\n \"`\" . $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`.\n `is_deleted`\",\n \"`$reftable`.`is_deleted`\",\n $tmpquery\n );\n }\n $replace = \"FROM `$reftable`\n INNER JOIN `$ctable`\n ON (`$reftable`.`items_id` =`$ctable`.`id`\n AND `$reftable`.`itemtype` = '$ctype')\";", " $query_num = str_replace(\n \"FROM `\" .\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`\",\n $replace,\n $tmpquery\n );\n $query_num = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $query_num\n );\n }\n $query_num = str_replace(\n \"ENTITYRESTRICT\",\n getEntitiesRestrictRequest(\n '',\n $ctable,\n '',\n '',\n $citem->maybeRecursive()\n ),\n $query_num\n );\n $data['sql']['count'][] = $query_num;\n }\n }\n } else {\n $data['sql']['count'][] = $query_num;\n }\n }", " // If export_all reset LIMIT condition\n if ($data['search']['export_all']) {\n $LIMIT = \"\";\n }", " if (!empty($WHERE) || !empty($COMMONWHERE)) {\n if (!empty($COMMONWHERE)) {\n $WHERE = ' WHERE ' . $COMMONWHERE . (!empty($WHERE) ? ' AND ( ' . $WHERE . ' )' : '');\n } else {\n $WHERE = ' WHERE ' . $WHERE . ' ';\n }\n $first = false;\n }", " if (!empty($HAVING)) {\n $HAVING = ' HAVING ' . $HAVING;\n }", " // Create QUERY\n if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n $first = true;\n $QUERY = \"\";\n foreach ($CFG_GLPI[$CFG_GLPI[\"union_search_type\"][$data['itemtype']]] as $ctype) {\n $ctable = $ctype::getTable();\n if (\n ($citem = getItemForItemtype($ctype))\n && $citem->canView()\n ) {\n if ($first) {\n $first = false;\n } else {\n $QUERY .= \" UNION \";\n }\n $tmpquery = \"\";\n // AllAssets case\n if ($data['itemtype'] == AllAssets::getType()) {\n $tmpquery = $SELECT . \", '$ctype' AS TYPE \" .\n $FROM .\n $WHERE;", " $tmpquery .= \" AND `$ctable`.`id` IS NOT NULL \";", " // Add deleted if item have it\n if ($citem && $citem->maybeDeleted()) {\n $tmpquery .= \" AND `$ctable`.`is_deleted` = 0 \";\n }", " // Remove template items\n if ($citem && $citem->maybeTemplate()) {\n $tmpquery .= \" AND `$ctable`.`is_template` = 0 \";\n }", " $tmpquery .= $GROUPBY .\n $HAVING;", " // Replace 'asset_types' by itemtype table name\n $tmpquery = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $tmpquery\n );\n // Replace 'AllAssets' by itemtype\n // Use quoted value to prevent replacement of AllAssets in column identifiers\n $tmpquery = str_replace(\n $DB->quoteValue(AllAssets::getType()),\n $DB->quoteValue($ctype),\n $tmpquery\n );\n } else {// Ref table case\n $reftable = $data['itemtype']::getTable();", " $tmpquery = $SELECT . \", '$ctype' AS TYPE,\n `$reftable`.`id` AS refID, \" . \"\n `$ctable`.`entities_id` AS ENTITY \" .\n $FROM .\n $WHERE;\n if ($data['item']->maybeDeleted()) {\n $tmpquery = str_replace(\n \"`\" . $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`.\n `is_deleted`\",\n \"`$reftable`.`is_deleted`\",\n $tmpquery\n );\n }", " $replace = \"FROM `$reftable`\" . \"\n INNER JOIN `$ctable`\" . \"\n ON (`$reftable`.`items_id`=`$ctable`.`id`\" . \"\n AND `$reftable`.`itemtype` = '$ctype')\";\n $tmpquery = str_replace(\n \"FROM `\" .\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`\",\n $replace,\n $tmpquery\n );\n $tmpquery = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $tmpquery\n );\n $name_field = $ctype::getNameField();\n $tmpquery = str_replace(\"`$ctable`.`name`\", \"`$ctable`.`$name_field`\", $tmpquery);\n }\n $tmpquery = str_replace(\n \"ENTITYRESTRICT\",\n getEntitiesRestrictRequest(\n '',\n $ctable,\n '',\n '',\n $citem->maybeRecursive()\n ),\n $tmpquery\n );", " // SOFTWARE HACK\n if ($ctype == 'Software') {\n $tmpquery = str_replace(\"`glpi_softwares`.`serial`\", \"''\", $tmpquery);\n $tmpquery = str_replace(\"`glpi_softwares`.`otherserial`\", \"''\", $tmpquery);\n }\n $QUERY .= $tmpquery;\n }\n }\n if (empty($QUERY)) {\n echo self::showError($data['display_type']);\n return;\n }\n $QUERY .= str_replace($CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \".\", \"\", $ORDER) .\n $LIMIT;\n } else {\n $QUERY = $SELECT .\n $FROM .\n $WHERE .\n $GROUPBY .\n $HAVING .\n $ORDER .\n $LIMIT;\n }\n $data['sql']['search'] = $QUERY;\n }", " /**\n * Construct WHERE (or HAVING) part of the sql based on passed criteria\n *\n * @since 9.4\n *\n * @param array $criteria list of search criterion, we should have these keys:\n * - link (optionnal): AND, OR, NOT AND, NOT OR\n * - field: id of the searchoption\n * - searchtype: how to match value (contains, equals, etc)\n * - value\n * @param array $data common array used by search engine,\n * contains all the search part (sql, criteria, params, itemtype etc)\n * TODO: should be a property of the class\n * @param array $searchopt Search options for the current itemtype\n * @param boolean $is_having Do we construct sql WHERE or HAVING part\n *\n * @return string the sql sub string\n */\n public static function constructCriteriaSQL($criteria = [], $data = [], $searchopt = [], $is_having = false)\n {\n $sql = \"\";", " foreach ($criteria as $criterion) {\n if (\n !isset($criterion['criteria'])\n && (!isset($criterion['value'])\n || strlen($criterion['value']) <= 0)\n ) {\n continue;\n }", " $itemtype = $data['itemtype'];\n $meta = false;\n if (\n isset($criterion['meta'])\n && $criterion['meta']\n && isset($criterion['itemtype'])\n ) {\n $itemtype = $criterion['itemtype'];\n $meta = true;\n $meta_searchopt = &self::getOptions($itemtype);\n } else {\n // Not a meta, use the same search option everywhere\n $meta_searchopt = $searchopt;\n }", " // common search\n if (\n !isset($criterion['field'])\n || ($criterion['field'] != \"all\"\n && $criterion['field'] != \"view\")\n ) {\n $LINK = \" \";\n $NOT = 0;\n $tmplink = \"\";", " if (\n isset($criterion['link'])\n && in_array($criterion['link'], array_keys(self::getLogicalOperators()))\n ) {\n if (strstr($criterion['link'], \"NOT\")) {\n $tmplink = \" \" . str_replace(\" NOT\", \"\", $criterion['link']);\n $NOT = 1;\n } else {\n $tmplink = \" \" . $criterion['link'];\n }\n } else {\n $tmplink = \" AND \";\n }", " // Manage Link if not first item\n if (!empty($sql)) {\n $LINK = $tmplink;\n }", " if (isset($criterion['criteria']) && count($criterion['criteria'])) {\n $sub_sql = self::constructCriteriaSQL($criterion['criteria'], $data, $meta_searchopt, $is_having);\n if (strlen($sub_sql)) {\n if ($NOT) {\n $sql .= \"$LINK NOT($sub_sql)\";\n } else {\n $sql .= \"$LINK ($sub_sql)\";\n }\n }\n } else if (\n isset($meta_searchopt[$criterion['field']][\"usehaving\"])\n || ($meta && \"AND NOT\" === $criterion['link'])\n ) {\n if (!$is_having) {\n // the having part will be managed in a second pass\n continue;\n }", " $new_having = self::addHaving(\n $LINK,\n $NOT,\n $itemtype,\n $criterion['field'],\n $criterion['searchtype'],\n $criterion['value']\n );\n if ($new_having !== false) {\n $sql .= $new_having;\n }\n } else {\n if ($is_having) {\n // the having part has been already managed in the first pass\n continue;\n }", " $new_where = self::addWhere(\n $LINK,\n $NOT,\n $itemtype,\n $criterion['field'],\n $criterion['searchtype'],\n $criterion['value'],\n $meta\n );\n if ($new_where !== false) {\n $sql .= $new_where;\n }\n }\n } else if (\n isset($criterion['value'])\n && strlen($criterion['value']) > 0\n ) { // view and all search\n $LINK = \" OR \";\n $NOT = 0;\n $globallink = \" AND \";\n if (isset($criterion['link'])) {\n switch ($criterion['link']) {\n case \"AND\":\n $LINK = \" OR \";\n $globallink = \" AND \";\n break;\n case \"AND NOT\":\n $LINK = \" AND \";\n $NOT = 1;\n $globallink = \" AND \";\n break;\n case \"OR\":\n $LINK = \" OR \";\n $globallink = \" OR \";\n break;\n case \"OR NOT\":\n $LINK = \" AND \";\n $NOT = 1;\n $globallink = \" OR \";\n break;\n }\n } else {\n $tmplink = \" AND \";\n }\n // Manage Link if not first item\n if (!empty($sql) && !$is_having) {\n $sql .= $globallink;\n }\n $first2 = true;\n $items = [];\n if (isset($criterion['field']) && $criterion['field'] == \"all\") {\n $items = $searchopt;\n } else { // toview case : populate toview\n foreach ($data['toview'] as $key2 => $val2) {\n $items[$val2] = $searchopt[$val2];\n }\n }\n $view_sql = \"\";\n foreach ($items as $key2 => $val2) {\n if (isset($val2['nosearch']) && $val2['nosearch']) {\n continue;\n }\n if (is_array($val2)) {\n // Add Where clause if not to be done in HAVING CLAUSE\n if (!$is_having && !isset($val2[\"usehaving\"])) {\n $tmplink = $LINK;\n if ($first2) {\n $tmplink = \" \";\n }", " $new_where = self::addWhere(\n $tmplink,\n $NOT,\n $itemtype,\n $key2,\n $criterion['searchtype'],\n $criterion['value'],\n $meta\n );\n if ($new_where !== false) {\n $first2 = false;\n $view_sql .= $new_where;\n }\n }\n }\n }\n if (strlen($view_sql)) {\n $sql .= \" ($view_sql) \";\n }\n }\n }\n return $sql;\n }", " /**\n * Construct aditionnal SQL (select, joins, etc) for meta-criteria\n *\n * @since 9.4\n *\n * @param array $criteria list of search criterion\n * @param string &$SELECT TODO: should be a class property (output parameter)\n * @param string &$FROM TODO: should be a class property (output parameter)\n * @param array &$already_link_tables TODO: should be a class property (output parameter)\n * @param array &$data TODO: should be a class property (output parameter)\n *\n * @return void\n */\n public static function constructAdditionalSqlForMetacriteria(\n $criteria = [],\n &$SELECT = \"\",\n &$FROM = \"\",\n &$already_link_tables = [],\n &$data = []\n ) {\n $data['meta_toview'] = [];\n foreach ($criteria as $criterion) {\n // manage sub criteria\n if (isset($criterion['criteria'])) {\n self::constructAdditionalSqlForMetacriteria(\n $criterion['criteria'],\n $SELECT,\n $FROM,\n $already_link_tables,\n $data\n );\n continue;\n }", " // parse only criterion with meta flag\n if (\n !isset($criterion['itemtype'])\n || empty($criterion['itemtype'])\n || !isset($criterion['meta'])\n || !$criterion['meta']\n || !isset($criterion['value'])\n || strlen($criterion['value']) <= 0\n ) {\n continue;\n }", " $m_itemtype = $criterion['itemtype'];\n $metaopt = &self::getOptions($m_itemtype);\n $sopt = $metaopt[$criterion['field']];", " //add toview for meta criterion\n $data['meta_toview'][$m_itemtype][] = $criterion['field'];", " $SELECT .= self::addSelect(\n $m_itemtype,\n $criterion['field'],\n true, // meta-criterion\n $m_itemtype\n );", " $FROM .= self::addMetaLeftJoin(\n $data['itemtype'],\n $m_itemtype,\n $already_link_tables,\n $sopt[\"joinparams\"]\n );", " $FROM .= self::addLeftJoin(\n $m_itemtype,\n $m_itemtype::getTable(),\n $already_link_tables,\n $sopt[\"table\"],\n $sopt[\"linkfield\"],\n 1,\n $m_itemtype,\n $sopt[\"joinparams\"],\n $sopt[\"field\"]\n );\n }\n }", "\n /**\n * Retrieve datas from DB : construct data array containing columns definitions and rows datas\n *\n * add to data array a field data containing :\n * cols : columns definition\n * rows : rows data\n *\n * @since 0.85\n *\n * @param array $data array of search data prepared to get data\n * @param boolean $onlycount If we just want to count results\n *\n * @return void|false May return false if the SQL data in $data is not valid\n **/\n public static function constructData(array &$data, $onlycount = false)\n {\n if (!isset($data['sql']) || !isset($data['sql']['search'])) {\n return false;\n }\n $data['data'] = [];", " // Use a ReadOnly connection if available and configured to be used\n $DBread = DBConnection::getReadConnection();\n $DBread->query(\"SET SESSION group_concat_max_len = 8194304;\");", " $DBread->execution_time = true;\n $result = $DBread->query($data['sql']['search']);", " if ($result) {\n $data['data']['execution_time'] = $DBread->execution_time;\n if (isset($data['search']['savedsearches_id'])) {\n SavedSearch::updateExecutionTime(\n (int)$data['search']['savedsearches_id'],\n $DBread->execution_time\n );\n }", " $data['data']['totalcount'] = 0;\n // if real search or complete export : get numrows from request\n if (\n !$data['search']['no_search']\n || $data['search']['export_all']\n ) {\n $data['data']['totalcount'] = $DBread->numrows($result);\n } else {\n if (\n !isset($data['sql']['count'])\n || (count($data['sql']['count']) == 0)\n ) {\n $data['data']['totalcount'] = $DBread->numrows($result);\n } else {\n foreach ($data['sql']['count'] as $sqlcount) {\n $result_num = $DBread->query($sqlcount);\n $data['data']['totalcount'] += $DBread->result($result_num, 0, 0);\n }\n }\n }", " if ($onlycount) {\n //we just want to coutn results; no need to continue process\n return;\n }", " if ($data['search']['start'] > $data['data']['totalcount']) {\n $data['search']['start'] = 0;\n }", " // Search case\n $data['data']['begin'] = $data['search']['start'];\n $data['data']['end'] = min(\n $data['data']['totalcount'],\n $data['search']['start'] + $data['search']['list_limit']\n ) - 1;\n //map case\n if (isset($data['search']['as_map']) && $data['search']['as_map'] == 1) {\n $data['data']['end'] = $data['data']['totalcount'] - 1;\n }", " // No search Case\n if ($data['search']['no_search']) {\n $data['data']['begin'] = 0;\n $data['data']['end'] = min(\n $data['data']['totalcount'] - $data['search']['start'],\n $data['search']['list_limit']\n ) - 1;\n }\n // Export All case\n if ($data['search']['export_all']) {\n $data['data']['begin'] = 0;\n $data['data']['end'] = $data['data']['totalcount'] - 1;\n }", " // Get columns\n $data['data']['cols'] = [];", " $searchopt = &self::getOptions($data['itemtype']);", " foreach ($data['toview'] as $opt_id) {\n $data['data']['cols'][] = [\n 'itemtype' => $data['itemtype'],\n 'id' => $opt_id,\n 'name' => $searchopt[$opt_id][\"name\"],\n 'meta' => 0,\n 'searchopt' => $searchopt[$opt_id],\n ];\n }", " // manage toview column for criteria with meta flag\n foreach ($data['meta_toview'] as $m_itemtype => $toview) {\n $searchopt = &self::getOptions($m_itemtype);\n foreach ($toview as $opt_id) {\n $data['data']['cols'][] = [\n 'itemtype' => $m_itemtype,\n 'id' => $opt_id,\n 'name' => $searchopt[$opt_id][\"name\"],\n 'meta' => 1,\n 'searchopt' => $searchopt[$opt_id],\n ];\n }\n }", " // Display columns Headers for meta items\n $already_printed = [];", " if (count($data['search']['metacriteria'])) {\n foreach ($data['search']['metacriteria'] as $metacriteria) {\n if (\n isset($metacriteria['itemtype']) && !empty($metacriteria['itemtype'])\n && isset($metacriteria['value']) && (strlen($metacriteria['value']) > 0)\n ) {\n if (!isset($already_printed[$metacriteria['itemtype'] . $metacriteria['field']])) {\n $searchopt = &self::getOptions($metacriteria['itemtype']);", " $data['data']['cols'][] = [\n 'itemtype' => $metacriteria['itemtype'],\n 'id' => $metacriteria['field'],\n 'name' => $searchopt[$metacriteria['field']][\"name\"],\n 'meta' => 1,\n 'searchopt' => $searchopt[$metacriteria['field']]\n ];", " $already_printed[$metacriteria['itemtype'] . $metacriteria['field']] = 1;\n }\n }\n }\n }", " // search group (corresponding of dropdown optgroup) of current col\n foreach ($data['data']['cols'] as $num => $col) {\n // search current col in searchoptions ()\n while (\n key($searchopt) !== null\n && key($searchopt) != $col['id']\n ) {\n next($searchopt);\n }\n if (key($searchopt) !== null) {\n //search optgroup (non array option)\n while (\n key($searchopt) !== null\n && is_numeric(key($searchopt))\n && is_array(current($searchopt))\n ) {\n prev($searchopt);\n }\n if (\n key($searchopt) !== null\n && key($searchopt) !== \"common\"\n ) {\n $data['data']['cols'][$num]['groupname'] = current($searchopt);\n }\n }\n //reset\n reset($searchopt);\n }", " // Get rows", " // if real search seek to begin of items to display (because of complete search)\n if (!$data['search']['no_search']) {\n $DBread->dataSeek($result, $data['search']['start']);\n }", " $i = $data['data']['begin'];\n $data['data']['warning']\n = \"For compatibility keep raw data (ITEM_X, META_X) at the top for the moment. Will be drop in next version\";", " $data['data']['rows'] = [];\n $data['data']['items'] = [];", " self::$output_type = $data['display_type'];", " while (($i < $data['data']['totalcount']) && ($i <= $data['data']['end'])) {\n $row = $DBread->fetchAssoc($result);\n $newrow = [];\n $newrow['raw'] = $row;", " // Parse datas\n foreach ($newrow['raw'] as $key => $val) {\n if (preg_match('/ITEM(_(\\w[^\\d]+))?_(\\d+)(_(.+))?/', $key, $matches)) {\n $j = $matches[3];\n if (isset($matches[2]) && !empty($matches[2])) {\n $j = $matches[2] . '_' . $matches[3];\n }\n $fieldname = 'name';\n if (isset($matches[5])) {\n $fieldname = $matches[5];\n }", " // No Group_concat case\n if ($fieldname == 'content' || !is_string($val) || strpos($val, self::LONGSEP) === false) {\n $newrow[$j]['count'] = 1;", " $handled = false;\n if ($fieldname != 'content' && is_string($val) && strpos($val, self::SHORTSEP) !== false) {\n $split2 = self::explodeWithID(self::SHORTSEP, $val);\n if (is_numeric($split2[1])) {\n $newrow[$j][0][$fieldname] = $split2[0];\n $newrow[$j][0]['id'] = $split2[1];\n $handled = true;\n }\n }", " if (!$handled) {\n if ($val === self::NULLVALUE) {\n $newrow[$j][0][$fieldname] = null;\n } else {\n $newrow[$j][0][$fieldname] = $val;\n }\n }\n } else {\n if (!isset($newrow[$j])) {\n $newrow[$j] = [];\n }\n $split = explode(self::LONGSEP, $val);\n $newrow[$j]['count'] = count($split);\n foreach ($split as $key2 => $val2) {\n $handled = false;\n if (strpos($val2, self::SHORTSEP) !== false) {\n $split2 = self::explodeWithID(self::SHORTSEP, $val2);\n if (is_numeric($split2[1])) {\n $newrow[$j][$key2]['id'] = $split2[1];\n if ($split2[0] == self::NULLVALUE) {\n $newrow[$j][$key2][$fieldname] = null;\n } else {\n $newrow[$j][$key2][$fieldname] = $split2[0];\n }\n $handled = true;\n }\n }", " if (!$handled) {\n $newrow[$j][$key2][$fieldname] = $val2;\n }\n }\n }\n } else {\n if ($key == 'currentuser') {\n if (!isset($data['data']['currentuser'])) {\n $data['data']['currentuser'] = $val;\n }\n } else {\n $newrow[$key] = $val;\n // Add id to items list\n if ($key == 'id') {\n $data['data']['items'][$val] = $i;\n }\n }\n }\n }\n foreach ($data['data']['cols'] as $val) {\n $newrow[$val['itemtype'] . '_' . $val['id']]['displayname'] = self::giveItem(\n $val['itemtype'],\n $val['id'],\n $newrow\n );\n }", " $data['data']['rows'][$i] = $newrow;\n $i++;\n }", " $data['data']['count'] = count($data['data']['rows']);\n } else {\n $error_no = $DBread->errno();\n if ($error_no == 1116) { // Too many tables; MySQL can only use 61 tables in a join\n echo self::showError(\n $data['search']['display_type'],\n __(\"'All' criterion is not usable with this object list, \" .\n \"sql query fails (too many tables). \" .\n \"Please use 'Items seen' criterion instead\")\n );\n } else {\n echo $DBread->error();\n }\n }\n }", "\n /**\n * Display datas extracted from DB\n *\n * @param array $data Array of search datas prepared to get datas\n *\n * @return void\n **/\n public static function displayData(array $data)\n {\n global $CFG_GLPI;", " if (!isset($data['data']) || !isset($data['data']['totalcount'])) {\n return false;\n }", " $search = $data['search'];\n $itemtype = $data['itemtype'];\n $item = $data['item'];\n $is_deleted = $search['is_deleted'];", " foreach ($search['criteria'] as $key => $criteria) {\n if (isset($criteria['virtual']) && $criteria['virtual']) {\n unset($search['criteria'][$key]);\n }\n }", " // Contruct parameters\n $globallinkto = Toolbox::append_params([\n 'criteria' => Sanitizer::unsanitize($search['criteria']),\n 'metacriteria' => Sanitizer::unsanitize($search['metacriteria'])\n ], '&');", " $parameters = http_build_query([\n 'sort' => $search['sort'],\n 'order' => $search['order']\n ]);", " $parameters .= \"&{$globallinkto}\";", " if (isset($_GET['_in_modal'])) {\n $parameters .= \"&_in_modal=1\";\n }", " // For plugin add new parameter if available\n if ($plug = isPluginItemType($data['itemtype'])) {\n $out = Plugin::doOneHook($plug['plugin'], 'addParamFordynamicReport', $data['itemtype']);\n if (is_array($out) && count($out)) {\n $parameters .= Toolbox::append_params($out, '&');\n }\n }", " $prehref = $search['target'] . (strpos($search['target'], \"?\") !== false ? \"&\" : \"?\");\n $href = $prehref . $parameters;", " Session::initNavigateListItems($data['itemtype'], '', $href);", " TemplateRenderer::getInstance()->display('components/search/display_data.html.twig', [\n 'data' => $data,\n 'union_search_type' => $CFG_GLPI[\"union_search_type\"],\n 'rand' => mt_rand(),\n 'no_sort' => $search['no_sort'] ?? false,\n 'order' => $search['order'] ?? [],\n 'sort' => $search['sort'] ?? [],\n 'start' => $search['start'] ?? 0,\n 'limit' => $_SESSION['glpilist_limit'],\n 'count' => $data['data']['totalcount'] ?? 0,\n 'item' => $item,\n 'itemtype' => $itemtype,\n 'href' => $href,\n 'prehref' => $prehref,\n 'posthref' => $globallinkto,\n 'showmassiveactions' => ($search['showmassiveactions'] ?? true)\n && $data['display_type'] != self::GLOBAL_SEARCH\n && ($itemtype == AllAssets::getType()\n || count(MassiveAction::getAllMassiveActions($item, $is_deleted))\n ),\n 'massiveactionparams' => $data['search']['massiveactionparams'] + [\n 'is_deleted' => $is_deleted,\n 'container' => \"massform$itemtype\",\n ],\n 'can_config' => Session::haveRightsOr('search_config', [\n DisplayPreference::PERSONAL,\n DisplayPreference::GENERAL\n ]),\n 'may_be_deleted' => $item instanceof CommonDBTM && $item->maybeDeleted(),\n 'may_be_located' => $item instanceof CommonDBTM && $item->maybeLocated(),\n 'may_be_browsed' => $item !== null && Toolbox::hasTrait($item, \\Glpi\\Features\\TreeBrowse::class),\n ]);", " // Add items in item list\n foreach ($data['data']['rows'] as $row) {\n if ($itemtype !== AllAssets::class) {\n Session::addToNavigateListItems($itemtype, $row[\"id\"]);\n } else {\n // In case of a global search, reset and empty navigation list to ensure navigation in\n // item header context is not shown. Indeed, this list does not support navigation through\n // multiple itemtypes, so it should not be displayed in global search context.\n Session::initNavigateListItems($row['TYPE'] ?? $data['itemtype']);\n }\n }", " // Clean previous selection\n $_SESSION['glpimassiveactionselected'] = [];\n }", " /**\n * Output data (for export in CSV, PDF, ...).\n *\n * @param array $data Array of search datas prepared to get datas\n *\n * @return void\n **/\n public static function outputData(array $data)\n {\n global $CFG_GLPI;", " if (\n !isset($data['data'])\n || !isset($data['data']['totalcount'])\n || $data['data']['count'] <= 0\n || $data['search']['as_map'] != 0\n ) {\n return false;\n }", " // Define begin and end var for loop\n // Search case\n $begin_display = $data['data']['begin'];\n $end_display = $data['data']['end'];", " // Compute number of columns to display\n // Add toview elements\n $nbcols = count($data['data']['cols']);", " // Display List Header\n echo self::showHeader($data['display_type'], $end_display - $begin_display + 1, $nbcols);", " // New Line for Header Items Line\n $headers_line = '';\n $headers_line_top = '';", " $headers_line_top .= self::showBeginHeader($data['display_type']);\n $headers_line_top .= self::showNewLine($data['display_type']);", " $header_num = 1;", " // Display column Headers for toview items\n $metanames = [];\n foreach ($data['data']['cols'] as $val) {\n $name = $val[\"name\"];", " // prefix by group name (corresponding to optgroup in dropdown) if exists\n if (isset($val['groupname'])) {\n $groupname = $val['groupname'];\n if (is_array($groupname)) {\n //since 9.2, getSearchOptions has been changed\n $groupname = $groupname['name'];\n }\n $name = \"$groupname - $name\";\n }", " // Not main itemtype add itemtype to display\n if ($data['itemtype'] != $val['itemtype']) {\n if (!isset($metanames[$val['itemtype']])) {\n if ($metaitem = getItemForItemtype($val['itemtype'])) {\n $metanames[$val['itemtype']] = $metaitem->getTypeName();\n }\n }\n $name = sprintf(\n __('%1$s - %2$s'),\n $metanames[$val['itemtype']],\n $val[\"name\"]\n );\n }", " $headers_line .= self::showHeaderItem(\n $data['display_type'],\n $name,\n $header_num,\n '',\n (!$val['meta']\n && ($data['search']['sort'] == $val['id'])),\n $data['search']['order']\n );\n }", " // Add specific column Header\n if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n $headers_line .= self::showHeaderItem(\n $data['display_type'],\n __('Item type'),\n $header_num\n );\n }\n // End Line for column headers\n $headers_line .= self::showEndLine($data['display_type'], true);", " $headers_line_top .= $headers_line;\n $headers_line_top .= self::showEndHeader($data['display_type']);", " echo $headers_line_top;", " // Num of the row (1=header_line)\n $row_num = 1;", " $typenames = [];\n // Display Loop\n foreach ($data['data']['rows'] as $row) {\n // Column num\n $item_num = 1;\n $row_num++;\n // New line\n echo self::showNewLine(\n $data['display_type'],\n ($row_num % 2),\n $data['search']['is_deleted']\n );", " // Print other toview items\n foreach ($data['data']['cols'] as $col) {\n $colkey = \"{$col['itemtype']}_{$col['id']}\";\n if (!$col['meta']) {\n echo self::showItem(\n $data['display_type'],\n $row[$colkey]['displayname'],\n $item_num,\n $row_num,\n self::displayConfigItem(\n $data['itemtype'],\n $col['id'],\n $row,\n $colkey\n )\n );\n } else { // META case\n echo self::showItem(\n $data['display_type'],\n $row[$colkey]['displayname'],\n $item_num,\n $row_num\n );\n }\n }", " if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n if (!isset($typenames[$row[\"TYPE\"]])) {\n if ($itemtmp = getItemForItemtype($row[\"TYPE\"])) {\n $typenames[$row[\"TYPE\"]] = $itemtmp->getTypeName();\n }\n }\n echo self::showItem(\n $data['display_type'],\n $typenames[$row[\"TYPE\"]],\n $item_num,\n $row_num\n );\n }\n // End Line\n echo self::showEndLine($data['display_type']);\n }", " // Create title\n $title = '';\n if (\n ($data['display_type'] == self::PDF_OUTPUT_LANDSCAPE)\n || ($data['display_type'] == self::PDF_OUTPUT_PORTRAIT)\n ) {\n $title = self::computeTitle($data);\n }", " // Display footer (close table)\n echo self::showFooter($data['display_type'], $title, $data['data']['count']);\n }", "\n /**\n * Compute title (use case of PDF OUTPUT)\n *\n * @param array $data Array data of search\n *\n * @return string Title\n **/\n public static function computeTitle($data)\n {\n $title = \"\";", " if (count($data['search']['criteria'])) {\n //Drop the first link as it is not needed, or convert to clean link (AND NOT -> NOT)\n if (isset($data['search']['criteria']['0']['link'])) {\n $notpos = strpos($data['search']['criteria']['0']['link'], 'NOT');\n //If link was like '%NOT%' just use NOT. Otherwise remove the link\n if ($notpos > 0) {\n $data['search']['criteria']['0']['link'] = 'NOT';\n } else if (!$notpos) {\n unset($data['search']['criteria']['0']['link']);\n }\n }", " foreach ($data['search']['criteria'] as $criteria) {\n if (isset($criteria['itemtype'])) {\n $searchopt = &self::getOptions($criteria['itemtype']);\n } else {\n $searchopt = &self::getOptions($data['itemtype']);\n }\n $titlecontain = '';", " if (isset($criteria['criteria'])) {\n //This is a group criteria, call computeTitle again and concat\n $newdata = $data;\n $oldlink = $criteria['link'];\n $newdata['search'] = $criteria;\n $titlecontain = sprintf(\n __('%1$s %2$s (%3$s)'),\n $titlecontain,\n $oldlink,\n Search::computeTitle($newdata)\n );\n } else {\n if (strlen($criteria['value']) > 0) {\n if (isset($criteria['link'])) {\n $titlecontain = \" \" . $criteria['link'] . \" \";\n }\n $gdname = '';\n $valuename = '';", " switch ($criteria['field']) {\n case \"all\":\n $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, __('All'));\n break;", " case \"view\":\n $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, __('Items seen'));\n break;", " default:\n if (isset($criteria['meta']) && $criteria['meta']) {\n $searchoptname = sprintf(\n __('%1$s / %2$s'),\n $criteria['itemtype'],\n $searchopt[$criteria['field']][\"name\"]\n );\n } else {\n $searchoptname = $searchopt[$criteria['field']][\"name\"];\n }", " $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, $searchoptname);\n $itemtype = getItemTypeForTable($searchopt[$criteria['field']][\"table\"]);\n $valuename = '';\n if ($item = getItemForItemtype($itemtype)) {\n $valuename = $item->getValueToDisplay(\n $searchopt[$criteria['field']],\n $criteria['value']\n );\n }", " $gdname = Dropdown::getDropdownName(\n $searchopt[$criteria['field']][\"table\"],\n $criteria['value']\n );\n }", " if (empty($valuename)) {\n $valuename = $criteria['value'];\n }\n switch ($criteria['searchtype']) {\n case \"equals\":\n if (\n in_array(\n $searchopt[$criteria['field']][\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $gdname);\n } else {\n $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $valuename);\n }\n break;", " case \"notequals\":\n if (\n in_array(\n $searchopt[$criteria['field']][\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain = sprintf(__('%1$s <> %2$s'), $titlecontain, $gdname);\n } else {\n $titlecontain = sprintf(__('%1$s <> %2$s'), $titlecontain, $valuename);\n }\n break;", " case \"lessthan\":\n $titlecontain = sprintf(__('%1$s < %2$s'), $titlecontain, $valuename);\n break;", " case \"morethan\":\n $titlecontain = sprintf(__('%1$s > %2$s'), $titlecontain, $valuename);\n break;", " case \"contains\":\n $titlecontain = sprintf(\n __('%1$s = %2$s'),\n $titlecontain,\n '%' . $valuename . '%'\n );\n break;", " case \"notcontains\":\n $titlecontain = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain,\n '%' . $valuename . '%'\n );\n break;", " case \"under\":\n $titlecontain = sprintf(\n __('%1$s %2$s'),\n $titlecontain,\n sprintf(__('%1$s %2$s'), __('under'), $gdname)\n );\n break;", " case \"notunder\":\n $titlecontain = sprintf(\n __('%1$s %2$s'),\n $titlecontain,\n sprintf(__('%1$s %2$s'), __('not under'), $gdname)\n );\n break;", " default:\n $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $valuename);\n break;\n }\n }\n }\n $title .= $titlecontain;\n }\n }\n if (\n isset($data['search']['metacriteria']) &&\n count($data['search']['metacriteria'])\n ) {\n $metanames = [];\n foreach ($data['search']['metacriteria'] as $metacriteria) {\n $searchopt = &self::getOptions($metacriteria['itemtype']);\n if (!isset($metanames[$metacriteria['itemtype']])) {\n if ($metaitem = getItemForItemtype($metacriteria['itemtype'])) {\n $metanames[$metacriteria['itemtype']] = $metaitem->getTypeName();\n }\n }", " $titlecontain2 = '';\n if (strlen($metacriteria['value']) > 0) {\n if (isset($metacriteria['link'])) {\n $titlecontain2 = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n $metacriteria['link']\n );\n }\n $titlecontain2\n = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n sprintf(\n __('%1$s / %2$s'),\n $metanames[$metacriteria['itemtype']],\n $searchopt[$metacriteria['field']][\"name\"]\n )\n );", " $gdname2 = Dropdown::getDropdownName(\n $searchopt[$metacriteria['field']][\"table\"],\n $metacriteria['value']\n );\n switch ($metacriteria['searchtype']) {\n case \"equals\":\n if (\n in_array(\n $searchopt[$metacriteria['link']]\n [\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n $gdname2\n );\n } else {\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n }\n break;", " case \"notequals\":\n if (\n in_array(\n $searchopt[$metacriteria['link']][\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain2 = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain2,\n $gdname2\n );\n } else {\n $titlecontain2 = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n }\n break;", " case \"lessthan\":\n $titlecontain2 = sprintf(\n __('%1$s < %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n break;", " case \"morethan\":\n $titlecontain2 = sprintf(\n __('%1$s > %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n break;", " case \"contains\":\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n '%' . $metacriteria['value'] . '%'\n );\n break;", " case \"notcontains\":\n $titlecontain2 = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain2,\n '%' . $metacriteria['value'] . '%'\n );\n break;", " case \"under\":\n $titlecontain2 = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n sprintf(\n __('%1$s %2$s'),\n __('under'),\n $gdname2\n )\n );\n break;", " case \"notunder\":\n $titlecontain2 = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n sprintf(\n __('%1$s %2$s'),\n __('not under'),\n $gdname2\n )\n );\n break;", " default:\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n break;\n }\n }\n $title .= $titlecontain2;\n }\n }\n return $title;\n }", " /**\n * Get meta types available for search engine\n *\n * @param class-string<CommonDBTM> $itemtype Type to display the form\n *\n * @return array Array of available itemtype\n **/\n public static function getMetaItemtypeAvailable($itemtype)\n {\n global $CFG_GLPI;", " $itemtype = self::getMetaReferenceItemtype($itemtype);", " if (!(($item = getItemForItemtype($itemtype)) instanceof CommonDBTM)) {\n return [];\n }", " $linked = [];\n foreach ($CFG_GLPI as $key => $values) {\n if ($key === 'link_types') {\n // Links are associated to all items of a type, it does not make any sense to use them in meta search\n continue;\n }\n if ($key === 'ticket_types' && $item instanceof CommonITILObject) {\n // Linked are filtered by CommonITILObject::getAllTypesForHelpdesk()\n $linked = array_merge($linked, array_keys($item::getAllTypesForHelpdesk()));\n continue;\n }", " foreach (self::getMetaParentItemtypesForTypesConfig($key) as $config_itemtype) {\n if ($itemtype === $config_itemtype::getType()) {\n // List is related to source itemtype, all types of list are so linked\n $linked = array_merge($linked, $values);\n } else if (in_array($itemtype, $values)) {\n // Source itemtype is inside list, type corresponding to list is so linked\n $linked[] = $config_itemtype::getType();\n }\n }\n }", " return array_unique($linked);\n }", " /**\n * Returns parents itemtypes having subitems defined in given config key.\n * This list is filtered and is only valid in a \"meta\" search context.\n *\n * @param string $config_key\n *\n * @return string[]\n */\n private static function getMetaParentItemtypesForTypesConfig(string $config_key): array\n {\n $matches = [];\n if (preg_match('/^(.+)_types$/', $config_key, $matches) === 0) {\n return [];\n }", " $key_to_itemtypes = [\n 'directconnect_types' => ['Computer'],\n 'infocom_types' => ['Budget', 'Infocom'],\n 'linkgroup_types' => ['Group'],\n // 'linkgroup_tech_types' => ['Group'], // Cannot handle ambiguity with 'Group' from 'linkgroup_types'\n 'linkuser_types' => ['User'],\n // 'linkuser_tech_types' => ['User'], // Cannot handle ambiguity with 'User' from 'linkuser_types'\n 'project_asset_types' => ['Project'],\n 'rackable_types' => ['Enclosure', 'Rack'],\n 'socket_types' => [Socket::class],\n 'ticket_types' => ['Change', 'Problem', 'Ticket'],\n ];", " if (array_key_exists($config_key, $key_to_itemtypes)) {\n return $key_to_itemtypes[$config_key];\n }", " $itemclass = $matches[1];\n if (is_a($itemclass, CommonDBTM::class, true)) {\n return [$itemclass::getType()];\n }", " return [];\n }", " /**\n * Check if an itemtype is a possible subitem of another itemtype in a \"meta\" search context.\n *\n * @param string $parent_itemtype\n * @param string $child_itemtype\n *\n * @return boolean\n */\n private static function isPossibleMetaSubitemOf(string $parent_itemtype, string $child_itemtype)\n {\n global $CFG_GLPI;", " if (\n is_a($parent_itemtype, CommonITILObject::class, true)\n && in_array($child_itemtype, array_keys($parent_itemtype::getAllTypesForHelpdesk()))\n ) {\n return true;\n }", " foreach ($CFG_GLPI as $key => $values) {\n if (\n in_array($parent_itemtype, self::getMetaParentItemtypesForTypesConfig($key))\n && in_array($child_itemtype, $values)\n ) {\n return true;\n }\n }", " return false;\n }", " /**\n * Gets the class to use if the specified itemtype extends one of the known reference types.\n *\n * @param class-string<CommonDBTM> $itemtype\n *\n * @return string|false The reference class name. If the provided itemtype is from a plugin, the provided itemtype is returned.\n * If the itemtype is not from a plugin and not exactly or extended from a reference itemtype, false will be returned.\n * @since 0.85\n */\n public static function getMetaReferenceItemtype($itemtype)\n {", " if (!isPluginItemType($itemtype)) {\n return $itemtype;\n }", " // Use reference type if given itemtype extends a reference type.\n $types = [\n 'Computer',\n 'Problem',\n 'Change',\n 'Ticket',\n 'Printer',\n 'Monitor',\n 'Peripheral',\n 'Software',\n 'Phone'\n ];\n foreach ($types as $type) {\n if (is_a($itemtype, $type, true)) {\n return $type;\n }\n }", " return false;\n }", "\n /**\n * Get dropdown options of logical operators.\n * @return string[]|array<string, string>\n * @since 0.85\n **/\n public static function getLogicalOperators($only_not = false)\n {\n if ($only_not) {\n return [\n 'AND' => Dropdown::EMPTY_VALUE,\n 'AND NOT' => __(\"NOT\")\n ];\n }", " return [\n 'AND' => __('AND'),\n 'OR' => __('OR'),\n 'AND NOT' => __('AND NOT'),\n 'OR NOT' => __('OR NOT')\n ];\n }", "\n /**\n * Print generic search form\n *\n * Params need to parsed before using Search::manageParams function\n *\n * @param class-string<CommonDBTM> $itemtype Type to display the form\n * @param array $params Array of parameters may include sort, is_deleted, criteria, metacriteria\n *\n * @return void\n **/\n public static function showGenericSearch($itemtype, array $params)\n {\n global $CFG_GLPI;", " // Default values of parameters\n $p['sort'] = '';\n $p['is_deleted'] = 0;\n $p['as_map'] = 0;\n $p['browse'] = 0;\n $p['criteria'] = [];\n $p['metacriteria'] = [];\n if (class_exists($itemtype)) {\n $p['target'] = $itemtype::getSearchURL();\n } else {\n $p['target'] = Toolbox::getItemTypeSearchURL($itemtype);\n }\n $p['showreset'] = true;\n $p['showbookmark'] = true;\n $p['showfolding'] = true;\n $p['mainform'] = true;\n $p['prefix_crit'] = '';\n $p['addhidden'] = [];\n $p['actionname'] = 'search';\n $p['actionvalue'] = _sx('button', 'Search');", " foreach ($params as $key => $val) {\n $p[$key] = $val;\n }", " // Itemtype name used in JS function names, etc\n $normalized_itemtype = strtolower(str_replace('\\\\', '', $itemtype));\n $rand_criteria = mt_rand();\n $main_block_class = '';\n $card_class = 'search-form card card-sm mb-4';\n if ($p['mainform']) {\n echo \"<form name='searchform$normalized_itemtype' class='search-form-container' method='get' action='\" . $p['target'] . \"'>\";\n } else {\n $main_block_class = \"sub_criteria\";\n $card_class = 'border d-inline-block ms-1';\n }\n $display = $_SESSION['glpifold_search'] ? 'style=\"display: none;\"' : '';\n echo \"<div class='$card_class' $display>\";", " echo \"<div id='searchcriteria$rand_criteria' class='$main_block_class' >\";\n $nbsearchcountvar = 'nbcriteria' . $normalized_itemtype . mt_rand();\n $searchcriteriatableid = 'criteriatable' . $normalized_itemtype . mt_rand();\n // init criteria count\n echo Html::scriptBlock(\"\n var $nbsearchcountvar = \" . count($p['criteria']) . \";\n \");", " echo \"<div class='list-group list-group-flush list-group-hoverable criteria-list pt-2' id='$searchcriteriatableid'>\";", " // Display normal search parameters\n $i = 0;\n foreach (array_keys($p['criteria']) as $i) {\n self::displayCriteria([\n 'itemtype' => $itemtype,\n 'num' => $i,\n 'p' => $p\n ]);\n }", " echo \"<a id='more-criteria$rand_criteria' role='button'\n class='normalcriteria fold-search list-group-item p-2 border-0'\n style='display: none;'></a>\";", " echo \"</div>\"; // .list", " // Keep track of the current savedsearches on reload\n if (isset($_GET['savedsearches_id'])) {\n echo Html::input(\"savedsearches_id\", [\n 'type' => \"hidden\",\n 'value' => $_GET['savedsearches_id'],\n ]);\n }", " echo \"<div class='card-footer d-flex search_actions'>\";\n $linked = self::getMetaItemtypeAvailable($itemtype);\n echo \"<button id='addsearchcriteria$rand_criteria' class='btn btn-sm btn-outline-secondary me-1' type='button'>\n <i class='ti ti-square-plus'></i>\n <span class='d-none d-sm-block'>\" . __s('rule') . \"</span>\n </button>\";\n if (count($linked)) {\n echo \"<button id='addmetasearchcriteria$rand_criteria' class='btn btn-sm btn-outline-secondary me-1' type='button'>\n <i class='ti ti-circle-plus'></i>\n <span class='d-none d-sm-block'>\" . __s('global rule') . \"</span>\n </button>\";\n }\n echo \"<button id='addcriteriagroup$rand_criteria' class='btn btn-sm btn-outline-secondary me-1' type='button'>\n <i class='ti ti-code-plus'></i>\n <span class='d-none d-sm-block'>\" . __s('group') . \"</span>\n </button>\";\n $json_p = json_encode($p);", " if ($p['mainform']) {\n // Display submit button\n echo \"<button class='btn btn-sm btn-primary me-1' type='submit' name='\" . $p['actionname'] . \"'>\n <i class='ti ti-list-search'></i>\n <span class='d-none d-sm-block'>\" . $p['actionvalue'] . \"</span>\n </button>\";\n if ($p['showbookmark'] || $p['showreset']) {\n if ($p['showbookmark']) {\n SavedSearch::showSaveButton(\n SavedSearch::SEARCH,\n $itemtype,\n isset($_GET['savedsearches_id'])\n );\n }", " if ($p['showreset']) {\n echo \"<a class='btn btn-ghost-secondary btn-icon btn-sm me-1 search-reset'\n data-bs-toggle='tooltip' data-bs-placement='bottom'\n href='\"\n . $p['target']\n . (strpos($p['target'], '?') ? '&amp;' : '?')\n . \"reset=reset' title=\\\"\" . __s('Blank') . \"\\\"\n ><i class='ti ti-circle-x'></i></a>\";\n }\n }\n }\n echo \"</div>\"; //.search_actions", " // idor checks\n $idor_display_criteria = Session::getNewIDORToken($itemtype);\n $idor_display_meta_criteria = Session::getNewIDORToken($itemtype);\n $idor_display_criteria_group = Session::getNewIDORToken($itemtype);", " $itemtype_escaped = addslashes($itemtype);\n $JS = <<<JAVASCRIPT\n $('#addsearchcriteria$rand_criteria').on('click', function(event) {\n event.preventDefault();\n $.post('{$CFG_GLPI['root_doc']}/ajax/search.php', {\n 'action': 'display_criteria',\n 'itemtype': '$itemtype_escaped',\n 'num': $nbsearchcountvar,\n 'p': $json_p,\n '_idor_token': '$idor_display_criteria'\n })\n .done(function(data) {\n $(data).insertBefore('#more-criteria$rand_criteria');\n $nbsearchcountvar++;\n });\n });", " $('#addmetasearchcriteria$rand_criteria').on('click', function(event) {\n event.preventDefault();\n $.post('{$CFG_GLPI['root_doc']}/ajax/search.php', {\n 'action': 'display_meta_criteria',\n 'itemtype': '$itemtype_escaped',\n 'meta': true,\n 'num': $nbsearchcountvar,\n 'p': $json_p,\n '_idor_token': '$idor_display_meta_criteria'\n })\n .done(function(data) {\n $(data).insertBefore('#more-criteria$rand_criteria');\n $nbsearchcountvar++;\n });\n });", " $('#addcriteriagroup$rand_criteria').on('click', function(event) {\n event.preventDefault();\n $.post('{$CFG_GLPI['root_doc']}/ajax/search.php', {\n 'action': 'display_criteria_group',\n 'itemtype': '$itemtype_escaped',\n 'meta': true,\n 'num': $nbsearchcountvar,\n 'p': $json_p,\n '_idor_token': '$idor_display_criteria_group'\n })\n .done(function(data) {\n $(data).insertBefore('#more-criteria$rand_criteria');\n $nbsearchcountvar++;\n });\n });\nJAVASCRIPT;", " if ($p['mainform']) {\n $JS .= <<<JAVASCRIPT\n var toggle_fold_search = function(show_search) {\n $('#searchcriteria{$rand_criteria}').closest('.search-form').toggle(show_search);\n };", " // Init search_criteria state\n var search_criteria_visibility = window.localStorage.getItem('show_full_searchcriteria');\n if (search_criteria_visibility !== undefined && search_criteria_visibility == 'false') {\n $('.fold-search').click();\n }", " $(document).on(\"click\", \".remove-search-criteria\", function() {\n // force removal of tooltip\n var tooltip = bootstrap.Tooltip.getInstance($(this)[0]);\n if (tooltip !== null) {\n tooltip.dispose();\n }", " var rowID = $(this).data('rowid');\n $('#' + rowID).remove();\n $('#searchcriteria{$rand_criteria} .criteria-list .list-group-item:first-child').addClass('headerRow').show();\n });\nJAVASCRIPT;\n }\n echo Html::scriptBlock($JS);", " if (count($p['addhidden'])) {\n foreach ($p['addhidden'] as $key => $val) {\n echo Html::hidden($key, ['value' => $val]);\n }\n }", " if ($p['mainform']) {\n // For dropdown\n echo Html::hidden('itemtype', ['value' => $itemtype]);\n // Reset to start when submit new search\n echo Html::hidden('start', ['value' => 0]);\n }", " echo \"</div>\"; // #searchcriteria\n echo \"</div>\"; // .card\n if ($p['mainform']) {\n Html::closeForm();\n }\n }", " /**\n * Display a criteria field set, this function should be called by ajax/search.php\n *\n * @since 9.4\n *\n * @param array $request we should have these keys of parameters:\n * - itemtype: main itemtype for criteria, sub one for metacriteria\n * - num: index of the criteria\n * - p: params of showGenericSearch method\n *\n * @return void\n */\n public static function displayCriteria($request = [])\n {\n global $CFG_GLPI;", " if (\n !isset($request[\"itemtype\"])\n || !isset($request[\"num\"])\n ) {\n return;\n }", " $num = (int) $request['num'];\n $p = $request['p'];\n $options = self::getCleanedOptions($request[\"itemtype\"]);\n $randrow = mt_rand();\n $normalized_itemtype = strtolower(str_replace('\\\\', '', $request[\"itemtype\"]));\n $rowid = 'searchrow' . $normalized_itemtype . $randrow;\n $addclass = $num == 0 ? ' headerRow' : '';\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];\n $criteria = [];\n $from_meta = isset($request['from_meta']) && $request['from_meta'];", " $sess_itemtype = $request[\"itemtype\"];\n if ($from_meta) {\n $sess_itemtype = $request[\"parent_itemtype\"];\n }", " if (!$criteria = self::findCriteriaInSession($sess_itemtype, $num, $parents_num)) {\n $criteria = self::getDefaultCriteria($request[\"itemtype\"]);\n }", " if (\n isset($criteria['meta'])\n && $criteria['meta']\n && !$from_meta\n ) {\n self::displayMetaCriteria($request);\n return;\n }", " if (\n isset($criteria['criteria'])\n && is_array($criteria['criteria'])\n ) {\n self::displayCriteriaGroup($request);\n return;\n }", " $add_padding = \"p-2\";\n if (isset($request[\"from_meta\"])) {\n $add_padding = \"p-0\";\n }", " echo \"<div class='list-group-item $add_padding border-0 normalcriteria$addclass' id='$rowid'>\";\n echo \"<div class='row g-1'>\";", " if (!$from_meta) {\n // First line display add / delete images for normal and meta search items\n if (\n $num == 0\n && isset($p['mainform'])\n && $p['mainform']\n ) {\n // Instanciate an object to access method\n $item = null;\n if ($request[\"itemtype\"] != AllAssets::getType()) {\n $item = getItemForItemtype($request[\"itemtype\"]);\n }\n if ($item && $item->maybeDeleted()) {\n echo Html::hidden('is_deleted', [\n 'value' => $p['is_deleted'],\n 'id' => 'is_deleted'\n ]);\n }\n echo Html::hidden('as_map', [\n 'value' => $p['as_map'],\n 'id' => 'as_map'\n ]);\n echo Html::hidden('browse', [\n 'value' => $p['browse'],\n 'id' => 'browse'\n ]);\n }\n echo \"<div class='col-auto'>\";\n echo \"<button class='btn btn-sm btn-icon btn-ghost-secondary remove-search-criteria' type='button' data-rowid='$rowid'\n data-bs-toggle='tooltip' data-bs-placement='left'\n title=\\\"\" . __s('Delete a rule') . \"\\\">\n <i class='ti ti-square-minus' alt='-'></i>\n </button>\";\n echo \"</div>\";\n }", " // Display link item\n $value = '';\n if (!$from_meta) {\n echo \"<div class='col-auto'>\";\n if (isset($criteria[\"link\"])) {\n $value = $criteria[\"link\"];\n }\n $operators = Search::getLogicalOperators(($num == 0));\n Dropdown::showFromArray(\"criteria{$prefix}[$num][link]\", $operators, [\n 'value' => $value,\n ]);\n echo \"</div>\";\n }", " $values = [];\n // display select box to define search item\n if ($CFG_GLPI['allow_search_view'] == 2 && !isset($request['from_meta'])) {\n $values['view'] = __('Items seen');\n }", " reset($options);\n $group = '';", " foreach ($options as $key => $val) {\n // print groups\n if (!is_array($val)) {\n $group = $val;\n } else if (count($val) == 1) {\n $group = $val['name'];\n } else {\n if (\n (!isset($val['nosearch']) || ($val['nosearch'] == false))\n && (!$from_meta || !array_key_exists('nometa', $val) || $val['nometa'] !== true)\n ) {\n $values[$group][$key] = $val[\"name\"];\n }\n }\n }\n if ($CFG_GLPI['allow_search_view'] == 1 && !isset($request['from_meta'])) {\n $values['view'] = __('Items seen');\n }\n if ($CFG_GLPI['allow_search_all'] && !isset($request['from_meta'])) {\n $values['all'] = __('All');\n }\n $value = '';", " if (isset($criteria['field'])) {\n $value = $criteria['field'];\n }", " echo \"<div class='col-auto'>\";\n $rand = Dropdown::showFromArray(\"criteria{$prefix}[$num][field]\", $values, [\n 'value' => $value,\n ]);\n echo \"</div>\";\n $field_id = Html::cleanId(\"dropdown_criteria{$prefix}[$num][field]$rand\");\n $spanid = Html::cleanId('SearchSpan' . $normalized_itemtype . $prefix . $num);", " echo \"<div class='col-auto'>\";\n echo \"<div class='row g-1' id='$spanid'>\";", " $used_itemtype = $request[\"itemtype\"];\n // Force Computer itemtype for AllAssets to permit to show specific items\n if ($request[\"itemtype\"] == AllAssets::getType()) {\n $used_itemtype = 'Computer';\n }", " $searchtype = isset($criteria['searchtype'])\n ? $criteria['searchtype']\n : \"\";\n $p_value = isset($criteria['value'])\n ? Sanitizer::dbUnescape($criteria['value'])\n : \"\";", " $params = [\n 'itemtype' => $used_itemtype,\n '_idor_token' => Session::getNewIDORToken($used_itemtype),\n 'field' => $value,\n 'searchtype' => $searchtype,\n 'value' => $p_value,\n 'num' => $num,\n 'p' => $p,\n ];\n Search::displaySearchoption($params);\n echo \"</div>\";", " Ajax::updateItemOnSelectEvent(\n $field_id,\n $spanid,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/search.php\",\n [\n 'action' => 'display_searchoption',\n 'field' => '__VALUE__',\n ] + $params\n );\n echo \"</div>\"; //.row\n echo \"</div>\"; //#$spanid\n echo \"</div>\";\n }", " /**\n * Display a meta-criteria field set, this function should be called by ajax/search.php\n * Call displayCriteria method after displaying its itemtype field\n *\n * @since 9.4\n *\n * @param array $request @see displayCriteria method\n *\n * @return void\n */\n public static function displayMetaCriteria($request = [])\n {\n global $CFG_GLPI;", " if (\n !isset($request[\"itemtype\"])\n || !isset($request[\"num\"])\n ) {\n return \"\";\n }", " $p = $request['p'];\n $num = (int) $request['num'];\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];\n $itemtype = $request[\"itemtype\"];\n $metacriteria = [];", " if (!$metacriteria = self::findCriteriaInSession($itemtype, $num, $parents_num)) {\n $metacriteria = [];\n // Set default field\n $options = Search::getCleanedOptions($itemtype);", " foreach ($options as $key => $val) {\n if (is_array($val) && isset($val['table'])) {\n $metacriteria['field'] = $key;\n break;\n }\n }\n }", " $linked = Search::getMetaItemtypeAvailable($itemtype);\n $rand = mt_rand();", " $rowid = 'metasearchrow' . $request['itemtype'] . $rand;", " echo \"<div class='list-group-item border-0 metacriteria p-2' id='$rowid'>\";\n echo \"<div class='row g-1'>\";", " echo \"<div class='col-auto'>\";\n echo \"<button class='btn btn-sm btn-icon btn-ghost-secondary remove-search-criteria' type='button' data-rowid='$rowid'>\n <i class='ti ti-square-minus' alt='-' title=\\\"\" .\n __s('Delete a global rule') . \"\\\"></i>\n </button>\";\n echo \"</div>\";", " // Display link item (not for the first item)\n echo \"<div class='col-auto'>\";\n Dropdown::showFromArray(\n \"criteria{$prefix}[$num][link]\",\n Search::getLogicalOperators(),\n [\n 'value' => isset($metacriteria[\"link\"])\n ? $metacriteria[\"link\"]\n : \"\",\n ]\n );\n echo \"</div>\";", " // Display select of the linked item type available\n echo \"<div class='col-auto'>\";\n $rand = Dropdown::showItemTypes(\"criteria{$prefix}[$num][itemtype]\", $linked, [\n 'value' => isset($metacriteria['itemtype'])\n && !empty($metacriteria['itemtype'])\n ? $metacriteria['itemtype']\n : \"\",\n ]);\n echo \"</div>\";\n echo Html::hidden(\"criteria{$prefix}[$num][meta]\", [\n 'value' => true\n ]);\n $field_id = Html::cleanId(\"dropdown_criteria{$prefix}[$num][itemtype]$rand\");\n $spanid = Html::cleanId(\"show_\" . $request[\"itemtype\"] . \"_\" . $prefix . $num . \"_$rand\");\n // Ajax script for display search met& item", " $params = [\n 'action' => 'display_criteria',\n 'itemtype' => '__VALUE__',\n 'parent_itemtype' => $request['itemtype'],\n 'from_meta' => true,\n 'num' => $num,\n 'p' => $request[\"p\"],\n '_idor_token' => Session::getNewIDORToken(\"\", [\n 'parent_itemtype' => $request['itemtype']\n ])\n ];\n Ajax::updateItemOnSelectEvent(\n $field_id,\n $spanid,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/search.php\",\n $params\n );", " echo \"<div class='col-auto' id='$spanid'>\";\n echo \"<div class=row'>\";\n if (\n isset($metacriteria['itemtype'])\n && !empty($metacriteria['itemtype'])\n ) {\n $params['itemtype'] = $metacriteria['itemtype'];\n self::displayCriteria($params);\n }\n echo \"</div>\";\n echo \"</div>\";\n echo \"</div>\";\n echo \"</div>\";\n }", " /**\n * Display a group of nested criteria.\n * A group (parent) criteria can contains children criteria (who also cantains children, etc)\n *\n * @since 9.4\n *\n * @param array $request @see displayCriteria method\n *\n * @return void\n */\n public static function displayCriteriaGroup($request = [])\n {\n $num = (int) $request['num'];\n $p = $request['p'];\n $randrow = mt_rand();\n $rowid = 'searchrow' . $request['itemtype'] . $randrow;\n $addclass = $num == 0 ? ' headerRow' : '';\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];", " if (!$criteria = self::findCriteriaInSession($request['itemtype'], $num, $parents_num)) {\n $criteria = [\n 'criteria' => self::getDefaultCriteria($request['itemtype']),\n ];\n }", " echo \"<div class='list-group-item p-2 border-0 normalcriteria$addclass' id='$rowid'>\";\n echo \"<div class='row g-1'>\";\n echo \"<div class='col-auto'>\";\n echo \"<button class='btn btn-sm btn-icon btn-ghost-secondary remove-search-criteria' type='button' data-rowid='$rowid'\n data-bs-toggle='tooltip' data-bs-placement='left'\n title=\\\"\" . __s('Delete a rule') . \"\\\"\n >\n <i class='ti ti-square-minus' alt='-'></i>\n </button>\";\n echo \"</div>\";\n echo \"<div class='col-auto'>\";\n Dropdown::showFromArray(\"criteria{$prefix}[$num][link]\", Search::getLogicalOperators(), [\n 'value' => isset($criteria[\"link\"]) ? $criteria[\"link\"] : '',\n ]);\n echo \"</div>\";", " $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];\n array_push($parents_num, $num);\n $params = [\n 'mainform' => false,\n 'prefix_crit' => \"{$prefix}[$num][criteria]\",\n 'parents_num' => $parents_num,\n 'criteria' => $criteria['criteria'],\n ];", " echo \"<div class='col-auto'>\";\n self::showGenericSearch($request['itemtype'], $params);\n echo \"</div>\";", " echo \"</div>\";//.row\n echo \"</div>\";//.list-group-item\n }", " /**\n * Retrieve a single criteria in Session by its index\n *\n * @since 9.4\n *\n * @param string $itemtype which glpi type we must search in session\n * @param integer $num index of the criteria\n * @param array $parents_num node indexes of the parents (@see displayCriteriaGroup)\n *\n * @return array|false the found criteria array, or false if nothing found\n */\n public static function findCriteriaInSession($itemtype = '', $num = 0, $parents_num = [])\n {\n if (!isset($_SESSION['glpisearch'][$itemtype]['criteria'])) {\n return false;\n }\n $criteria = &$_SESSION['glpisearch'][$itemtype]['criteria'];", " if (count($parents_num)) {\n foreach ($parents_num as $parent) {\n if (!isset($criteria[$parent]['criteria'])) {\n return false;\n }\n $criteria = &$criteria[$parent]['criteria'];\n }\n }", " if (\n isset($criteria[$num])\n && is_array($criteria[$num])\n ) {\n return $criteria[$num];\n }", " return false;\n }", " /**\n * construct the default criteria for an itemtype\n *\n * @since 9.4\n *\n * @param class-string<CommonDBTM> $itemtype\n *\n * @return array criteria\n */\n public static function getDefaultCriteria($itemtype = '')\n {\n global $CFG_GLPI;", " $field = '';", " if ($CFG_GLPI['allow_search_view'] == 2) {\n $field = 'view';\n } else {\n $options = self::getCleanedOptions($itemtype);\n foreach ($options as $key => $val) {\n if (\n is_array($val)\n && isset($val['table'])\n ) {\n $field = $key;\n break;\n }\n }\n }", " return [\n [\n 'field' => $field,\n 'link' => 'contains',\n 'value' => ''\n ]\n ];\n }", " /**\n * Display first part of criteria (field + searchtype, just after link)\n * will call displaySearchoptionValue for the next part (value)\n *\n * @since 9.4\n *\n * @param array $request we should have these keys of parameters:\n * - itemtype: main itemtype for criteria, sub one for metacriteria\n * - num: index of the criteria\n * - field: field key of the criteria\n * - p: params of showGenericSearch method\n *\n * @return void\n */\n public static function displaySearchoption($request = [])\n {\n global $CFG_GLPI;\n if (\n !isset($request[\"itemtype\"])\n || !isset($request[\"field\"])\n || !isset($request[\"num\"])\n ) {\n return \"\";\n }", " $p = $request['p'];\n $num = (int) $request['num'];\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';", " if (!is_subclass_of($request['itemtype'], 'CommonDBTM')) {\n throw new \\RuntimeException('Invalid itemtype provided!');\n }", " if (isset($request['meta']) && $request['meta']) {\n $fieldname = 'metacriteria';\n } else {\n $fieldname = 'criteria';\n $request['meta'] = 0;\n }", " $actions = Search::getActionsFor($request[\"itemtype\"], $request[\"field\"]);", " // is it a valid action for type ?\n if (\n count($actions)\n && (empty($request['searchtype']) || !isset($actions[$request['searchtype']]))\n ) {\n $tmp = $actions;\n unset($tmp['searchopt']);\n $request['searchtype'] = key($tmp);\n unset($tmp);\n }", " $rands = -1;\n $normalized_itemtype = strtolower(str_replace('\\\\', '', $request[\"itemtype\"]));\n $dropdownname = Html::cleanId(\"spansearchtype$fieldname\" .\n $normalized_itemtype .\n $prefix .\n $num);\n $searchopt = [];\n if (count($actions) > 0) {\n // get already get search options\n if (isset($actions['searchopt'])) {\n $searchopt = $actions['searchopt'];\n // No name for clean array with quotes\n unset($searchopt['name']);\n unset($actions['searchopt']);\n }\n $searchtype_name = \"{$fieldname}{$prefix}[$num][searchtype]\";\n echo \"<div class='col-auto'>\";\n $rands = Dropdown::showFromArray($searchtype_name, $actions, [\n 'value' => $request[\"searchtype\"],\n ]);\n echo \"</div>\";\n $fieldsearch_id = Html::cleanId(\"dropdown_$searchtype_name$rands\");\n }", " echo \"<div class='col-auto' id='$dropdownname' data-itemtype='{$request[\"itemtype\"]}' data-fieldname='$fieldname' data-prefix='$prefix' data-num='$num'>\";\n $params = [\n 'value' => rawurlencode(Sanitizer::dbUnescape($request['value'])),\n 'searchopt' => $searchopt,\n 'searchtype' => $request[\"searchtype\"],\n 'num' => $num,\n 'itemtype' => $request[\"itemtype\"],\n '_idor_token' => Session::getNewIDORToken($request[\"itemtype\"]),\n 'from_meta' => isset($request['from_meta'])\n ? $request['from_meta']\n : false,\n 'field' => $request[\"field\"],\n 'p' => $p,\n ];\n self::displaySearchoptionValue($params);\n echo \"</div>\";", " Ajax::updateItemOnSelectEvent(\n $fieldsearch_id,\n $dropdownname,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/search.php\",\n [\n 'action' => 'display_searchoption_value',\n 'searchtype' => '__VALUE__',\n ] + $params\n );\n }", " /**\n * Display last part of criteria (value, just after searchtype)\n * called by displaySearchoptionValue\n *\n * @since 9.4\n *\n * @param array $request we should have these keys of parameters:\n * - searchtype: (contains, equals) passed by displaySearchoption\n *\n * @return void\n */\n public static function displaySearchoptionValue($request = [])\n {\n if (!isset($request['searchtype'])) {\n return \"\";\n }", " $p = $request['p'];\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $searchopt = isset($request['searchopt']) ? $request['searchopt'] : [];\n $request['value'] = rawurldecode($request['value']);\n $fieldname = isset($request['meta']) && $request['meta']\n ? 'metacriteria'\n : 'criteria';\n $inputname = $fieldname . $prefix . '[' . $request['num'] . '][value]';\n $display = false;\n $item = getItemForItemtype($request['itemtype']);\n $options2 = [];\n $options2['value'] = $request['value'];\n $options2['width'] = '100%';\n // For tree dropdpowns\n $options2['permit_select_parent'] = true;", " switch ($request['searchtype']) {\n case \"equals\":\n case \"notequals\":\n case \"morethan\":\n case \"lessthan\":\n case \"under\":\n case \"notunder\":\n if (!$display && isset($searchopt['field'])) {\n // Specific cases\n switch ($searchopt['table'] . \".\" . $searchopt['field']) {\n // Add mygroups choice to searchopt\n case \"glpi_groups.completename\":\n $searchopt['toadd'] = ['mygroups' => __('My groups')];\n break;", " case \"glpi_changes.status\":\n case \"glpi_changes.impact\":\n case \"glpi_changes.urgency\":\n case \"glpi_problems.status\":\n case \"glpi_problems.impact\":\n case \"glpi_problems.urgency\":\n case \"glpi_tickets.status\":\n case \"glpi_tickets.impact\":\n case \"glpi_tickets.urgency\":\n $options2['showtype'] = 'search';\n break;", " case \"glpi_changes.priority\":\n case \"glpi_problems.priority\":\n case \"glpi_tickets.priority\":\n $options2['showtype'] = 'search';\n $options2['withmajor'] = true;\n break;", " case \"glpi_tickets.global_validation\":\n $options2['all'] = true;\n break;", " case \"glpi_ticketvalidations.status\":\n $options2['all'] = true;\n break;", " case \"glpi_users.name\":\n $options2['right'] = (isset($searchopt['right']) ? $searchopt['right'] : 'all');\n $options2['inactive_deleted'] = 1;\n $searchopt['toadd'] = [\n [\n 'id' => 'myself',\n 'text' => __('Myself'),\n ]\n ];", " break;\n }", " // Standard datatype usage\n if (!$display && isset($searchopt['datatype'])) {\n switch ($searchopt['datatype']) {\n case \"date\":\n case \"date_delay\":\n case \"datetime\":\n $options2['relative_dates'] = true;\n break;\n }\n }", " $out = $item->getValueToSelect($searchopt, $inputname, $request['value'], $options2);\n if (strlen($out)) {\n echo $out;\n $display = true;\n }", " //Could display be handled by a plugin ?\n if (\n !$display\n && $plug = isPluginItemType(getItemTypeForTable($searchopt['table']))\n ) {\n $display = Plugin::doOneHook(\n $plug['plugin'],\n 'searchOptionsValues',\n [\n 'name' => $inputname,\n 'searchtype' => $request['searchtype'],\n 'searchoption' => $searchopt,\n 'value' => $request['value']\n ]\n );\n }\n }\n break;\n }", " // Default case : text field\n if (!$display) {\n echo \"<input type='text' class='form-control' size='13' name='$inputname' value=\\\"\" .\n Html::cleanInputText($request['value']) . \"\\\">\";\n }\n }", "\n /**\n * Generic Function to add to a HAVING clause\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $LINK link to use\n * @param string $NOT is is a negative search ?\n * @param string $itemtype item type\n * @param integer $ID ID of the item to search\n * @param string $searchtype search type ('contains' or 'equals')\n * @param string $val value search\n *\n * @return string|false HAVING clause sub-string (Does not include the \"HAVING\" keyword).\n * May return false if the related search option is not valid for SQL searching.\n **/\n public static function addHaving($LINK, $NOT, $itemtype, $ID, $searchtype, $val)\n {", " global $DB;", " $searchopt = &self::getOptions($itemtype);\n if (!isset($searchopt[$ID]['table'])) {\n return false;\n }\n $table = $searchopt[$ID][\"table\"];\n $NAME = \"ITEM_{$itemtype}_{$ID}\";", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addHaving',\n $LINK,\n $NOT,\n $itemtype,\n $ID,\n $val,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }", " //// Default cases\n // Link with plugin tables\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addHaving',\n $LINK,\n $NOT,\n $itemtype,\n $ID,\n $val,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }", " if (in_array($searchtype, [\"notequals\", \"notcontains\"])) {\n $NOT = !$NOT;\n }", " // Preformat items\n if (isset($searchopt[$ID][\"datatype\"])) {\n if ($searchopt[$ID][\"datatype\"] == \"mio\") {\n // Parse value as it may contain a few different formats\n $val = Toolbox::getMioSizeFromString($val);\n }", " switch ($searchopt[$ID][\"datatype\"]) {\n case \"datetime\":\n if (in_array($searchtype, ['contains', 'notcontains'])) {\n break;\n }", " $force_day = false;\n if (strstr($val, 'BEGIN') || strstr($val, 'LAST')) {\n $force_day = true;\n }", " $val = Html::computeGenericDateTimeSearch($val, $force_day);", " $operator = '';\n switch ($searchtype) {\n case 'equals':\n $operator = !$NOT ? '=' : '!=';\n break;\n case 'notequals':\n $operator = !$NOT ? '!=' : '=';\n break;\n case 'lessthan':\n $operator = !$NOT ? '<' : '>';\n break;\n case 'morethan':\n $operator = !$NOT ? '>' : '<';\n break;\n }", " return \" {$LINK} ({$DB->quoteName($NAME)} $operator {$DB->quoteValue($val)}) \";\n break;\n case \"count\":\n case \"mio\":\n case \"number\":\n case \"decimal\":\n case \"timestamp\":\n $search = [\"/\\&lt;/\",\"/\\&gt;/\"];\n $replace = [\"<\",\">\"];\n $val = preg_replace($search, $replace, $val);\n if (preg_match(\"/([<>])([=]*)[[:space:]]*([0-9]+)/\", $val, $regs)) {\n if ($NOT) {\n if ($regs[1] == '<') {\n $regs[1] = '>';\n } else {\n $regs[1] = '<';\n }\n }\n $regs[1] .= $regs[2];\n return \" $LINK (`$NAME` \" . $regs[1] . \" \" . $regs[3] . \" ) \";\n }", " if (is_numeric($val)) {\n if (isset($searchopt[$ID][\"width\"])) {\n if (!$NOT) {\n return \" $LINK (`$NAME` < \" . (intval($val) + $searchopt[$ID][\"width\"]) . \"\n AND `$NAME` > \" .\n (intval($val) - $searchopt[$ID][\"width\"]) . \") \";\n }\n return \" $LINK (`$NAME` > \" . (intval($val) + $searchopt[$ID][\"width\"]) . \"\n OR `$NAME` < \" .\n (intval($val) - $searchopt[$ID][\"width\"]) . \" ) \";\n }\n // Exact search\n if (!$NOT) {\n return \" $LINK (`$NAME` = \" . (intval($val)) . \") \";\n }\n return \" $LINK (`$NAME` <> \" . (intval($val)) . \") \";\n }\n break;\n }\n }", " return self::makeTextCriteria(\"`$NAME`\", $val, $NOT, $LINK);\n }", "\n /**\n * Generic Function to add ORDER BY to a request\n *\n * @since 9.4: $key param has been dropped\n * @since 10.0.0: Parameters changed to allow multiple sort fields.\n * Old functionality maintained by checking the type of the first parameter.\n * This backwards compatibility will be removed in a later version.\n *\n * @param class-string<CommonDBTM> $itemtype The itemtype\n * @param array $sort_fields The search options to order on. This array should contain one or more associative arrays containing:\n * - id: The search option ID\n * - order: The sort direction (Default: ASC). Invalid sort directions will be replaced with the default option\n * @param ?integer $_id field to add (Deprecated)\n *\n * @return string ORDER BY query string\n *\n **/\n public static function addOrderBy($itemtype, $sort_fields, $_id = 'ASC')\n {\n global $CFG_GLPI;", " // BC parameter conversion\n if (!is_array($sort_fields)) {\n // < 10.0.0 parameters\n Toolbox::deprecated('The parameters for Search::addOrderBy have changed to allow sorting by multiple fields. Please update your calling code.');\n $sort_fields = [\n [\n 'searchopt_id' => $sort_fields,\n 'order' => $_id\n ]\n ];\n }", " $orderby_criteria = [];\n $searchopt = &self::getOptions($itemtype);", " foreach ($sort_fields as $sort_field) {\n $ID = $sort_field['searchopt_id'];\n if (isset($searchopt[$ID]['nosort']) && $searchopt[$ID]['nosort']) {\n continue;\n }\n $order = $sort_field['order'] ?? 'ASC';\n // Order security check\n if ($order != 'ASC') {\n $order = 'DESC';\n }", " $criterion = null;", " $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];", " $addtable = '';", " $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);\n $orig_table = self::getOrigTableName($itemtype);\n if (\n ($is_fkey_composite_on_self || $table != $orig_table)\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable .= \"_\" . $searchopt[$ID][\"linkfield\"];\n }", " if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);", " if (!empty($complexjoin)) {\n $addtable .= \"_\" . $complexjoin;\n }\n }", " if (isset($CFG_GLPI[\"union_search_type\"][$itemtype])) {\n $criterion = \"`ITEM_{$itemtype}_{$ID}` $order\";\n }", " // Plugin can override core definition for its type\n if ($criterion === null && $plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addOrderBy',\n $itemtype,\n $ID,\n $order,\n \"{$itemtype}_{$ID}\"\n );\n $out = $out !== null ? trim($out) : null;\n if (!empty($out)) {\n $out = preg_replace('/^ORDER BY /', '', $out);\n $criterion = $out;\n }\n }", " if ($criterion === null) {\n switch ($table . \".\" . $field) {\n // FIXME Dead case? Can't see any itemtype referencing this table in their search options to be able to get here.\n case \"glpi_auth_tables.name\":\n $user_searchopt = self::getOptions('User');\n $criterion = \"`glpi_users`.`authtype` $order,\n `glpi_authldaps\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[30]['joinparams']) . \"`.\n `name` $order,\n `glpi_authmails\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[31]['joinparams']) . \"`.\n `name` $order\";\n break;", " case \"glpi_users.name\":\n if ($itemtype != 'User') {\n if ($_SESSION[\"glpinames_format\"] == User::FIRSTNAME_BEFORE) {\n $name1 = 'firstname';\n $name2 = 'realname';\n } else {\n $name1 = 'realname';\n $name2 = 'firstname';\n }\n $criterion = \"`\" . $table . $addtable . \"`.`$name1` $order,\n `\" . $table . $addtable . \"`.`$name2` $order,\n `\" . $table . $addtable . \"`.`name` $order\";\n } else {\n $criterion = \"`\" . $table . $addtable . \"`.`name` $order\";\n }\n break;\n //FIXME glpi_networkequipments.ip seems like a dead case\n case \"glpi_networkequipments.ip\":\n case \"glpi_ipaddresses.name\":\n $criterion = \"INET6_ATON(`$table$addtable`.`$field`) $order\";\n break;\n }\n }", " //// Default cases", " // Link with plugin tables\n if ($criterion === null && preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addOrderBy',\n $itemtype,\n $ID,\n $order,\n \"{$itemtype}_{$ID}\"\n );\n $out = $out !== null ? trim($out) : null;\n if (!empty($out)) {\n $out = preg_replace('/^ORDER BY /', '', $out);\n $criterion = $out;\n }\n }\n }", " // Preformat items\n if ($criterion === null && isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"date_delay\":\n $interval = \"MONTH\";\n if (isset($searchopt[$ID]['delayunit'])) {\n $interval = $searchopt[$ID]['delayunit'];\n }", " $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"- `$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n $criterion = \"ADDDATE(`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][1] . \"`,\n INTERVAL (`$table$addtable`.`\" .\n $searchopt[$ID][\"datafields\"][2] . \"` $add_minus)\n $interval) $order\";\n }\n }", " $orderby_criteria[] = $criterion ?? \"`ITEM_{$itemtype}_{$ID}` $order\";\n }", " if (count($orderby_criteria) === 0) {\n return '';\n }\n return ' ORDER BY ' . implode(', ', $orderby_criteria) . ' ';\n }", "\n /**\n * Generic Function to add default columns to view\n *\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param array $params array of parameters\n *\n * @return array Array of search option IDs to be shown in the results\n **/\n public static function addDefaultToView($itemtype, $params)\n {\n global $CFG_GLPI;", " $toview = [];\n $item = null;\n $entity_check = true;", " if ($itemtype != AllAssets::getType()) {\n $item = getItemForItemtype($itemtype);\n $entity_check = $item->isEntityAssign();\n }\n // Add first element (name)\n array_push($toview, 1);", " if (isset($params['as_map']) && $params['as_map'] == 1) {\n // Add location name when map mode\n array_push($toview, ($itemtype == 'Location' ? 1 : ($itemtype == 'Ticket' ? 83 : 3)));\n }", " // Add entity view :\n if (\n Session::isMultiEntitiesMode()\n && $entity_check\n && (isset($CFG_GLPI[\"union_search_type\"][$itemtype])\n || ($item && $item->maybeRecursive())\n || isset($_SESSION['glpiactiveentities']) && (count($_SESSION[\"glpiactiveentities\"]) > 1))\n ) {\n array_push($toview, 80);\n }\n return $toview;\n }", "\n /**\n * Generic Function to add default select to a request\n *\n * @param class-string<CommonDBTM> $itemtype device type\n *\n * @return string Select string\n **/\n public static function addDefaultSelect($itemtype)\n {\n global $DB;", " $itemtable = self::getOrigTableName($itemtype);\n $item = null;\n $mayberecursive = false;\n if ($itemtype != AllAssets::getType()) {\n $item = getItemForItemtype($itemtype);\n $mayberecursive = $item->maybeRecursive();\n }\n $ret = \"\";\n switch ($itemtype) {\n case 'FieldUnicity':\n $ret = \"`glpi_fieldunicities`.`itemtype` AS ITEMTYPE,\";\n break;", " default:\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $ret = Plugin::doOneHook(\n $plug['plugin'],\n 'addDefaultSelect',\n $itemtype\n );\n }\n }\n if ($itemtable == 'glpi_entities') {\n $ret .= \"`$itemtable`.`id` AS entities_id, '1' AS is_recursive, \";\n } else if ($mayberecursive) {\n if ($item->isField('entities_id')) {\n $ret .= $DB->quoteName(\"$itemtable.entities_id\") . \", \";\n }\n if ($item->isField('is_recursive')) {\n $ret .= $DB->quoteName(\"$itemtable.is_recursive\") . \", \";\n }\n }\n return $ret;\n }", "\n /**\n * Generic Function to add select to a request\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $itemtype item type\n * @param integer $ID ID of the item to add\n * @param boolean $meta boolean is a meta\n * @param integer $meta_type meta type table ID (default 0)\n *\n * @return string Select string\n **/\n public static function addSelect($itemtype, $ID, $meta = 0, $meta_type = 0)\n {\n global $DB, $CFG_GLPI;", " $searchopt = &self::getOptions($itemtype);\n $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];\n $addtable = \"\";\n $addtable2 = \"\";\n $NAME = \"ITEM_{$itemtype}_{$ID}\";\n $complexjoin = '';", " if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);\n }", " $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);", " $orig_table = self::getOrigTableName($itemtype);\n if (\n ((($is_fkey_composite_on_self || $table != $orig_table)\n && (!isset($CFG_GLPI[\"union_search_type\"][$itemtype])\n || ($CFG_GLPI[\"union_search_type\"][$itemtype] != $table)))\n || !empty($complexjoin))\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable .= \"_\" . $searchopt[$ID][\"linkfield\"];\n }", " if (!empty($complexjoin)) {\n $addtable .= \"_\" . $complexjoin;\n $addtable2 .= \"_\" . $complexjoin;\n }", " $addmeta = \"\";\n if ($meta) {\n // $NAME = \"META\";\n if ($meta_type::getTable() != $table) {\n $addmeta = \"_\" . $meta_type;\n $addtable .= $addmeta;\n $addtable2 .= $addmeta;\n }\n }", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addSelect',\n $itemtype,\n $ID,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }", " $tocompute = \"`$table$addtable`.`$field`\";\n $tocomputeid = \"`$table$addtable`.`id`\";", " $tocomputetrans = \"IFNULL(`$table\" . $addtable . \"_trans_\" . $field . \"`.`value`,'\" . self::NULLVALUE . \"') \";", " $ADDITONALFIELDS = '';\n if (\n isset($searchopt[$ID][\"additionalfields\"])\n && count($searchopt[$ID][\"additionalfields\"])\n ) {\n foreach ($searchopt[$ID][\"additionalfields\"] as $key) {\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])\n ) {\n $ADDITONALFIELDS .= \" IFNULL(GROUP_CONCAT(DISTINCT CONCAT(IFNULL(`$table$addtable`.`$key`,\n '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"', $tocomputeid)ORDER BY $tocomputeid SEPARATOR '\" . self::LONGSEP . \"'), '\" . self::NULLVALUE . self::SHORTSEP . \"')\n AS `\" . $NAME . \"_$key`, \";\n } else {\n $ADDITONALFIELDS .= \"`$table$addtable`.`$key` AS `\" . $NAME . \"_$key`, \";\n }\n }\n }", " // Virtual display no select : only get additional fields\n if (strpos($field, '_virtual') === 0) {\n return $ADDITONALFIELDS;\n }", " switch ($table . \".\" . $field) {\n case \"glpi_users.name\":\n if ($itemtype != 'User') {\n if ((isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])) {\n $addaltemail = \"\";\n if (\n (($itemtype == 'Ticket') || ($itemtype == 'Problem'))\n && isset($searchopt[$ID]['joinparams']['beforejoin']['table'])\n && (($searchopt[$ID]['joinparams']['beforejoin']['table']\n == 'glpi_tickets_users')\n || ($searchopt[$ID]['joinparams']['beforejoin']['table']\n == 'glpi_problems_users')\n || ($searchopt[$ID]['joinparams']['beforejoin']['table']\n == 'glpi_changes_users'))\n ) { // For tickets_users\n $ticket_user_table\n = $searchopt[$ID]['joinparams']['beforejoin']['table'] .\n \"_\" . self::computeComplexJoinID($searchopt[$ID]['joinparams']['beforejoin']\n ['joinparams']) . $addmeta;\n $addaltemail\n = \"GROUP_CONCAT(DISTINCT CONCAT(`$ticket_user_table`.`users_id`, ' ',\n `$ticket_user_table`.`alternative_email`)\n SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"_2`, \";\n }\n return \" GROUP_CONCAT(DISTINCT `$table$addtable`.`id` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $addaltemail\n $ADDITONALFIELDS\";\n }\n return \" `$table$addtable`.`$field` AS `\" . $NAME . \"`,\n `$table$addtable`.`realname` AS `\" . $NAME . \"_realname`,\n `$table$addtable`.`id` AS `\" . $NAME . \"_id`,\n `$table$addtable`.`firstname` AS `\" . $NAME . \"_firstname`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_softwarelicenses.number\":\n if ($meta) {\n return \" FLOOR(SUM(`$table$addtable2`.`$field`)\n * COUNT(DISTINCT `$table$addtable2`.`id`)\n / COUNT(`$table$addtable2`.`id`)) AS `\" . $NAME . \"`,\n MIN(`$table$addtable2`.`$field`) AS `\" . $NAME . \"_min`,\n $ADDITONALFIELDS\";\n } else {\n return \" FLOOR(SUM(`$table$addtable`.`$field`)\n * COUNT(DISTINCT `$table$addtable`.`id`)\n / COUNT(`$table$addtable`.`id`)) AS `\" . $NAME . \"`,\n MIN(`$table$addtable`.`$field`) AS `\" . $NAME . \"_min`,\n $ADDITONALFIELDS\";\n }", " case \"glpi_profiles.name\":\n if (\n ($itemtype == 'User')\n && ($ID == 20)\n ) {\n $addtable2 = '';\n if ($meta) {\n $addtable2 = \"_\" . $meta_type;\n }\n return \" GROUP_CONCAT(`$table$addtable`.`$field` SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`entities_id` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_entities_id`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_recursive` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_recursive`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_dynamic` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_dynamic`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_entities.completename\":\n if (\n ($itemtype == 'User')\n && ($ID == 80)\n ) {\n $addtable2 = '';\n if ($meta) {\n $addtable2 = \"_\" . $meta_type;\n }\n return \" GROUP_CONCAT(`$table$addtable`.`completename` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`profiles_id` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_profiles_id`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_recursive` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_recursive`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_dynamic` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_dynamic`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_auth_tables.name\":\n $user_searchopt = self::getOptions('User');\n return \" `glpi_users`.`authtype` AS `\" . $NAME . \"`,\n `glpi_users`.`auths_id` AS `\" . $NAME . \"_auths_id`,\n `glpi_authldaps\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[30]['joinparams']) . $addmeta . \"`.`$field`\n AS `\" . $NAME . \"_\" . $ID . \"_ldapname`,\n `glpi_authmails\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[31]['joinparams']) . $addmeta . \"`.`$field`\n AS `\" . $NAME . \"_mailname`,\n $ADDITONALFIELDS\";", " case \"glpi_softwareversions.name\":\n if ($meta && ($meta_type == 'Software')) {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwares`.`name`, ' - ',\n `$table$addtable2`.`$field`, '\" . self::SHORTSEP . \"',\n `$table$addtable2`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_softwareversions.comment\":\n if ($meta && ($meta_type == 'Software')) {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwares`.`name`, ' - ',\n `$table$addtable2`.`$field`,'\" . self::SHORTSEP . \"',\n `$table$addtable2`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n return \" GROUP_CONCAT(DISTINCT CONCAT(`$table$addtable`.`name`, ' - ',\n `$table$addtable`.`$field`, '\" . self::SHORTSEP . \"',\n `$table$addtable`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";", " case \"glpi_states.name\":\n if ($meta && ($meta_type == 'Software')) {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwares`.`name`, ' - ',\n `glpi_softwareversions$addtable`.`name`, ' - ',\n `$table$addtable2`.`$field`, '\" . self::SHORTSEP . \"',\n `$table$addtable2`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n } else if ($itemtype == 'Software') {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwareversions`.`name`, ' - ',\n `$table$addtable`.`$field`,'\" . self::SHORTSEP . \"',\n `$table$addtable`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_itilfollowups.content\":\n case \"glpi_tickettasks.content\":\n case \"glpi_changetasks.content\":\n if (is_subclass_of($itemtype, \"CommonITILObject\")) {\n // force ordering by date desc\n return \" GROUP_CONCAT(\n DISTINCT CONCAT(\n IFNULL($tocompute, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',\n $tocomputeid\n )\n ORDER BY `$table$addtable`.`date` DESC\n SEPARATOR '\" . self::LONGSEP . \"'\n ) AS `\" . $NAME . \"`, $ADDITONALFIELDS\";\n }\n break;", " default:\n break;\n }", " //// Default cases\n // Link with plugin tables\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addSelect',\n $itemtype,\n $ID,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }", " if (isset($searchopt[$ID][\"computation\"])) {\n $tocompute = $searchopt[$ID][\"computation\"];\n $tocompute = str_replace($DB->quoteName('TABLE'), 'TABLE', $tocompute);\n $tocompute = str_replace(\"TABLE\", $DB->quoteName(\"$table$addtable\"), $tocompute);\n }\n // Preformat items\n if (isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"count\":\n return \" COUNT(DISTINCT `$table$addtable`.`$field`) AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";", " case \"date_delay\":\n $interval = \"MONTH\";\n if (isset($searchopt[$ID]['delayunit'])) {\n $interval = $searchopt[$ID]['delayunit'];\n }", " $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"-`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])\n ) {\n return \" GROUP_CONCAT(DISTINCT ADDDATE(`$table$addtable`.`\" .\n $searchopt[$ID][\"datafields\"][1] . \"`,\n INTERVAL (`$table$addtable`.`\" .\n $searchopt[$ID][\"datafields\"][2] .\n \"` $add_minus) $interval)\n SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n return \"ADDDATE(`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][1] . \"`,\n INTERVAL (`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][2] .\n \"` $add_minus) $interval) AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";", " case \"itemlink\":\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])\n ) {\n $TRANS = '';\n if (Session::haveTranslations(getItemTypeForTable($table), $field)) {\n $TRANS = \"GROUP_CONCAT(DISTINCT CONCAT(IFNULL($tocomputetrans, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',$tocomputeid) ORDER BY $tocomputeid\n SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_trans_\" . $field . \"`, \";\n }", " return \" GROUP_CONCAT(DISTINCT CONCAT($tocompute, '\" . self::SHORTSEP . \"' ,\n `$table$addtable`.`id`) ORDER BY `$table$addtable`.`id`\n SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"`,\n $TRANS\n $ADDITONALFIELDS\";\n }\n return \" $tocompute AS `\" . $NAME . \"`,\n `$table$addtable`.`id` AS `\" . $NAME . \"_id`,\n $ADDITONALFIELDS\";\n }\n }", " // Default case\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"]\n && (!isset($searchopt[$ID][\"computation\"])\n || isset($searchopt[$ID][\"computationgroupby\"])\n && $searchopt[$ID][\"computationgroupby\"]))\n ) { // Not specific computation\n $TRANS = '';\n if (Session::haveTranslations(getItemTypeForTable($table), $field)) {\n $TRANS = \"GROUP_CONCAT(DISTINCT CONCAT(IFNULL($tocomputetrans, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',$tocomputeid) ORDER BY $tocomputeid SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_trans_\" . $field . \"`, \";\n }\n return \" GROUP_CONCAT(DISTINCT CONCAT(IFNULL($tocompute, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',$tocomputeid) ORDER BY $tocomputeid SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $TRANS\n $ADDITONALFIELDS\";\n }\n $TRANS = '';\n if (Session::haveTranslations(getItemTypeForTable($table), $field)) {\n $TRANS = $tocomputetrans . \" AS `\" . $NAME . \"_trans_\" . $field . \"`, \";\n }\n return \"$tocompute AS `\" . $NAME . \"`, $TRANS $ADDITONALFIELDS\";\n }", "\n /**\n * Generic Function to add default where to a request\n *\n * @param class-string<CommonDBTM> $itemtype device type\n *\n * @return string Where string\n **/\n public static function addDefaultWhere($itemtype)\n {\n $condition = '';", " switch ($itemtype) {\n case 'Reservation':\n $condition = getEntitiesRestrictRequest(\"\", ReservationItem::getTable(), '', '', true);\n break;", " case 'Reminder':\n $condition = Reminder::addVisibilityRestrict();\n break;", " case 'RSSFeed':\n $condition = RSSFeed::addVisibilityRestrict();\n break;", " case 'Notification':\n if (!Config::canView()) {\n $condition = \" `glpi_notifications`.`itemtype` NOT IN ('CronTask', 'DBConnection') \";\n }\n break;", " // No link\n case 'User':\n // View all entities\n if (!Session::canViewAllEntities()) {\n $condition = getEntitiesRestrictRequest(\"\", \"glpi_profiles_users\", '', '', true);\n }\n break;", " case 'ProjectTask':\n $condition = '';\n $teamtable = 'glpi_projecttaskteams';\n $condition .= \"`glpi_projects`.`is_template` = 0\";\n $condition .= \" AND ((`$teamtable`.`itemtype` = 'User'\n AND `$teamtable`.`items_id` = '\" . Session::getLoginUserID() . \"')\";\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR (`$teamtable`.`itemtype` = 'Group'\n AND `$teamtable`.`items_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \"))\";\n }\n $condition .= \") \";\n break;", " case 'Project':\n $condition = '';\n if (!Session::haveRight(\"project\", Project::READALL)) {\n $teamtable = 'glpi_projectteams';\n $condition .= \"(`glpi_projects`.users_id = '\" . Session::getLoginUserID() . \"'\n OR (`$teamtable`.`itemtype` = 'User'\n AND `$teamtable`.`items_id` = '\" . Session::getLoginUserID() . \"')\";\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR (`glpi_projects`.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \"))\";\n $condition .= \" OR (`$teamtable`.`itemtype` = 'Group'\n AND `$teamtable`.`items_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \"))\";\n }\n $condition .= \") \";\n }\n break;", " case 'Ticket':\n // Same structure in addDefaultJoin\n $condition = '';\n if (!Session::haveRight(\"ticket\", Ticket::READALL)) {\n $searchopt\n = &self::getOptions($itemtype);\n $requester_table\n = '`glpi_tickets_users_' .\n self::computeComplexJoinID($searchopt[4]['joinparams']['beforejoin']\n ['joinparams']) . '`';\n $requestergroup_table\n = '`glpi_groups_tickets_' .\n self::computeComplexJoinID($searchopt[71]['joinparams']['beforejoin']\n ['joinparams']) . '`';", " $assign_table\n = '`glpi_tickets_users_' .\n self::computeComplexJoinID($searchopt[5]['joinparams']['beforejoin']\n ['joinparams']) . '`';\n $assigngroup_table\n = '`glpi_groups_tickets_' .\n self::computeComplexJoinID($searchopt[8]['joinparams']['beforejoin']\n ['joinparams']) . '`';", " $observer_table\n = '`glpi_tickets_users_' .\n self::computeComplexJoinID($searchopt[66]['joinparams']['beforejoin']\n ['joinparams']) . '`';\n $observergroup_table\n = '`glpi_groups_tickets_' .\n self::computeComplexJoinID($searchopt[65]['joinparams']['beforejoin']\n ['joinparams']) . '`';", " $condition = \"(\";", " if (Session::haveRight(\"ticket\", Ticket::READMY)) {\n $condition .= \" $requester_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR $observer_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR `glpi_tickets`.`users_id_recipient` = '\" . Session::getLoginUserID() . \"'\";\n } else {\n $condition .= \"0=1\";\n }", " if (Session::haveRight(\"ticket\", Ticket::READGROUP)) {\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR $requestergroup_table.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \")\";\n $condition .= \" OR $observergroup_table.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \")\";\n }\n }", " if (Session::haveRight(\"ticket\", Ticket::OWN)) {// Can own ticket : show assign to me\n $condition .= \" OR $assign_table.users_id = '\" . Session::getLoginUserID() . \"' \";\n }", " if (Session::haveRight(\"ticket\", Ticket::READASSIGN)) { // assign to me\n $condition .= \" OR $assign_table.`users_id` = '\" . Session::getLoginUserID() . \"'\";\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR $assigngroup_table.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \")\";\n }\n if (Session::haveRight('ticket', Ticket::ASSIGN)) {\n $condition .= \" OR `glpi_tickets`.`status`='\" . CommonITILObject::INCOMING . \"'\";\n }\n }", " if (\n Session::haveRightsOr(\n 'ticketvalidation',\n [TicketValidation::VALIDATEINCIDENT,\n TicketValidation::VALIDATEREQUEST\n ]\n )\n ) {\n $condition .= \" OR `glpi_ticketvalidations`.`users_id_validate`\n = '\" . Session::getLoginUserID() . \"'\";\n }\n $condition .= \") \";\n }\n break;", " case 'Change':\n case 'Problem':\n if ($itemtype == 'Change') {\n $right = 'change';\n $table = 'changes';\n $groupetable = \"`glpi_changes_groups_\";\n } else if ($itemtype == 'Problem') {\n $right = 'problem';\n $table = 'problems';\n $groupetable = \"`glpi_groups_problems_\";\n }\n // Same structure in addDefaultJoin\n $condition = '';\n if (!Session::haveRight(\"$right\", $itemtype::READALL)) {\n $searchopt = &self::getOptions($itemtype);\n if (Session::haveRight(\"$right\", $itemtype::READMY)) {\n $requester_table = '`glpi_' . $table . '_users_' .\n self::computeComplexJoinID($searchopt[4]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n $requestergroup_table = $groupetable .\n self::computeComplexJoinID($searchopt[71]['joinparams']\n ['beforejoin']['joinparams']) . '`';", " $observer_table = '`glpi_' . $table . '_users_' .\n self::computeComplexJoinID($searchopt[66]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n $observergroup_table = $groupetable .\n self::computeComplexJoinID($searchopt[65]['joinparams']\n ['beforejoin']['joinparams']) . '`';", " $assign_table = '`glpi_' . $table . '_users_' .\n self::computeComplexJoinID($searchopt[5]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n $assigngroup_table = $groupetable .\n self::computeComplexJoinID($searchopt[8]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n }\n $condition = \"(\";", " if (Session::haveRight(\"$right\", $itemtype::READMY)) {\n $condition .= \" $requester_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR $observer_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR $assign_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR `glpi_\" . $table . \"`.`users_id_recipient` = '\" . Session::getLoginUserID() . \"'\";\n if (count($_SESSION['glpigroups'])) {\n $my_groups_keys = \"'\" . implode(\"','\", $_SESSION['glpigroups']) . \"'\";\n $condition .= \" OR $requestergroup_table.groups_id IN ($my_groups_keys)\n OR $observergroup_table.groups_id IN ($my_groups_keys)\n OR $assigngroup_table.groups_id IN ($my_groups_keys)\";\n }\n } else {\n $condition .= \"0=1\";\n }", " $condition .= \") \";\n }\n break;", " case 'Config':\n $availableContexts = ['core'] + Plugin::getPlugins();\n $availableContexts = implode(\"', '\", $availableContexts);\n $condition = \"`context` IN ('$availableContexts')\";\n break;", " case 'SavedSearch':\n $condition = SavedSearch::addVisibilityRestrict();\n break;", " case 'TicketTask':\n // Filter on is_private\n $allowed_is_private = [];\n if (Session::haveRight(TicketTask::$rightname, CommonITILTask::SEEPRIVATE)) {\n $allowed_is_private[] = 1;\n }\n if (Session::haveRight(TicketTask::$rightname, CommonITILTask::SEEPUBLIC)) {\n $allowed_is_private[] = 0;\n }", " // If the user can't see public and private\n if (!count($allowed_is_private)) {\n $condition = \"0 = 1\";\n break;\n }", " $in = \"IN ('\" . implode(\"','\", $allowed_is_private) . \"')\";\n $condition = \"(`glpi_tickettasks`.`is_private` $in \";", " // Check for assigned or created tasks\n $condition .= \"OR `glpi_tickettasks`.`users_id` = \" . Session::getLoginUserID() . \" \";\n $condition .= \"OR `glpi_tickettasks`.`users_id_tech` = \" . Session::getLoginUserID() . \" \";", " // Check for parent item visibility unless the user can see all the\n // possible parents\n if (!Session::haveRight('ticket', Ticket::READALL)) {\n $condition .= \"AND \" . TicketTask::buildParentCondition();\n }", " $condition .= \")\";", " break;", " case 'ITILFollowup':\n // Filter on is_private\n $allowed_is_private = [];\n if (Session::haveRight(ITILFollowup::$rightname, ITILFollowup::SEEPRIVATE)) {\n $allowed_is_private[] = 1;\n }\n if (Session::haveRight(ITILFollowup::$rightname, ITILFollowup::SEEPUBLIC)) {\n $allowed_is_private[] = 0;\n }", " // If the user can't see public and private\n if (!count($allowed_is_private)) {\n $condition = \"0 = 1\";\n break;\n }", " $in = \"IN ('\" . implode(\"','\", $allowed_is_private) . \"')\";\n $condition = \"(`glpi_itilfollowups`.`is_private` $in \";", " // Now filter on parent item visiblity\n $condition .= \"AND (\";", " // Filter for \"ticket\" parents\n $condition .= ITILFollowup::buildParentCondition(\\Ticket::getType());\n $condition .= \"OR \";", " // Filter for \"change\" parents\n $condition .= ITILFollowup::buildParentCondition(\n \\Change::getType(),\n 'changes_id',\n \"glpi_changes_users\",\n \"glpi_changes_groups\"\n );\n $condition .= \"OR \";", " // Fitler for \"problem\" parents\n $condition .= ITILFollowup::buildParentCondition(\n \\Problem::getType(),\n 'problems_id',\n \"glpi_problems_users\",\n \"glpi_groups_problems\"\n );\n $condition .= \"))\";", " break;", " default:\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $condition = Plugin::doOneHook($plug['plugin'], 'addDefaultWhere', $itemtype);\n }\n break;\n }", " /* Hook to restrict user right on current itemtype */\n list($itemtype, $condition) = Plugin::doHookFunction('add_default_where', [$itemtype, $condition]);\n return $condition;\n }", " /**\n * Generic Function to add where to a request\n *\n * @param string $link Link string\n * @param boolean $nott Is it a negative search ?\n * @param string $itemtype Item type\n * @param integer $ID ID of the item to search\n * @param string $searchtype Searchtype used (equals or contains)\n * @param string $val Item num in the request\n * @param integer $meta Is a meta search (meta=2 in search.class.php) (default 0)\n *\n * @return string Where string\n **/\n public static function addWhere($link, $nott, $itemtype, $ID, $searchtype, $val, $meta = 0)\n {", " global $DB;", " $searchopt = &self::getOptions($itemtype);\n if (!isset($searchopt[$ID]['table'])) {\n return false;\n }\n $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];", " $inittable = $table;\n $addtable = '';\n $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);\n $orig_table = self::getOrigTableName($itemtype);\n if (\n ($table != 'asset_types')\n && ($is_fkey_composite_on_self || $table != $orig_table)\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable = \"_\" . $searchopt[$ID][\"linkfield\"];\n $table .= $addtable;\n }", " if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);", " if (!empty($complexjoin)) {\n $table .= \"_\" . $complexjoin;\n }\n }", " $addmeta = \"\";\n if (\n $meta\n && ($itemtype::getTable() != $inittable)\n ) {\n $addmeta = \"_\" . $itemtype;\n $table .= $addmeta;\n }", " // Hack to allow search by ID on every sub-table\n if (preg_match('/^\\$\\$\\$\\$([0-9]+)$/', $val, $regs)) {\n return $link . \" (`$table`.`id` \" . ($nott ? \"<>\" : \"=\") . $regs[1] . \" \" .\n (($regs[1] == 0) ? \" OR `$table`.`id` IS NULL\" : '') . \") \";\n }", " // Preparse value\n if (isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"datetime\":\n case \"date\":\n case \"date_delay\":\n $force_day = true;\n if (\n $searchopt[$ID][\"datatype\"] == 'datetime'\n && !(strstr($val, 'BEGIN') || strstr($val, 'LAST') || strstr($val, 'DAY'))\n ) {\n $force_day = false;\n }", " $val = Html::computeGenericDateTimeSearch($val, $force_day);", " break;\n }\n }\n switch ($searchtype) {\n case \"notcontains\":\n $nott = !$nott;\n //negated, use contains case\n case \"contains\":\n if (isset($searchopt[$ID][\"datatype\"]) && ($searchopt[$ID][\"datatype\"] === 'decimal')) {\n $matches = [];\n if (preg_match('/^(\\d+.?\\d?)/', $val, $matches)) {\n $val = $matches[1];\n if (!str_contains($val, '.')) {\n $val .= '.';\n }\n }\n }\n $SEARCH = self::makeTextSearch($val, $nott);\n break;", " case \"equals\":\n if ($nott) {\n $SEARCH = \" <> \" . DBmysql::quoteValue($val);\n } else {\n $SEARCH = \" = \" . DBmysql::quoteValue($val);\n }\n break;", " case \"notequals\":\n if ($nott) {\n $SEARCH = \" = \" . DBmysql::quoteValue($val);\n } else {\n $SEARCH = \" <> \" . DBmysql::quoteValue($val);\n }\n break;", " case \"under\":\n if ($nott) {\n $SEARCH = \" NOT IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n } else {\n $SEARCH = \" IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n }\n break;", " case \"notunder\":\n if ($nott) {\n $SEARCH = \" IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n } else {\n $SEARCH = \" NOT IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n }\n break;\n }", " //Check in current item if a specific where is defined\n if (method_exists($itemtype, 'addWhere')) {\n $out = $itemtype::addWhere($link, $nott, $itemtype, $ID, $searchtype, $val);\n if (!empty($out)) {\n return $out;\n }\n }", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addWhere',\n $link,\n $nott,\n $itemtype,\n $ID,\n $val,\n $searchtype\n );\n if (!empty($out)) {\n return $out;\n }\n }", " switch ($inittable . \".\" . $field) {\n // case \"glpi_users_validation.name\" :", " case \"glpi_users.name\":\n if ($val == 'myself') {\n switch ($searchtype) {\n case 'equals':\n return \" $link (`$table`.`id` = \" . $DB->quoteValue($_SESSION['glpiID']) . \") \";", " case 'notequals':\n return \" $link (`$table`.`id` <> \" . $DB->quoteValue($_SESSION['glpiID']) . \") \";\n }\n }", " if ($itemtype == 'User') { // glpi_users case / not link table\n if (in_array($searchtype, ['equals', 'notequals'])) {\n $search_str = \"`$table`.`id`\" . $SEARCH;", " if ($searchtype == 'notequals') {\n $nott = !$nott;\n }", " // Add NULL if $val = 0 and not negative search\n // Or negative search on real value\n if ((!$nott && ($val == 0)) || ($nott && ($val != 0))) {\n $search_str .= \" OR `$table`.`id` IS NULL\";\n }", " return \" $link ($search_str)\";\n }\n return self::makeTextCriteria(\"`$table`.`$field`\", $val, $nott, $link);\n }\n if ($_SESSION[\"glpinames_format\"] == User::FIRSTNAME_BEFORE) {\n $name1 = 'firstname';\n $name2 = 'realname';\n } else {\n $name1 = 'realname';\n $name2 = 'firstname';\n }", " if (in_array($searchtype, ['equals', 'notequals'])) {\n return \" $link (`$table`.`id`\" . $SEARCH .\n (($val == 0) ? \" OR `$table`.`id` IS\" .\n (($searchtype == \"notequals\") ? \" NOT\" : \"\") . \" NULL\" : '') . ') ';\n }\n $toadd = '';", " $tmplink = 'OR';\n if ($nott) {\n $tmplink = 'AND';\n }", " if (is_a($itemtype, CommonITILObject::class, true)) {\n if (\n isset($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"])\n && isset($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"joinparams\"])\n && (($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"]\n == 'glpi_tickets_users')\n || ($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"]\n == 'glpi_problems_users')\n || ($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"]\n == 'glpi_changes_users'))\n ) {\n $bj = $searchopt[$ID][\"joinparams\"][\"beforejoin\"];\n $linktable = $bj['table'] . '_' . self::computeComplexJoinID($bj['joinparams']) . $addmeta;\n //$toadd = \"`$linktable`.`alternative_email` $SEARCH $tmplink \";\n $toadd = self::makeTextCriteria(\n \"`$linktable`.`alternative_email`\",\n $val,\n $nott,\n $tmplink\n );\n if ($val == '^$') {\n return $link . \" ((`$linktable`.`users_id` IS NULL)\n OR `$linktable`.`alternative_email` IS NULL)\";\n }\n }\n }\n $toadd2 = '';\n if (\n $nott\n && ($val != 'NULL') && ($val != 'null')\n ) {\n $toadd2 = \" OR `$table`.`$field` IS NULL\";\n }\n return $link . \" (((`$table`.`$name1` $SEARCH\n $tmplink `$table`.`$name2` $SEARCH\n $tmplink `$table`.`$field` $SEARCH\n $tmplink CONCAT(`$table`.`$name1`, ' ', `$table`.`$name2`) $SEARCH )\n $toadd2) $toadd)\";", " case \"glpi_groups.completename\":\n if ($val == 'mygroups') {\n switch ($searchtype) {\n case 'equals':\n return \" $link (`$table`.`id` IN ('\" . implode(\n \"','\",\n $_SESSION['glpigroups']\n ) . \"')) \";", " case 'notequals':\n return \" $link (`$table`.`id` NOT IN ('\" . implode(\n \"','\",\n $_SESSION['glpigroups']\n ) . \"')) \";", " case 'under':\n $groups = $_SESSION['glpigroups'];\n foreach ($_SESSION['glpigroups'] as $g) {\n $groups += getSonsOf($inittable, $g);\n }\n $groups = array_unique($groups);\n return \" $link (`$table`.`id` IN ('\" . implode(\"','\", $groups) . \"')) \";", " case 'notunder':\n $groups = $_SESSION['glpigroups'];\n foreach ($_SESSION['glpigroups'] as $g) {\n $groups += getSonsOf($inittable, $g);\n }\n $groups = array_unique($groups);\n return \" $link (`$table`.`id` NOT IN ('\" . implode(\"','\", $groups) . \"')) \";\n }\n }\n break;", " case \"glpi_auth_tables.name\":\n $user_searchopt = self::getOptions('User');\n $tmplink = 'OR';\n if ($nott) {\n $tmplink = 'AND';\n }\n return $link . \" (`glpi_authmails\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[31]['joinparams']) . $addmeta . \"`.`name`\n $SEARCH\n $tmplink `glpi_authldaps\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[30]['joinparams']) . $addmeta . \"`.`name`\n $SEARCH ) \";", " case \"glpi_ipaddresses.name\":\n $search = [\"/\\&lt;/\",\"/\\&gt;/\"];\n $replace = [\"<\",\">\"];\n $val = preg_replace($search, $replace, $val);\n if (preg_match(\"/^\\s*([<>])([=]*)[[:space:]]*([0-9\\.]+)/\", $val, $regs)) {\n if ($nott) {\n if ($regs[1] == '<') {\n $regs[1] = '>';\n } else {\n $regs[1] = '<';\n }\n }\n $regs[1] .= $regs[2];\n return $link . \" (INET_ATON(`$table`.`$field`) \" . $regs[1] . \" INET_ATON('\" . $regs[3] . \"')) \";\n }\n break;", " case \"glpi_tickets.status\":\n case \"glpi_problems.status\":\n case \"glpi_changes.status\":\n $tocheck = [];\n if ($item = getItemForItemtype($itemtype)) {\n switch ($val) {\n case 'process':\n $tocheck = $item->getProcessStatusArray();\n break;", " case 'notclosed':\n $tocheck = $item->getAllStatusArray();\n foreach ($item->getClosedStatusArray() as $status) {\n if (isset($tocheck[$status])) {\n unset($tocheck[$status]);\n }\n }\n $tocheck = array_keys($tocheck);\n break;", " case 'old':\n $tocheck = array_merge(\n $item->getSolvedStatusArray(),\n $item->getClosedStatusArray()\n );\n break;", " case 'notold':\n $tocheck = $item::getNotSolvedStatusArray();\n break;", " case 'all':\n $tocheck = array_keys($item->getAllStatusArray());\n break;\n }\n }", " if (count($tocheck) == 0) {\n $statuses = $item->getAllStatusArray();\n if (isset($statuses[$val])) {\n $tocheck = [$val];\n }\n }", " if (count($tocheck)) {\n if ($nott) {\n return $link . \" `$table`.`$field` NOT IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n return $link . \" `$table`.`$field` IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n break;", " case \"glpi_tickets_tickets.tickets_id_1\":\n $tmplink = 'OR';\n $compare = '=';\n if ($nott) {\n $tmplink = 'AND';\n $compare = '<>';\n }\n $toadd2 = '';\n if (\n $nott\n && ($val != 'NULL') && ($val != 'null')\n ) {\n $toadd2 = \" OR `$table`.`$field` IS NULL\";\n }", " return $link . \" (((`$table`.`tickets_id_1` $compare '$val'\n $tmplink `$table`.`tickets_id_2` $compare '$val')\n AND `glpi_tickets`.`id` <> '$val')\n $toadd2)\";", " case \"glpi_tickets.priority\":\n case \"glpi_tickets.impact\":\n case \"glpi_tickets.urgency\":\n case \"glpi_problems.priority\":\n case \"glpi_problems.impact\":\n case \"glpi_problems.urgency\":\n case \"glpi_changes.priority\":\n case \"glpi_changes.impact\":\n case \"glpi_changes.urgency\":\n case \"glpi_projects.priority\":\n if (is_numeric($val)) {\n if ($val > 0) {\n $compare = ($nott ? '<>' : '=');\n return $link . \" `$table`.`$field` $compare '$val'\";\n }\n if ($val < 0) {\n $compare = ($nott ? '<' : '>=');\n return $link . \" `$table`.`$field` $compare '\" . abs($val) . \"'\";\n }\n // Show all\n $compare = ($nott ? '<' : '>=');\n return $link . \" `$table`.`$field` $compare '0' \";\n }\n return \"\";", " case \"glpi_tickets.global_validation\":\n case \"glpi_ticketvalidations.status\":\n case \"glpi_changes.global_validation\":\n case \"glpi_changevalidations.status\":\n if ($val == 'all') {\n return \"\";\n }\n $tocheck = [];\n switch ($val) {\n case 'can':\n $tocheck = CommonITILValidation::getCanValidationStatusArray();\n break;", " case 'all':\n $tocheck = CommonITILValidation::getAllValidationStatusArray();\n break;\n }\n if (count($tocheck) == 0) {\n $tocheck = [$val];\n }\n if (count($tocheck)) {\n if ($nott) {\n return $link . \" `$table`.`$field` NOT IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n return $link . \" `$table`.`$field` IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n break;", " case \"glpi_notifications.event\":\n if (in_array($searchtype, ['equals', 'notequals']) && strpos($val, self::SHORTSEP)) {\n $not = 'notequals' === $searchtype ? 'NOT' : '';\n list($itemtype_val, $event_val) = explode(self::SHORTSEP, $val);\n return \" $link $not(`$table`.`event` = '$event_val'\n AND `$table`.`itemtype` = '$itemtype_val')\";\n }\n break;\n }", " //// Default cases", " // Link with plugin tables\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $inittable, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addWhere',\n $link,\n $nott,\n $itemtype,\n $ID,\n $val,\n $searchtype\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }", " $tocompute = \"`$table`.`$field`\";\n $tocomputetrans = \"`\" . $table . \"_trans_\" . $field . \"`.`value`\";\n if (isset($searchopt[$ID][\"computation\"])) {\n $tocompute = $searchopt[$ID][\"computation\"];\n $tocompute = str_replace($DB->quoteName('TABLE'), 'TABLE', $tocompute);\n $tocompute = str_replace(\"TABLE\", $DB->quoteName(\"$table\"), $tocompute);\n }", " // Preformat items\n if (isset($searchopt[$ID][\"datatype\"])) {\n if ($searchopt[$ID][\"datatype\"] == \"mio\") {\n // Parse value as it may contain a few different formats\n $val = Toolbox::getMioSizeFromString($val);\n }", " switch ($searchopt[$ID][\"datatype\"]) {\n case \"itemtypename\":\n if (in_array($searchtype, ['equals', 'notequals'])) {\n return \" $link (`$table`.`$field`\" . $SEARCH . ') ';\n }\n break;", " case \"itemlink\":\n if (in_array($searchtype, ['equals', 'notequals', 'under', 'notunder'])) {\n return \" $link (`$table`.`id`\" . $SEARCH . ') ';\n }\n break;", " case \"datetime\":\n case \"date\":\n case \"date_delay\":\n if ($searchopt[$ID][\"datatype\"] == 'datetime') {\n // Specific search for datetime\n if (in_array($searchtype, ['equals', 'notequals'])) {\n $val = preg_replace(\"/:00$/\", '', $val);\n $val = '^' . $val;\n if ($searchtype == 'notequals') {\n $nott = !$nott;\n }\n return self::makeTextCriteria(\"`$table`.`$field`\", $val, $nott, $link);\n }\n }\n if ($searchtype == 'lessthan') {\n $val = '<' . $val;\n }\n if ($searchtype == 'morethan') {\n $val = '>' . $val;\n }\n if ($searchtype) {\n $date_computation = $tocompute;\n }\n if (in_array($searchtype, [\"contains\", \"notcontains\"])) {\n $default_charset = DBConnection::getDefaultCharset();\n $date_computation = \"CONVERT($date_computation USING {$default_charset})\";\n }\n $search_unit = ' MONTH ';\n if (isset($searchopt[$ID]['searchunit'])) {\n $search_unit = $searchopt[$ID]['searchunit'];\n }\n if ($searchopt[$ID][\"datatype\"] == \"date_delay\") {\n $delay_unit = ' MONTH ';\n if (isset($searchopt[$ID]['delayunit'])) {\n $delay_unit = $searchopt[$ID]['delayunit'];\n }\n $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"-`$table`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n $date_computation = \"ADDDATE(`$table`.\" . $searchopt[$ID][\"datafields\"][1] . \",\n INTERVAL (`$table`.\" . $searchopt[$ID][\"datafields\"][2] . \"\n $add_minus)\n $delay_unit)\";\n }\n if (in_array($searchtype, ['equals', 'notequals'])) {\n return \" $link ($date_computation \" . $SEARCH . ') ';\n }\n $search = [\"/\\&lt;/\",\"/\\&gt;/\"];\n $replace = [\"<\",\">\"];\n $val = preg_replace($search, $replace, $val);\n if (preg_match(\"/^\\s*([<>=]+)(.*)/\", $val, $regs)) {\n if (is_numeric($regs[2])) {\n return $link . \" $date_computation \" . $regs[1] . \"\n ADDDATE(NOW(), INTERVAL \" . $regs[2] . \" $search_unit) \";\n }\n // ELSE Reformat date if needed\n $regs[2] = preg_replace(\n '@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@',\n '\\5-\\3-\\1',\n $regs[2]\n );\n if (preg_match('/[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/', $regs[2])) {\n $ret = $link;\n if ($nott) {\n $ret .= \" NOT(\";\n }\n $ret .= \" $date_computation {$regs[1]} '{$regs[2]}'\";\n if ($nott) {\n $ret .= \")\";\n }\n return $ret;\n }\n return \"\";\n }\n // ELSE standard search\n // Date format modification if needed\n $val = preg_replace('@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@', '\\5-\\3-\\1', $val);\n if ($date_computation) {\n return self::makeTextCriteria($date_computation, $val, $nott, $link);\n }\n return '';", " case \"right\":\n if ($searchtype == 'notequals') {\n $nott = !$nott;\n }\n return $link . ($nott ? ' NOT' : '') . \" ($tocompute & '$val') \";", " case \"bool\":\n if (!is_numeric($val)) {\n if (strcasecmp($val, __('No')) == 0) {\n $val = 0;\n } else if (strcasecmp($val, __('Yes')) == 0) {\n $val = 1;\n }\n }\n // No break here : use number comparaison case", " case \"count\":\n case \"mio\":\n case \"number\":\n case \"decimal\":\n case \"timestamp\":\n case \"progressbar\":\n $decimal_contains = $searchopt[$ID][\"datatype\"] === 'decimal' && $searchtype === 'contains';\n $search = [\"/\\&lt;/\", \"/\\&gt;/\"];\n $replace = [\"<\", \">\"];\n $val = preg_replace($search, $replace, $val);", " if (preg_match(\"/([<>])([=]*)[[:space:]]*([0-9]+)/\", $val, $regs)) {\n if (in_array($searchtype, [\"notequals\", \"notcontains\"])) {\n $nott = !$nott;\n }\n if ($nott) {\n if ($regs[1] == '<') {\n $regs[1] = '>';\n } else {\n $regs[1] = '<';\n }\n }\n $regs[1] .= $regs[2];\n return $link . \" ($tocompute \" . $regs[1] . \" \" . $regs[3] . \") \";\n }", " if (is_numeric($val) && !$decimal_contains) {\n $numeric_val = floatval($val);", " if (in_array($searchtype, [\"notequals\", \"notcontains\"])) {\n $nott = !$nott;\n }", " if (isset($searchopt[$ID][\"width\"])) {\n $ADD = \"\";\n if (\n $nott\n && ($val != 'NULL') && ($val != 'null')\n ) {\n $ADD = \" OR $tocompute IS NULL\";\n }\n if ($nott) {\n return $link . \" ($tocompute < \" . ($numeric_val - $searchopt[$ID][\"width\"]) . \"\n OR $tocompute > \" . ($numeric_val + $searchopt[$ID][\"width\"]) . \"\n $ADD) \";\n }\n return $link . \" (($tocompute >= \" . ($numeric_val - $searchopt[$ID][\"width\"]) . \"\n AND $tocompute <= \" . ($numeric_val + $searchopt[$ID][\"width\"]) . \")\n $ADD) \";\n }\n if (!$nott) {\n return \" $link ($tocompute = $numeric_val) \";\n }\n return \" $link ($tocompute <> $numeric_val) \";\n }\n break;\n }\n }", " // Default case\n if (in_array($searchtype, ['equals', 'notequals','under', 'notunder'])) {\n if (\n (!isset($searchopt[$ID]['searchequalsonfield'])\n || !$searchopt[$ID]['searchequalsonfield'])\n && ($itemtype == AllAssets::getType()\n || $table != $itemtype::getTable())\n ) {\n $out = \" $link (`$table`.`id`\" . $SEARCH;\n } else {\n $out = \" $link (`$table`.`$field`\" . $SEARCH;\n }\n if ($searchtype == 'notequals') {\n $nott = !$nott;\n }\n // Add NULL if $val = 0 and not negative search\n // Or negative search on real value\n if (\n (!$nott && ($val == 0))\n || ($nott && ($val != 0))\n ) {\n $out .= \" OR `$table`.`id` IS NULL\";\n }\n $out .= ')';\n return $out;\n }\n $transitemtype = getItemTypeForTable($inittable);\n if (Session::haveTranslations($transitemtype, $field)) {\n return \" $link (\" . self::makeTextCriteria($tocompute, $val, $nott, '') . \"\n OR \" . self::makeTextCriteria($tocomputetrans, $val, $nott, '') . \")\";\n }", " return self::makeTextCriteria($tocompute, $val, $nott, $link);\n }", "\n /**\n * Generic Function to add Default left join to a request\n *\n * @param class-string<CommonDBTM> $itemtype Reference item type\n * @param string $ref_table Reference table\n * @param array &$already_link_tables Array of tables already joined\n *\n * @return string Left join string\n **/\n public static function addDefaultJoin($itemtype, $ref_table, array &$already_link_tables)\n {\n $out = '';", " switch ($itemtype) {\n // No link\n case 'User':\n $out = self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_profiles_users\",\n \"profiles_users_id\",\n 0,\n 0,\n ['jointype' => 'child']\n );\n break;", " case 'Reservation':\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n ReservationItem::getTable(),\n ReservationItem::getForeignKeyField(),\n );\n break;", " case 'Reminder':\n $out = Reminder::addVisibilityJoins();\n break;", " case 'RSSFeed':\n $out = RSSFeed::addVisibilityJoins();\n break;", " case 'ProjectTask':\n // Same structure in addDefaultWhere\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_projects\",\n \"projects_id\"\n );\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_projecttaskteams\",\n \"projecttaskteams_id\",\n 0,\n 0,\n ['jointype' => 'child']\n );\n break;", " case 'Project':\n // Same structure in addDefaultWhere\n if (!Session::haveRight(\"project\", Project::READALL)) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_projectteams\",\n \"projectteams_id\",\n 0,\n 0,\n ['jointype' => 'child']\n );\n }\n break;", " case 'Ticket':\n // Same structure in addDefaultWhere\n if (!Session::haveRight(\"ticket\", Ticket::READALL)) {\n $searchopt = &self::getOptions($itemtype);", " // show mine : requester\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[4]['joinparams']['beforejoin']['joinparams']\n );", " if (Session::haveRight(\"ticket\", Ticket::READGROUP)) {\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_groups_tickets\",\n \"groups_tickets_id\",\n 0,\n 0,\n $searchopt[71]['joinparams']['beforejoin']\n ['joinparams']\n );\n }\n }", " // show mine : observer\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[66]['joinparams']['beforejoin']['joinparams']\n );", " if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_groups_tickets\",\n \"groups_tickets_id\",\n 0,\n 0,\n $searchopt[65]['joinparams']['beforejoin']['joinparams']\n );\n }", " if (Session::haveRight(\"ticket\", Ticket::OWN)) { // Can own ticket : show assign to me\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[5]['joinparams']['beforejoin']['joinparams']\n );\n }", " if (Session::haveRightsOr(\"ticket\", [Ticket::READMY, Ticket::READASSIGN])) { // show mine + assign to me\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[5]['joinparams']['beforejoin']['joinparams']\n );", " if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_groups_tickets\",\n \"groups_tickets_id\",\n 0,\n 0,\n $searchopt[8]['joinparams']['beforejoin']\n ['joinparams']\n );\n }\n }", " if (\n Session::haveRightsOr(\n 'ticketvalidation',\n [TicketValidation::VALIDATEINCIDENT,\n TicketValidation::VALIDATEREQUEST\n ]\n )\n ) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_ticketvalidations\",\n \"ticketvalidations_id\",\n 0,\n 0,\n $searchopt[58]['joinparams']['beforejoin']['joinparams']\n );\n }\n }\n break;", " case 'Change':\n case 'Problem':\n if ($itemtype == 'Change') {\n $right = 'change';\n $table = 'changes';\n $groupetable = \"glpi_changes_groups\";\n $linkfield = \"changes_groups_id\";\n } else if ($itemtype == 'Problem') {\n $right = 'problem';\n $table = 'problems';\n $groupetable = \"glpi_groups_problems\";\n $linkfield = \"groups_problems_id\";\n }", " // Same structure in addDefaultWhere\n $out = '';\n if (!Session::haveRight(\"$right\", $itemtype::READALL)) {\n $searchopt = &self::getOptions($itemtype);", " if (Session::haveRight(\"$right\", $itemtype::READMY)) {\n // show mine : requester\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_\" . $table . \"_users\",\n $table . \"_users_id\",\n 0,\n 0,\n $searchopt[4]['joinparams']['beforejoin']['joinparams']\n );\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $groupetable,\n $linkfield,\n 0,\n 0,\n $searchopt[71]['joinparams']['beforejoin']['joinparams']\n );\n }", " // show mine : observer\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_\" . $table . \"_users\",\n $table . \"_users_id\",\n 0,\n 0,\n $searchopt[66]['joinparams']['beforejoin']['joinparams']\n );\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $groupetable,\n $linkfield,\n 0,\n 0,\n $searchopt[65]['joinparams']['beforejoin']['joinparams']\n );\n }", " // show mine : assign\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_\" . $table . \"_users\",\n $table . \"_users_id\",\n 0,\n 0,\n $searchopt[5]['joinparams']['beforejoin']['joinparams']\n );\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $groupetable,\n $linkfield,\n 0,\n 0,\n $searchopt[8]['joinparams']['beforejoin']['joinparams']\n );\n }\n }\n }\n break;", " default:\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $plugin_name = $plug['plugin'];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addDefaultJoin';\n $hook_closure = function () use ($hook_function, $itemtype, $ref_table, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $already_link_tables);\n }\n };\n $out = Plugin::doOneHook($plugin_name, $hook_closure);\n }\n break;\n }", " list($itemtype, $out) = Plugin::doHookFunction('add_default_join', [$itemtype, $out]);\n return $out;\n }", "\n /**\n * Generic Function to add left join to a request\n *\n * @param string $itemtype Item type\n * @param string $ref_table Reference table\n * @param array $already_link_tables Array of tables already joined\n * @param string $new_table New table to join\n * @param string $linkfield Linkfield for LeftJoin\n * @param boolean $meta Is it a meta item ? (default 0)\n * @param integer $meta_type Meta type table (default 0)\n * @param array $joinparams Array join parameters (condition / joinbefore...)\n * @param string $field Field to display (needed for translation join) (default '')\n *\n * @return string Left join string\n **/\n public static function addLeftJoin(\n $itemtype,\n $ref_table,\n array &$already_link_tables,\n $new_table,\n $linkfield,\n $meta = 0,\n $meta_type = 0,\n $joinparams = [],\n $field = ''\n ) {", " // Rename table for meta left join\n $AS = \"\";\n $nt = $new_table;\n $cleannt = $nt;", " // Virtual field no link\n if (strpos($linkfield, '_virtual') === 0) {\n return '';\n }", " $complexjoin = self::computeComplexJoinID($joinparams);", " $is_fkey_composite_on_self = getTableNameForForeignKeyField($linkfield) == $ref_table\n && $linkfield != getForeignKeyFieldForTable($ref_table);", " // Auto link\n if (\n ($ref_table == $new_table)\n && empty($complexjoin)\n && !$is_fkey_composite_on_self\n ) {\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n return self::joinDropdownTranslations(\n $transAS,\n $nt,\n $transitemtype,\n $field\n );\n }\n return \"\";\n }", " // Multiple link possibilies case\n if (!empty($linkfield) && ($linkfield != getForeignKeyFieldForTable($new_table))) {\n $nt .= \"_\" . $linkfield;\n $AS = \" AS `$nt`\";\n }", " if (!empty($complexjoin)) {\n $nt .= \"_\" . $complexjoin;\n $AS = \" AS `$nt`\";\n }", " $addmetanum = \"\";\n $rt = $ref_table;\n $cleanrt = $rt;\n if ($meta && $meta_type::getTable() != $new_table) {\n $addmetanum = \"_\" . $meta_type;\n $AS = \" AS `$nt$addmetanum`\";\n $nt = $nt . $addmetanum;\n }", " // Do not take into account standard linkfield\n $tocheck = $nt . \".\" . $linkfield;\n if ($linkfield == getForeignKeyFieldForTable($new_table)) {\n $tocheck = $nt;\n }", " if (in_array($tocheck, $already_link_tables)) {\n return \"\";\n }\n array_push($already_link_tables, $tocheck);", " $specific_leftjoin = '';", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $plugin_name = $plug['plugin'];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addLeftJoin';\n $hook_closure = function () use ($hook_function, $itemtype, $ref_table, $new_table, $linkfield, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $new_table, $linkfield, $already_link_tables);\n }\n };\n $specific_leftjoin = Plugin::doOneHook($plugin_name, $hook_closure);\n }", " // Link with plugin tables : need to know left join structure\n if (\n empty($specific_leftjoin)\n && preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $new_table, $matches)\n ) {\n if (count($matches) == 2) {\n $plugin_name = $matches[1];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addLeftJoin';\n $hook_closure = function () use ($hook_function, $itemtype, $ref_table, $new_table, $linkfield, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $new_table, $linkfield, $already_link_tables);\n }\n };\n $specific_leftjoin = Plugin::doOneHook($plugin_name, $hook_closure);\n }\n }\n if (!empty($linkfield)) {\n $before = '';", " if (isset($joinparams['beforejoin']) && is_array($joinparams['beforejoin'])) {\n if (isset($joinparams['beforejoin']['table'])) {\n $joinparams['beforejoin'] = [$joinparams['beforejoin']];\n }", " foreach ($joinparams['beforejoin'] as $tab) {\n if (isset($tab['table'])) {\n $intertable = $tab['table'];\n if (isset($tab['linkfield'])) {\n $interlinkfield = $tab['linkfield'];\n } else {\n $interlinkfield = getForeignKeyFieldForTable($intertable);\n }", " $interjoinparams = [];\n if (isset($tab['joinparams'])) {\n $interjoinparams = $tab['joinparams'];\n }\n $before .= self::addLeftJoin(\n $itemtype,\n $rt,\n $already_link_tables,\n $intertable,\n $interlinkfield,\n $meta,\n $meta_type,\n $interjoinparams\n );\n }", " // No direct link with the previous joins\n if (!isset($tab['joinparams']['nolink']) || !$tab['joinparams']['nolink']) {\n $cleanrt = $intertable;\n $complexjoin = self::computeComplexJoinID($interjoinparams);\n if (!empty($interlinkfield) && ($interlinkfield != getForeignKeyFieldForTable($intertable))) {\n $intertable .= \"_\" . $interlinkfield;\n }\n if (!empty($complexjoin)) {\n $intertable .= \"_\" . $complexjoin;\n }\n if ($meta && $meta_type::getTable() != $cleanrt) {\n $intertable .= \"_\" . $meta_type;\n }\n $rt = $intertable;\n }\n }\n }", " $addcondition = '';\n if (isset($joinparams['condition'])) {\n $condition = $joinparams['condition'];\n if (is_array($condition)) {\n $it = new DBmysqlIterator(null);\n $condition = ' AND ' . $it->analyseCrit($condition);\n }\n $from = [\"`REFTABLE`\", \"REFTABLE\", \"`NEWTABLE`\", \"NEWTABLE\"];\n $to = [\"`$rt`\", \"`$rt`\", \"`$nt`\", \"`$nt`\"];\n $addcondition = str_replace($from, $to, $condition);\n $addcondition = $addcondition . \" \";\n }", " if (!isset($joinparams['jointype'])) {\n $joinparams['jointype'] = 'standard';\n }", " if (empty($specific_leftjoin)) {\n switch ($new_table) {\n // No link\n case \"glpi_auth_tables\":\n $user_searchopt = self::getOptions('User');", " $specific_leftjoin = self::addLeftJoin(\n $itemtype,\n $rt,\n $already_link_tables,\n \"glpi_authldaps\",\n 'auths_id',\n 0,\n 0,\n $user_searchopt[30]['joinparams']\n );\n $specific_leftjoin .= self::addLeftJoin(\n $itemtype,\n $rt,\n $already_link_tables,\n \"glpi_authmails\",\n 'auths_id',\n 0,\n 0,\n $user_searchopt[31]['joinparams']\n );\n break;\n }\n }", " if (empty($specific_leftjoin)) {\n switch ($joinparams['jointype']) {\n case 'child':\n $linkfield = getForeignKeyFieldForTable($cleanrt);\n if (isset($joinparams['linkfield'])) {\n $linkfield = $joinparams['linkfield'];\n }", " // Child join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$rt`.`id` = `$nt`.`$linkfield`\n $addcondition)\";\n break;", " case 'item_item':\n // Item_Item join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON ((`$rt`.`id`\n = `$nt`.`\" . getForeignKeyFieldForTable($cleanrt) . \"_1`\n OR `$rt`.`id`\n = `$nt`.`\" . getForeignKeyFieldForTable($cleanrt) . \"_2`)\n $addcondition)\";\n break;", " case 'item_item_revert':\n // Item_Item join reverting previous item_item\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON ((`$nt`.`id`\n = `$rt`.`\" . getForeignKeyFieldForTable($cleannt) . \"_1`\n OR `$nt`.`id`\n = `$rt`.`\" . getForeignKeyFieldForTable($cleannt) . \"_2`)\n $addcondition)\";\n break;", " case \"mainitemtype_mainitem\":\n $addmain = 'main';\n //addmain defined to be used in itemtype_item case", " case \"itemtype_item\":\n if (!isset($addmain)) {\n $addmain = '';\n }\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$rt`.`id` = `$nt`.`\" . $addmain . \"items_id`\n AND `$nt`.`\" . $addmain . \"itemtype` = '$used_itemtype'\n $addcondition) \";\n break;", " case \"itemtype_item_revert\":\n if (!isset($addmain)) {\n $addmain = '';\n }\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$nt`.`id` = `$rt`.`\" . $addmain . \"items_id`\n AND `$rt`.`\" . $addmain . \"itemtype` = '$used_itemtype'\n $addcondition) \";\n break;", " case \"itemtypeonly\":\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$nt`.`itemtype` = '$used_itemtype'\n $addcondition) \";\n break;", " default:\n // Standard join\n $specific_leftjoin = \"LEFT JOIN `$new_table` $AS\n ON (`$rt`.`$linkfield` = `$nt`.`id`\n $addcondition)\";\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n $specific_leftjoin .= self::joinDropdownTranslations(\n $transAS,\n $nt,\n $transitemtype,\n $field\n );\n }\n break;\n }\n }\n return $before . $specific_leftjoin;\n }", " return '';\n }", "\n /**\n * Generic Function to add left join for meta items\n *\n * @param string $from_type Reference item type ID\n * @param string $to_type Item type to add\n * @param array $already_link_tables2 Array of tables already joined\n *showGenericSearch\n * @return string Meta Left join string\n **/\n public static function addMetaLeftJoin(\n $from_type,\n $to_type,\n array &$already_link_tables2,\n $joinparams = []\n ) {\n global $CFG_GLPI;", " $from_referencetype = self::getMetaReferenceItemtype($from_type);", " $LINK = \" LEFT JOIN \";", " $from_table = $from_type::getTable();\n $from_fk = getForeignKeyFieldForTable($from_table);\n $to_table = $to_type::getTable();\n $to_fk = getForeignKeyFieldForTable($to_table);", " $to_obj = getItemForItemtype($to_type);\n $to_entity_restrict = $to_obj->isField('entities_id') ? getEntitiesRestrictRequest('AND', $to_table) : '';", " $complexjoin = self::computeComplexJoinID($joinparams);\n $alias_suffix = ($complexjoin != '' ? '_' . $complexjoin : '') . '_' . $to_type;", " $JOIN = \"\";", " // Specific JOIN\n if ($from_referencetype === 'Software' && in_array($to_type, $CFG_GLPI['software_types'])) {\n // From Software to software_types\n $softwareversions_table = \"glpi_softwareversions{$alias_suffix}\";\n if (!in_array($softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $softwareversions_table);\n $JOIN .= \"$LINK `glpi_softwareversions` AS `$softwareversions_table`\n ON (`$softwareversions_table`.`softwares_id` = `$from_table`.`id`) \";\n }\n $items_softwareversions_table = \"glpi_items_softwareversions_{$alias_suffix}\";\n if (!in_array($items_softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $items_softwareversions_table);\n $JOIN .= \"$LINK `glpi_items_softwareversions` AS `$items_softwareversions_table`\n ON (`$items_softwareversions_table`.`softwareversions_id` = `$softwareversions_table`.`id`\n AND `$items_softwareversions_table`.`itemtype` = '$to_type'\n AND `$items_softwareversions_table`.`is_deleted` = 0) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$items_softwareversions_table`.`items_id` = `$to_table`.`id`\n AND `$items_softwareversions_table`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($to_type === 'Software' && in_array($from_referencetype, $CFG_GLPI['software_types'])) {\n // From software_types to Software\n $items_softwareversions_table = \"glpi_items_softwareversions{$alias_suffix}\";\n if (!in_array($items_softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $items_softwareversions_table);\n $JOIN .= \"$LINK `glpi_items_softwareversions` AS `$items_softwareversions_table`\n ON (`$items_softwareversions_table`.`items_id` = `$from_table`.`id`\n AND `$items_softwareversions_table`.`itemtype` = '$from_type'\n AND `$items_softwareversions_table`.`is_deleted` = 0) \";\n }\n $softwareversions_table = \"glpi_softwareversions{$alias_suffix}\";\n if (!in_array($softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $softwareversions_table);\n $JOIN .= \"$LINK `glpi_softwareversions` AS `$softwareversions_table`\n ON (`$items_softwareversions_table`.`softwareversions_id` = `$softwareversions_table`.`id`) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$softwareversions_table`.`softwares_id` = `$to_table`.`id`) \";\n }\n $softwarelicenses_table = \"glpi_softwarelicenses{$alias_suffix}\";\n if (!in_array($softwarelicenses_table, $already_link_tables2)) {\n array_push($already_link_tables2, $softwarelicenses_table);\n $JOIN .= \"$LINK `glpi_softwarelicenses` AS `$softwarelicenses_table`\n ON ($to_table.`id` = `$softwarelicenses_table`.`softwares_id`\"\n . getEntitiesRestrictRequest(' AND', $softwarelicenses_table, '', '', true) . \") \";\n }\n return $JOIN;\n }", " if ($from_referencetype === 'Budget' && in_array($to_type, $CFG_GLPI['infocom_types'])) {\n // From Budget to infocom_types\n $infocom_alias = \"glpi_infocoms{$alias_suffix}\";\n if (!in_array($infocom_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $infocom_alias);\n $JOIN .= \"$LINK `glpi_infocoms` AS `$infocom_alias`\n ON (`$from_table`.`id` = `$infocom_alias`.`budgets_id`) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$to_table`.`id` = `$infocom_alias`.`items_id`\n AND `$infocom_alias`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($to_type === 'Budget' && in_array($from_referencetype, $CFG_GLPI['infocom_types'])) {\n // From infocom_types to Budget\n $infocom_alias = \"glpi_infocoms{$alias_suffix}\";\n if (!in_array($infocom_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $infocom_alias);\n $JOIN .= \"$LINK `glpi_infocoms` AS `$infocom_alias`\n ON (`$from_table`.`id` = `$infocom_alias`.`items_id`\n AND `$infocom_alias`.`itemtype` = '$from_type') \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$infocom_alias`.`$to_fk` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($from_referencetype === 'Reservation' && in_array($to_type, $CFG_GLPI['reservation_types'])) {\n // From Reservation to reservation_types\n $reservationitems_alias = \"glpi_reservationitems{$alias_suffix}\";\n if (!in_array($reservationitems_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $reservationitems_alias);\n $JOIN .= \"$LINK `glpi_reservationitems` AS `$reservationitems_alias`\n ON (`$from_table`.`reservationitems_id` = `$reservationitems_alias`.`id`) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$to_table`.`id` = `$reservationitems_alias`.`items_id`\n AND `$reservationitems_alias`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($to_type === 'Reservation' && in_array($from_referencetype, $CFG_GLPI['reservation_types'])) {\n // From reservation_types to Reservation\n $reservationitems_alias = \"glpi_reservationitems{$alias_suffix}\";\n if (!in_array($reservationitems_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $reservationitems_alias);\n $JOIN .= \"$LINK `glpi_reservationitems` AS `$reservationitems_alias`\n ON (`$from_table`.`id` = `$reservationitems_alias`.`items_id`\n AND `$reservationitems_alias`.`itemtype` = '$from_type') \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$reservationitems_alias`.`id` = `$to_table`.`reservationitems_id`\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " // Generic JOIN\n $from_obj = getItemForItemtype($from_referencetype);\n $from_item_obj = null;\n $to_obj = getItemForItemtype($to_type);\n $to_item_obj = null;\n if (self::isPossibleMetaSubitemOf($from_referencetype, $to_type)) {\n $from_item_obj = getItemForItemtype($from_referencetype . '_Item');\n if (!$from_item_obj) {\n $from_item_obj = getItemForItemtype('Item_' . $from_referencetype);\n }\n }\n if (self::isPossibleMetaSubitemOf($to_type, $from_referencetype)) {\n $to_item_obj = getItemForItemtype($to_type . '_Item');\n if (!$to_item_obj) {\n $to_item_obj = getItemForItemtype('Item_' . $to_type);\n }\n }", " if ($from_obj && $from_obj->isField($to_fk)) {\n // $from_table has a foreign key corresponding to $to_table\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`$to_fk` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n } else if ($to_obj && $to_obj->isField($from_fk)) {\n // $to_table has a foreign key corresponding to $from_table\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`id` = `$to_table`.`$from_fk`\n $to_entity_restrict) \";\n }\n } else if ($from_obj && $from_obj->isField('itemtype') && $from_obj->isField('items_id')) {\n // $from_table has items_id/itemtype fields\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`items_id` = `$to_table`.`id`\n AND `$from_table`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n } else if ($to_obj && $to_obj->isField('itemtype') && $to_obj->isField('items_id')) {\n // $to_table has items_id/itemtype fields\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`id` = `$to_table`.`items_id`\n AND `$to_table`.`itemtype` = '$from_type'\n $to_entity_restrict) \";\n }\n } else if ($from_item_obj && $from_item_obj->isField($from_fk)) {\n // glpi_$from_items table exists and has a foreign key corresponding to $to_table\n $items_table = $from_item_obj::getTable();\n $items_table_alias = $items_table . $alias_suffix;\n if (!in_array($items_table_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $items_table_alias);\n $deleted = $from_item_obj->isField('is_deleted') ? \"AND `$items_table_alias`.`is_deleted` = 0\" : \"\";\n $JOIN .= \"$LINK `$items_table` AS `$items_table_alias`\n ON (`$items_table_alias`.`$from_fk` = `$from_table`.`id`\n AND `$items_table_alias`.`itemtype` = '$to_type'\n $deleted)\";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$items_table_alias`.`items_id` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n } else if ($to_item_obj && $to_item_obj->isField($to_fk)) {\n // glpi_$to_items table exists and has a foreign key corresponding to $from_table\n $items_table = $to_item_obj::getTable();\n $items_table_alias = $items_table . $alias_suffix;\n if (!in_array($items_table_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $items_table_alias);\n $deleted = $to_item_obj->isField('is_deleted') ? \"AND `$items_table_alias`.`is_deleted` = 0\" : \"\";\n $JOIN .= \"$LINK `$items_table` AS `$items_table_alias`\n ON (`$items_table_alias`.`items_id` = `$from_table`.`id`\n AND `$items_table_alias`.`itemtype` = '$from_type'\n $deleted)\";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$items_table_alias`.`$to_fk` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n }", " return $JOIN;\n }", "\n /**\n * Generic Function to display Items\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $itemtype item type\n * @param integer $ID ID of the SEARCH_OPTION item\n * @param array $data array retrieved data array\n *\n * @return string String to print\n **/\n public static function displayConfigItem($itemtype, $ID, $data = [])\n {", " $searchopt = &self::getOptions($itemtype);", " $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'displayConfigItem',\n $itemtype,\n $ID,\n $data,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }", " $out = \"\";\n $NAME = \"{$itemtype}_{$ID}\";", " switch ($table . \".\" . $field) {\n case \"glpi_tickets.time_to_resolve\":\n case \"glpi_tickets.internal_time_to_resolve\":\n case \"glpi_problems.time_to_resolve\":\n case \"glpi_changes.time_to_resolve\":\n if (in_array($ID, [151, 181])) {\n break; // Skip \"TTR + progress\" search options\n }", " $value = $data[$NAME][0]['name'];\n $status = $data[$NAME][0]['status'];\n $solve_date = $data[$NAME][0]['solvedate'];", " $is_late = !empty($value)\n && $status != CommonITILObject::WAITING\n && (\n $solve_date > $value\n || ($solve_date == null && $value < $_SESSION['glpi_currenttime'])\n );", " if ($is_late) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: #cf9b9b\\\" \";\n }\n break;\n case \"glpi_tickets.time_to_own\":\n case \"glpi_tickets.internal_time_to_own\":\n if (in_array($ID, [158, 186])) {\n break; // Skip \"TTO + progress\" search options\n }", " $value = $data[$NAME][0]['name'];\n $status = $data[$NAME][0]['status'];\n $opening_date = $data[$NAME][0]['date'];\n $tia_time = $data[$NAME][0]['takeintoaccount_delay_stat'];", " $is_late = !empty($value)\n && $status != CommonITILObject::WAITING\n && (\n $tia_time > strtotime($opening_date) - strtotime($value)\n || ($tia_time == 0 && $value < $_SESSION['glpi_currenttime'])\n );", " if ($is_late) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: #cf9b9b\\\" \";\n }\n break;", " case \"glpi_projectstates.color\":\n case \"glpi_cables.color\":\n $bg_color = $data[$NAME][0]['name'];\n if (!empty($bg_color)) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: $bg_color;\\\" \";\n }\n break;", " case \"glpi_projectstates.name\":\n if (array_key_exists('color', $data[$NAME][0])) {\n $bg_color = $data[$NAME][0]['color'];\n if (!empty($bg_color)) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: $bg_color;\\\" \";\n }\n }\n break;", " case \"glpi_domains.date_expiration\":\n case \"glpi_certificates.date_expiration\":\n if (\n !empty($data[$NAME][0]['name'])\n && ($data[$NAME][0]['name'] < $_SESSION['glpi_currenttime'])\n ) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: #cf9b9b\\\" \";\n }\n break;\n }", " return $out;\n }", "\n /**\n * Generic Function to display Items\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $itemtype item type\n * @param integer $ID ID of the SEARCH_OPTION item\n * @param array $data array containing data results\n * @param boolean $meta is a meta item ? (default 0)\n * @param array $addobjectparams array added parameters for union search\n * @param string $orig_itemtype Original itemtype, used for union_search_type\n *\n * @return string String to print\n **/\n public static function giveItem(\n $itemtype,\n $ID,\n array $data,\n $meta = 0,\n array $addobjectparams = [],\n $orig_itemtype = null\n ) {\n global $CFG_GLPI;", " $searchopt = &self::getOptions($itemtype);\n if (\n isset($CFG_GLPI[\"union_search_type\"][$itemtype])\n && ($CFG_GLPI[\"union_search_type\"][$itemtype] == $searchopt[$ID][\"table\"])\n ) {\n $oparams = [];\n if (\n isset($searchopt[$ID]['addobjectparams'])\n && $searchopt[$ID]['addobjectparams']\n ) {\n $oparams = $searchopt[$ID]['addobjectparams'];\n }", " // Search option may not exists in subtype\n // This is the case for \"Inventory number\" for a Software listed from ReservationItem search\n $subtype_so = &self::getOptions($data[\"TYPE\"]);\n if (!array_key_exists($ID, $subtype_so)) {\n return '';\n }", " return self::giveItem($data[\"TYPE\"], $ID, $data, $meta, $oparams, $itemtype);\n }\n $so = $searchopt[$ID];\n $orig_id = $ID;\n $ID = ($orig_itemtype !== null ? $orig_itemtype : $itemtype) . '_' . $ID;", " if (count($addobjectparams)) {\n $so = array_merge($so, $addobjectparams);\n }\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'giveItem',\n $itemtype,\n $orig_id,\n $data,\n $ID\n );\n if (!empty($out)) {\n return $out;\n }\n }", "", "\n if (isset($so[\"table\"])) {\n $table = $so[\"table\"];\n $field = $so[\"field\"];\n $linkfield = $so[\"linkfield\"];", " /// TODO try to clean all specific cases using SpecificToDisplay", " switch ($table . '.' . $field) {\n case \"glpi_users.name\":\n // USER search case\n if (\n ($itemtype != 'User')\n && isset($so[\"forcegroupby\"]) && $so[\"forcegroupby\"]\n ) {\n $out = \"\";\n $count_display = 0;\n $added = [];", " $showuserlink = 0;\n if (Session::haveRight('user', READ)) {\n $showuserlink = 1;\n }", " for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n (isset($data[$ID][$k]['name']) && ($data[$ID][$k]['name'] > 0))\n || (isset($data[$ID][$k][2]) && ($data[$ID][$k][2] != ''))\n ) {\n if ($count_display) {\n $out .= self::LBBR;\n }", " if ($itemtype == 'Ticket') {\n if (\n isset($data[$ID][$k]['name'])\n && $data[$ID][$k]['name'] > 0\n ) {\n if (\n Session::getCurrentInterface() == 'helpdesk'\n && $orig_id == 5 // -> Assigned user\n && !empty($anon_name = User::getAnonymizedNameForUser(\n $data[$ID][$k]['name'],\n $itemtype::getById($data['id'])->getEntityId()\n ))\n ) {\n $out .= $anon_name;\n } else {\n $userdata = getUserName($data[$ID][$k]['name'], 2);\n $tooltip = \"\";\n if (Session::haveRight('user', READ)) {\n $tooltip = Html::showToolTip(\n $userdata[\"comment\"],\n ['link' => $userdata[\"link\"],\n 'display' => false\n ]\n );\n }\n $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);\n }", " $count_display++;\n }\n } else {\n $out .= getUserName($data[$ID][$k]['name'], $showuserlink);\n $count_display++;\n }", " // Manage alternative_email for tickets_users\n if (\n ($itemtype == 'Ticket')\n && isset($data[$ID][$k][2])\n ) {\n $split = explode(self::LONGSEP, $data[$ID][$k][2]);\n for ($l = 0; $l < count($split); $l++) {\n $split2 = explode(\" \", $split[$l]);\n if ((count($split2) == 2) && ($split2[0] == 0) && !empty($split2[1])) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= \"<a href='mailto:\" . $split2[1] . \"'>\" . $split2[1] . \"</a>\";\n }\n }\n }\n }\n }\n return $out;\n }\n if ($itemtype != 'User') {\n $toadd = '';\n if (\n ($itemtype == 'Ticket')\n && ($data[$ID][0]['id'] > 0)\n ) {\n $userdata = getUserName($data[$ID][0]['id'], 2);\n $toadd = Html::showToolTip(\n $userdata[\"comment\"],\n ['link' => $userdata[\"link\"],\n 'display' => false\n ]\n );\n }\n $usernameformat = formatUserName(\n $data[$ID][0]['id'],\n $data[$ID][0]['name'],\n $data[$ID][0]['realname'],\n $data[$ID][0]['firstname'],\n 1\n );\n return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);\n }", " $current_users_id = $data[$ID][0]['id'] ?? 0;\n if ($current_users_id > 0) {\n return TemplateRenderer::getInstance()->render('components/user/picture.html.twig', [\n 'users_id' => $current_users_id,\n 'display_login' => true,\n 'force_login' => true,\n 'avatar_size' => \"avatar-sm\",\n ]);\n }\n break;", " case \"glpi_profiles.name\":\n if (\n ($itemtype == 'User')\n && ($orig_id == 20)\n ) {\n $out = \"\";", " $count_display = 0;\n $added = [];\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n strlen(trim($data[$ID][$k]['name'])) > 0\n && !in_array(\n $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['entities_id'],\n $added\n )\n ) {\n $text = sprintf(\n __('%1$s - %2$s'),\n $data[$ID][$k]['name'],\n Dropdown::getDropdownName(\n 'glpi_entities',\n $data[$ID][$k]['entities_id']\n )\n );\n $comp = '';\n if ($data[$ID][$k]['is_recursive']) {\n $comp = __('R');\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, \", \");\n }\n }\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));\n }\n if (!empty($comp)) {\n $text = sprintf(__('%1$s %2$s'), $text, \"(\" . $comp . \")\");\n }\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= $text;\n $added[] = $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['entities_id'];\n }\n }\n return $out;\n }\n break;", " case \"glpi_entities.completename\":\n if ($itemtype == 'User') {\n $out = \"\";\n $added = [];\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n isset($data[$ID][$k]['name'])\n && (strlen(trim($data[$ID][$k]['name'])) > 0)\n && !in_array(\n $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['profiles_id'],\n $added\n )\n ) {\n $text = sprintf(\n __('%1$s - %2$s'),\n Entity::badgeCompletename($data[$ID][$k]['name']),\n Dropdown::getDropdownName(\n 'glpi_profiles',\n $data[$ID][$k]['profiles_id']\n )\n );\n $comp = '';\n if ($data[$ID][$k]['is_recursive']) {\n $comp = __('R');\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, \", \");\n }\n }\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));\n }\n if (!empty($comp)) {\n $text = sprintf(__('%1$s %2$s'), $text, \"(\" . $comp . \")\");\n }\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= $text;\n $added[] = $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['profiles_id'];\n }\n }\n return $out;\n } else if (($so[\"datatype\"] ?? \"\") != \"itemlink\" && !empty($data[$ID][0]['name'])) {\n return Entity::badgeCompletename($data[$ID][0]['name']);\n }\n break;", " case \"glpi_documenttypes.icon\":\n if (!empty($data[$ID][0]['name'])) {\n return \"<img class='middle' alt='' src='\" . $CFG_GLPI[\"typedoc_icon_dir\"] . \"/\" .\n $data[$ID][0]['name'] . \"'>\";\n }\n return \"&nbsp;\";", " case \"glpi_documents.filename\":\n $doc = new Document();\n if ($doc->getFromDB($data['id'])) {\n return $doc->getDownloadLink();\n }\n return NOT_AVAILABLE;", " case \"glpi_tickets_tickets.tickets_id_1\":\n $out = \"\";\n $displayed = [];\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n $linkid = ($data[$ID][$k]['tickets_id_2'] == $data['id'])\n ? $data[$ID][$k]['name']\n : $data[$ID][$k]['tickets_id_2'];", " // If link ID is int or integer string, force conversion to int. Coversion to int and then string to compare is needed to ensure it isn't a decimal\n if (is_numeric($linkid) && ((string)(int)$linkid === (string)$linkid)) {\n $linkid = (int) $linkid;\n }\n if ((is_int($linkid) && $linkid > 0) && !isset($displayed[$linkid])) {\n $text = \"<a \";\n $text .= \"href=\\\"\" . Ticket::getFormURLWithID($linkid) . \"\\\">\";\n $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . \"</a>\";\n if (count($displayed)) {\n $out .= self::LBBR;\n }\n $displayed[$linkid] = $linkid;\n $out .= $text;\n }\n }\n return $out;", " case \"glpi_problems.id\":\n if ($so[\"datatype\"] == 'count') {\n if (\n ($data[$ID][0]['name'] > 0)\n && Session::haveRight(\"problem\", Problem::READALL)\n ) {\n if ($itemtype == 'ITILCategory') {\n $options['criteria'][0]['field'] = 7;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n } else {\n $options['criteria'][0]['field'] = 12;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = 'all';\n $options['criteria'][0]['link'] = 'AND';", " $options['metacriteria'][0]['itemtype'] = $itemtype;\n $options['metacriteria'][0]['field'] = self::getOptionNumber(\n $itemtype,\n 'name'\n );\n $options['metacriteria'][0]['searchtype'] = 'equals';\n $options['metacriteria'][0]['value'] = $data['id'];\n $options['metacriteria'][0]['link'] = 'AND';\n }", " $options['reset'] = 'reset';", " $out = \"<a id='problem$itemtype\" . $data['id'] . \"' \";\n $out .= \"href=\\\"\" . $CFG_GLPI[\"root_doc\"] . \"/front/problem.php?\" .\n Toolbox::append_params($options, '&amp;') . \"\\\">\";\n $out .= $data[$ID][0]['name'] . \"</a>\";\n return $out;\n }\n }\n break;", " case \"glpi_tickets.id\":\n if ($so[\"datatype\"] == 'count') {\n if (\n ($data[$ID][0]['name'] > 0)\n && Session::haveRight(\"ticket\", Ticket::READALL)\n ) {\n if ($itemtype == 'User') {\n // Requester\n if ($ID == 'User_60') {\n $options['criteria'][0]['field'] = 4;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n }", " // Writer\n if ($ID == 'User_61') {\n $options['criteria'][0]['field'] = 22;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n }\n // Assign\n if ($ID == 'User_64') {\n $options['criteria'][0]['field'] = 5;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n }\n } else if ($itemtype == 'ITILCategory') {\n $options['criteria'][0]['field'] = 7;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n } else {\n $options['criteria'][0]['field'] = 12;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = 'all';\n $options['criteria'][0]['link'] = 'AND';", " $options['metacriteria'][0]['itemtype'] = $itemtype;\n $options['metacriteria'][0]['field'] = self::getOptionNumber(\n $itemtype,\n 'name'\n );\n $options['metacriteria'][0]['searchtype'] = 'equals';\n $options['metacriteria'][0]['value'] = $data['id'];\n $options['metacriteria'][0]['link'] = 'AND';\n }", " $options['reset'] = 'reset';", " $out = \"<a id='ticket$itemtype\" . $data['id'] . \"' \";\n $out .= \"href=\\\"\" . $CFG_GLPI[\"root_doc\"] . \"/front/ticket.php?\" .\n Toolbox::append_params($options, '&amp;') . \"\\\">\";\n $out .= $data[$ID][0]['name'] . \"</a>\";\n return $out;\n }\n }\n break;", " case \"glpi_tickets.time_to_resolve\":\n case \"glpi_problems.time_to_resolve\":\n case \"glpi_changes.time_to_resolve\":\n case \"glpi_tickets.time_to_own\":\n case \"glpi_tickets.internal_time_to_own\":\n case \"glpi_tickets.internal_time_to_resolve\":\n // Due date + progress\n if (in_array($orig_id, [151, 158, 181, 186])) {\n $out = Html::convDateTime($data[$ID][0]['name']);", " // No due date in waiting status\n if ($data[$ID][0]['status'] == CommonITILObject::WAITING) {\n return '';\n }\n if (empty($data[$ID][0]['name'])) {\n return '';\n }\n if (\n ($data[$ID][0]['status'] == Ticket::SOLVED)\n || ($data[$ID][0]['status'] == Ticket::CLOSED)\n ) {\n return $out;\n }", " $itemtype = getItemTypeForTable($table);\n $item = new $itemtype();\n $item->getFromDB($data['id']);\n $percentage = 0;\n $totaltime = 0;\n $currenttime = 0;\n $slaField = 'slas_id';", " // define correct sla field\n switch ($table . '.' . $field) {\n case \"glpi_tickets.time_to_resolve\":\n $slaField = 'slas_id_ttr';\n $sla_class = 'SLA';\n break;\n case \"glpi_tickets.time_to_own\":\n $slaField = 'slas_id_tto';\n $sla_class = 'SLA';\n break;\n case \"glpi_tickets.internal_time_to_own\":\n $slaField = 'olas_id_tto';\n $sla_class = 'OLA';\n break;\n case \"glpi_tickets.internal_time_to_resolve\":\n $slaField = 'olas_id_ttr';\n $sla_class = 'OLA';\n break;\n }", " switch ($table . '.' . $field) {\n // If ticket has been taken into account : no progression display\n case \"glpi_tickets.time_to_own\":\n case \"glpi_tickets.internal_time_to_own\":\n if (($item->fields['takeintoaccount_delay_stat'] > 0)) {\n return $out;\n }\n break;\n }", " if ($item->isField($slaField) && $item->fields[$slaField] != 0) { // Have SLA\n $sla = new $sla_class();\n $sla->getFromDB($item->fields[$slaField]);\n $currenttime = $sla->getActiveTimeBetween(\n $item->fields['date'],\n date('Y-m-d H:i:s')\n );\n $totaltime = $sla->getActiveTimeBetween(\n $item->fields['date'],\n $data[$ID][0]['name']\n );\n } else {\n $calendars_id = Entity::getUsedConfig(\n 'calendars_strategy',\n $item->fields['entities_id'],\n 'calendars_id',\n 0\n );\n $calendar = new Calendar();\n if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { // Ticket entity have calendar\n $currenttime = $calendar->getActiveTimeBetween(\n $item->fields['date'],\n date('Y-m-d H:i:s')\n );\n $totaltime = $calendar->getActiveTimeBetween(\n $item->fields['date'],\n $data[$ID][0]['name']\n );\n } else { // No calendar\n $currenttime = strtotime(date('Y-m-d H:i:s'))\n - strtotime($item->fields['date']);\n $totaltime = strtotime($data[$ID][0]['name'])\n - strtotime($item->fields['date']);\n }\n }\n if ($totaltime != 0) {\n $percentage = round((100 * $currenttime) / $totaltime);\n } else {\n // Total time is null : no active time\n $percentage = 100;\n }\n if ($percentage > 100) {\n $percentage = 100;\n }\n $percentage_text = $percentage;", " if ($_SESSION['glpiduedatewarning_unit'] == '%') {\n $less_warn_limit = $_SESSION['glpiduedatewarning_less'];\n $less_warn = (100 - $percentage);\n } else if ($_SESSION['glpiduedatewarning_unit'] == 'hour') {\n $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;\n $less_warn = ($totaltime - $currenttime);\n } else if ($_SESSION['glpiduedatewarning_unit'] == 'day') {\n $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;\n $less_warn = ($totaltime - $currenttime);\n }", " if ($_SESSION['glpiduedatecritical_unit'] == '%') {\n $less_crit_limit = $_SESSION['glpiduedatecritical_less'];\n $less_crit = (100 - $percentage);\n } else if ($_SESSION['glpiduedatecritical_unit'] == 'hour') {\n $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;\n $less_crit = ($totaltime - $currenttime);\n } else if ($_SESSION['glpiduedatecritical_unit'] == 'day') {\n $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;\n $less_crit = ($totaltime - $currenttime);\n }", " $color = $_SESSION['glpiduedateok_color'];\n if ($less_crit < $less_crit_limit) {\n $color = $_SESSION['glpiduedatecritical_color'];\n } else if ($less_warn < $less_warn_limit) {\n $color = $_SESSION['glpiduedatewarning_color'];\n }", " if (!isset($so['datatype'])) {\n $so['datatype'] = 'progressbar';\n }", " $progressbar_data = [\n 'text' => Html::convDateTime($data[$ID][0]['name']),\n 'percent' => $percentage,\n 'percent_text' => $percentage_text,\n 'color' => $color\n ];\n }\n break;", " case \"glpi_softwarelicenses.number\":\n if ($data[$ID][0]['min'] == -1) {\n return __('Unlimited');\n }\n if (empty($data[$ID][0]['name'])) {\n return 0;\n }\n return $data[$ID][0]['name'];", " case \"glpi_auth_tables.name\":\n return Auth::getMethodName(\n $data[$ID][0]['name'],\n $data[$ID][0]['auths_id'],\n 1,\n $data[$ID][0]['ldapname'] . $data[$ID][0]['mailname']\n );", " case \"glpi_reservationitems.comment\":\n if (empty($data[$ID][0]['name'])) {\n $text = __('None');\n } else {\n $text = Html::resume_text($data[$ID][0]['name']);\n }\n if (Session::haveRight('reservation', UPDATE)) {\n return \"<a title=\\\"\" . __s('Modify the comment') . \"\\\"\n href='\" . ReservationItem::getFormURLWithID($data['refID']) . \"' >\" . $text . \"</a>\";\n }\n return $text;", " case 'glpi_crontasks.description':\n $tmp = new CronTask();\n return $tmp->getDescription($data[$ID][0]['name']);", " case 'glpi_changes.status':\n $status = Change::getStatus($data[$ID][0]['name']);\n return \"<span class='text-nowrap'>\" .\n Change::getStatusIcon($data[$ID][0]['name']) . \"&nbsp;$status\" .\n \"</span>\";", " case 'glpi_problems.status':\n $status = Problem::getStatus($data[$ID][0]['name']);\n return \"<span class='text-nowrap'>\" .\n Problem::getStatusIcon($data[$ID][0]['name']) . \"&nbsp;$status\" .\n \"</span>\";", " case 'glpi_tickets.status':\n $status = Ticket::getStatus($data[$ID][0]['name']);\n return \"<span class='text-nowrap'>\" .\n Ticket::getStatusIcon($data[$ID][0]['name']) . \"&nbsp;$status\" .\n \"</span>\";", " case 'glpi_projectstates.name':\n $out = '';\n $name = $data[$ID][0]['name'];\n if (isset($data[$ID][0]['trans'])) {\n $name = $data[$ID][0]['trans'];\n }\n if ($itemtype == 'ProjectState') {\n $out = \"<a href='\" . ProjectState::getFormURLWithID($data[$ID][0][\"id\"]) . \"'>\" . $name . \"</a></div>\";\n } else {\n $out = $name;\n }\n return $out;", " case 'glpi_items_tickets.items_id':\n case 'glpi_items_problems.items_id':\n case 'glpi_changes_items.items_id':\n case 'glpi_certificates_items.items_id':\n case 'glpi_appliances_items.items_id':\n if (!empty($data[$ID])) {\n $items = [];\n foreach ($data[$ID] as $key => $val) {\n if (is_numeric($key)) {\n if (\n !empty($val['itemtype'])\n && ($item = getItemForItemtype($val['itemtype']))\n ) {\n if ($item->getFromDB($val['name'])) {\n $items[] = $item->getLink(['comments' => true]);\n }\n }\n }\n }\n if (!empty($items)) {\n return implode(\"<br>\", $items);\n }\n }\n return '&nbsp;';", " case 'glpi_items_tickets.itemtype':\n case 'glpi_items_problems.itemtype':\n if (!empty($data[$ID])) {\n $itemtypes = [];\n foreach ($data[$ID] as $key => $val) {\n if (is_numeric($key)) {\n if (\n !empty($val['name'])\n && ($item = getItemForItemtype($val['name']))\n ) {\n $item = new $val['name']();\n $name = $item->getTypeName();\n $itemtypes[] = __($name);\n }\n }\n }\n if (!empty($itemtypes)) {\n return implode(\"<br>\", $itemtypes);\n }\n }", " return '&nbsp;';", " case 'glpi_tickets.name':\n case 'glpi_problems.name':\n case 'glpi_changes.name':\n if (\n isset($data[$ID][0]['content'])\n && isset($data[$ID][0]['id'])\n && isset($data[$ID][0]['status'])\n ) {\n $link = $itemtype::getFormURLWithID($data[$ID][0]['id']);", " $out = \"<a id='$itemtype\" . $data[$ID][0]['id'] . \"' href=\\\"\" . $link;\n // Force solution tab if solved\n if ($item = getItemForItemtype($itemtype)) {\n if (in_array($data[$ID][0]['status'], $item->getSolvedStatusArray())) {\n $out .= \"&amp;forcetab=$itemtype$2\";\n }\n }\n $out .= \"\\\">\";\n $name = $data[$ID][0]['name'];\n if (\n $_SESSION[\"glpiis_ids_visible\"]\n || empty($data[$ID][0]['name'])\n ) {\n $name = sprintf(__('%1$s (%2$s)'), $name, $data[$ID][0]['id']);\n }\n $out .= $name . \"</a>\";\n $out = sprintf(\n __('%1$s %2$s'),\n $out,\n Html::showToolTip(\n RichText::getEnhancedHtml($data[$ID][0]['content']),\n [\n 'applyto' => $itemtype . $data[$ID][0]['id'],\n 'display' => false,\n 'images_gallery' => false, // don't show photoswipe gallery in tooltips\n ]\n )\n );\n return $out;\n }\n break;", " case 'glpi_ticketvalidations.status':\n $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if ($data[$ID][$k]['name']) {\n $status = TicketValidation::getStatus($data[$ID][$k]['name']);\n $bgcolor = TicketValidation::getStatusColor($data[$ID][$k]['name']);\n $out .= (empty($out) ? '' : self::LBBR) .\n \"<div style=\\\"background-color:\" . $bgcolor . \";\\\">\" . $status . '</div>';\n }\n }\n return $out;", " case 'glpi_cables.color':\n //do not display 'real' value (#.....)\n return \"\";", " case 'glpi_ticketsatisfactions.satisfaction':", " if (self::$output_type == self::HTML_OUTPUT) {", " return TicketSatisfaction::displaySatisfaction($data[$ID][0]['name']);\n }\n break;", " case 'glpi_projects._virtual_planned_duration':\n return Html::timestampToString(\n ProjectTask::getTotalPlannedDurationForProject($data[\"id\"]),\n false\n );", " case 'glpi_projects._virtual_effective_duration':\n return Html::timestampToString(\n ProjectTask::getTotalEffectiveDurationForProject($data[\"id\"]),\n false\n );", " case 'glpi_cartridgeitems._virtual':\n return Cartridge::getCount(\n $data[\"id\"],\n $data[$ID][0]['alarm_threshold'],", " self::$output_type != self::HTML_OUTPUT", " );", " case 'glpi_printers._virtual':\n return Cartridge::getCountForPrinter(\n $data[\"id\"],", " self::$output_type != self::HTML_OUTPUT", " );", " case 'glpi_consumableitems._virtual':\n return Consumable::getCount(\n $data[\"id\"],\n $data[$ID][0]['alarm_threshold'],", " self::$output_type != self::HTML_OUTPUT", " );", " case 'glpi_links._virtual':\n $out = '';\n $link = new Link();\n if (\n ($item = getItemForItemtype($itemtype))\n && $item->getFromDB($data['id'])\n ) {\n $data = Link::getLinksDataForItem($item);\n $count_display = 0;\n foreach ($data as $val) {\n $links = Link::getAllLinksFor($item, $val);\n foreach ($links as $link) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $out .= $link;\n $count_display++;\n }\n }\n }\n return $out;", " case 'glpi_reservationitems._virtual':\n if ($data[$ID][0]['is_active']) {\n return \"<a href='reservation.php?reservationitems_id=\" .\n $data[\"refID\"] . \"' title=\\\"\" . __s('See planning') . \"\\\">\" .\n \"<i class='far fa-calendar-alt'></i><span class='sr-only'>\" . __('See planning') . \"</span></a>\";\n } else {\n return \"&nbsp;\";\n }", " case \"glpi_tickets.priority\":\n case \"glpi_problems.priority\":\n case \"glpi_changes.priority\":\n case \"glpi_projects.priority\":\n $index = $data[$ID][0]['name'];\n $color = $_SESSION[\"glpipriority_$index\"];\n $name = CommonITILObject::getPriorityName($index);\n return \"<div class='priority_block' style='border-color: $color'>\n <span style='background: $color'></span>&nbsp;$name\n </div>\";\n }\n }", " //// Default case", " if (\n $itemtype == 'Ticket'\n && Session::getCurrentInterface() == 'helpdesk'\n && $orig_id == 8\n && !empty($anon_name = Group::getAnonymizedName(\n $itemtype::getById($data['id'])->getEntityId()\n ))\n ) {\n // Assigned groups\n return $anon_name;\n }", " // Link with plugin tables : need to know left join structure\n if (isset($table)) {\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table . '.' . $field, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'giveItem',\n $itemtype,\n $orig_id,\n $data,\n $ID\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }\n }\n $unit = '';\n if (isset($so['unit'])) {\n $unit = $so['unit'];\n }", " // Preformat items\n if (isset($so[\"datatype\"])) {\n switch ($so[\"datatype\"]) {\n case \"itemlink\":\n $linkitemtype = getItemTypeForTable($so[\"table\"]);", " $out = \"\";\n $count_display = 0;\n $separate = self::LBBR;\n if (isset($so['splititems']) && $so['splititems']) {\n $separate = self::LBHR;\n }", " for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (isset($data[$ID][$k]['id'])) {\n if ($count_display) {\n $out .= $separate;\n }\n $count_display++;\n $page = $linkitemtype::getFormURLWithID($data[$ID][$k]['id']);\n $name = $data[$ID][$k]['name'];\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($data[$ID][$k]['name'])) {\n $name = sprintf(__('%1$s (%2$s)'), $name, $data[$ID][$k]['id']);\n }\n if ($field === 'completename') {\n $chunks = preg_split('/ > /', $name);\n $completename = '';\n foreach ($chunks as $key => $element_name) {\n $class = $key === array_key_last($chunks) ? '' : 'class=\"text-muted\"';\n $separator = $key === array_key_last($chunks) ? '' : ' &gt; ';\n $completename .= sprintf('<span %s>%s</span>%s', $class, $element_name, $separator);\n }\n $name = $completename;\n }", " $out .= \"<a id='\" . $linkitemtype . \"_\" . $data['id'] . \"_\" .\n $data[$ID][$k]['id'] . \"' href='$page'>\" .\n $name . \"</a>\";\n }\n }\n return $out;", " case \"text\":\n $separate = self::LBBR;\n if (isset($so['splititems']) && $so['splititems']) {\n $separate = self::LBHR;\n }", " $out = '';\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= $separate;\n }\n $count_display++;\n", "\n $plaintext = RichText::getTextFromHtml($data[$ID][$k]['name'], false, true, self::$output_type == self::HTML_OUTPUT);", " if (self::$output_type == self::HTML_OUTPUT && (Toolbox::strlen($plaintext) > $CFG_GLPI['cut'])) {", " $rand = mt_rand();\n $popup_params = [\n 'display' => false,\n 'awesome-class' => 'fa-comments',\n 'autoclose' => false,\n 'onclick' => true,\n ];\n $out .= sprintf(\n __('%1$s %2$s'),\n \"<span id='text$rand'>\" . Html::resume_text($plaintext, $CFG_GLPI['cut']) . '</span>',\n Html::showToolTip(\n '<div class=\"fup-popup\">' . RichText::getEnhancedHtml($data[$ID][$k]['name']) . '</div>',\n $popup_params\n )\n );\n } else {\n $out .= $plaintext;\n }\n }\n }\n return $out;", " case \"date\":\n case \"date_delay\":\n $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n is_null($data[$ID][$k]['name'])\n && isset($so['emptylabel']) && $so['emptylabel']\n ) {\n $out .= (empty($out) ? '' : self::LBBR) . $so['emptylabel'];\n } else {\n $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$ID][$k]['name']);\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"datetime\":\n $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n is_null($data[$ID][$k]['name'])\n && isset($so['emptylabel']) && $so['emptylabel']\n ) {\n $out .= (empty($out) ? '' : self::LBBR) . $so['emptylabel'];\n } else {\n $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$ID][$k]['name']);\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"timestamp\":\n $withseconds = false;\n if (isset($so['withseconds'])) {\n $withseconds = $so['withseconds'];\n }\n $withdays = true;\n if (isset($so['withdays'])) {\n $withdays = $so['withdays'];\n }", " $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n $out .= (empty($out) ? '' : '<br>') . Html::timestampToString(\n $data[$ID][$k]['name'],\n $withseconds,\n $withdays\n );\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"email\":\n $out = '';\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n if (!empty($data[$ID][$k]['name'])) {\n $out .= (empty($out) ? '' : self::LBBR);\n $out .= \"<a href='mailto:\" . Html::entities_deep($data[$ID][$k]['name']) . \"'>\" . $data[$ID][$k]['name'];\n $out .= \"</a>\";\n }\n }\n return (empty($out) ? \"&nbsp;\" : $out);", " case \"weblink\":\n $orig_link = trim((string)$data[$ID][0]['name']);\n if (!empty($orig_link) && Toolbox::isValidWebUrl($orig_link)) {\n // strip begin of link\n $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);\n $link = preg_replace('/\\/$/', '', $link);\n if (Toolbox::strlen($link) > $CFG_GLPI[\"url_maxlength\"]) {\n $link = Toolbox::substr($link, 0, $CFG_GLPI[\"url_maxlength\"]) . \"...\";\n }\n return \"<a href=\\\"\" . Toolbox::formatOutputWebLink($orig_link) . \"\\\" target='_blank'>$link</a>\";\n }\n return \"&nbsp;\";", " case \"count\":\n case \"number\":\n case \"mio\":\n $out = \"\";\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n if (\n isset($so['toadd'])\n && isset($so['toadd'][$data[$ID][$k]['name']])\n ) {\n $out .= $so['toadd'][$data[$ID][$k]['name']];\n } else {\n $out .= Dropdown::getValueWithUnit($data[$ID][$k]['name'], $unit);\n }\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"decimal\":\n $out = \"\";\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n if (\n isset($so['toadd'])\n && isset($so['toadd'][$data[$ID][$k]['name']])\n ) {\n $out .= $so['toadd'][$data[$ID][$k]['name']];\n } else {\n $out .= Dropdown::getValueWithUnit($data[$ID][$k]['name'], $unit, $CFG_GLPI[\"decimal_number\"]);\n }\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"bool\":\n $out = \"\";\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= Dropdown::getYesNo($data[$ID][$k]['name']);\n }\n }\n return $out;", " case \"itemtypename\":\n if ($obj = getItemForItemtype($data[$ID][0]['name'])) {\n return $obj->getTypeName();\n }\n return \"\";", " case \"language\":\n if (isset($CFG_GLPI['languages'][$data[$ID][0]['name']])) {\n return $CFG_GLPI['languages'][$data[$ID][0]['name']][0];\n }\n return __('Default value');\n case 'progressbar':\n if (!isset($progressbar_data)) {\n $bar_color = 'green';\n $percent = ltrim(($data[$ID][0]['name'] ?? \"\"), 0);\n $progressbar_data = [\n 'percent' => $percent,\n 'percent_text' => $percent,\n 'color' => $bar_color,\n 'text' => ''\n ];\n }", " $out = \"\";\n if ($progressbar_data['percent'] !== null) {\n $out = <<<HTML\n <span class='text-nowrap'>\n {$progressbar_data['text']}\n </span>\n <div class=\"progress\" style=\"height: 16px\">\n <div class=\"progress-bar progress-bar-striped\" role=\"progressbar\"\n style=\"width: {$progressbar_data['percent']}%; background-color: {$progressbar_data['color']};\"\n aria-valuenow=\"{$progressbar_data['percent']}\"\n aria-valuemin=\"0\" aria-valuemax=\"100\">\n {$progressbar_data['percent_text']}%\n </div>\n </div>\nHTML;\n }", " return $out;\n break;\n }\n }\n // Manage items with need group by / group_concat\n $out = \"\";\n $count_display = 0;\n $separate = self::LBBR;\n if (isset($so['splititems']) && $so['splititems']) {\n $separate = self::LBHR;\n }\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if ($count_display) {\n $out .= $separate;\n }\n $count_display++;\n // Get specific display if available\n if (isset($table)) {\n $itemtype = getItemTypeForTable($table);\n if ($item = getItemForItemtype($itemtype)) {\n $tmpdata = $data[$ID][$k];\n // Copy name to real field\n $tmpdata[$field] = $data[$ID][$k]['name'] ?? '';", " $specific = $item->getSpecificValueToDisplay(\n $field,\n $tmpdata,\n [\n 'html' => true,\n 'searchopt' => $so,\n 'raw_data' => $data\n ]\n );\n }\n }\n if (!empty($specific)) {\n $out .= $specific;\n } else {\n if (\n isset($so['toadd'])\n && isset($so['toadd'][$data[$ID][$k]['name']])\n ) {\n $out .= $so['toadd'][$data[$ID][$k]['name']];\n } else {\n // Empty is 0 or empty\n if (empty($split[0]) && isset($so['emptylabel'])) {\n $out .= $so['emptylabel'];\n } else {\n // Trans field exists\n if (isset($data[$ID][$k]['trans']) && !empty($data[$ID][$k]['trans'])) {\n $out .= $data[$ID][$k]['trans'];\n } else {\n $value = $data[$ID][$k]['name'];\n $out .= $so['field'] === 'completename'\n ? CommonTreeDropdown::sanitizeSeparatorInCompletename($value)\n : $value;\n }\n }\n }\n }\n }\n return $out;\n }", "\n /**\n * Reset save searches\n *\n * @return void\n **/\n public static function resetSaveSearch()\n {", " unset($_SESSION['glpisearch']);\n $_SESSION['glpisearch'] = [];\n }", "\n /**\n * Completion of the URL $_GET values with the $_SESSION values or define default values\n *\n * @param string $itemtype Item type to manage\n * @param array $params Params to parse\n * @param boolean $usesession Use datas save in session (true by default)\n * @param boolean $forcebookmark Force trying to load parameters from default bookmark:\n * used for global search (false by default)\n *\n * @return array parsed params\n **/\n public static function manageParams(\n $itemtype,\n $params = [],\n $usesession = true,\n $forcebookmark = false\n ) {\n $default_values = [];", " $default_values[\"start\"] = 0;\n $default_values[\"order\"] = \"ASC\";\n $default_values[\"sort\"] = 1;\n $default_values[\"is_deleted\"] = 0;\n $default_values[\"as_map\"] = 0;\n $default_values[\"browse\"] = 0;", " if (isset($params['start'])) {\n $params['start'] = (int)$params['start'];\n }", " $default_values[\"criteria\"] = self::getDefaultCriteria($itemtype);\n $default_values[\"metacriteria\"] = [];", " // Reorg search array\n // start\n // order\n // sort\n // is_deleted\n // itemtype\n // criteria : array (0 => array (link =>\n // field =>\n // searchtype =>\n // value => (contains)\n // metacriteria : array (0 => array (itemtype =>\n // link =>\n // field =>\n // searchtype =>\n // value => (contains)", " if ($itemtype != AllAssets::getType() && class_exists($itemtype)) {\n // retrieve default values for current itemtype\n $itemtype_default_values = [];\n if (method_exists($itemtype, 'getDefaultSearchRequest')) {\n $itemtype_default_values = call_user_func([$itemtype, 'getDefaultSearchRequest']);\n }", " // retrieve default values for the current user\n $user_default_values = SavedSearch_User::getDefault(Session::getLoginUserID(), $itemtype);\n if ($user_default_values === false) {\n $user_default_values = [];\n }", " // we construct default values in this order:\n // - general default\n // - itemtype default\n // - user default\n //\n // The last ones erase values or previous\n // So, we can combine each part (order from itemtype, criteria from user, etc)\n $default_values = array_merge(\n $default_values,\n $itemtype_default_values,\n $user_default_values\n );\n }", " // First view of the page or force bookmark : try to load a bookmark\n if (\n $forcebookmark\n || ($usesession\n && !isset($params[\"reset\"])\n && !isset($_SESSION['glpisearch'][$itemtype]))\n ) {\n $user_default_values = SavedSearch_User::getDefault(Session::getLoginUserID(), $itemtype);\n if ($user_default_values) {\n $_SESSION['glpisearch'][$itemtype] = [];\n // Only get datas for bookmarks\n if ($forcebookmark) {\n $params = $user_default_values;\n } else {\n $bookmark = new SavedSearch();\n $bookmark->load($user_default_values['savedsearches_id'], false);\n }\n }\n }\n // Force reorder criterias\n if (\n isset($params[\"criteria\"])\n && is_array($params[\"criteria\"])\n && count($params[\"criteria\"])\n ) {\n $tmp = $params[\"criteria\"];\n $params[\"criteria\"] = [];\n foreach ($tmp as $val) {\n $params[\"criteria\"][] = $val;\n }\n }", " // transform legacy meta-criteria in criteria (with flag meta=true)\n // at the end of the array, as before there was only at the end of the query\n if (\n isset($params[\"metacriteria\"])\n && is_array($params[\"metacriteria\"])\n ) {\n // as we will append meta to criteria, check the key exists\n if (!isset($params[\"criteria\"])) {\n $params[\"criteria\"] = [];\n }\n foreach ($params[\"metacriteria\"] as $val) {\n $params[\"criteria\"][] = $val + ['meta' => 1];\n }\n $params[\"metacriteria\"] = [];\n }", " if (\n $usesession\n && isset($params[\"reset\"])\n ) {\n if (isset($_SESSION['glpisearch'][$itemtype])) {\n unset($_SESSION['glpisearch'][$itemtype]);\n }\n }", " if (\n isset($params) && is_array($params)\n && $usesession\n ) {\n foreach ($params as $key => $val) {\n $_SESSION['glpisearch'][$itemtype][$key] = $val;\n }\n }", " $saved_params = $params;\n foreach ($default_values as $key => $val) {\n if (!isset($params[$key])) {\n if (\n $usesession\n && ($key == 'is_deleted' || $key == 'as_map' || $key == 'browse' || !isset($saved_params['criteria'])) // retrieve session only if not a new request\n && isset($_SESSION['glpisearch'][$itemtype][$key])\n ) {\n $params[$key] = $_SESSION['glpisearch'][$itemtype][$key];\n } else {\n $params[$key] = $val;\n $_SESSION['glpisearch'][$itemtype][$key] = $val;\n }\n }\n }", " return $params;\n }", "\n /**\n * Clean search options depending of user active profile\n *\n * @param string $itemtype Item type to manage\n * @param integer $action Action which is used to manupulate searchoption\n * (default READ)\n * @param boolean $withplugins Get plugins options (true by default)\n *\n * @return array Clean $SEARCH_OPTION array\n **/\n public static function getCleanedOptions($itemtype, $action = READ, $withplugins = true)\n {\n global $CFG_GLPI;", " $options = &self::getOptions($itemtype, $withplugins);\n $todel = [];", " if (\n !Session::haveRight('infocom', $action)\n && Infocom::canApplyOn($itemtype)\n ) {\n $itemstodel = Infocom::getSearchOptionsToAdd($itemtype);\n $todel = array_merge($todel, array_keys($itemstodel));\n }", " if (\n !Session::haveRight('contract', $action)\n && in_array($itemtype, $CFG_GLPI[\"contract_types\"])\n ) {\n $itemstodel = Contract::getSearchOptionsToAdd();\n $todel = array_merge($todel, array_keys($itemstodel));\n }", " if (\n !Session::haveRight('document', $action)\n && Document::canApplyOn($itemtype)\n ) {\n $itemstodel = Document::getSearchOptionsToAdd();\n $todel = array_merge($todel, array_keys($itemstodel));\n }", " // do not show priority if you don't have right in profile\n if (\n ($itemtype == 'Ticket')\n && ($action == UPDATE)\n && !Session::haveRight('ticket', Ticket::CHANGEPRIORITY)\n ) {\n $todel[] = 3;\n }", " if ($itemtype == 'Computer') {\n if (!Session::haveRight('networking', $action)) {\n $itemstodel = NetworkPort::getSearchOptionsToAdd($itemtype);\n $todel = array_merge($todel, array_keys($itemstodel));\n }\n }\n if (!Session::haveRight(strtolower($itemtype), READNOTE)) {\n $todel[] = 90;\n }", " if (count($todel)) {\n foreach ($todel as $ID) {\n if (isset($options[$ID])) {\n unset($options[$ID]);\n }\n }\n }", " return $options;\n }", "\n /**\n *\n * Get an option number in the SEARCH_OPTION array\n *\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param string $field Name\n *\n * @return integer\n **/\n public static function getOptionNumber($itemtype, $field)\n {", " $table = $itemtype::getTable();\n $opts = &self::getOptions($itemtype);", " foreach ($opts as $num => $opt) {\n if (\n is_array($opt) && isset($opt['table'])\n && ($opt['table'] == $table)\n && ($opt['field'] == $field)\n ) {\n return $num;\n }\n }\n return 0;\n }", "\n /**\n * Get the SEARCH_OPTION array\n *\n * @param string $itemtype Item type\n * @param boolean $withplugins Get search options from plugins (true by default)\n *\n * @return array The reference to the array of search options for the given item type\n **/\n public static function &getOptions($itemtype, $withplugins = true)\n {\n global $CFG_GLPI;", " $item = null;", " if (!isset(self::$search[$itemtype])) {\n // standard type first\n switch ($itemtype) {\n case 'Internet':\n self::$search[$itemtype]['common'] = __('Characteristics');", " self::$search[$itemtype][1]['table'] = 'networkport_types';\n self::$search[$itemtype][1]['field'] = 'name';\n self::$search[$itemtype][1]['name'] = __('Name');\n self::$search[$itemtype][1]['datatype'] = 'itemlink';\n self::$search[$itemtype][1]['searchtype'] = 'contains';", " self::$search[$itemtype][2]['table'] = 'networkport_types';\n self::$search[$itemtype][2]['field'] = 'id';\n self::$search[$itemtype][2]['name'] = __('ID');\n self::$search[$itemtype][2]['searchtype'] = 'contains';", " self::$search[$itemtype][31]['table'] = 'glpi_states';\n self::$search[$itemtype][31]['field'] = 'completename';\n self::$search[$itemtype][31]['name'] = __('Status');", " self::$search[$itemtype] += NetworkPort::getSearchOptionsToAdd('networkport_types');\n break;", " case AllAssets::getType():\n self::$search[$itemtype]['common'] = __('Characteristics');", " self::$search[$itemtype][1]['table'] = 'asset_types';\n self::$search[$itemtype][1]['field'] = 'name';\n self::$search[$itemtype][1]['name'] = __('Name');\n self::$search[$itemtype][1]['datatype'] = 'itemlink';\n self::$search[$itemtype][1]['searchtype'] = 'contains';", " self::$search[$itemtype][2]['table'] = 'asset_types';\n self::$search[$itemtype][2]['field'] = 'id';\n self::$search[$itemtype][2]['name'] = __('ID');\n self::$search[$itemtype][2]['searchtype'] = 'contains';", " self::$search[$itemtype][31]['table'] = 'glpi_states';\n self::$search[$itemtype][31]['field'] = 'completename';\n self::$search[$itemtype][31]['name'] = __('Status');", " self::$search[$itemtype] += Location::getSearchOptionsToAdd();", " self::$search[$itemtype][5]['table'] = 'asset_types';\n self::$search[$itemtype][5]['field'] = 'serial';\n self::$search[$itemtype][5]['name'] = __('Serial number');", " self::$search[$itemtype][6]['table'] = 'asset_types';\n self::$search[$itemtype][6]['field'] = 'otherserial';\n self::$search[$itemtype][6]['name'] = __('Inventory number');", " self::$search[$itemtype][16]['table'] = 'asset_types';\n self::$search[$itemtype][16]['field'] = 'comment';\n self::$search[$itemtype][16]['name'] = __('Comments');\n self::$search[$itemtype][16]['datatype'] = 'text';", " self::$search[$itemtype][70]['table'] = 'glpi_users';\n self::$search[$itemtype][70]['field'] = 'name';\n self::$search[$itemtype][70]['name'] = User::getTypeName(1);", " self::$search[$itemtype][7]['table'] = 'asset_types';\n self::$search[$itemtype][7]['field'] = 'contact';\n self::$search[$itemtype][7]['name'] = __('Alternate username');\n self::$search[$itemtype][7]['datatype'] = 'string';", " self::$search[$itemtype][8]['table'] = 'asset_types';\n self::$search[$itemtype][8]['field'] = 'contact_num';\n self::$search[$itemtype][8]['name'] = __('Alternate username number');\n self::$search[$itemtype][8]['datatype'] = 'string';", " self::$search[$itemtype][71]['table'] = 'glpi_groups';\n self::$search[$itemtype][71]['field'] = 'completename';\n self::$search[$itemtype][71]['name'] = Group::getTypeName(1);", " self::$search[$itemtype][19]['table'] = 'asset_types';\n self::$search[$itemtype][19]['field'] = 'date_mod';\n self::$search[$itemtype][19]['name'] = __('Last update');\n self::$search[$itemtype][19]['datatype'] = 'datetime';\n self::$search[$itemtype][19]['massiveaction'] = false;", " self::$search[$itemtype][23]['table'] = 'glpi_manufacturers';\n self::$search[$itemtype][23]['field'] = 'name';\n self::$search[$itemtype][23]['name'] = Manufacturer::getTypeName(1);", " self::$search[$itemtype][24]['table'] = 'glpi_users';\n self::$search[$itemtype][24]['field'] = 'name';\n self::$search[$itemtype][24]['linkfield'] = 'users_id_tech';\n self::$search[$itemtype][24]['name'] = __('Technician in charge of the hardware');\n self::$search[$itemtype][24]['condition'] = ['is_assign' => 1];", " self::$search[$itemtype][49]['table'] = 'glpi_groups';\n self::$search[$itemtype][49]['field'] = 'completename';\n self::$search[$itemtype][49]['linkfield'] = 'groups_id_tech';\n self::$search[$itemtype][49]['name'] = __('Group in charge of the hardware');\n self::$search[$itemtype][49]['condition'] = ['is_assign' => 1];\n self::$search[$itemtype][49]['datatype'] = 'dropdown';", " self::$search[$itemtype][80]['table'] = 'glpi_entities';\n self::$search[$itemtype][80]['field'] = 'completename';\n self::$search[$itemtype][80]['name'] = Entity::getTypeName(1);\n break;", " default:\n if ($item = getItemForItemtype($itemtype)) {\n self::$search[$itemtype] = $item->searchOptions();\n }\n break;\n }", " if (\n Session::getLoginUserID()\n && in_array($itemtype, $CFG_GLPI[\"ticket_types\"])\n ) {\n self::$search[$itemtype]['tracking'] = __('Assistance');", " self::$search[$itemtype][60]['table'] = 'glpi_tickets';\n self::$search[$itemtype][60]['field'] = 'id';\n self::$search[$itemtype][60]['datatype'] = 'count';\n self::$search[$itemtype][60]['name'] = _x('quantity', 'Number of tickets');\n self::$search[$itemtype][60]['forcegroupby'] = true;\n self::$search[$itemtype][60]['usehaving'] = true;\n self::$search[$itemtype][60]['massiveaction'] = false;\n self::$search[$itemtype][60]['joinparams'] = ['beforejoin'\n => ['table'\n => 'glpi_items_tickets',\n 'joinparams'\n => ['jointype'\n => 'itemtype_item'\n ]\n ],\n 'condition'\n => getEntitiesRestrictRequest(\n 'AND',\n 'NEWTABLE'\n )\n ];", " self::$search[$itemtype][140]['table'] = 'glpi_problems';\n self::$search[$itemtype][140]['field'] = 'id';\n self::$search[$itemtype][140]['datatype'] = 'count';\n self::$search[$itemtype][140]['name'] = _x('quantity', 'Number of problems');\n self::$search[$itemtype][140]['forcegroupby'] = true;\n self::$search[$itemtype][140]['usehaving'] = true;\n self::$search[$itemtype][140]['massiveaction'] = false;\n self::$search[$itemtype][140]['joinparams'] = ['beforejoin'\n => ['table'\n => 'glpi_items_problems',\n 'joinparams'\n => ['jointype'\n => 'itemtype_item'\n ]\n ],\n 'condition'\n => getEntitiesRestrictRequest(\n 'AND',\n 'NEWTABLE'\n )\n ];\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"networkport_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += NetworkPort::getSearchOptionsToAdd($itemtype);\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"contract_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Contract::getSearchOptionsToAdd();\n }", " if (\n Document::canApplyOn($itemtype)\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Document::getSearchOptionsToAdd();\n }", " if (\n Infocom::canApplyOn($itemtype)\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Infocom::getSearchOptionsToAdd($itemtype);\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"domain_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Domain::getSearchOptionsToAdd($itemtype);\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"appliance_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Appliance::getSearchOptionsToAdd($itemtype);\n }", " if (in_array($itemtype, $CFG_GLPI[\"link_types\"])) {\n self::$search[$itemtype]['link'] = Link::getTypeName(Session::getPluralNumber());\n self::$search[$itemtype] += Link::getSearchOptionsToAdd($itemtype);\n self::$search[$itemtype]['manuallink'] = ManualLink::getTypeName(Session::getPluralNumber());\n self::$search[$itemtype] += ManualLink::getSearchOptionsToAdd($itemtype);\n }", " if ($withplugins) {\n // Search options added by plugins\n $plugsearch = Plugin::getAddSearchOptions($itemtype);\n $plugsearch = $plugsearch + Plugin::getAddSearchOptionsNew($itemtype);\n if (count($plugsearch)) {\n self::$search[$itemtype] += ['plugins' => _n('Plugin', 'Plugins', Session::getPluralNumber())];\n self::$search[$itemtype] += $plugsearch;\n }\n }", " // Complete linkfield if not define\n if (is_null($item)) { // Special union type\n $itemtable = $CFG_GLPI['union_search_type'][$itemtype];\n } else {\n if ($item = getItemForItemtype($itemtype)) {\n $itemtable = $item->getTable();\n }\n }", " foreach (self::$search[$itemtype] as $key => $val) {\n if (!is_array($val) || count($val) == 1) {\n // skip sub-menu\n continue;\n }\n // Compatibility before 0.80 : Force massive action to false if linkfield is empty :\n if (isset($val['linkfield']) && empty($val['linkfield'])) {\n self::$search[$itemtype][$key]['massiveaction'] = false;\n }", " // Set default linkfield\n if (!isset($val['linkfield']) || empty($val['linkfield'])) {\n if (\n (strcmp($itemtable, $val['table']) == 0)\n && (!isset($val['joinparams']) || (count($val['joinparams']) == 0))\n ) {\n self::$search[$itemtype][$key]['linkfield'] = $val['field'];\n } else {\n self::$search[$itemtype][$key]['linkfield'] = getForeignKeyFieldForTable($val['table']);\n }\n }\n // Add default joinparams\n if (!isset($val['joinparams'])) {\n self::$search[$itemtype][$key]['joinparams'] = [];\n }\n }\n }", " return self::$search[$itemtype];\n }", " /**\n * Is the search item related to infocoms\n *\n * @param string $itemtype Item type\n * @param integer $searchID ID of the element in $SEARCHOPTION\n *\n * @return boolean\n **/\n public static function isInfocomOption($itemtype, $searchID)\n {\n if (!Infocom::canApplyOn($itemtype)) {\n return false;\n }", " $infocom_options = Infocom::rawSearchOptionsToAdd($itemtype);\n $found_infocoms = array_filter($infocom_options, function ($option) use ($searchID) {\n return isset($option['id']) && $searchID == $option['id'];\n });", " return (count($found_infocoms) > 0);\n }", "\n /**\n * @param string $itemtype\n * @param integer $field_num\n **/\n public static function getActionsFor($itemtype, $field_num)\n {", " $searchopt = &self::getOptions($itemtype);\n $actions = [\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'searchopt' => []\n ];", " if (isset($searchopt[$field_num]) && isset($searchopt[$field_num]['table'])) {\n $actions['searchopt'] = $searchopt[$field_num];", " // Force search type\n if (isset($actions['searchopt']['searchtype'])) {\n // Reset search option\n $actions = [];\n $actions['searchopt'] = $searchopt[$field_num];\n if (!is_array($actions['searchopt']['searchtype'])) {\n $actions['searchopt']['searchtype'] = [$actions['searchopt']['searchtype']];\n }\n foreach ($actions['searchopt']['searchtype'] as $searchtype) {\n switch ($searchtype) {\n case \"equals\":\n $actions['equals'] = __('is');\n break;", " case \"notequals\":\n $actions['notequals'] = __('is not');\n break;", " case \"contains\":\n $actions['contains'] = __('contains');\n $actions['notcontains'] = __('not contains');\n break;", " case \"notcontains\":\n $actions['notcontains'] = __('not contains');\n break;", " case \"under\":\n $actions['under'] = __('under');\n break;", " case \"notunder\":\n $actions['notunder'] = __('not under');\n break;", " case \"lessthan\":\n $actions['lessthan'] = __('before');\n break;", " case \"morethan\":\n $actions['morethan'] = __('after');\n break;\n }\n }\n return $actions;\n }", " if (isset($searchopt[$field_num]['datatype'])) {\n switch ($searchopt[$field_num]['datatype']) {\n case 'mio':\n case 'count':\n case 'number':\n $opt = [\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];\n // No is / isnot if no limits defined\n if (\n !isset($searchopt[$field_num]['min'])\n && !isset($searchopt[$field_num]['max'])\n ) {\n unset($opt['equals']);\n unset($opt['notequals']);", " // https://github.com/glpi-project/glpi/issues/6917\n // change filter wording for numeric values to be more\n // obvious if the number dropdown will not be used\n $opt['contains'] = __('is');\n $opt['notcontains'] = __('is not');\n }\n return $opt;", " case 'bool':\n return [\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'right':\n return ['equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'itemtypename':\n return ['equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'date':\n case 'datetime':\n case 'date_delay':\n return [\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'lessthan' => __('before'),\n 'morethan' => __('after'),\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'searchopt' => $searchopt[$field_num]\n ];\n }\n }", " // switch ($searchopt[$field_num]['table']) {\n // case 'glpi_users_validation' :\n // return array('equals' => __('is'),\n // 'notequals' => __('is not'),\n // 'searchopt' => $searchopt[$field_num]);\n // }", " switch ($searchopt[$field_num]['field']) {\n case 'id':\n return ['equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'name':\n case 'completename':\n $actions = [\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " // Specific case of TreeDropdown : add under\n $itemtype_linked = getItemTypeForTable($searchopt[$field_num]['table']);\n if ($itemlinked = getItemForItemtype($itemtype_linked)) {\n if ($itemlinked instanceof CommonTreeDropdown) {\n $actions['under'] = __('under');\n $actions['notunder'] = __('not under');\n }\n return $actions;\n }\n }\n }\n return $actions;\n }", "\n /**\n * Print generic Header Column\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $value Value to display\n * @param integer &$num Column number\n * @param string $linkto Link display element (HTML specific) (default '')\n * @param boolean|integer $issort Is the sort column ? (default 0)\n * @param string $order Order type ASC or DESC (defaut '')\n * @param string $options Options to add (default '')\n *\n * @return string HTML to display\n **/\n public static function showHeaderItem(\n $type,\n $value,\n &$num,\n $linkto = \"\",\n $issort = 0,\n $order = \"\",\n $options = \"\"\n ) {\n $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE:\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= \"<th $options>\";\n $PDF_TABLE .= htmlspecialchars($value);\n $PDF_TABLE .= \"</th>\";\n break;", " case self::SYLK_OUTPUT: //sylk\n global $SYLK_HEADER,$SYLK_SIZE;\n $SYLK_HEADER[$num] = self::sylk_clean($value);\n $SYLK_SIZE[$num] = Toolbox::strlen($SYLK_HEADER[$num]);\n break;", " case self::CSV_OUTPUT: //CSV\n $out = \"\\\"\" . self::csv_clean($value) . \"\\\"\" . $_SESSION[\"glpicsv_delimiter\"];\n break;", " case self::NAMES_OUTPUT:\n $out = \"\";\n break;", " default:\n $class = \"\";\n if ($issort) {\n $class = \"order_$order\";\n }\n $out = \"<th $options class='$class'>\";\n if (!empty($linkto)) {\n $out .= \"<a href=\\\"$linkto\\\">\";\n }\n $out .= $value;\n if (!empty($linkto)) {\n $out .= \"</a>\";\n }\n $out .= \"</th>\\n\";\n }\n $num++;\n return $out;\n }", "\n /**\n * Print generic normal Item Cell\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $value Value to display\n * @param integer &$num Column number\n * @param integer $row Row number\n * @param string $extraparam Extra parameters for display (default '')\n *\n * @return string HTML to display\n **/\n public static function showItem($type, $value, &$num, $row, $extraparam = '')\n {", " $out = \"\";\n // Handle null values\n if ($value === null) {\n $value = '';\n }", " switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $value = DataExport::normalizeValueForTextExport($value ?? '');\n $value = htmlspecialchars($value);\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $PDF_TABLE .= \"<td $extraparam valign='top'>\";\n $PDF_TABLE .= $value;\n $PDF_TABLE .= \"</td>\";", " break;", " case self::SYLK_OUTPUT: //sylk\n global $SYLK_ARRAY,$SYLK_SIZE;\n $value = DataExport::normalizeValueForTextExport($value);\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $SYLK_ARRAY[$row][$num] = self::sylk_clean($value);\n $SYLK_SIZE[$num] = max(\n $SYLK_SIZE[$num],\n Toolbox::strlen($SYLK_ARRAY[$row][$num])\n );\n break;", " case self::CSV_OUTPUT: //csv\n $value = DataExport::normalizeValueForTextExport($value);\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $out = \"\\\"\" . self::csv_clean($value) . \"\\\"\" . $_SESSION[\"glpicsv_delimiter\"];\n break;", " case self::NAMES_OUTPUT:\n // We only want to display one column (the name of the item).\n // The name field is always the first column expect for tickets\n // which have their ids as the first column instead, thus moving the\n // name to the second column.\n // We don't have access to the itemtype so we must rely on data\n // types to figure which column to use :\n // - Ticket will have a numeric first column (id) and an HTML\n // link containing the name as the second column.\n // - Other items will have an HTML link containing the name as\n // the first column and a simple string containing the entity\n // name as the second column.\n // -> We can check that the column is the first or second AND is html\n if (\n strip_tags($value) !== $value\n && ($num == 1 || $num == 2)\n ) {\n // Use a regex to keep only the link, there may be other content\n // after that we don't need (script, tooltips, ...)\n if (preg_match('/<a.*<\\/a>/', $value, $matches)) {\n $out = html_entity_decode(strip_tags($matches[0]));\n }\n }\n break;", " default:\n global $CFG_GLPI;\n $out = \"<td $extraparam valign='top'>\";", " if (!preg_match('/' . self::LBHR . '/', $value)) {\n $values = preg_split('/' . self::LBBR . '/i', $value);\n $line_delimiter = '<br>';\n } else {\n $values = preg_split('/' . self::LBHR . '/i', $value);\n $line_delimiter = '<hr>';\n }", " if (\n count($values) > 1\n && Toolbox::strlen($value) > $CFG_GLPI['cut']\n ) {\n $value = '';\n foreach ($values as $v) {\n $value .= $v . $line_delimiter;\n }\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $value = '<div class=\"fup-popup\">' . $value . '</div>';\n $valTip = \"&nbsp;\" . Html::showToolTip(\n $value,\n [\n 'awesome-class' => 'fa-comments',\n 'display' => false,\n 'autoclose' => false,\n 'onclick' => true\n ]\n );\n $out .= $values[0] . $valTip;\n } else {\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $out .= $value;\n }\n $out .= \"</td>\\n\";\n }\n $num++;\n return $out;\n }", "\n /**\n * Print generic error\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $message Message to display, if empty \"no item found\" will be displayed\n *\n * @return string HTML to display\n **/\n public static function showError($type, $message = \"\")\n {\n if (strlen($message) == 0) {\n $message = __('No item found');\n }", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n break;", " default:\n $out = \"<div class='center b'>$message</div>\\n\";\n }\n return $out;\n }", "\n /**\n * Print generic footer\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $title title of file : used for PDF (default '')\n * @param integer $count Total number of results\n *\n * @return string HTML to display\n **/\n public static function showFooter($type, $title = \"\", $count = null)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;", " $font = 'helvetica';\n $fontsize = 8;\n if (isset($_SESSION['glpipdffont']) && $_SESSION['glpipdffont']) {\n $font = $_SESSION['glpipdffont'];\n }", " $pdf = new GLPIPDF(\n [\n 'font_size' => $fontsize,\n 'font' => $font,\n 'orientation' => $type == self::PDF_OUTPUT_LANDSCAPE ? 'L' : 'P',\n ],\n $count,\n $title,\n );", " $PDF_TABLE .= '</table>';\n $pdf->writeHTML($PDF_TABLE, true, false, true);\n $pdf->Output('glpi.pdf', 'I');\n break;", " case self::SYLK_OUTPUT: //sylk\n global $SYLK_HEADER,$SYLK_ARRAY,$SYLK_SIZE;\n // largeurs des colonnes\n foreach ($SYLK_SIZE as $num => $val) {\n $out .= \"F;W\" . $num . \" \" . $num . \" \" . min(50, $val) . \"\\n\";\n }\n $out .= \"\\n\";\n // Header\n foreach ($SYLK_HEADER as $num => $val) {\n $out .= \"F;SDM4;FG0C;\" . ($num == 1 ? \"Y1;\" : \"\") . \"X$num\\n\";\n $out .= \"C;N;K\\\"$val\\\"\\n\";\n $out .= \"\\n\";\n }\n // Datas\n foreach ($SYLK_ARRAY as $row => $tab) {\n foreach ($tab as $num => $val) {\n $out .= \"F;P3;FG0L;\" . ($num == 1 ? \"Y\" . $row . \";\" : \"\") . \"X$num\\n\";\n $out .= \"C;N;K\\\"$val\\\"\\n\";\n }\n }\n $out .= \"E\\n\";\n break;", " case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $out = \"</table></div>\\n\";\n }\n return $out;\n }", "\n /**\n * Print generic footer\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param integer $rows Number of rows\n * @param integer $cols Number of columns\n * @param boolean|integer $fixed Used tab_cadre_fixe table for HTML export ? (default 0)\n *\n * @return string HTML to display\n **/\n public static function showHeader($type, $rows, $cols, $fixed = 0)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE = \"<table cellspacing=\\\"0\\\" cellpadding=\\\"1\\\" border=\\\"1\\\" >\";\n break;", " case self::SYLK_OUTPUT: // Sylk\n global $SYLK_ARRAY, $SYLK_HEADER, $SYLK_SIZE;\n $SYLK_ARRAY = [];\n $SYLK_HEADER = [];\n $SYLK_SIZE = [];\n // entetes HTTP\n header(\"Expires: Mon, 26 Nov 1962 00:00:00 GMT\");\n header('Pragma: private'); /// IE BUG + SSL\n header('Cache-control: private, must-revalidate'); /// IE BUG + SSL\n header(\"Content-disposition: filename=glpi.slk\");\n header('Content-type: application/octetstream');\n // entete du fichier\n echo \"ID;PGLPI_EXPORT\\n\"; // ID;Pappli\n echo \"\\n\";\n // formats\n echo \"P;PGeneral\\n\";\n echo \"P;P#,##0.00\\n\"; // P;Pformat_1 (reels)\n echo \"P;P#,##0\\n\"; // P;Pformat_2 (entiers)\n echo \"P;P@\\n\"; // P;Pformat_3 (textes)\n echo \"\\n\";\n // polices\n echo \"P;EArial;M200\\n\";\n echo \"P;EArial;M200\\n\";\n echo \"P;EArial;M200\\n\";\n echo \"P;FArial;M200;SB\\n\";\n echo \"\\n\";\n // nb lignes * nb colonnes\n echo \"B;Y\" . $rows;\n echo \";X\" . $cols . \"\\n\"; // B;Yligmax;Xcolmax\n echo \"\\n\";\n break;", " case self::CSV_OUTPUT: // csv\n header(\"Expires: Mon, 26 Nov 1962 00:00:00 GMT\");\n header('Pragma: private'); /// IE BUG + SSL\n header('Cache-control: private, must-revalidate'); /// IE BUG + SSL\n header(\"Content-disposition: filename=glpi.csv\");\n header('Content-type: text/csv');\n // zero width no break space (for excel)\n echo\"\\xEF\\xBB\\xBF\";\n break;", " case self::NAMES_OUTPUT:\n header(\"Content-disposition: filename=glpi.txt\");\n header('Content-type: file/txt');\n break;", " default:\n if ($fixed) {\n $out = \"<div class='center'><table border='0' class='table'>\";\n } else {\n $out = \"<div class='center'><table border='0' class='table card-table table-hover'>\";\n }\n }\n return $out;\n }", "\n /**\n * Print begin of header part\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n *\n * @since 0.85\n *\n * @return string HTML to display\n **/\n public static function showBeginHeader($type)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= \"<thead>\";\n break;", " case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $out = \"<thead>\";\n }\n return $out;\n }", "\n /**\n * Print end of header part\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n *\n * @since 0.85\n *\n * @return string to display\n **/\n public static function showEndHeader($type)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= \"</thead>\";\n break;", " case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $out = \"</thead>\";\n }\n return $out;\n }", "\n /**\n * Print generic new line\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param boolean $odd Is it a new odd line ? (false by default)\n * @param boolean $is_deleted Is it a deleted search ? (false by default)\n *\n * @return string HTML to display\n **/\n public static function showNewLine($type, $odd = false, $is_deleted = false)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $style = \"\";\n if ($odd) {\n $style = \" style=\\\"background-color:#DDDDDD;\\\" \";\n }\n $PDF_TABLE .= \"<tr $style nobr=\\\"true\\\">\";\n break;", " case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $class = \" class='tab_bg_2\" . ($is_deleted ? '_2' : '') . \"' \";\n if ($odd) {\n $class = \" class='tab_bg_1\" . ($is_deleted ? '_2' : '') . \"' \";\n }\n $out = \"<tr $class>\";\n }\n return $out;\n }", "\n /**\n * Print generic end line\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n *\n * @return string HTML to display\n **/\n public static function showEndLine($type, bool $is_header_line = false)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= '</tr>';\n break;", " case self::SYLK_OUTPUT: //sylk\n break;", " case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n // NAMES_OUTPUT has no output on header lines\n $newline = $type != self::NAMES_OUTPUT || !$is_header_line;\n if ($newline) {\n $out = \"\\n\";\n }\n break;", " default:\n $out = \"</tr>\";\n }\n return $out;\n }", "\n /**\n * @param array $joinparams\n */\n public static function computeComplexJoinID(array $joinparams)\n {", " $complexjoin = '';", " if (isset($joinparams['condition'])) {\n if (!is_array($joinparams['condition'])) {\n $complexjoin .= $joinparams['condition'];\n } else {\n global $DB;\n $dbi = new DBmysqlIterator($DB);\n $sql_clause = $dbi->analyseCrit($joinparams['condition']);\n $complexjoin .= ' AND ' . $sql_clause; //TODO: and should came from conf\n }\n }", " // For jointype == child\n if (\n isset($joinparams['jointype']) && ($joinparams['jointype'] == 'child')\n && isset($joinparams['linkfield'])\n ) {\n $complexjoin .= $joinparams['linkfield'];\n }", " if (isset($joinparams['beforejoin'])) {\n if (isset($joinparams['beforejoin']['table'])) {\n $joinparams['beforejoin'] = [$joinparams['beforejoin']];\n }\n foreach ($joinparams['beforejoin'] as $tab) {\n if (isset($tab['table'])) {\n $complexjoin .= $tab['table'];\n }\n if (isset($tab['joinparams']) && isset($tab['joinparams']['condition'])) {\n if (!is_array($tab['joinparams']['condition'])) {\n $complexjoin .= $tab['joinparams']['condition'];\n } else {\n global $DB;\n $dbi = new DBmysqlIterator($DB);\n $sql_clause = $dbi->analyseCrit($tab['joinparams']['condition']);\n $complexjoin .= ' AND ' . $sql_clause; //TODO: and should came from conf\n }\n }\n }\n }", " if (!empty($complexjoin)) {\n $complexjoin = md5($complexjoin);\n }\n return $complexjoin;\n }", "\n /**\n * Clean display value for csv export\n *\n * @param string $value value\n *\n * @return string Clean value\n **/\n public static function csv_clean($value)\n {", " $value = str_replace(\"\\\"\", \"''\", $value);", " return $value;\n }", "\n /**\n * Clean display value for sylk export\n *\n * @param string $value value\n *\n * @return string Clean value\n **/\n public static function sylk_clean($value)\n {", " $value = preg_replace('/\\x0A/', ' ', $value);\n $value = preg_replace('/\\x0D/', '', $value);\n $value = str_replace(\"\\\"\", \"''\", $value);\n $value = str_replace(\"\\n\", \" | \", $value);", " return $value;\n }", "\n /**\n * Create SQL search condition\n *\n * @param string $field Nname (should be ` protected)\n * @param string $val Value to search\n * @param boolean $not Is a negative search ? (false by default)\n * @param string $link With previous criteria (default 'AND')\n *\n * @return search SQL string\n **/\n public static function makeTextCriteria($field, $val, $not = false, $link = 'AND')\n {", " $sql = $field . self::makeTextSearch($val, $not);\n // mange empty field (string with length = 0)\n $sql_or = \"\";\n if (strtolower($val) == \"null\") {\n $sql_or = \"OR $field = ''\";\n }", " if (\n ($not && ($val != 'NULL') && ($val != 'null') && ($val != '^$')) // Not something\n || (!$not && ($val == '^$'))\n ) { // Empty\n $sql = \"($sql OR $field IS NULL)\";\n }\n return \" $link ($sql $sql_or)\";\n }", " /**\n * Create SQL search value\n *\n * @since 9.4\n *\n * @param string $val value to search\n *\n * @return string|null\n **/\n public static function makeTextSearchValue($val)\n {\n // `$val` will mostly comes from sanitized input, but may also be raw value.\n // 1. Unsanitize value to be sure to use raw value.\n // 2. Escape raw value to protect SQL special chars.\n $val = Sanitizer::dbEscape(Sanitizer::unsanitize($val));", " // escape _ char used as wildcard in mysql likes\n $val = str_replace('_', '\\\\_', $val);", " if ($val === 'NULL' || $val === 'null') {\n return null;\n }", " $val = trim($val);", " if ($val === '^') {\n // Special case, searching \"^\" means we are searching for a non empty/null field\n return '%';\n }", " if ($val === '' || $val === '^$' || $val === '$') {\n return '';\n }", " if (preg_match('/^\\^/', $val)) {\n // Remove leading `^`\n $val = ltrim(preg_replace('/^\\^/', '', $val));\n } else {\n // Add % wildcard before searched string if not begining by a `^`\n $val = '%' . $val;\n }", " if (preg_match('/\\$$/', $val)) {\n // Remove trailing `$`\n $val = rtrim(preg_replace('/\\$$/', '', $val));\n } else {\n // Add % wildcard after searched string if not ending by a `$`\n $val = $val . '%';\n }", " return $val;\n }", "\n /**\n * Create SQL search condition\n *\n * @param string $val Value to search\n * @param boolean $not Is a negative search ? (false by default)\n *\n * @return string Search string\n **/\n public static function makeTextSearch($val, $not = false)\n {", " $NOT = \"\";\n if ($not) {\n $NOT = \"NOT\";\n }", " $val = self::makeTextSearchValue($val);\n if ($val == null) {\n $SEARCH = \" IS $NOT NULL \";\n } else {\n $SEARCH = \" $NOT LIKE \" . DBmysql::quoteValue($val) . \" \";\n }\n return $SEARCH;\n }", "\n /**\n * @since 0.84\n *\n * @param string $pattern\n * @param string $subject\n **/\n public static function explodeWithID($pattern, $subject)\n {", " $tab = explode($pattern, $subject);", " if (isset($tab[1]) && !is_numeric($tab[1])) {\n // Report $ to tab[0]\n if (preg_match('/^(\\\\$*)(.*)/', $tab[1], $matchs)) {\n if (isset($matchs[2]) && is_numeric($matchs[2])) {\n $tab[1] = $matchs[2];\n $tab[0] .= $matchs[1];\n }\n }\n }\n // Manage NULL value\n if ($tab[0] == self::NULLVALUE) {\n $tab[0] = null;\n }\n return $tab;\n }", " /**\n * Add join for dropdown translations\n *\n * @param string $alias Alias for translation table\n * @param string $table Table to join on\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param string $field Field name\n *\n * @return string\n */\n public static function joinDropdownTranslations($alias, $table, $itemtype, $field)\n {\n return \"LEFT JOIN `glpi_dropdowntranslations` AS `$alias`\n ON (`$alias`.`itemtype` = '$itemtype'\n AND `$alias`.`items_id` = `$table`.`id`\n AND `$alias`.`language` = '\" .\n $_SESSION['glpilanguage'] . \"'\n AND `$alias`.`field` = '$field')\";\n }", " /**\n * Get table name for item type\n *\n * @param class-string<CommonDBTM> $itemtype\n *\n * @return string\n */\n public static function getOrigTableName(string $itemtype): string\n {\n return (is_a($itemtype, CommonDBTM::class, true)) ? $itemtype::getTable() : getTableForItemType($itemtype);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [7171], "buggy_code_start_loc": [6308], "filenames": ["src/Search.php"], "fixing_code_end_loc": [7178], "fixing_code_start_loc": [6309], "message": "GLPI stands for Gestionnaire Libre de Parc Informatique and is a Free Asset and IT Management Software package, that provides ITIL Service Desk features, licenses tracking and software auditing. Affected versions were found to not properly neutralize HTML tags in the global search context. Users are advised to upgrade to version 10.0.3 to resolve this issue. Users unable to upgrade should disable global search.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "F1118A51-CFED-4D17-8344-EA94C8F77EAD", "versionEndExcluding": "10.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI stands for Gestionnaire Libre de Parc Informatique and is a Free Asset and IT Management Software package, that provides ITIL Service Desk features, licenses tracking and software auditing. Affected versions were found to not properly neutralize HTML tags in the global search context. Users are advised to upgrade to version 10.0.3 to resolve this issue. Users unable to upgrade should disable global search."}, {"lang": "es", "value": "GLPI son las siglas de Gestionnaire Libre de Parc Informatique y es un Paquete de Software Libre de Administraci\u00f3n de Activos y TI, que proporciona funciones de Service Desk de ITIL, seguimiento de licencias y auditor\u00eda de software. Se ha detectado que las versiones afectadas no neutralizan correctamente las etiquetas HTML en el contexto de la b\u00fasqueda global. Es recomendado a usuarios actualizar a versi\u00f3n 10.0.3 para resolver este problema. Los usuarios que no puedan actualizarse deber\u00e1n deshabilitar la b\u00fasqueda global"}], "evaluatorComment": null, "id": "CVE-2022-31187", "lastModified": "2022-09-19T14:08:43.310", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-09-14T18:15:10.437", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/e248ed5649d267c0f61a17d99b7bd6be4074aadb"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-43j5-xhvj-9236"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/e248ed5649d267c0f61a17d99b7bd6be4074aadb"}, "type": "CWE-79"}
282
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * ---------------------------------------------------------------------\n *\n * GLPI - Gestionnaire Libre de Parc Informatique\n *\n * http://glpi-project.org\n *\n * @copyright 2015-2022 Teclib' and contributors.\n * @copyright 2003-2014 by the INDEPNET Development Team.\n * @licence https://www.gnu.org/licenses/gpl-3.0.html\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n *\n * ---------------------------------------------------------------------\n */", "use Glpi\\Application\\View\\TemplateRenderer;\nuse Glpi\\RichText\\RichText;\nuse Glpi\\Socket;\nuse Glpi\\Toolbox\\DataExport;\nuse Glpi\\Toolbox\\Sanitizer;", "/**\n * Search Class\n *\n * Generic class for Search Engine\n **/\nclass Search\n{\n /**\n * Default number of items displayed in global search\n * @var int\n * @see GLOBAL_SEARCH\n */\n const GLOBAL_DISPLAY_COUNT = 10;", " // EXPORT TYPE\n /**\n * The global search view (Search across many item types).\n * This is NOT the same as the AllAssets view which is just a special itemtype.\n * @var int\n */\n const GLOBAL_SEARCH = -1;", " /**\n * The standard view.\n * This includes the following sub-views:\n * - Table/List\n * - Map\n * - Browse\n * @var int\n */\n const HTML_OUTPUT = 0;", " /**\n * SYLK export format\n * @var int\n */\n const SYLK_OUTPUT = 1;", " /**\n * PDF export format (Landscape mode)\n * @var int\n */\n const PDF_OUTPUT_LANDSCAPE = 2;", " /**\n * CSV export format\n * @var int\n */\n const CSV_OUTPUT = 3;", " /**\n * PDF export format (Portrait mode)\n * @var int\n */\n const PDF_OUTPUT_PORTRAIT = 4;", " /**\n * Names list export format\n * @var int\n */\n const NAMES_OUTPUT = 5;", " /**\n * Placeholder for a <br> line break\n * @var string\n */\n const LBBR = '#LBBR#';", " /**\n * Placeholder for a <hr> line break\n * @var string\n */\n const LBHR = '#LBHR#';", " /**\n * Separator used to separate values of a same element in CONCAT MySQL function.\n *\n * @var string\n * @see LONGSEP\n */\n const SHORTSEP = '$#$';", " /**\n * Separator used to separate each element in GROUP_CONCAT MySQL function.\n *\n * @var string\n * @see SHORTSEP\n */\n const LONGSEP = '$$##$$';", " /**\n * Placeholder for a null value\n * @var string\n */\n const NULLVALUE = '__NULL__';", " /**\n * The output format for the search results\n * @var int\n */\n public static $output_type = self::HTML_OUTPUT;\n public static $search = [];", " /**\n * Display search engine for an type\n *\n * @param string $itemtype Item type to manage\n *\n * @return void\n **/\n public static function show($itemtype)\n {", " $params = self::manageParams($itemtype, $_GET);\n echo \"<div class='search_page row'>\";\n TemplateRenderer::getInstance()->display('layout/parts/saved_searches.html.twig', [\n 'itemtype' => $itemtype,\n ]);\n echo \"<div class='col search-container'>\";", " if (\n $itemtype == \"Ticket\"\n && $default = Glpi\\Dashboard\\Grid::getDefaultDashboardForMenu('mini_ticket', true)\n ) {\n $dashboard = new Glpi\\Dashboard\\Grid($default, 33, 2);\n $dashboard->show(true);\n }", " self::showGenericSearch($itemtype, $params);\n if ($params['as_map'] == 1) {\n self::showMap($itemtype, $params);\n } elseif ($params['browse'] == 1) {\n $itemtype::showBrowseView($itemtype, $params);\n } else {\n self::showList($itemtype, $params);\n }\n echo \"</div>\";\n echo \"</div>\";\n }", "\n /**\n * Display result table for search engine for an type\n *\n * @param class-string<CommonDBTM> $itemtype Item type to manage\n * @param array $params Search params passed to\n * prepareDatasForSearch function\n * @param array $forcedisplay Array of columns to display (default empty\n * = use display pref and search criteria)\n *\n * @return void\n **/\n public static function showList(\n $itemtype,\n $params,\n array $forcedisplay = []\n ) {\n $data = self::getDatas($itemtype, $params, $forcedisplay);", " switch ($data['display_type']) {\n case self::CSV_OUTPUT:\n case self::PDF_OUTPUT_LANDSCAPE:\n case self::PDF_OUTPUT_PORTRAIT:\n case self::SYLK_OUTPUT:\n case self::NAMES_OUTPUT:\n self::outputData($data);\n break;\n case self::GLOBAL_SEARCH:\n case self::HTML_OUTPUT:\n default:\n self::displayData($data);\n break;\n }\n }", " /**\n * Display result table for search engine for an type as a map\n *\n * @param class-string<CommonDBTM> $itemtype Item type to manage\n * @param array $params Search params passed to prepareDatasForSearch function\n *\n * @return void\n **/\n public static function showMap($itemtype, $params)\n {\n global $CFG_GLPI;", " if ($itemtype == 'Location') {\n $latitude = 21;\n $longitude = 20;\n } else if ($itemtype == 'Entity') {\n $latitude = 67;\n $longitude = 68;\n } else {\n $latitude = 998;\n $longitude = 999;\n }", " $params['criteria'][] = [\n 'link' => 'AND NOT',\n 'field' => $latitude,\n 'searchtype' => 'contains',\n 'value' => 'NULL'\n ];\n $params['criteria'][] = [\n 'link' => 'AND NOT',\n 'field' => $longitude,\n 'searchtype' => 'contains',\n 'value' => 'NULL'\n ];", " $data = self::getDatas($itemtype, $params);\n self::displayData($data);", " if ($data['data']['totalcount'] > 0) {\n $target = $data['search']['target'];\n $criteria = $data['search']['criteria'];\n array_pop($criteria);\n array_pop($criteria);\n $criteria[] = [\n 'link' => 'AND',\n 'field' => ($itemtype == 'Location' || $itemtype == 'Entity') ? 1 : (($itemtype == 'Ticket') ? 83 : 3),\n 'searchtype' => 'equals',\n 'value' => 'CURLOCATION'\n ];\n $globallinkto = Toolbox::append_params(\n [\n 'criteria' => Sanitizer::unsanitize($criteria),\n 'metacriteria' => Sanitizer::unsanitize($data['search']['metacriteria'])\n ],\n '&amp;'\n );\n $sort_params = Toolbox::append_params([\n 'sort' => $data['search']['sort'],\n 'order' => $data['search']['order']\n ], '&amp;');\n $parameters = \"as_map=0&amp;\" . $sort_params . '&amp;' .\n $globallinkto;", " if (strpos($target, '?') == false) {\n $fulltarget = $target . \"?\" . $parameters;\n } else {\n $fulltarget = $target . \"&\" . $parameters;\n }\n $typename = class_exists($itemtype) ? $itemtype::getTypeName($data['data']['totalcount']) : $itemtype;", " echo \"<div class='card border-top-0 rounded-0 search-as-map'>\";\n echo \"<div class='card-body px-0' id='map_container'>\";\n echo \"<small class='text-muted p-1'>\" . __('Search results for localized items only') . \"</small>\";\n $js = \"$(function() {\n var map = initMap($('#map_container'), 'map', 'full');\n _loadMap(map, '$itemtype');\n });", " var _loadMap = function(map_elt, itemtype) {\n L.AwesomeMarkers.Icon.prototype.options.prefix = 'far';\n var _micon = 'circle';", " var stdMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'blue'\n });", " var aMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'cadetblue'\n });", " var bMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'purple'\n });", " var cMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'darkpurple'\n });", " var dMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'red'\n });", " var eMarker = L.AwesomeMarkers.icon({\n icon: _micon,\n markerColor: 'darkred'\n });", "\n //retrieve geojson data\n map_elt.spin(true);\n $.ajax({\n dataType: 'json',\n method: 'POST',\n url: '{$CFG_GLPI['root_doc']}/ajax/map.php',\n data: {\n itemtype: itemtype,\n params: \" . json_encode($params) . \"\n }\n }).done(function(data) {\n var _points = data.points;\n var _markers = L.markerClusterGroup({\n iconCreateFunction: function(cluster) {\n var childCount = cluster.getChildCount();", " var markers = cluster.getAllChildMarkers();\n var n = 0;\n for (var i = 0; i < markers.length; i++) {\n n += markers[i].count;\n }", " var c = ' marker-cluster-';\n if (n < 10) {\n c += 'small';\n } else if (n < 100) {\n c += 'medium';\n } else {\n c += 'large';\n }", " return new L.DivIcon({ html: '<div><span>' + n + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });\n }\n });", " $.each(_points, function(index, point) {\n var _title = '<strong>' + point.title + '</strong><br/><a href=\\''+'$fulltarget'.replace(/CURLOCATION/, point.loc_id)+'\\'>\" . sprintf(__('%1$s %2$s'), 'COUNT', $typename) . \"'.replace(/COUNT/, point.count)+'</a>';\n if (point.types) {\n $.each(point.types, function(tindex, type) {\n _title += '<br/>\" . sprintf(__('%1$s %2$s'), 'COUNT', 'TYPE') . \"'.replace(/COUNT/, type.count).replace(/TYPE/, type.name);\n });\n }\n var _icon = stdMarker;\n if (point.count < 10) {\n _icon = stdMarker;\n } else if (point.count < 100) {\n _icon = aMarker;\n } else if (point.count < 1000) {\n _icon = bMarker;\n } else if (point.count < 5000) {\n _icon = cMarker;\n } else if (point.count < 10000) {\n _icon = dMarker;\n } else {\n _icon = eMarker;\n }\n var _marker = L.marker([point.lat, point.lng], { icon: _icon, title: point.title });\n _marker.count = point.count;\n _marker.bindPopup(_title);\n _markers.addLayer(_marker);\n });", " map_elt.addLayer(_markers);\n map_elt.fitBounds(\n _markers.getBounds(), {\n padding: [50, 50],\n maxZoom: 12\n }\n );\n }).fail(function (response) {\n var _data = response.responseJSON;\n var _message = '\" . __s('An error occurred loading data :(') . \"';\n if (_data.message) {\n _message = _data.message;\n }\n var fail_info = L.control();\n fail_info.onAdd = function (map) {\n this._div = L.DomUtil.create('div', 'fail_info');\n this._div.innerHTML = _message + '<br/><span id=\\'reload_data\\'><i class=\\'fa fa-sync\\'></i> \" . __s('Reload') . \"</span>';\n return this._div;\n };\n fail_info.addTo(map_elt);\n $('#reload_data').on('click', function() {\n $('.fail_info').remove();\n _loadMap(map_elt);\n });\n }).always(function() {\n //hide spinner\n map_elt.spin(false);\n });\n }", " \";\n echo Html::scriptBlock($js);\n echo \"</div>\"; // .card-body\n echo \"</div>\"; // .card\n }\n }", "\n /**\n * Get data based on search parameters\n *\n * @since 0.85\n *\n * @param class-string<CommonDBTM> $itemtype Item type to manage\n * @param array $params Search params passed to prepareDatasForSearch function\n * @param array $forcedisplay Array of columns to display (default empty = empty use display pref and search criteria)\n *\n * @return array The data\n **/\n public static function getDatas($itemtype, $params, array $forcedisplay = [])\n {", " $data = self::prepareDatasForSearch($itemtype, $params, $forcedisplay);\n self::constructSQL($data);\n self::constructData($data);", " return $data;\n }", "\n /**\n * Prepare search criteria to be used for a search\n *\n * @since 0.85\n *\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param array $params Array of parameters\n * may include sort, order, start, list_limit, deleted, criteria, metacriteria\n * @param array $forcedisplay Array of columns to display (default empty = empty use display pref and search criterias)\n *\n * @return array prepare to be used for a search (include criteria and others needed information)\n **/\n public static function prepareDatasForSearch($itemtype, array $params, array $forcedisplay = [])\n {\n global $CFG_GLPI;", " // Default values of parameters\n $p['criteria'] = [];\n $p['metacriteria'] = [];\n $p['sort'] = ['1'];\n $p['order'] = ['ASC'];\n $p['start'] = 0;//\n $p['is_deleted'] = 0;\n $p['export_all'] = 0;\n if (class_exists($itemtype)) {\n $p['target'] = $itemtype::getSearchURL();\n } else {\n $p['target'] = Toolbox::getItemTypeSearchURL($itemtype);\n }\n $p['display_type'] = self::HTML_OUTPUT;\n $p['showmassiveactions'] = true;\n $p['dont_flush'] = false;\n $p['show_pager'] = true;\n $p['show_footer'] = true;\n $p['no_sort'] = false;\n $p['list_limit'] = $_SESSION['glpilist_limit'];\n $p['massiveactionparams'] = [];", " foreach ($params as $key => $val) {\n switch ($key) {\n case 'order':\n if (!is_array($val)) {\n // Backward compatibility with GLPI < 10.0 links\n if (in_array($val, ['ASC', 'DESC'])) {\n $p[$key] = [$val];\n }\n break;\n }\n $p[$key] = $val;\n break;\n case 'sort':\n if (!is_array($val)) {\n // Backward compatibility with GLPI < 10.0 links\n $val = (int) $val;\n if ($val >= 0) {\n $p[$key] = [$val];\n }\n break;\n }\n $p[$key] = $val;\n break;\n case 'is_deleted':\n if ($val == 1) {\n $p[$key] = '1';\n }\n break;\n default:\n $p[$key] = $val;\n break;\n }\n }", " // Set display type for export if define\n if (isset($p['display_type'])) {\n // Limit to 10 element\n if ($p['display_type'] == self::GLOBAL_SEARCH) {\n $p['list_limit'] = self::GLOBAL_DISPLAY_COUNT;\n }\n }", " if ($p['export_all']) {\n $p['start'] = 0;\n }", " $data = [];\n $data['search'] = $p;\n $data['itemtype'] = $itemtype;", " // Instanciate an object to access method\n $data['item'] = null;", " if ($itemtype != AllAssets::getType()) {\n $data['item'] = getItemForItemtype($itemtype);\n }", " $data['display_type'] = $data['search']['display_type'];", " if (!$CFG_GLPI['allow_search_all']) {\n foreach ($p['criteria'] as $val) {\n if (isset($val['field']) && $val['field'] == 'all') {\n Html::displayRightError();\n }\n }\n }\n if (!$CFG_GLPI['allow_search_view']) {\n foreach ($p['criteria'] as $val) {\n if (isset($val['field']) && $val['field'] == 'view') {\n Html::displayRightError();\n }\n }\n }", " /// Get the items to display\n // Add searched items", " $forcetoview = false;\n if (is_array($forcedisplay) && count($forcedisplay)) {\n $forcetoview = true;\n }\n $data['search']['all_search'] = false;\n $data['search']['view_search'] = false;\n // If no research limit research to display item and compute number of item using simple request\n $data['search']['no_search'] = true;", " $data['toview'] = self::addDefaultToView($itemtype, $params);\n $data['meta_toview'] = [];\n if (!$forcetoview) {\n // Add items to display depending of personal prefs\n $displaypref = DisplayPreference::getForTypeUser($itemtype, Session::getLoginUserID());\n if (count($displaypref)) {\n foreach ($displaypref as $val) {\n array_push($data['toview'], $val);\n }\n }\n } else {\n $data['toview'] = array_merge($data['toview'], $forcedisplay);\n }", " if (count($p['criteria']) > 0) {\n // use a recursive closure to push searchoption when using nested criteria\n $parse_criteria = function ($criteria) use (&$parse_criteria, &$data) {\n foreach ($criteria as $criterion) {\n // recursive call\n if (isset($criterion['criteria'])) {\n $parse_criteria($criterion['criteria']);\n } else {\n // normal behavior\n if (\n isset($criterion['field'])\n && !in_array($criterion['field'], $data['toview'])\n ) {\n if (\n $criterion['field'] != 'all'\n && $criterion['field'] != 'view'\n && (!isset($criterion['meta'])\n || !$criterion['meta'])\n ) {\n array_push($data['toview'], $criterion['field']);\n } else if ($criterion['field'] == 'all') {\n $data['search']['all_search'] = true;\n } else if ($criterion['field'] == 'view') {\n $data['search']['view_search'] = true;\n }\n }", " if (\n isset($criterion['value'])\n && (strlen($criterion['value']) > 0)\n ) {\n $data['search']['no_search'] = false;\n }\n }\n }\n };", " // call the closure\n $parse_criteria($p['criteria']);\n }", " if (count($p['metacriteria'])) {\n $data['search']['no_search'] = false;\n }", " // Add order item\n $to_add_view = array_diff($p['sort'], $data['toview']);\n array_push($data['toview'], ...$to_add_view);", " // Special case for CommonITILObjects : put ID in front\n if (is_a($itemtype, CommonITILObject::class, true)) {\n array_unshift($data['toview'], 2);\n }", " $limitsearchopt = self::getCleanedOptions($itemtype);\n // Clean and reorder toview\n $tmpview = [];\n foreach ($data['toview'] as $val) {\n if (isset($limitsearchopt[$val]) && !in_array($val, $tmpview)) {\n $tmpview[] = $val;\n }\n }\n $data['toview'] = $tmpview;\n $data['tocompute'] = $data['toview'];", " // Force item to display\n if ($forcetoview) {\n foreach ($data['toview'] as $val) {\n if (!in_array($val, $data['tocompute'])) {\n array_push($data['tocompute'], $val);\n }\n }\n }", " return $data;\n }", "\n /**\n * Construct SQL request depending of search parameters\n *\n * Add to data array a field sql containing an array of requests :\n * search : request to get items limited to wanted ones\n * count : to count all items based on search criterias\n * may be an array a request : need to add counts\n * maybe empty : use search one to count\n *\n * @since 0.85\n *\n * @param array $data Array of search datas prepared to generate SQL\n *\n * @return void|false May return false if the search request data is invalid\n **/\n public static function constructSQL(array &$data)\n {\n global $DB, $CFG_GLPI;", " if (!isset($data['itemtype'])) {\n return false;\n }", " $data['sql']['count'] = [];\n $data['sql']['search'] = '';", " $searchopt = &self::getOptions($data['itemtype']);", " $blacklist_tables = [];\n $orig_table = self::getOrigTableName($data['itemtype']);\n if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {\n $itemtable = $CFG_GLPI['union_search_type'][$data['itemtype']];\n $blacklist_tables[] = $orig_table;\n } else {\n $itemtable = $orig_table;\n }", " // hack for AllAssets and ReservationItem\n if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {\n $entity_restrict = true;\n } else {\n $entity_restrict = $data['item']->isEntityAssign() && $data['item']->isField('entities_id');\n }", " // Construct the request", " //// 1 - SELECT\n // request currentuser for SQL supervision, not displayed\n $SELECT = \"SELECT DISTINCT `$itemtable`.`id` AS id, '\" . Toolbox::addslashes_deep($_SESSION['glpiname']) . \"' AS currentuser,\n \" . self::addDefaultSelect($data['itemtype']);", " // Add select for all toview item\n foreach ($data['toview'] as $val) {\n $SELECT .= self::addSelect($data['itemtype'], $val);\n }", " if (isset($data['search']['as_map']) && $data['search']['as_map'] == 1 && $data['itemtype'] != 'Entity') {\n $SELECT .= ' `glpi_locations`.`id` AS loc_id, ';\n }", " //// 2 - FROM AND LEFT JOIN\n // Set reference table\n $FROM = \" FROM `$itemtable`\";", " // Init already linked tables array in order not to link a table several times\n $already_link_tables = [];\n // Put reference table\n array_push($already_link_tables, $itemtable);", " // Add default join\n $COMMONLEFTJOIN = self::addDefaultJoin($data['itemtype'], $itemtable, $already_link_tables);\n $FROM .= $COMMONLEFTJOIN;", " // Add all table for toview items\n foreach ($data['tocompute'] as $val) {\n if (!in_array($searchopt[$val][\"table\"], $blacklist_tables)) {\n $FROM .= self::addLeftJoin(\n $data['itemtype'],\n $itemtable,\n $already_link_tables,\n $searchopt[$val][\"table\"],\n $searchopt[$val][\"linkfield\"],\n 0,\n 0,\n $searchopt[$val][\"joinparams\"],\n $searchopt[$val][\"field\"]\n );\n }\n }", " // Search all case :\n if ($data['search']['all_search']) {\n foreach ($searchopt as $key => $val) {\n // Do not search on Group Name\n if (is_array($val) && isset($val['table'])) {\n if (!in_array($searchopt[$key][\"table\"], $blacklist_tables)) {\n $FROM .= self::addLeftJoin(\n $data['itemtype'],\n $itemtable,\n $already_link_tables,\n $searchopt[$key][\"table\"],\n $searchopt[$key][\"linkfield\"],\n 0,\n 0,\n $searchopt[$key][\"joinparams\"],\n $searchopt[$key][\"field\"]\n );\n }\n }\n }\n }", " //// 3 - WHERE", " // default string\n $COMMONWHERE = self::addDefaultWhere($data['itemtype']);\n $first = empty($COMMONWHERE);", " // Add deleted if item have it\n if ($data['item'] && $data['item']->maybeDeleted()) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" \";\n $first = false;\n }\n $COMMONWHERE .= $LINK . \"`$itemtable`.`is_deleted` = \" . (int)$data['search']['is_deleted'] . \" \";\n }", " // Remove template items\n if ($data['item'] && $data['item']->maybeTemplate()) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" \";\n $first = false;\n }\n $COMMONWHERE .= $LINK . \"`$itemtable`.`is_template` = 0 \";\n }", " // Add Restrict to current entities\n if ($entity_restrict) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" \";\n $first = false;\n }", " if ($data['itemtype'] == 'Entity') {\n $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable);\n } else if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n // Will be replace below in Union/Recursivity Hack\n $COMMONWHERE .= $LINK . \" ENTITYRESTRICT \";\n } else {\n $COMMONWHERE .= getEntitiesRestrictRequest(\n $LINK,\n $itemtable,\n '',\n '',\n $data['item']->maybeRecursive() && $data['item']->isField('is_recursive')\n );\n }\n }\n $WHERE = \"\";\n $HAVING = \"\";", " // Add search conditions\n // If there is search items\n if (count($data['search']['criteria'])) {\n $WHERE = self::constructCriteriaSQL($data['search']['criteria'], $data, $searchopt);\n $HAVING = self::constructCriteriaSQL($data['search']['criteria'], $data, $searchopt, true);", " // if criteria (with meta flag) need additional join/from sql\n self::constructAdditionalSqlForMetacriteria($data['search']['criteria'], $SELECT, $FROM, $already_link_tables, $data);\n }", " //// 4 - ORDER\n $ORDER = \" ORDER BY `id` \";\n $sort_fields = [];\n $sort_count = count($data['search']['sort']);\n for ($i = 0; $i < $sort_count; $i++) {\n foreach ($data['tocompute'] as $val) {\n if ($data['search']['sort'][$i] == $val) {\n $sort_fields[] = [\n 'searchopt_id' => $data['search']['sort'][$i],\n 'order' => $data['search']['order'][$i] ?? null\n ];\n }\n }\n }\n if (count($sort_fields)) {\n $ORDER = self::addOrderBy($data['itemtype'], $sort_fields);\n }", " $SELECT = rtrim(trim($SELECT), ',');", " //// 7 - Manage GROUP BY\n $GROUPBY = \"\";\n // Meta Search / Search All / Count tickets\n $criteria_with_meta = array_filter($data['search']['criteria'], function ($criterion) {\n return isset($criterion['meta'])\n && $criterion['meta'];\n });\n if (\n (count($data['search']['metacriteria']))\n || count($criteria_with_meta)\n || !empty($HAVING)\n || $data['search']['all_search']\n ) {\n $GROUPBY = \" GROUP BY `$itemtable`.`id`\";\n }", " if (empty($GROUPBY)) {\n foreach ($data['toview'] as $val2) {\n if (!empty($GROUPBY)) {\n break;\n }\n if (isset($searchopt[$val2][\"forcegroupby\"])) {\n $GROUPBY = \" GROUP BY `$itemtable`.`id`\";\n }\n }\n }", " $LIMIT = \"\";\n $numrows = 0;\n //No search : count number of items using a simple count(ID) request and LIMIT search\n if ($data['search']['no_search']) {\n $LIMIT = \" LIMIT \" . (int)$data['search']['start'] . \", \" . (int)$data['search']['list_limit'];", " $count = \"count(DISTINCT `$itemtable`.`id`)\";\n // request currentuser for SQL supervision, not displayed\n $query_num = \"SELECT $count,\n '\" . Toolbox::addslashes_deep($_SESSION['glpiname']) . \"' AS currentuser\n FROM `$itemtable`\" .\n $COMMONLEFTJOIN;", " $first = true;", " if (!empty($COMMONWHERE)) {\n $LINK = \" AND \";\n if ($first) {\n $LINK = \" WHERE \";\n $first = false;\n }\n $query_num .= $LINK . $COMMONWHERE;\n }\n // Union Search :\n if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n $tmpquery = $query_num;", " foreach ($CFG_GLPI[$CFG_GLPI[\"union_search_type\"][$data['itemtype']]] as $ctype) {\n $ctable = $ctype::getTable();\n if (\n ($citem = getItemForItemtype($ctype))\n && $citem->canView()\n ) {\n // State case\n if ($data['itemtype'] == AllAssets::getType()) {\n $query_num = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $tmpquery\n );\n $query_num = str_replace($data['itemtype'], $ctype, $query_num);\n $query_num .= \" AND `$ctable`.`id` IS NOT NULL \";", " // Add deleted if item have it\n if ($citem && $citem->maybeDeleted()) {\n $query_num .= \" AND `$ctable`.`is_deleted` = 0 \";\n }", " // Remove template items\n if ($citem && $citem->maybeTemplate()) {\n $query_num .= \" AND `$ctable`.`is_template` = 0 \";\n }\n } else {// Ref table case\n $reftable = $data['itemtype']::getTable();\n if ($data['item'] && $data['item']->maybeDeleted()) {\n $tmpquery = str_replace(\n \"`\" . $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`.\n `is_deleted`\",\n \"`$reftable`.`is_deleted`\",\n $tmpquery\n );\n }\n $replace = \"FROM `$reftable`\n INNER JOIN `$ctable`\n ON (`$reftable`.`items_id` =`$ctable`.`id`\n AND `$reftable`.`itemtype` = '$ctype')\";", " $query_num = str_replace(\n \"FROM `\" .\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`\",\n $replace,\n $tmpquery\n );\n $query_num = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $query_num\n );\n }\n $query_num = str_replace(\n \"ENTITYRESTRICT\",\n getEntitiesRestrictRequest(\n '',\n $ctable,\n '',\n '',\n $citem->maybeRecursive()\n ),\n $query_num\n );\n $data['sql']['count'][] = $query_num;\n }\n }\n } else {\n $data['sql']['count'][] = $query_num;\n }\n }", " // If export_all reset LIMIT condition\n if ($data['search']['export_all']) {\n $LIMIT = \"\";\n }", " if (!empty($WHERE) || !empty($COMMONWHERE)) {\n if (!empty($COMMONWHERE)) {\n $WHERE = ' WHERE ' . $COMMONWHERE . (!empty($WHERE) ? ' AND ( ' . $WHERE . ' )' : '');\n } else {\n $WHERE = ' WHERE ' . $WHERE . ' ';\n }\n $first = false;\n }", " if (!empty($HAVING)) {\n $HAVING = ' HAVING ' . $HAVING;\n }", " // Create QUERY\n if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n $first = true;\n $QUERY = \"\";\n foreach ($CFG_GLPI[$CFG_GLPI[\"union_search_type\"][$data['itemtype']]] as $ctype) {\n $ctable = $ctype::getTable();\n if (\n ($citem = getItemForItemtype($ctype))\n && $citem->canView()\n ) {\n if ($first) {\n $first = false;\n } else {\n $QUERY .= \" UNION \";\n }\n $tmpquery = \"\";\n // AllAssets case\n if ($data['itemtype'] == AllAssets::getType()) {\n $tmpquery = $SELECT . \", '$ctype' AS TYPE \" .\n $FROM .\n $WHERE;", " $tmpquery .= \" AND `$ctable`.`id` IS NOT NULL \";", " // Add deleted if item have it\n if ($citem && $citem->maybeDeleted()) {\n $tmpquery .= \" AND `$ctable`.`is_deleted` = 0 \";\n }", " // Remove template items\n if ($citem && $citem->maybeTemplate()) {\n $tmpquery .= \" AND `$ctable`.`is_template` = 0 \";\n }", " $tmpquery .= $GROUPBY .\n $HAVING;", " // Replace 'asset_types' by itemtype table name\n $tmpquery = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $tmpquery\n );\n // Replace 'AllAssets' by itemtype\n // Use quoted value to prevent replacement of AllAssets in column identifiers\n $tmpquery = str_replace(\n $DB->quoteValue(AllAssets::getType()),\n $DB->quoteValue($ctype),\n $tmpquery\n );\n } else {// Ref table case\n $reftable = $data['itemtype']::getTable();", " $tmpquery = $SELECT . \", '$ctype' AS TYPE,\n `$reftable`.`id` AS refID, \" . \"\n `$ctable`.`entities_id` AS ENTITY \" .\n $FROM .\n $WHERE;\n if ($data['item']->maybeDeleted()) {\n $tmpquery = str_replace(\n \"`\" . $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`.\n `is_deleted`\",\n \"`$reftable`.`is_deleted`\",\n $tmpquery\n );\n }", " $replace = \"FROM `$reftable`\" . \"\n INNER JOIN `$ctable`\" . \"\n ON (`$reftable`.`items_id`=`$ctable`.`id`\" . \"\n AND `$reftable`.`itemtype` = '$ctype')\";\n $tmpquery = str_replace(\n \"FROM `\" .\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \"`\",\n $replace,\n $tmpquery\n );\n $tmpquery = str_replace(\n $CFG_GLPI[\"union_search_type\"][$data['itemtype']],\n $ctable,\n $tmpquery\n );\n $name_field = $ctype::getNameField();\n $tmpquery = str_replace(\"`$ctable`.`name`\", \"`$ctable`.`$name_field`\", $tmpquery);\n }\n $tmpquery = str_replace(\n \"ENTITYRESTRICT\",\n getEntitiesRestrictRequest(\n '',\n $ctable,\n '',\n '',\n $citem->maybeRecursive()\n ),\n $tmpquery\n );", " // SOFTWARE HACK\n if ($ctype == 'Software') {\n $tmpquery = str_replace(\"`glpi_softwares`.`serial`\", \"''\", $tmpquery);\n $tmpquery = str_replace(\"`glpi_softwares`.`otherserial`\", \"''\", $tmpquery);\n }\n $QUERY .= $tmpquery;\n }\n }\n if (empty($QUERY)) {\n echo self::showError($data['display_type']);\n return;\n }\n $QUERY .= str_replace($CFG_GLPI[\"union_search_type\"][$data['itemtype']] . \".\", \"\", $ORDER) .\n $LIMIT;\n } else {\n $QUERY = $SELECT .\n $FROM .\n $WHERE .\n $GROUPBY .\n $HAVING .\n $ORDER .\n $LIMIT;\n }\n $data['sql']['search'] = $QUERY;\n }", " /**\n * Construct WHERE (or HAVING) part of the sql based on passed criteria\n *\n * @since 9.4\n *\n * @param array $criteria list of search criterion, we should have these keys:\n * - link (optionnal): AND, OR, NOT AND, NOT OR\n * - field: id of the searchoption\n * - searchtype: how to match value (contains, equals, etc)\n * - value\n * @param array $data common array used by search engine,\n * contains all the search part (sql, criteria, params, itemtype etc)\n * TODO: should be a property of the class\n * @param array $searchopt Search options for the current itemtype\n * @param boolean $is_having Do we construct sql WHERE or HAVING part\n *\n * @return string the sql sub string\n */\n public static function constructCriteriaSQL($criteria = [], $data = [], $searchopt = [], $is_having = false)\n {\n $sql = \"\";", " foreach ($criteria as $criterion) {\n if (\n !isset($criterion['criteria'])\n && (!isset($criterion['value'])\n || strlen($criterion['value']) <= 0)\n ) {\n continue;\n }", " $itemtype = $data['itemtype'];\n $meta = false;\n if (\n isset($criterion['meta'])\n && $criterion['meta']\n && isset($criterion['itemtype'])\n ) {\n $itemtype = $criterion['itemtype'];\n $meta = true;\n $meta_searchopt = &self::getOptions($itemtype);\n } else {\n // Not a meta, use the same search option everywhere\n $meta_searchopt = $searchopt;\n }", " // common search\n if (\n !isset($criterion['field'])\n || ($criterion['field'] != \"all\"\n && $criterion['field'] != \"view\")\n ) {\n $LINK = \" \";\n $NOT = 0;\n $tmplink = \"\";", " if (\n isset($criterion['link'])\n && in_array($criterion['link'], array_keys(self::getLogicalOperators()))\n ) {\n if (strstr($criterion['link'], \"NOT\")) {\n $tmplink = \" \" . str_replace(\" NOT\", \"\", $criterion['link']);\n $NOT = 1;\n } else {\n $tmplink = \" \" . $criterion['link'];\n }\n } else {\n $tmplink = \" AND \";\n }", " // Manage Link if not first item\n if (!empty($sql)) {\n $LINK = $tmplink;\n }", " if (isset($criterion['criteria']) && count($criterion['criteria'])) {\n $sub_sql = self::constructCriteriaSQL($criterion['criteria'], $data, $meta_searchopt, $is_having);\n if (strlen($sub_sql)) {\n if ($NOT) {\n $sql .= \"$LINK NOT($sub_sql)\";\n } else {\n $sql .= \"$LINK ($sub_sql)\";\n }\n }\n } else if (\n isset($meta_searchopt[$criterion['field']][\"usehaving\"])\n || ($meta && \"AND NOT\" === $criterion['link'])\n ) {\n if (!$is_having) {\n // the having part will be managed in a second pass\n continue;\n }", " $new_having = self::addHaving(\n $LINK,\n $NOT,\n $itemtype,\n $criterion['field'],\n $criterion['searchtype'],\n $criterion['value']\n );\n if ($new_having !== false) {\n $sql .= $new_having;\n }\n } else {\n if ($is_having) {\n // the having part has been already managed in the first pass\n continue;\n }", " $new_where = self::addWhere(\n $LINK,\n $NOT,\n $itemtype,\n $criterion['field'],\n $criterion['searchtype'],\n $criterion['value'],\n $meta\n );\n if ($new_where !== false) {\n $sql .= $new_where;\n }\n }\n } else if (\n isset($criterion['value'])\n && strlen($criterion['value']) > 0\n ) { // view and all search\n $LINK = \" OR \";\n $NOT = 0;\n $globallink = \" AND \";\n if (isset($criterion['link'])) {\n switch ($criterion['link']) {\n case \"AND\":\n $LINK = \" OR \";\n $globallink = \" AND \";\n break;\n case \"AND NOT\":\n $LINK = \" AND \";\n $NOT = 1;\n $globallink = \" AND \";\n break;\n case \"OR\":\n $LINK = \" OR \";\n $globallink = \" OR \";\n break;\n case \"OR NOT\":\n $LINK = \" AND \";\n $NOT = 1;\n $globallink = \" OR \";\n break;\n }\n } else {\n $tmplink = \" AND \";\n }\n // Manage Link if not first item\n if (!empty($sql) && !$is_having) {\n $sql .= $globallink;\n }\n $first2 = true;\n $items = [];\n if (isset($criterion['field']) && $criterion['field'] == \"all\") {\n $items = $searchopt;\n } else { // toview case : populate toview\n foreach ($data['toview'] as $key2 => $val2) {\n $items[$val2] = $searchopt[$val2];\n }\n }\n $view_sql = \"\";\n foreach ($items as $key2 => $val2) {\n if (isset($val2['nosearch']) && $val2['nosearch']) {\n continue;\n }\n if (is_array($val2)) {\n // Add Where clause if not to be done in HAVING CLAUSE\n if (!$is_having && !isset($val2[\"usehaving\"])) {\n $tmplink = $LINK;\n if ($first2) {\n $tmplink = \" \";\n }", " $new_where = self::addWhere(\n $tmplink,\n $NOT,\n $itemtype,\n $key2,\n $criterion['searchtype'],\n $criterion['value'],\n $meta\n );\n if ($new_where !== false) {\n $first2 = false;\n $view_sql .= $new_where;\n }\n }\n }\n }\n if (strlen($view_sql)) {\n $sql .= \" ($view_sql) \";\n }\n }\n }\n return $sql;\n }", " /**\n * Construct aditionnal SQL (select, joins, etc) for meta-criteria\n *\n * @since 9.4\n *\n * @param array $criteria list of search criterion\n * @param string &$SELECT TODO: should be a class property (output parameter)\n * @param string &$FROM TODO: should be a class property (output parameter)\n * @param array &$already_link_tables TODO: should be a class property (output parameter)\n * @param array &$data TODO: should be a class property (output parameter)\n *\n * @return void\n */\n public static function constructAdditionalSqlForMetacriteria(\n $criteria = [],\n &$SELECT = \"\",\n &$FROM = \"\",\n &$already_link_tables = [],\n &$data = []\n ) {\n $data['meta_toview'] = [];\n foreach ($criteria as $criterion) {\n // manage sub criteria\n if (isset($criterion['criteria'])) {\n self::constructAdditionalSqlForMetacriteria(\n $criterion['criteria'],\n $SELECT,\n $FROM,\n $already_link_tables,\n $data\n );\n continue;\n }", " // parse only criterion with meta flag\n if (\n !isset($criterion['itemtype'])\n || empty($criterion['itemtype'])\n || !isset($criterion['meta'])\n || !$criterion['meta']\n || !isset($criterion['value'])\n || strlen($criterion['value']) <= 0\n ) {\n continue;\n }", " $m_itemtype = $criterion['itemtype'];\n $metaopt = &self::getOptions($m_itemtype);\n $sopt = $metaopt[$criterion['field']];", " //add toview for meta criterion\n $data['meta_toview'][$m_itemtype][] = $criterion['field'];", " $SELECT .= self::addSelect(\n $m_itemtype,\n $criterion['field'],\n true, // meta-criterion\n $m_itemtype\n );", " $FROM .= self::addMetaLeftJoin(\n $data['itemtype'],\n $m_itemtype,\n $already_link_tables,\n $sopt[\"joinparams\"]\n );", " $FROM .= self::addLeftJoin(\n $m_itemtype,\n $m_itemtype::getTable(),\n $already_link_tables,\n $sopt[\"table\"],\n $sopt[\"linkfield\"],\n 1,\n $m_itemtype,\n $sopt[\"joinparams\"],\n $sopt[\"field\"]\n );\n }\n }", "\n /**\n * Retrieve datas from DB : construct data array containing columns definitions and rows datas\n *\n * add to data array a field data containing :\n * cols : columns definition\n * rows : rows data\n *\n * @since 0.85\n *\n * @param array $data array of search data prepared to get data\n * @param boolean $onlycount If we just want to count results\n *\n * @return void|false May return false if the SQL data in $data is not valid\n **/\n public static function constructData(array &$data, $onlycount = false)\n {\n if (!isset($data['sql']) || !isset($data['sql']['search'])) {\n return false;\n }\n $data['data'] = [];", " // Use a ReadOnly connection if available and configured to be used\n $DBread = DBConnection::getReadConnection();\n $DBread->query(\"SET SESSION group_concat_max_len = 8194304;\");", " $DBread->execution_time = true;\n $result = $DBread->query($data['sql']['search']);", " if ($result) {\n $data['data']['execution_time'] = $DBread->execution_time;\n if (isset($data['search']['savedsearches_id'])) {\n SavedSearch::updateExecutionTime(\n (int)$data['search']['savedsearches_id'],\n $DBread->execution_time\n );\n }", " $data['data']['totalcount'] = 0;\n // if real search or complete export : get numrows from request\n if (\n !$data['search']['no_search']\n || $data['search']['export_all']\n ) {\n $data['data']['totalcount'] = $DBread->numrows($result);\n } else {\n if (\n !isset($data['sql']['count'])\n || (count($data['sql']['count']) == 0)\n ) {\n $data['data']['totalcount'] = $DBread->numrows($result);\n } else {\n foreach ($data['sql']['count'] as $sqlcount) {\n $result_num = $DBread->query($sqlcount);\n $data['data']['totalcount'] += $DBread->result($result_num, 0, 0);\n }\n }\n }", " if ($onlycount) {\n //we just want to coutn results; no need to continue process\n return;\n }", " if ($data['search']['start'] > $data['data']['totalcount']) {\n $data['search']['start'] = 0;\n }", " // Search case\n $data['data']['begin'] = $data['search']['start'];\n $data['data']['end'] = min(\n $data['data']['totalcount'],\n $data['search']['start'] + $data['search']['list_limit']\n ) - 1;\n //map case\n if (isset($data['search']['as_map']) && $data['search']['as_map'] == 1) {\n $data['data']['end'] = $data['data']['totalcount'] - 1;\n }", " // No search Case\n if ($data['search']['no_search']) {\n $data['data']['begin'] = 0;\n $data['data']['end'] = min(\n $data['data']['totalcount'] - $data['search']['start'],\n $data['search']['list_limit']\n ) - 1;\n }\n // Export All case\n if ($data['search']['export_all']) {\n $data['data']['begin'] = 0;\n $data['data']['end'] = $data['data']['totalcount'] - 1;\n }", " // Get columns\n $data['data']['cols'] = [];", " $searchopt = &self::getOptions($data['itemtype']);", " foreach ($data['toview'] as $opt_id) {\n $data['data']['cols'][] = [\n 'itemtype' => $data['itemtype'],\n 'id' => $opt_id,\n 'name' => $searchopt[$opt_id][\"name\"],\n 'meta' => 0,\n 'searchopt' => $searchopt[$opt_id],\n ];\n }", " // manage toview column for criteria with meta flag\n foreach ($data['meta_toview'] as $m_itemtype => $toview) {\n $searchopt = &self::getOptions($m_itemtype);\n foreach ($toview as $opt_id) {\n $data['data']['cols'][] = [\n 'itemtype' => $m_itemtype,\n 'id' => $opt_id,\n 'name' => $searchopt[$opt_id][\"name\"],\n 'meta' => 1,\n 'searchopt' => $searchopt[$opt_id],\n ];\n }\n }", " // Display columns Headers for meta items\n $already_printed = [];", " if (count($data['search']['metacriteria'])) {\n foreach ($data['search']['metacriteria'] as $metacriteria) {\n if (\n isset($metacriteria['itemtype']) && !empty($metacriteria['itemtype'])\n && isset($metacriteria['value']) && (strlen($metacriteria['value']) > 0)\n ) {\n if (!isset($already_printed[$metacriteria['itemtype'] . $metacriteria['field']])) {\n $searchopt = &self::getOptions($metacriteria['itemtype']);", " $data['data']['cols'][] = [\n 'itemtype' => $metacriteria['itemtype'],\n 'id' => $metacriteria['field'],\n 'name' => $searchopt[$metacriteria['field']][\"name\"],\n 'meta' => 1,\n 'searchopt' => $searchopt[$metacriteria['field']]\n ];", " $already_printed[$metacriteria['itemtype'] . $metacriteria['field']] = 1;\n }\n }\n }\n }", " // search group (corresponding of dropdown optgroup) of current col\n foreach ($data['data']['cols'] as $num => $col) {\n // search current col in searchoptions ()\n while (\n key($searchopt) !== null\n && key($searchopt) != $col['id']\n ) {\n next($searchopt);\n }\n if (key($searchopt) !== null) {\n //search optgroup (non array option)\n while (\n key($searchopt) !== null\n && is_numeric(key($searchopt))\n && is_array(current($searchopt))\n ) {\n prev($searchopt);\n }\n if (\n key($searchopt) !== null\n && key($searchopt) !== \"common\"\n ) {\n $data['data']['cols'][$num]['groupname'] = current($searchopt);\n }\n }\n //reset\n reset($searchopt);\n }", " // Get rows", " // if real search seek to begin of items to display (because of complete search)\n if (!$data['search']['no_search']) {\n $DBread->dataSeek($result, $data['search']['start']);\n }", " $i = $data['data']['begin'];\n $data['data']['warning']\n = \"For compatibility keep raw data (ITEM_X, META_X) at the top for the moment. Will be drop in next version\";", " $data['data']['rows'] = [];\n $data['data']['items'] = [];", " self::$output_type = $data['display_type'];", " while (($i < $data['data']['totalcount']) && ($i <= $data['data']['end'])) {\n $row = $DBread->fetchAssoc($result);\n $newrow = [];\n $newrow['raw'] = $row;", " // Parse datas\n foreach ($newrow['raw'] as $key => $val) {\n if (preg_match('/ITEM(_(\\w[^\\d]+))?_(\\d+)(_(.+))?/', $key, $matches)) {\n $j = $matches[3];\n if (isset($matches[2]) && !empty($matches[2])) {\n $j = $matches[2] . '_' . $matches[3];\n }\n $fieldname = 'name';\n if (isset($matches[5])) {\n $fieldname = $matches[5];\n }", " // No Group_concat case\n if ($fieldname == 'content' || !is_string($val) || strpos($val, self::LONGSEP) === false) {\n $newrow[$j]['count'] = 1;", " $handled = false;\n if ($fieldname != 'content' && is_string($val) && strpos($val, self::SHORTSEP) !== false) {\n $split2 = self::explodeWithID(self::SHORTSEP, $val);\n if (is_numeric($split2[1])) {\n $newrow[$j][0][$fieldname] = $split2[0];\n $newrow[$j][0]['id'] = $split2[1];\n $handled = true;\n }\n }", " if (!$handled) {\n if ($val === self::NULLVALUE) {\n $newrow[$j][0][$fieldname] = null;\n } else {\n $newrow[$j][0][$fieldname] = $val;\n }\n }\n } else {\n if (!isset($newrow[$j])) {\n $newrow[$j] = [];\n }\n $split = explode(self::LONGSEP, $val);\n $newrow[$j]['count'] = count($split);\n foreach ($split as $key2 => $val2) {\n $handled = false;\n if (strpos($val2, self::SHORTSEP) !== false) {\n $split2 = self::explodeWithID(self::SHORTSEP, $val2);\n if (is_numeric($split2[1])) {\n $newrow[$j][$key2]['id'] = $split2[1];\n if ($split2[0] == self::NULLVALUE) {\n $newrow[$j][$key2][$fieldname] = null;\n } else {\n $newrow[$j][$key2][$fieldname] = $split2[0];\n }\n $handled = true;\n }\n }", " if (!$handled) {\n $newrow[$j][$key2][$fieldname] = $val2;\n }\n }\n }\n } else {\n if ($key == 'currentuser') {\n if (!isset($data['data']['currentuser'])) {\n $data['data']['currentuser'] = $val;\n }\n } else {\n $newrow[$key] = $val;\n // Add id to items list\n if ($key == 'id') {\n $data['data']['items'][$val] = $i;\n }\n }\n }\n }\n foreach ($data['data']['cols'] as $val) {\n $newrow[$val['itemtype'] . '_' . $val['id']]['displayname'] = self::giveItem(\n $val['itemtype'],\n $val['id'],\n $newrow\n );\n }", " $data['data']['rows'][$i] = $newrow;\n $i++;\n }", " $data['data']['count'] = count($data['data']['rows']);\n } else {\n $error_no = $DBread->errno();\n if ($error_no == 1116) { // Too many tables; MySQL can only use 61 tables in a join\n echo self::showError(\n $data['search']['display_type'],\n __(\"'All' criterion is not usable with this object list, \" .\n \"sql query fails (too many tables). \" .\n \"Please use 'Items seen' criterion instead\")\n );\n } else {\n echo $DBread->error();\n }\n }\n }", "\n /**\n * Display datas extracted from DB\n *\n * @param array $data Array of search datas prepared to get datas\n *\n * @return void\n **/\n public static function displayData(array $data)\n {\n global $CFG_GLPI;", " if (!isset($data['data']) || !isset($data['data']['totalcount'])) {\n return false;\n }", " $search = $data['search'];\n $itemtype = $data['itemtype'];\n $item = $data['item'];\n $is_deleted = $search['is_deleted'];", " foreach ($search['criteria'] as $key => $criteria) {\n if (isset($criteria['virtual']) && $criteria['virtual']) {\n unset($search['criteria'][$key]);\n }\n }", " // Contruct parameters\n $globallinkto = Toolbox::append_params([\n 'criteria' => Sanitizer::unsanitize($search['criteria']),\n 'metacriteria' => Sanitizer::unsanitize($search['metacriteria'])\n ], '&');", " $parameters = http_build_query([\n 'sort' => $search['sort'],\n 'order' => $search['order']\n ]);", " $parameters .= \"&{$globallinkto}\";", " if (isset($_GET['_in_modal'])) {\n $parameters .= \"&_in_modal=1\";\n }", " // For plugin add new parameter if available\n if ($plug = isPluginItemType($data['itemtype'])) {\n $out = Plugin::doOneHook($plug['plugin'], 'addParamFordynamicReport', $data['itemtype']);\n if (is_array($out) && count($out)) {\n $parameters .= Toolbox::append_params($out, '&');\n }\n }", " $prehref = $search['target'] . (strpos($search['target'], \"?\") !== false ? \"&\" : \"?\");\n $href = $prehref . $parameters;", " Session::initNavigateListItems($data['itemtype'], '', $href);", " TemplateRenderer::getInstance()->display('components/search/display_data.html.twig', [\n 'data' => $data,\n 'union_search_type' => $CFG_GLPI[\"union_search_type\"],\n 'rand' => mt_rand(),\n 'no_sort' => $search['no_sort'] ?? false,\n 'order' => $search['order'] ?? [],\n 'sort' => $search['sort'] ?? [],\n 'start' => $search['start'] ?? 0,\n 'limit' => $_SESSION['glpilist_limit'],\n 'count' => $data['data']['totalcount'] ?? 0,\n 'item' => $item,\n 'itemtype' => $itemtype,\n 'href' => $href,\n 'prehref' => $prehref,\n 'posthref' => $globallinkto,\n 'showmassiveactions' => ($search['showmassiveactions'] ?? true)\n && $data['display_type'] != self::GLOBAL_SEARCH\n && ($itemtype == AllAssets::getType()\n || count(MassiveAction::getAllMassiveActions($item, $is_deleted))\n ),\n 'massiveactionparams' => $data['search']['massiveactionparams'] + [\n 'is_deleted' => $is_deleted,\n 'container' => \"massform$itemtype\",\n ],\n 'can_config' => Session::haveRightsOr('search_config', [\n DisplayPreference::PERSONAL,\n DisplayPreference::GENERAL\n ]),\n 'may_be_deleted' => $item instanceof CommonDBTM && $item->maybeDeleted(),\n 'may_be_located' => $item instanceof CommonDBTM && $item->maybeLocated(),\n 'may_be_browsed' => $item !== null && Toolbox::hasTrait($item, \\Glpi\\Features\\TreeBrowse::class),\n ]);", " // Add items in item list\n foreach ($data['data']['rows'] as $row) {\n if ($itemtype !== AllAssets::class) {\n Session::addToNavigateListItems($itemtype, $row[\"id\"]);\n } else {\n // In case of a global search, reset and empty navigation list to ensure navigation in\n // item header context is not shown. Indeed, this list does not support navigation through\n // multiple itemtypes, so it should not be displayed in global search context.\n Session::initNavigateListItems($row['TYPE'] ?? $data['itemtype']);\n }\n }", " // Clean previous selection\n $_SESSION['glpimassiveactionselected'] = [];\n }", " /**\n * Output data (for export in CSV, PDF, ...).\n *\n * @param array $data Array of search datas prepared to get datas\n *\n * @return void\n **/\n public static function outputData(array $data)\n {\n global $CFG_GLPI;", " if (\n !isset($data['data'])\n || !isset($data['data']['totalcount'])\n || $data['data']['count'] <= 0\n || $data['search']['as_map'] != 0\n ) {\n return false;\n }", " // Define begin and end var for loop\n // Search case\n $begin_display = $data['data']['begin'];\n $end_display = $data['data']['end'];", " // Compute number of columns to display\n // Add toview elements\n $nbcols = count($data['data']['cols']);", " // Display List Header\n echo self::showHeader($data['display_type'], $end_display - $begin_display + 1, $nbcols);", " // New Line for Header Items Line\n $headers_line = '';\n $headers_line_top = '';", " $headers_line_top .= self::showBeginHeader($data['display_type']);\n $headers_line_top .= self::showNewLine($data['display_type']);", " $header_num = 1;", " // Display column Headers for toview items\n $metanames = [];\n foreach ($data['data']['cols'] as $val) {\n $name = $val[\"name\"];", " // prefix by group name (corresponding to optgroup in dropdown) if exists\n if (isset($val['groupname'])) {\n $groupname = $val['groupname'];\n if (is_array($groupname)) {\n //since 9.2, getSearchOptions has been changed\n $groupname = $groupname['name'];\n }\n $name = \"$groupname - $name\";\n }", " // Not main itemtype add itemtype to display\n if ($data['itemtype'] != $val['itemtype']) {\n if (!isset($metanames[$val['itemtype']])) {\n if ($metaitem = getItemForItemtype($val['itemtype'])) {\n $metanames[$val['itemtype']] = $metaitem->getTypeName();\n }\n }\n $name = sprintf(\n __('%1$s - %2$s'),\n $metanames[$val['itemtype']],\n $val[\"name\"]\n );\n }", " $headers_line .= self::showHeaderItem(\n $data['display_type'],\n $name,\n $header_num,\n '',\n (!$val['meta']\n && ($data['search']['sort'] == $val['id'])),\n $data['search']['order']\n );\n }", " // Add specific column Header\n if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n $headers_line .= self::showHeaderItem(\n $data['display_type'],\n __('Item type'),\n $header_num\n );\n }\n // End Line for column headers\n $headers_line .= self::showEndLine($data['display_type'], true);", " $headers_line_top .= $headers_line;\n $headers_line_top .= self::showEndHeader($data['display_type']);", " echo $headers_line_top;", " // Num of the row (1=header_line)\n $row_num = 1;", " $typenames = [];\n // Display Loop\n foreach ($data['data']['rows'] as $row) {\n // Column num\n $item_num = 1;\n $row_num++;\n // New line\n echo self::showNewLine(\n $data['display_type'],\n ($row_num % 2),\n $data['search']['is_deleted']\n );", " // Print other toview items\n foreach ($data['data']['cols'] as $col) {\n $colkey = \"{$col['itemtype']}_{$col['id']}\";\n if (!$col['meta']) {\n echo self::showItem(\n $data['display_type'],\n $row[$colkey]['displayname'],\n $item_num,\n $row_num,\n self::displayConfigItem(\n $data['itemtype'],\n $col['id'],\n $row,\n $colkey\n )\n );\n } else { // META case\n echo self::showItem(\n $data['display_type'],\n $row[$colkey]['displayname'],\n $item_num,\n $row_num\n );\n }\n }", " if (isset($CFG_GLPI[\"union_search_type\"][$data['itemtype']])) {\n if (!isset($typenames[$row[\"TYPE\"]])) {\n if ($itemtmp = getItemForItemtype($row[\"TYPE\"])) {\n $typenames[$row[\"TYPE\"]] = $itemtmp->getTypeName();\n }\n }\n echo self::showItem(\n $data['display_type'],\n $typenames[$row[\"TYPE\"]],\n $item_num,\n $row_num\n );\n }\n // End Line\n echo self::showEndLine($data['display_type']);\n }", " // Create title\n $title = '';\n if (\n ($data['display_type'] == self::PDF_OUTPUT_LANDSCAPE)\n || ($data['display_type'] == self::PDF_OUTPUT_PORTRAIT)\n ) {\n $title = self::computeTitle($data);\n }", " // Display footer (close table)\n echo self::showFooter($data['display_type'], $title, $data['data']['count']);\n }", "\n /**\n * Compute title (use case of PDF OUTPUT)\n *\n * @param array $data Array data of search\n *\n * @return string Title\n **/\n public static function computeTitle($data)\n {\n $title = \"\";", " if (count($data['search']['criteria'])) {\n //Drop the first link as it is not needed, or convert to clean link (AND NOT -> NOT)\n if (isset($data['search']['criteria']['0']['link'])) {\n $notpos = strpos($data['search']['criteria']['0']['link'], 'NOT');\n //If link was like '%NOT%' just use NOT. Otherwise remove the link\n if ($notpos > 0) {\n $data['search']['criteria']['0']['link'] = 'NOT';\n } else if (!$notpos) {\n unset($data['search']['criteria']['0']['link']);\n }\n }", " foreach ($data['search']['criteria'] as $criteria) {\n if (isset($criteria['itemtype'])) {\n $searchopt = &self::getOptions($criteria['itemtype']);\n } else {\n $searchopt = &self::getOptions($data['itemtype']);\n }\n $titlecontain = '';", " if (isset($criteria['criteria'])) {\n //This is a group criteria, call computeTitle again and concat\n $newdata = $data;\n $oldlink = $criteria['link'];\n $newdata['search'] = $criteria;\n $titlecontain = sprintf(\n __('%1$s %2$s (%3$s)'),\n $titlecontain,\n $oldlink,\n Search::computeTitle($newdata)\n );\n } else {\n if (strlen($criteria['value']) > 0) {\n if (isset($criteria['link'])) {\n $titlecontain = \" \" . $criteria['link'] . \" \";\n }\n $gdname = '';\n $valuename = '';", " switch ($criteria['field']) {\n case \"all\":\n $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, __('All'));\n break;", " case \"view\":\n $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, __('Items seen'));\n break;", " default:\n if (isset($criteria['meta']) && $criteria['meta']) {\n $searchoptname = sprintf(\n __('%1$s / %2$s'),\n $criteria['itemtype'],\n $searchopt[$criteria['field']][\"name\"]\n );\n } else {\n $searchoptname = $searchopt[$criteria['field']][\"name\"];\n }", " $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, $searchoptname);\n $itemtype = getItemTypeForTable($searchopt[$criteria['field']][\"table\"]);\n $valuename = '';\n if ($item = getItemForItemtype($itemtype)) {\n $valuename = $item->getValueToDisplay(\n $searchopt[$criteria['field']],\n $criteria['value']\n );\n }", " $gdname = Dropdown::getDropdownName(\n $searchopt[$criteria['field']][\"table\"],\n $criteria['value']\n );\n }", " if (empty($valuename)) {\n $valuename = $criteria['value'];\n }\n switch ($criteria['searchtype']) {\n case \"equals\":\n if (\n in_array(\n $searchopt[$criteria['field']][\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $gdname);\n } else {\n $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $valuename);\n }\n break;", " case \"notequals\":\n if (\n in_array(\n $searchopt[$criteria['field']][\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain = sprintf(__('%1$s <> %2$s'), $titlecontain, $gdname);\n } else {\n $titlecontain = sprintf(__('%1$s <> %2$s'), $titlecontain, $valuename);\n }\n break;", " case \"lessthan\":\n $titlecontain = sprintf(__('%1$s < %2$s'), $titlecontain, $valuename);\n break;", " case \"morethan\":\n $titlecontain = sprintf(__('%1$s > %2$s'), $titlecontain, $valuename);\n break;", " case \"contains\":\n $titlecontain = sprintf(\n __('%1$s = %2$s'),\n $titlecontain,\n '%' . $valuename . '%'\n );\n break;", " case \"notcontains\":\n $titlecontain = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain,\n '%' . $valuename . '%'\n );\n break;", " case \"under\":\n $titlecontain = sprintf(\n __('%1$s %2$s'),\n $titlecontain,\n sprintf(__('%1$s %2$s'), __('under'), $gdname)\n );\n break;", " case \"notunder\":\n $titlecontain = sprintf(\n __('%1$s %2$s'),\n $titlecontain,\n sprintf(__('%1$s %2$s'), __('not under'), $gdname)\n );\n break;", " default:\n $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $valuename);\n break;\n }\n }\n }\n $title .= $titlecontain;\n }\n }\n if (\n isset($data['search']['metacriteria']) &&\n count($data['search']['metacriteria'])\n ) {\n $metanames = [];\n foreach ($data['search']['metacriteria'] as $metacriteria) {\n $searchopt = &self::getOptions($metacriteria['itemtype']);\n if (!isset($metanames[$metacriteria['itemtype']])) {\n if ($metaitem = getItemForItemtype($metacriteria['itemtype'])) {\n $metanames[$metacriteria['itemtype']] = $metaitem->getTypeName();\n }\n }", " $titlecontain2 = '';\n if (strlen($metacriteria['value']) > 0) {\n if (isset($metacriteria['link'])) {\n $titlecontain2 = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n $metacriteria['link']\n );\n }\n $titlecontain2\n = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n sprintf(\n __('%1$s / %2$s'),\n $metanames[$metacriteria['itemtype']],\n $searchopt[$metacriteria['field']][\"name\"]\n )\n );", " $gdname2 = Dropdown::getDropdownName(\n $searchopt[$metacriteria['field']][\"table\"],\n $metacriteria['value']\n );\n switch ($metacriteria['searchtype']) {\n case \"equals\":\n if (\n in_array(\n $searchopt[$metacriteria['link']]\n [\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n $gdname2\n );\n } else {\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n }\n break;", " case \"notequals\":\n if (\n in_array(\n $searchopt[$metacriteria['link']][\"field\"],\n ['name', 'completename']\n )\n ) {\n $titlecontain2 = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain2,\n $gdname2\n );\n } else {\n $titlecontain2 = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n }\n break;", " case \"lessthan\":\n $titlecontain2 = sprintf(\n __('%1$s < %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n break;", " case \"morethan\":\n $titlecontain2 = sprintf(\n __('%1$s > %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n break;", " case \"contains\":\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n '%' . $metacriteria['value'] . '%'\n );\n break;", " case \"notcontains\":\n $titlecontain2 = sprintf(\n __('%1$s <> %2$s'),\n $titlecontain2,\n '%' . $metacriteria['value'] . '%'\n );\n break;", " case \"under\":\n $titlecontain2 = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n sprintf(\n __('%1$s %2$s'),\n __('under'),\n $gdname2\n )\n );\n break;", " case \"notunder\":\n $titlecontain2 = sprintf(\n __('%1$s %2$s'),\n $titlecontain2,\n sprintf(\n __('%1$s %2$s'),\n __('not under'),\n $gdname2\n )\n );\n break;", " default:\n $titlecontain2 = sprintf(\n __('%1$s = %2$s'),\n $titlecontain2,\n $metacriteria['value']\n );\n break;\n }\n }\n $title .= $titlecontain2;\n }\n }\n return $title;\n }", " /**\n * Get meta types available for search engine\n *\n * @param class-string<CommonDBTM> $itemtype Type to display the form\n *\n * @return array Array of available itemtype\n **/\n public static function getMetaItemtypeAvailable($itemtype)\n {\n global $CFG_GLPI;", " $itemtype = self::getMetaReferenceItemtype($itemtype);", " if (!(($item = getItemForItemtype($itemtype)) instanceof CommonDBTM)) {\n return [];\n }", " $linked = [];\n foreach ($CFG_GLPI as $key => $values) {\n if ($key === 'link_types') {\n // Links are associated to all items of a type, it does not make any sense to use them in meta search\n continue;\n }\n if ($key === 'ticket_types' && $item instanceof CommonITILObject) {\n // Linked are filtered by CommonITILObject::getAllTypesForHelpdesk()\n $linked = array_merge($linked, array_keys($item::getAllTypesForHelpdesk()));\n continue;\n }", " foreach (self::getMetaParentItemtypesForTypesConfig($key) as $config_itemtype) {\n if ($itemtype === $config_itemtype::getType()) {\n // List is related to source itemtype, all types of list are so linked\n $linked = array_merge($linked, $values);\n } else if (in_array($itemtype, $values)) {\n // Source itemtype is inside list, type corresponding to list is so linked\n $linked[] = $config_itemtype::getType();\n }\n }\n }", " return array_unique($linked);\n }", " /**\n * Returns parents itemtypes having subitems defined in given config key.\n * This list is filtered and is only valid in a \"meta\" search context.\n *\n * @param string $config_key\n *\n * @return string[]\n */\n private static function getMetaParentItemtypesForTypesConfig(string $config_key): array\n {\n $matches = [];\n if (preg_match('/^(.+)_types$/', $config_key, $matches) === 0) {\n return [];\n }", " $key_to_itemtypes = [\n 'directconnect_types' => ['Computer'],\n 'infocom_types' => ['Budget', 'Infocom'],\n 'linkgroup_types' => ['Group'],\n // 'linkgroup_tech_types' => ['Group'], // Cannot handle ambiguity with 'Group' from 'linkgroup_types'\n 'linkuser_types' => ['User'],\n // 'linkuser_tech_types' => ['User'], // Cannot handle ambiguity with 'User' from 'linkuser_types'\n 'project_asset_types' => ['Project'],\n 'rackable_types' => ['Enclosure', 'Rack'],\n 'socket_types' => [Socket::class],\n 'ticket_types' => ['Change', 'Problem', 'Ticket'],\n ];", " if (array_key_exists($config_key, $key_to_itemtypes)) {\n return $key_to_itemtypes[$config_key];\n }", " $itemclass = $matches[1];\n if (is_a($itemclass, CommonDBTM::class, true)) {\n return [$itemclass::getType()];\n }", " return [];\n }", " /**\n * Check if an itemtype is a possible subitem of another itemtype in a \"meta\" search context.\n *\n * @param string $parent_itemtype\n * @param string $child_itemtype\n *\n * @return boolean\n */\n private static function isPossibleMetaSubitemOf(string $parent_itemtype, string $child_itemtype)\n {\n global $CFG_GLPI;", " if (\n is_a($parent_itemtype, CommonITILObject::class, true)\n && in_array($child_itemtype, array_keys($parent_itemtype::getAllTypesForHelpdesk()))\n ) {\n return true;\n }", " foreach ($CFG_GLPI as $key => $values) {\n if (\n in_array($parent_itemtype, self::getMetaParentItemtypesForTypesConfig($key))\n && in_array($child_itemtype, $values)\n ) {\n return true;\n }\n }", " return false;\n }", " /**\n * Gets the class to use if the specified itemtype extends one of the known reference types.\n *\n * @param class-string<CommonDBTM> $itemtype\n *\n * @return string|false The reference class name. If the provided itemtype is from a plugin, the provided itemtype is returned.\n * If the itemtype is not from a plugin and not exactly or extended from a reference itemtype, false will be returned.\n * @since 0.85\n */\n public static function getMetaReferenceItemtype($itemtype)\n {", " if (!isPluginItemType($itemtype)) {\n return $itemtype;\n }", " // Use reference type if given itemtype extends a reference type.\n $types = [\n 'Computer',\n 'Problem',\n 'Change',\n 'Ticket',\n 'Printer',\n 'Monitor',\n 'Peripheral',\n 'Software',\n 'Phone'\n ];\n foreach ($types as $type) {\n if (is_a($itemtype, $type, true)) {\n return $type;\n }\n }", " return false;\n }", "\n /**\n * Get dropdown options of logical operators.\n * @return string[]|array<string, string>\n * @since 0.85\n **/\n public static function getLogicalOperators($only_not = false)\n {\n if ($only_not) {\n return [\n 'AND' => Dropdown::EMPTY_VALUE,\n 'AND NOT' => __(\"NOT\")\n ];\n }", " return [\n 'AND' => __('AND'),\n 'OR' => __('OR'),\n 'AND NOT' => __('AND NOT'),\n 'OR NOT' => __('OR NOT')\n ];\n }", "\n /**\n * Print generic search form\n *\n * Params need to parsed before using Search::manageParams function\n *\n * @param class-string<CommonDBTM> $itemtype Type to display the form\n * @param array $params Array of parameters may include sort, is_deleted, criteria, metacriteria\n *\n * @return void\n **/\n public static function showGenericSearch($itemtype, array $params)\n {\n global $CFG_GLPI;", " // Default values of parameters\n $p['sort'] = '';\n $p['is_deleted'] = 0;\n $p['as_map'] = 0;\n $p['browse'] = 0;\n $p['criteria'] = [];\n $p['metacriteria'] = [];\n if (class_exists($itemtype)) {\n $p['target'] = $itemtype::getSearchURL();\n } else {\n $p['target'] = Toolbox::getItemTypeSearchURL($itemtype);\n }\n $p['showreset'] = true;\n $p['showbookmark'] = true;\n $p['showfolding'] = true;\n $p['mainform'] = true;\n $p['prefix_crit'] = '';\n $p['addhidden'] = [];\n $p['actionname'] = 'search';\n $p['actionvalue'] = _sx('button', 'Search');", " foreach ($params as $key => $val) {\n $p[$key] = $val;\n }", " // Itemtype name used in JS function names, etc\n $normalized_itemtype = strtolower(str_replace('\\\\', '', $itemtype));\n $rand_criteria = mt_rand();\n $main_block_class = '';\n $card_class = 'search-form card card-sm mb-4';\n if ($p['mainform']) {\n echo \"<form name='searchform$normalized_itemtype' class='search-form-container' method='get' action='\" . $p['target'] . \"'>\";\n } else {\n $main_block_class = \"sub_criteria\";\n $card_class = 'border d-inline-block ms-1';\n }\n $display = $_SESSION['glpifold_search'] ? 'style=\"display: none;\"' : '';\n echo \"<div class='$card_class' $display>\";", " echo \"<div id='searchcriteria$rand_criteria' class='$main_block_class' >\";\n $nbsearchcountvar = 'nbcriteria' . $normalized_itemtype . mt_rand();\n $searchcriteriatableid = 'criteriatable' . $normalized_itemtype . mt_rand();\n // init criteria count\n echo Html::scriptBlock(\"\n var $nbsearchcountvar = \" . count($p['criteria']) . \";\n \");", " echo \"<div class='list-group list-group-flush list-group-hoverable criteria-list pt-2' id='$searchcriteriatableid'>\";", " // Display normal search parameters\n $i = 0;\n foreach (array_keys($p['criteria']) as $i) {\n self::displayCriteria([\n 'itemtype' => $itemtype,\n 'num' => $i,\n 'p' => $p\n ]);\n }", " echo \"<a id='more-criteria$rand_criteria' role='button'\n class='normalcriteria fold-search list-group-item p-2 border-0'\n style='display: none;'></a>\";", " echo \"</div>\"; // .list", " // Keep track of the current savedsearches on reload\n if (isset($_GET['savedsearches_id'])) {\n echo Html::input(\"savedsearches_id\", [\n 'type' => \"hidden\",\n 'value' => $_GET['savedsearches_id'],\n ]);\n }", " echo \"<div class='card-footer d-flex search_actions'>\";\n $linked = self::getMetaItemtypeAvailable($itemtype);\n echo \"<button id='addsearchcriteria$rand_criteria' class='btn btn-sm btn-outline-secondary me-1' type='button'>\n <i class='ti ti-square-plus'></i>\n <span class='d-none d-sm-block'>\" . __s('rule') . \"</span>\n </button>\";\n if (count($linked)) {\n echo \"<button id='addmetasearchcriteria$rand_criteria' class='btn btn-sm btn-outline-secondary me-1' type='button'>\n <i class='ti ti-circle-plus'></i>\n <span class='d-none d-sm-block'>\" . __s('global rule') . \"</span>\n </button>\";\n }\n echo \"<button id='addcriteriagroup$rand_criteria' class='btn btn-sm btn-outline-secondary me-1' type='button'>\n <i class='ti ti-code-plus'></i>\n <span class='d-none d-sm-block'>\" . __s('group') . \"</span>\n </button>\";\n $json_p = json_encode($p);", " if ($p['mainform']) {\n // Display submit button\n echo \"<button class='btn btn-sm btn-primary me-1' type='submit' name='\" . $p['actionname'] . \"'>\n <i class='ti ti-list-search'></i>\n <span class='d-none d-sm-block'>\" . $p['actionvalue'] . \"</span>\n </button>\";\n if ($p['showbookmark'] || $p['showreset']) {\n if ($p['showbookmark']) {\n SavedSearch::showSaveButton(\n SavedSearch::SEARCH,\n $itemtype,\n isset($_GET['savedsearches_id'])\n );\n }", " if ($p['showreset']) {\n echo \"<a class='btn btn-ghost-secondary btn-icon btn-sm me-1 search-reset'\n data-bs-toggle='tooltip' data-bs-placement='bottom'\n href='\"\n . $p['target']\n . (strpos($p['target'], '?') ? '&amp;' : '?')\n . \"reset=reset' title=\\\"\" . __s('Blank') . \"\\\"\n ><i class='ti ti-circle-x'></i></a>\";\n }\n }\n }\n echo \"</div>\"; //.search_actions", " // idor checks\n $idor_display_criteria = Session::getNewIDORToken($itemtype);\n $idor_display_meta_criteria = Session::getNewIDORToken($itemtype);\n $idor_display_criteria_group = Session::getNewIDORToken($itemtype);", " $itemtype_escaped = addslashes($itemtype);\n $JS = <<<JAVASCRIPT\n $('#addsearchcriteria$rand_criteria').on('click', function(event) {\n event.preventDefault();\n $.post('{$CFG_GLPI['root_doc']}/ajax/search.php', {\n 'action': 'display_criteria',\n 'itemtype': '$itemtype_escaped',\n 'num': $nbsearchcountvar,\n 'p': $json_p,\n '_idor_token': '$idor_display_criteria'\n })\n .done(function(data) {\n $(data).insertBefore('#more-criteria$rand_criteria');\n $nbsearchcountvar++;\n });\n });", " $('#addmetasearchcriteria$rand_criteria').on('click', function(event) {\n event.preventDefault();\n $.post('{$CFG_GLPI['root_doc']}/ajax/search.php', {\n 'action': 'display_meta_criteria',\n 'itemtype': '$itemtype_escaped',\n 'meta': true,\n 'num': $nbsearchcountvar,\n 'p': $json_p,\n '_idor_token': '$idor_display_meta_criteria'\n })\n .done(function(data) {\n $(data).insertBefore('#more-criteria$rand_criteria');\n $nbsearchcountvar++;\n });\n });", " $('#addcriteriagroup$rand_criteria').on('click', function(event) {\n event.preventDefault();\n $.post('{$CFG_GLPI['root_doc']}/ajax/search.php', {\n 'action': 'display_criteria_group',\n 'itemtype': '$itemtype_escaped',\n 'meta': true,\n 'num': $nbsearchcountvar,\n 'p': $json_p,\n '_idor_token': '$idor_display_criteria_group'\n })\n .done(function(data) {\n $(data).insertBefore('#more-criteria$rand_criteria');\n $nbsearchcountvar++;\n });\n });\nJAVASCRIPT;", " if ($p['mainform']) {\n $JS .= <<<JAVASCRIPT\n var toggle_fold_search = function(show_search) {\n $('#searchcriteria{$rand_criteria}').closest('.search-form').toggle(show_search);\n };", " // Init search_criteria state\n var search_criteria_visibility = window.localStorage.getItem('show_full_searchcriteria');\n if (search_criteria_visibility !== undefined && search_criteria_visibility == 'false') {\n $('.fold-search').click();\n }", " $(document).on(\"click\", \".remove-search-criteria\", function() {\n // force removal of tooltip\n var tooltip = bootstrap.Tooltip.getInstance($(this)[0]);\n if (tooltip !== null) {\n tooltip.dispose();\n }", " var rowID = $(this).data('rowid');\n $('#' + rowID).remove();\n $('#searchcriteria{$rand_criteria} .criteria-list .list-group-item:first-child').addClass('headerRow').show();\n });\nJAVASCRIPT;\n }\n echo Html::scriptBlock($JS);", " if (count($p['addhidden'])) {\n foreach ($p['addhidden'] as $key => $val) {\n echo Html::hidden($key, ['value' => $val]);\n }\n }", " if ($p['mainform']) {\n // For dropdown\n echo Html::hidden('itemtype', ['value' => $itemtype]);\n // Reset to start when submit new search\n echo Html::hidden('start', ['value' => 0]);\n }", " echo \"</div>\"; // #searchcriteria\n echo \"</div>\"; // .card\n if ($p['mainform']) {\n Html::closeForm();\n }\n }", " /**\n * Display a criteria field set, this function should be called by ajax/search.php\n *\n * @since 9.4\n *\n * @param array $request we should have these keys of parameters:\n * - itemtype: main itemtype for criteria, sub one for metacriteria\n * - num: index of the criteria\n * - p: params of showGenericSearch method\n *\n * @return void\n */\n public static function displayCriteria($request = [])\n {\n global $CFG_GLPI;", " if (\n !isset($request[\"itemtype\"])\n || !isset($request[\"num\"])\n ) {\n return;\n }", " $num = (int) $request['num'];\n $p = $request['p'];\n $options = self::getCleanedOptions($request[\"itemtype\"]);\n $randrow = mt_rand();\n $normalized_itemtype = strtolower(str_replace('\\\\', '', $request[\"itemtype\"]));\n $rowid = 'searchrow' . $normalized_itemtype . $randrow;\n $addclass = $num == 0 ? ' headerRow' : '';\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];\n $criteria = [];\n $from_meta = isset($request['from_meta']) && $request['from_meta'];", " $sess_itemtype = $request[\"itemtype\"];\n if ($from_meta) {\n $sess_itemtype = $request[\"parent_itemtype\"];\n }", " if (!$criteria = self::findCriteriaInSession($sess_itemtype, $num, $parents_num)) {\n $criteria = self::getDefaultCriteria($request[\"itemtype\"]);\n }", " if (\n isset($criteria['meta'])\n && $criteria['meta']\n && !$from_meta\n ) {\n self::displayMetaCriteria($request);\n return;\n }", " if (\n isset($criteria['criteria'])\n && is_array($criteria['criteria'])\n ) {\n self::displayCriteriaGroup($request);\n return;\n }", " $add_padding = \"p-2\";\n if (isset($request[\"from_meta\"])) {\n $add_padding = \"p-0\";\n }", " echo \"<div class='list-group-item $add_padding border-0 normalcriteria$addclass' id='$rowid'>\";\n echo \"<div class='row g-1'>\";", " if (!$from_meta) {\n // First line display add / delete images for normal and meta search items\n if (\n $num == 0\n && isset($p['mainform'])\n && $p['mainform']\n ) {\n // Instanciate an object to access method\n $item = null;\n if ($request[\"itemtype\"] != AllAssets::getType()) {\n $item = getItemForItemtype($request[\"itemtype\"]);\n }\n if ($item && $item->maybeDeleted()) {\n echo Html::hidden('is_deleted', [\n 'value' => $p['is_deleted'],\n 'id' => 'is_deleted'\n ]);\n }\n echo Html::hidden('as_map', [\n 'value' => $p['as_map'],\n 'id' => 'as_map'\n ]);\n echo Html::hidden('browse', [\n 'value' => $p['browse'],\n 'id' => 'browse'\n ]);\n }\n echo \"<div class='col-auto'>\";\n echo \"<button class='btn btn-sm btn-icon btn-ghost-secondary remove-search-criteria' type='button' data-rowid='$rowid'\n data-bs-toggle='tooltip' data-bs-placement='left'\n title=\\\"\" . __s('Delete a rule') . \"\\\">\n <i class='ti ti-square-minus' alt='-'></i>\n </button>\";\n echo \"</div>\";\n }", " // Display link item\n $value = '';\n if (!$from_meta) {\n echo \"<div class='col-auto'>\";\n if (isset($criteria[\"link\"])) {\n $value = $criteria[\"link\"];\n }\n $operators = Search::getLogicalOperators(($num == 0));\n Dropdown::showFromArray(\"criteria{$prefix}[$num][link]\", $operators, [\n 'value' => $value,\n ]);\n echo \"</div>\";\n }", " $values = [];\n // display select box to define search item\n if ($CFG_GLPI['allow_search_view'] == 2 && !isset($request['from_meta'])) {\n $values['view'] = __('Items seen');\n }", " reset($options);\n $group = '';", " foreach ($options as $key => $val) {\n // print groups\n if (!is_array($val)) {\n $group = $val;\n } else if (count($val) == 1) {\n $group = $val['name'];\n } else {\n if (\n (!isset($val['nosearch']) || ($val['nosearch'] == false))\n && (!$from_meta || !array_key_exists('nometa', $val) || $val['nometa'] !== true)\n ) {\n $values[$group][$key] = $val[\"name\"];\n }\n }\n }\n if ($CFG_GLPI['allow_search_view'] == 1 && !isset($request['from_meta'])) {\n $values['view'] = __('Items seen');\n }\n if ($CFG_GLPI['allow_search_all'] && !isset($request['from_meta'])) {\n $values['all'] = __('All');\n }\n $value = '';", " if (isset($criteria['field'])) {\n $value = $criteria['field'];\n }", " echo \"<div class='col-auto'>\";\n $rand = Dropdown::showFromArray(\"criteria{$prefix}[$num][field]\", $values, [\n 'value' => $value,\n ]);\n echo \"</div>\";\n $field_id = Html::cleanId(\"dropdown_criteria{$prefix}[$num][field]$rand\");\n $spanid = Html::cleanId('SearchSpan' . $normalized_itemtype . $prefix . $num);", " echo \"<div class='col-auto'>\";\n echo \"<div class='row g-1' id='$spanid'>\";", " $used_itemtype = $request[\"itemtype\"];\n // Force Computer itemtype for AllAssets to permit to show specific items\n if ($request[\"itemtype\"] == AllAssets::getType()) {\n $used_itemtype = 'Computer';\n }", " $searchtype = isset($criteria['searchtype'])\n ? $criteria['searchtype']\n : \"\";\n $p_value = isset($criteria['value'])\n ? Sanitizer::dbUnescape($criteria['value'])\n : \"\";", " $params = [\n 'itemtype' => $used_itemtype,\n '_idor_token' => Session::getNewIDORToken($used_itemtype),\n 'field' => $value,\n 'searchtype' => $searchtype,\n 'value' => $p_value,\n 'num' => $num,\n 'p' => $p,\n ];\n Search::displaySearchoption($params);\n echo \"</div>\";", " Ajax::updateItemOnSelectEvent(\n $field_id,\n $spanid,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/search.php\",\n [\n 'action' => 'display_searchoption',\n 'field' => '__VALUE__',\n ] + $params\n );\n echo \"</div>\"; //.row\n echo \"</div>\"; //#$spanid\n echo \"</div>\";\n }", " /**\n * Display a meta-criteria field set, this function should be called by ajax/search.php\n * Call displayCriteria method after displaying its itemtype field\n *\n * @since 9.4\n *\n * @param array $request @see displayCriteria method\n *\n * @return void\n */\n public static function displayMetaCriteria($request = [])\n {\n global $CFG_GLPI;", " if (\n !isset($request[\"itemtype\"])\n || !isset($request[\"num\"])\n ) {\n return \"\";\n }", " $p = $request['p'];\n $num = (int) $request['num'];\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];\n $itemtype = $request[\"itemtype\"];\n $metacriteria = [];", " if (!$metacriteria = self::findCriteriaInSession($itemtype, $num, $parents_num)) {\n $metacriteria = [];\n // Set default field\n $options = Search::getCleanedOptions($itemtype);", " foreach ($options as $key => $val) {\n if (is_array($val) && isset($val['table'])) {\n $metacriteria['field'] = $key;\n break;\n }\n }\n }", " $linked = Search::getMetaItemtypeAvailable($itemtype);\n $rand = mt_rand();", " $rowid = 'metasearchrow' . $request['itemtype'] . $rand;", " echo \"<div class='list-group-item border-0 metacriteria p-2' id='$rowid'>\";\n echo \"<div class='row g-1'>\";", " echo \"<div class='col-auto'>\";\n echo \"<button class='btn btn-sm btn-icon btn-ghost-secondary remove-search-criteria' type='button' data-rowid='$rowid'>\n <i class='ti ti-square-minus' alt='-' title=\\\"\" .\n __s('Delete a global rule') . \"\\\"></i>\n </button>\";\n echo \"</div>\";", " // Display link item (not for the first item)\n echo \"<div class='col-auto'>\";\n Dropdown::showFromArray(\n \"criteria{$prefix}[$num][link]\",\n Search::getLogicalOperators(),\n [\n 'value' => isset($metacriteria[\"link\"])\n ? $metacriteria[\"link\"]\n : \"\",\n ]\n );\n echo \"</div>\";", " // Display select of the linked item type available\n echo \"<div class='col-auto'>\";\n $rand = Dropdown::showItemTypes(\"criteria{$prefix}[$num][itemtype]\", $linked, [\n 'value' => isset($metacriteria['itemtype'])\n && !empty($metacriteria['itemtype'])\n ? $metacriteria['itemtype']\n : \"\",\n ]);\n echo \"</div>\";\n echo Html::hidden(\"criteria{$prefix}[$num][meta]\", [\n 'value' => true\n ]);\n $field_id = Html::cleanId(\"dropdown_criteria{$prefix}[$num][itemtype]$rand\");\n $spanid = Html::cleanId(\"show_\" . $request[\"itemtype\"] . \"_\" . $prefix . $num . \"_$rand\");\n // Ajax script for display search met& item", " $params = [\n 'action' => 'display_criteria',\n 'itemtype' => '__VALUE__',\n 'parent_itemtype' => $request['itemtype'],\n 'from_meta' => true,\n 'num' => $num,\n 'p' => $request[\"p\"],\n '_idor_token' => Session::getNewIDORToken(\"\", [\n 'parent_itemtype' => $request['itemtype']\n ])\n ];\n Ajax::updateItemOnSelectEvent(\n $field_id,\n $spanid,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/search.php\",\n $params\n );", " echo \"<div class='col-auto' id='$spanid'>\";\n echo \"<div class=row'>\";\n if (\n isset($metacriteria['itemtype'])\n && !empty($metacriteria['itemtype'])\n ) {\n $params['itemtype'] = $metacriteria['itemtype'];\n self::displayCriteria($params);\n }\n echo \"</div>\";\n echo \"</div>\";\n echo \"</div>\";\n echo \"</div>\";\n }", " /**\n * Display a group of nested criteria.\n * A group (parent) criteria can contains children criteria (who also cantains children, etc)\n *\n * @since 9.4\n *\n * @param array $request @see displayCriteria method\n *\n * @return void\n */\n public static function displayCriteriaGroup($request = [])\n {\n $num = (int) $request['num'];\n $p = $request['p'];\n $randrow = mt_rand();\n $rowid = 'searchrow' . $request['itemtype'] . $randrow;\n $addclass = $num == 0 ? ' headerRow' : '';\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];", " if (!$criteria = self::findCriteriaInSession($request['itemtype'], $num, $parents_num)) {\n $criteria = [\n 'criteria' => self::getDefaultCriteria($request['itemtype']),\n ];\n }", " echo \"<div class='list-group-item p-2 border-0 normalcriteria$addclass' id='$rowid'>\";\n echo \"<div class='row g-1'>\";\n echo \"<div class='col-auto'>\";\n echo \"<button class='btn btn-sm btn-icon btn-ghost-secondary remove-search-criteria' type='button' data-rowid='$rowid'\n data-bs-toggle='tooltip' data-bs-placement='left'\n title=\\\"\" . __s('Delete a rule') . \"\\\"\n >\n <i class='ti ti-square-minus' alt='-'></i>\n </button>\";\n echo \"</div>\";\n echo \"<div class='col-auto'>\";\n Dropdown::showFromArray(\"criteria{$prefix}[$num][link]\", Search::getLogicalOperators(), [\n 'value' => isset($criteria[\"link\"]) ? $criteria[\"link\"] : '',\n ]);\n echo \"</div>\";", " $parents_num = isset($p['parents_num']) ? $p['parents_num'] : [];\n array_push($parents_num, $num);\n $params = [\n 'mainform' => false,\n 'prefix_crit' => \"{$prefix}[$num][criteria]\",\n 'parents_num' => $parents_num,\n 'criteria' => $criteria['criteria'],\n ];", " echo \"<div class='col-auto'>\";\n self::showGenericSearch($request['itemtype'], $params);\n echo \"</div>\";", " echo \"</div>\";//.row\n echo \"</div>\";//.list-group-item\n }", " /**\n * Retrieve a single criteria in Session by its index\n *\n * @since 9.4\n *\n * @param string $itemtype which glpi type we must search in session\n * @param integer $num index of the criteria\n * @param array $parents_num node indexes of the parents (@see displayCriteriaGroup)\n *\n * @return array|false the found criteria array, or false if nothing found\n */\n public static function findCriteriaInSession($itemtype = '', $num = 0, $parents_num = [])\n {\n if (!isset($_SESSION['glpisearch'][$itemtype]['criteria'])) {\n return false;\n }\n $criteria = &$_SESSION['glpisearch'][$itemtype]['criteria'];", " if (count($parents_num)) {\n foreach ($parents_num as $parent) {\n if (!isset($criteria[$parent]['criteria'])) {\n return false;\n }\n $criteria = &$criteria[$parent]['criteria'];\n }\n }", " if (\n isset($criteria[$num])\n && is_array($criteria[$num])\n ) {\n return $criteria[$num];\n }", " return false;\n }", " /**\n * construct the default criteria for an itemtype\n *\n * @since 9.4\n *\n * @param class-string<CommonDBTM> $itemtype\n *\n * @return array criteria\n */\n public static function getDefaultCriteria($itemtype = '')\n {\n global $CFG_GLPI;", " $field = '';", " if ($CFG_GLPI['allow_search_view'] == 2) {\n $field = 'view';\n } else {\n $options = self::getCleanedOptions($itemtype);\n foreach ($options as $key => $val) {\n if (\n is_array($val)\n && isset($val['table'])\n ) {\n $field = $key;\n break;\n }\n }\n }", " return [\n [\n 'field' => $field,\n 'link' => 'contains',\n 'value' => ''\n ]\n ];\n }", " /**\n * Display first part of criteria (field + searchtype, just after link)\n * will call displaySearchoptionValue for the next part (value)\n *\n * @since 9.4\n *\n * @param array $request we should have these keys of parameters:\n * - itemtype: main itemtype for criteria, sub one for metacriteria\n * - num: index of the criteria\n * - field: field key of the criteria\n * - p: params of showGenericSearch method\n *\n * @return void\n */\n public static function displaySearchoption($request = [])\n {\n global $CFG_GLPI;\n if (\n !isset($request[\"itemtype\"])\n || !isset($request[\"field\"])\n || !isset($request[\"num\"])\n ) {\n return \"\";\n }", " $p = $request['p'];\n $num = (int) $request['num'];\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';", " if (!is_subclass_of($request['itemtype'], 'CommonDBTM')) {\n throw new \\RuntimeException('Invalid itemtype provided!');\n }", " if (isset($request['meta']) && $request['meta']) {\n $fieldname = 'metacriteria';\n } else {\n $fieldname = 'criteria';\n $request['meta'] = 0;\n }", " $actions = Search::getActionsFor($request[\"itemtype\"], $request[\"field\"]);", " // is it a valid action for type ?\n if (\n count($actions)\n && (empty($request['searchtype']) || !isset($actions[$request['searchtype']]))\n ) {\n $tmp = $actions;\n unset($tmp['searchopt']);\n $request['searchtype'] = key($tmp);\n unset($tmp);\n }", " $rands = -1;\n $normalized_itemtype = strtolower(str_replace('\\\\', '', $request[\"itemtype\"]));\n $dropdownname = Html::cleanId(\"spansearchtype$fieldname\" .\n $normalized_itemtype .\n $prefix .\n $num);\n $searchopt = [];\n if (count($actions) > 0) {\n // get already get search options\n if (isset($actions['searchopt'])) {\n $searchopt = $actions['searchopt'];\n // No name for clean array with quotes\n unset($searchopt['name']);\n unset($actions['searchopt']);\n }\n $searchtype_name = \"{$fieldname}{$prefix}[$num][searchtype]\";\n echo \"<div class='col-auto'>\";\n $rands = Dropdown::showFromArray($searchtype_name, $actions, [\n 'value' => $request[\"searchtype\"],\n ]);\n echo \"</div>\";\n $fieldsearch_id = Html::cleanId(\"dropdown_$searchtype_name$rands\");\n }", " echo \"<div class='col-auto' id='$dropdownname' data-itemtype='{$request[\"itemtype\"]}' data-fieldname='$fieldname' data-prefix='$prefix' data-num='$num'>\";\n $params = [\n 'value' => rawurlencode(Sanitizer::dbUnescape($request['value'])),\n 'searchopt' => $searchopt,\n 'searchtype' => $request[\"searchtype\"],\n 'num' => $num,\n 'itemtype' => $request[\"itemtype\"],\n '_idor_token' => Session::getNewIDORToken($request[\"itemtype\"]),\n 'from_meta' => isset($request['from_meta'])\n ? $request['from_meta']\n : false,\n 'field' => $request[\"field\"],\n 'p' => $p,\n ];\n self::displaySearchoptionValue($params);\n echo \"</div>\";", " Ajax::updateItemOnSelectEvent(\n $fieldsearch_id,\n $dropdownname,\n $CFG_GLPI[\"root_doc\"] . \"/ajax/search.php\",\n [\n 'action' => 'display_searchoption_value',\n 'searchtype' => '__VALUE__',\n ] + $params\n );\n }", " /**\n * Display last part of criteria (value, just after searchtype)\n * called by displaySearchoptionValue\n *\n * @since 9.4\n *\n * @param array $request we should have these keys of parameters:\n * - searchtype: (contains, equals) passed by displaySearchoption\n *\n * @return void\n */\n public static function displaySearchoptionValue($request = [])\n {\n if (!isset($request['searchtype'])) {\n return \"\";\n }", " $p = $request['p'];\n $prefix = isset($p['prefix_crit']) ? $p['prefix_crit'] : '';\n $searchopt = isset($request['searchopt']) ? $request['searchopt'] : [];\n $request['value'] = rawurldecode($request['value']);\n $fieldname = isset($request['meta']) && $request['meta']\n ? 'metacriteria'\n : 'criteria';\n $inputname = $fieldname . $prefix . '[' . $request['num'] . '][value]';\n $display = false;\n $item = getItemForItemtype($request['itemtype']);\n $options2 = [];\n $options2['value'] = $request['value'];\n $options2['width'] = '100%';\n // For tree dropdpowns\n $options2['permit_select_parent'] = true;", " switch ($request['searchtype']) {\n case \"equals\":\n case \"notequals\":\n case \"morethan\":\n case \"lessthan\":\n case \"under\":\n case \"notunder\":\n if (!$display && isset($searchopt['field'])) {\n // Specific cases\n switch ($searchopt['table'] . \".\" . $searchopt['field']) {\n // Add mygroups choice to searchopt\n case \"glpi_groups.completename\":\n $searchopt['toadd'] = ['mygroups' => __('My groups')];\n break;", " case \"glpi_changes.status\":\n case \"glpi_changes.impact\":\n case \"glpi_changes.urgency\":\n case \"glpi_problems.status\":\n case \"glpi_problems.impact\":\n case \"glpi_problems.urgency\":\n case \"glpi_tickets.status\":\n case \"glpi_tickets.impact\":\n case \"glpi_tickets.urgency\":\n $options2['showtype'] = 'search';\n break;", " case \"glpi_changes.priority\":\n case \"glpi_problems.priority\":\n case \"glpi_tickets.priority\":\n $options2['showtype'] = 'search';\n $options2['withmajor'] = true;\n break;", " case \"glpi_tickets.global_validation\":\n $options2['all'] = true;\n break;", " case \"glpi_ticketvalidations.status\":\n $options2['all'] = true;\n break;", " case \"glpi_users.name\":\n $options2['right'] = (isset($searchopt['right']) ? $searchopt['right'] : 'all');\n $options2['inactive_deleted'] = 1;\n $searchopt['toadd'] = [\n [\n 'id' => 'myself',\n 'text' => __('Myself'),\n ]\n ];", " break;\n }", " // Standard datatype usage\n if (!$display && isset($searchopt['datatype'])) {\n switch ($searchopt['datatype']) {\n case \"date\":\n case \"date_delay\":\n case \"datetime\":\n $options2['relative_dates'] = true;\n break;\n }\n }", " $out = $item->getValueToSelect($searchopt, $inputname, $request['value'], $options2);\n if (strlen($out)) {\n echo $out;\n $display = true;\n }", " //Could display be handled by a plugin ?\n if (\n !$display\n && $plug = isPluginItemType(getItemTypeForTable($searchopt['table']))\n ) {\n $display = Plugin::doOneHook(\n $plug['plugin'],\n 'searchOptionsValues',\n [\n 'name' => $inputname,\n 'searchtype' => $request['searchtype'],\n 'searchoption' => $searchopt,\n 'value' => $request['value']\n ]\n );\n }\n }\n break;\n }", " // Default case : text field\n if (!$display) {\n echo \"<input type='text' class='form-control' size='13' name='$inputname' value=\\\"\" .\n Html::cleanInputText($request['value']) . \"\\\">\";\n }\n }", "\n /**\n * Generic Function to add to a HAVING clause\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $LINK link to use\n * @param string $NOT is is a negative search ?\n * @param string $itemtype item type\n * @param integer $ID ID of the item to search\n * @param string $searchtype search type ('contains' or 'equals')\n * @param string $val value search\n *\n * @return string|false HAVING clause sub-string (Does not include the \"HAVING\" keyword).\n * May return false if the related search option is not valid for SQL searching.\n **/\n public static function addHaving($LINK, $NOT, $itemtype, $ID, $searchtype, $val)\n {", " global $DB;", " $searchopt = &self::getOptions($itemtype);\n if (!isset($searchopt[$ID]['table'])) {\n return false;\n }\n $table = $searchopt[$ID][\"table\"];\n $NAME = \"ITEM_{$itemtype}_{$ID}\";", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addHaving',\n $LINK,\n $NOT,\n $itemtype,\n $ID,\n $val,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }", " //// Default cases\n // Link with plugin tables\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addHaving',\n $LINK,\n $NOT,\n $itemtype,\n $ID,\n $val,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }", " if (in_array($searchtype, [\"notequals\", \"notcontains\"])) {\n $NOT = !$NOT;\n }", " // Preformat items\n if (isset($searchopt[$ID][\"datatype\"])) {\n if ($searchopt[$ID][\"datatype\"] == \"mio\") {\n // Parse value as it may contain a few different formats\n $val = Toolbox::getMioSizeFromString($val);\n }", " switch ($searchopt[$ID][\"datatype\"]) {\n case \"datetime\":\n if (in_array($searchtype, ['contains', 'notcontains'])) {\n break;\n }", " $force_day = false;\n if (strstr($val, 'BEGIN') || strstr($val, 'LAST')) {\n $force_day = true;\n }", " $val = Html::computeGenericDateTimeSearch($val, $force_day);", " $operator = '';\n switch ($searchtype) {\n case 'equals':\n $operator = !$NOT ? '=' : '!=';\n break;\n case 'notequals':\n $operator = !$NOT ? '!=' : '=';\n break;\n case 'lessthan':\n $operator = !$NOT ? '<' : '>';\n break;\n case 'morethan':\n $operator = !$NOT ? '>' : '<';\n break;\n }", " return \" {$LINK} ({$DB->quoteName($NAME)} $operator {$DB->quoteValue($val)}) \";\n break;\n case \"count\":\n case \"mio\":\n case \"number\":\n case \"decimal\":\n case \"timestamp\":\n $search = [\"/\\&lt;/\",\"/\\&gt;/\"];\n $replace = [\"<\",\">\"];\n $val = preg_replace($search, $replace, $val);\n if (preg_match(\"/([<>])([=]*)[[:space:]]*([0-9]+)/\", $val, $regs)) {\n if ($NOT) {\n if ($regs[1] == '<') {\n $regs[1] = '>';\n } else {\n $regs[1] = '<';\n }\n }\n $regs[1] .= $regs[2];\n return \" $LINK (`$NAME` \" . $regs[1] . \" \" . $regs[3] . \" ) \";\n }", " if (is_numeric($val)) {\n if (isset($searchopt[$ID][\"width\"])) {\n if (!$NOT) {\n return \" $LINK (`$NAME` < \" . (intval($val) + $searchopt[$ID][\"width\"]) . \"\n AND `$NAME` > \" .\n (intval($val) - $searchopt[$ID][\"width\"]) . \") \";\n }\n return \" $LINK (`$NAME` > \" . (intval($val) + $searchopt[$ID][\"width\"]) . \"\n OR `$NAME` < \" .\n (intval($val) - $searchopt[$ID][\"width\"]) . \" ) \";\n }\n // Exact search\n if (!$NOT) {\n return \" $LINK (`$NAME` = \" . (intval($val)) . \") \";\n }\n return \" $LINK (`$NAME` <> \" . (intval($val)) . \") \";\n }\n break;\n }\n }", " return self::makeTextCriteria(\"`$NAME`\", $val, $NOT, $LINK);\n }", "\n /**\n * Generic Function to add ORDER BY to a request\n *\n * @since 9.4: $key param has been dropped\n * @since 10.0.0: Parameters changed to allow multiple sort fields.\n * Old functionality maintained by checking the type of the first parameter.\n * This backwards compatibility will be removed in a later version.\n *\n * @param class-string<CommonDBTM> $itemtype The itemtype\n * @param array $sort_fields The search options to order on. This array should contain one or more associative arrays containing:\n * - id: The search option ID\n * - order: The sort direction (Default: ASC). Invalid sort directions will be replaced with the default option\n * @param ?integer $_id field to add (Deprecated)\n *\n * @return string ORDER BY query string\n *\n **/\n public static function addOrderBy($itemtype, $sort_fields, $_id = 'ASC')\n {\n global $CFG_GLPI;", " // BC parameter conversion\n if (!is_array($sort_fields)) {\n // < 10.0.0 parameters\n Toolbox::deprecated('The parameters for Search::addOrderBy have changed to allow sorting by multiple fields. Please update your calling code.');\n $sort_fields = [\n [\n 'searchopt_id' => $sort_fields,\n 'order' => $_id\n ]\n ];\n }", " $orderby_criteria = [];\n $searchopt = &self::getOptions($itemtype);", " foreach ($sort_fields as $sort_field) {\n $ID = $sort_field['searchopt_id'];\n if (isset($searchopt[$ID]['nosort']) && $searchopt[$ID]['nosort']) {\n continue;\n }\n $order = $sort_field['order'] ?? 'ASC';\n // Order security check\n if ($order != 'ASC') {\n $order = 'DESC';\n }", " $criterion = null;", " $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];", " $addtable = '';", " $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);\n $orig_table = self::getOrigTableName($itemtype);\n if (\n ($is_fkey_composite_on_self || $table != $orig_table)\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable .= \"_\" . $searchopt[$ID][\"linkfield\"];\n }", " if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);", " if (!empty($complexjoin)) {\n $addtable .= \"_\" . $complexjoin;\n }\n }", " if (isset($CFG_GLPI[\"union_search_type\"][$itemtype])) {\n $criterion = \"`ITEM_{$itemtype}_{$ID}` $order\";\n }", " // Plugin can override core definition for its type\n if ($criterion === null && $plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addOrderBy',\n $itemtype,\n $ID,\n $order,\n \"{$itemtype}_{$ID}\"\n );\n $out = $out !== null ? trim($out) : null;\n if (!empty($out)) {\n $out = preg_replace('/^ORDER BY /', '', $out);\n $criterion = $out;\n }\n }", " if ($criterion === null) {\n switch ($table . \".\" . $field) {\n // FIXME Dead case? Can't see any itemtype referencing this table in their search options to be able to get here.\n case \"glpi_auth_tables.name\":\n $user_searchopt = self::getOptions('User');\n $criterion = \"`glpi_users`.`authtype` $order,\n `glpi_authldaps\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[30]['joinparams']) . \"`.\n `name` $order,\n `glpi_authmails\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[31]['joinparams']) . \"`.\n `name` $order\";\n break;", " case \"glpi_users.name\":\n if ($itemtype != 'User') {\n if ($_SESSION[\"glpinames_format\"] == User::FIRSTNAME_BEFORE) {\n $name1 = 'firstname';\n $name2 = 'realname';\n } else {\n $name1 = 'realname';\n $name2 = 'firstname';\n }\n $criterion = \"`\" . $table . $addtable . \"`.`$name1` $order,\n `\" . $table . $addtable . \"`.`$name2` $order,\n `\" . $table . $addtable . \"`.`name` $order\";\n } else {\n $criterion = \"`\" . $table . $addtable . \"`.`name` $order\";\n }\n break;\n //FIXME glpi_networkequipments.ip seems like a dead case\n case \"glpi_networkequipments.ip\":\n case \"glpi_ipaddresses.name\":\n $criterion = \"INET6_ATON(`$table$addtable`.`$field`) $order\";\n break;\n }\n }", " //// Default cases", " // Link with plugin tables\n if ($criterion === null && preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addOrderBy',\n $itemtype,\n $ID,\n $order,\n \"{$itemtype}_{$ID}\"\n );\n $out = $out !== null ? trim($out) : null;\n if (!empty($out)) {\n $out = preg_replace('/^ORDER BY /', '', $out);\n $criterion = $out;\n }\n }\n }", " // Preformat items\n if ($criterion === null && isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"date_delay\":\n $interval = \"MONTH\";\n if (isset($searchopt[$ID]['delayunit'])) {\n $interval = $searchopt[$ID]['delayunit'];\n }", " $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"- `$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n $criterion = \"ADDDATE(`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][1] . \"`,\n INTERVAL (`$table$addtable`.`\" .\n $searchopt[$ID][\"datafields\"][2] . \"` $add_minus)\n $interval) $order\";\n }\n }", " $orderby_criteria[] = $criterion ?? \"`ITEM_{$itemtype}_{$ID}` $order\";\n }", " if (count($orderby_criteria) === 0) {\n return '';\n }\n return ' ORDER BY ' . implode(', ', $orderby_criteria) . ' ';\n }", "\n /**\n * Generic Function to add default columns to view\n *\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param array $params array of parameters\n *\n * @return array Array of search option IDs to be shown in the results\n **/\n public static function addDefaultToView($itemtype, $params)\n {\n global $CFG_GLPI;", " $toview = [];\n $item = null;\n $entity_check = true;", " if ($itemtype != AllAssets::getType()) {\n $item = getItemForItemtype($itemtype);\n $entity_check = $item->isEntityAssign();\n }\n // Add first element (name)\n array_push($toview, 1);", " if (isset($params['as_map']) && $params['as_map'] == 1) {\n // Add location name when map mode\n array_push($toview, ($itemtype == 'Location' ? 1 : ($itemtype == 'Ticket' ? 83 : 3)));\n }", " // Add entity view :\n if (\n Session::isMultiEntitiesMode()\n && $entity_check\n && (isset($CFG_GLPI[\"union_search_type\"][$itemtype])\n || ($item && $item->maybeRecursive())\n || isset($_SESSION['glpiactiveentities']) && (count($_SESSION[\"glpiactiveentities\"]) > 1))\n ) {\n array_push($toview, 80);\n }\n return $toview;\n }", "\n /**\n * Generic Function to add default select to a request\n *\n * @param class-string<CommonDBTM> $itemtype device type\n *\n * @return string Select string\n **/\n public static function addDefaultSelect($itemtype)\n {\n global $DB;", " $itemtable = self::getOrigTableName($itemtype);\n $item = null;\n $mayberecursive = false;\n if ($itemtype != AllAssets::getType()) {\n $item = getItemForItemtype($itemtype);\n $mayberecursive = $item->maybeRecursive();\n }\n $ret = \"\";\n switch ($itemtype) {\n case 'FieldUnicity':\n $ret = \"`glpi_fieldunicities`.`itemtype` AS ITEMTYPE,\";\n break;", " default:\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $ret = Plugin::doOneHook(\n $plug['plugin'],\n 'addDefaultSelect',\n $itemtype\n );\n }\n }\n if ($itemtable == 'glpi_entities') {\n $ret .= \"`$itemtable`.`id` AS entities_id, '1' AS is_recursive, \";\n } else if ($mayberecursive) {\n if ($item->isField('entities_id')) {\n $ret .= $DB->quoteName(\"$itemtable.entities_id\") . \", \";\n }\n if ($item->isField('is_recursive')) {\n $ret .= $DB->quoteName(\"$itemtable.is_recursive\") . \", \";\n }\n }\n return $ret;\n }", "\n /**\n * Generic Function to add select to a request\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $itemtype item type\n * @param integer $ID ID of the item to add\n * @param boolean $meta boolean is a meta\n * @param integer $meta_type meta type table ID (default 0)\n *\n * @return string Select string\n **/\n public static function addSelect($itemtype, $ID, $meta = 0, $meta_type = 0)\n {\n global $DB, $CFG_GLPI;", " $searchopt = &self::getOptions($itemtype);\n $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];\n $addtable = \"\";\n $addtable2 = \"\";\n $NAME = \"ITEM_{$itemtype}_{$ID}\";\n $complexjoin = '';", " if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);\n }", " $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);", " $orig_table = self::getOrigTableName($itemtype);\n if (\n ((($is_fkey_composite_on_self || $table != $orig_table)\n && (!isset($CFG_GLPI[\"union_search_type\"][$itemtype])\n || ($CFG_GLPI[\"union_search_type\"][$itemtype] != $table)))\n || !empty($complexjoin))\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable .= \"_\" . $searchopt[$ID][\"linkfield\"];\n }", " if (!empty($complexjoin)) {\n $addtable .= \"_\" . $complexjoin;\n $addtable2 .= \"_\" . $complexjoin;\n }", " $addmeta = \"\";\n if ($meta) {\n // $NAME = \"META\";\n if ($meta_type::getTable() != $table) {\n $addmeta = \"_\" . $meta_type;\n $addtable .= $addmeta;\n $addtable2 .= $addmeta;\n }\n }", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addSelect',\n $itemtype,\n $ID,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }", " $tocompute = \"`$table$addtable`.`$field`\";\n $tocomputeid = \"`$table$addtable`.`id`\";", " $tocomputetrans = \"IFNULL(`$table\" . $addtable . \"_trans_\" . $field . \"`.`value`,'\" . self::NULLVALUE . \"') \";", " $ADDITONALFIELDS = '';\n if (\n isset($searchopt[$ID][\"additionalfields\"])\n && count($searchopt[$ID][\"additionalfields\"])\n ) {\n foreach ($searchopt[$ID][\"additionalfields\"] as $key) {\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])\n ) {\n $ADDITONALFIELDS .= \" IFNULL(GROUP_CONCAT(DISTINCT CONCAT(IFNULL(`$table$addtable`.`$key`,\n '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"', $tocomputeid)ORDER BY $tocomputeid SEPARATOR '\" . self::LONGSEP . \"'), '\" . self::NULLVALUE . self::SHORTSEP . \"')\n AS `\" . $NAME . \"_$key`, \";\n } else {\n $ADDITONALFIELDS .= \"`$table$addtable`.`$key` AS `\" . $NAME . \"_$key`, \";\n }\n }\n }", " // Virtual display no select : only get additional fields\n if (strpos($field, '_virtual') === 0) {\n return $ADDITONALFIELDS;\n }", " switch ($table . \".\" . $field) {\n case \"glpi_users.name\":\n if ($itemtype != 'User') {\n if ((isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])) {\n $addaltemail = \"\";\n if (\n (($itemtype == 'Ticket') || ($itemtype == 'Problem'))\n && isset($searchopt[$ID]['joinparams']['beforejoin']['table'])\n && (($searchopt[$ID]['joinparams']['beforejoin']['table']\n == 'glpi_tickets_users')\n || ($searchopt[$ID]['joinparams']['beforejoin']['table']\n == 'glpi_problems_users')\n || ($searchopt[$ID]['joinparams']['beforejoin']['table']\n == 'glpi_changes_users'))\n ) { // For tickets_users\n $ticket_user_table\n = $searchopt[$ID]['joinparams']['beforejoin']['table'] .\n \"_\" . self::computeComplexJoinID($searchopt[$ID]['joinparams']['beforejoin']\n ['joinparams']) . $addmeta;\n $addaltemail\n = \"GROUP_CONCAT(DISTINCT CONCAT(`$ticket_user_table`.`users_id`, ' ',\n `$ticket_user_table`.`alternative_email`)\n SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"_2`, \";\n }\n return \" GROUP_CONCAT(DISTINCT `$table$addtable`.`id` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $addaltemail\n $ADDITONALFIELDS\";\n }\n return \" `$table$addtable`.`$field` AS `\" . $NAME . \"`,\n `$table$addtable`.`realname` AS `\" . $NAME . \"_realname`,\n `$table$addtable`.`id` AS `\" . $NAME . \"_id`,\n `$table$addtable`.`firstname` AS `\" . $NAME . \"_firstname`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_softwarelicenses.number\":\n if ($meta) {\n return \" FLOOR(SUM(`$table$addtable2`.`$field`)\n * COUNT(DISTINCT `$table$addtable2`.`id`)\n / COUNT(`$table$addtable2`.`id`)) AS `\" . $NAME . \"`,\n MIN(`$table$addtable2`.`$field`) AS `\" . $NAME . \"_min`,\n $ADDITONALFIELDS\";\n } else {\n return \" FLOOR(SUM(`$table$addtable`.`$field`)\n * COUNT(DISTINCT `$table$addtable`.`id`)\n / COUNT(`$table$addtable`.`id`)) AS `\" . $NAME . \"`,\n MIN(`$table$addtable`.`$field`) AS `\" . $NAME . \"_min`,\n $ADDITONALFIELDS\";\n }", " case \"glpi_profiles.name\":\n if (\n ($itemtype == 'User')\n && ($ID == 20)\n ) {\n $addtable2 = '';\n if ($meta) {\n $addtable2 = \"_\" . $meta_type;\n }\n return \" GROUP_CONCAT(`$table$addtable`.`$field` SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`entities_id` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_entities_id`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_recursive` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_recursive`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_dynamic` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_dynamic`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_entities.completename\":\n if (\n ($itemtype == 'User')\n && ($ID == 80)\n ) {\n $addtable2 = '';\n if ($meta) {\n $addtable2 = \"_\" . $meta_type;\n }\n return \" GROUP_CONCAT(`$table$addtable`.`completename` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`profiles_id` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_profiles_id`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_recursive` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_recursive`,\n GROUP_CONCAT(`glpi_profiles_users$addtable2`.`is_dynamic` SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_is_dynamic`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_auth_tables.name\":\n $user_searchopt = self::getOptions('User');\n return \" `glpi_users`.`authtype` AS `\" . $NAME . \"`,\n `glpi_users`.`auths_id` AS `\" . $NAME . \"_auths_id`,\n `glpi_authldaps\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[30]['joinparams']) . $addmeta . \"`.`$field`\n AS `\" . $NAME . \"_\" . $ID . \"_ldapname`,\n `glpi_authmails\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[31]['joinparams']) . $addmeta . \"`.`$field`\n AS `\" . $NAME . \"_mailname`,\n $ADDITONALFIELDS\";", " case \"glpi_softwareversions.name\":\n if ($meta && ($meta_type == 'Software')) {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwares`.`name`, ' - ',\n `$table$addtable2`.`$field`, '\" . self::SHORTSEP . \"',\n `$table$addtable2`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_softwareversions.comment\":\n if ($meta && ($meta_type == 'Software')) {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwares`.`name`, ' - ',\n `$table$addtable2`.`$field`,'\" . self::SHORTSEP . \"',\n `$table$addtable2`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n return \" GROUP_CONCAT(DISTINCT CONCAT(`$table$addtable`.`name`, ' - ',\n `$table$addtable`.`$field`, '\" . self::SHORTSEP . \"',\n `$table$addtable`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";", " case \"glpi_states.name\":\n if ($meta && ($meta_type == 'Software')) {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwares`.`name`, ' - ',\n `glpi_softwareversions$addtable`.`name`, ' - ',\n `$table$addtable2`.`$field`, '\" . self::SHORTSEP . \"',\n `$table$addtable2`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n } else if ($itemtype == 'Software') {\n return \" GROUP_CONCAT(DISTINCT CONCAT(`glpi_softwareversions`.`name`, ' - ',\n `$table$addtable`.`$field`,'\" . self::SHORTSEP . \"',\n `$table$addtable`.`id`) SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n break;", " case \"glpi_itilfollowups.content\":\n case \"glpi_tickettasks.content\":\n case \"glpi_changetasks.content\":\n if (is_subclass_of($itemtype, \"CommonITILObject\")) {\n // force ordering by date desc\n return \" GROUP_CONCAT(\n DISTINCT CONCAT(\n IFNULL($tocompute, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',\n $tocomputeid\n )\n ORDER BY `$table$addtable`.`date` DESC\n SEPARATOR '\" . self::LONGSEP . \"'\n ) AS `\" . $NAME . \"`, $ADDITONALFIELDS\";\n }\n break;", " default:\n break;\n }", " //// Default cases\n // Link with plugin tables\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addSelect',\n $itemtype,\n $ID,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }", " if (isset($searchopt[$ID][\"computation\"])) {\n $tocompute = $searchopt[$ID][\"computation\"];\n $tocompute = str_replace($DB->quoteName('TABLE'), 'TABLE', $tocompute);\n $tocompute = str_replace(\"TABLE\", $DB->quoteName(\"$table$addtable\"), $tocompute);\n }\n // Preformat items\n if (isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"count\":\n return \" COUNT(DISTINCT `$table$addtable`.`$field`) AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";", " case \"date_delay\":\n $interval = \"MONTH\";\n if (isset($searchopt[$ID]['delayunit'])) {\n $interval = $searchopt[$ID]['delayunit'];\n }", " $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"-`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])\n ) {\n return \" GROUP_CONCAT(DISTINCT ADDDATE(`$table$addtable`.`\" .\n $searchopt[$ID][\"datafields\"][1] . \"`,\n INTERVAL (`$table$addtable`.`\" .\n $searchopt[$ID][\"datafields\"][2] .\n \"` $add_minus) $interval)\n SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";\n }\n return \"ADDDATE(`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][1] . \"`,\n INTERVAL (`$table$addtable`.`\" . $searchopt[$ID][\"datafields\"][2] .\n \"` $add_minus) $interval) AS `\" . $NAME . \"`,\n $ADDITONALFIELDS\";", " case \"itemlink\":\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"])\n ) {\n $TRANS = '';\n if (Session::haveTranslations(getItemTypeForTable($table), $field)) {\n $TRANS = \"GROUP_CONCAT(DISTINCT CONCAT(IFNULL($tocomputetrans, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',$tocomputeid) ORDER BY $tocomputeid\n SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_trans_\" . $field . \"`, \";\n }", " return \" GROUP_CONCAT(DISTINCT CONCAT($tocompute, '\" . self::SHORTSEP . \"' ,\n `$table$addtable`.`id`) ORDER BY `$table$addtable`.`id`\n SEPARATOR '\" . self::LONGSEP . \"') AS `\" . $NAME . \"`,\n $TRANS\n $ADDITONALFIELDS\";\n }\n return \" $tocompute AS `\" . $NAME . \"`,\n `$table$addtable`.`id` AS `\" . $NAME . \"_id`,\n $ADDITONALFIELDS\";\n }\n }", " // Default case\n if (\n $meta\n || (isset($searchopt[$ID][\"forcegroupby\"]) && $searchopt[$ID][\"forcegroupby\"]\n && (!isset($searchopt[$ID][\"computation\"])\n || isset($searchopt[$ID][\"computationgroupby\"])\n && $searchopt[$ID][\"computationgroupby\"]))\n ) { // Not specific computation\n $TRANS = '';\n if (Session::haveTranslations(getItemTypeForTable($table), $field)) {\n $TRANS = \"GROUP_CONCAT(DISTINCT CONCAT(IFNULL($tocomputetrans, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',$tocomputeid) ORDER BY $tocomputeid SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"_trans_\" . $field . \"`, \";\n }\n return \" GROUP_CONCAT(DISTINCT CONCAT(IFNULL($tocompute, '\" . self::NULLVALUE . \"'),\n '\" . self::SHORTSEP . \"',$tocomputeid) ORDER BY $tocomputeid SEPARATOR '\" . self::LONGSEP . \"')\n AS `\" . $NAME . \"`,\n $TRANS\n $ADDITONALFIELDS\";\n }\n $TRANS = '';\n if (Session::haveTranslations(getItemTypeForTable($table), $field)) {\n $TRANS = $tocomputetrans . \" AS `\" . $NAME . \"_trans_\" . $field . \"`, \";\n }\n return \"$tocompute AS `\" . $NAME . \"`, $TRANS $ADDITONALFIELDS\";\n }", "\n /**\n * Generic Function to add default where to a request\n *\n * @param class-string<CommonDBTM> $itemtype device type\n *\n * @return string Where string\n **/\n public static function addDefaultWhere($itemtype)\n {\n $condition = '';", " switch ($itemtype) {\n case 'Reservation':\n $condition = getEntitiesRestrictRequest(\"\", ReservationItem::getTable(), '', '', true);\n break;", " case 'Reminder':\n $condition = Reminder::addVisibilityRestrict();\n break;", " case 'RSSFeed':\n $condition = RSSFeed::addVisibilityRestrict();\n break;", " case 'Notification':\n if (!Config::canView()) {\n $condition = \" `glpi_notifications`.`itemtype` NOT IN ('CronTask', 'DBConnection') \";\n }\n break;", " // No link\n case 'User':\n // View all entities\n if (!Session::canViewAllEntities()) {\n $condition = getEntitiesRestrictRequest(\"\", \"glpi_profiles_users\", '', '', true);\n }\n break;", " case 'ProjectTask':\n $condition = '';\n $teamtable = 'glpi_projecttaskteams';\n $condition .= \"`glpi_projects`.`is_template` = 0\";\n $condition .= \" AND ((`$teamtable`.`itemtype` = 'User'\n AND `$teamtable`.`items_id` = '\" . Session::getLoginUserID() . \"')\";\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR (`$teamtable`.`itemtype` = 'Group'\n AND `$teamtable`.`items_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \"))\";\n }\n $condition .= \") \";\n break;", " case 'Project':\n $condition = '';\n if (!Session::haveRight(\"project\", Project::READALL)) {\n $teamtable = 'glpi_projectteams';\n $condition .= \"(`glpi_projects`.users_id = '\" . Session::getLoginUserID() . \"'\n OR (`$teamtable`.`itemtype` = 'User'\n AND `$teamtable`.`items_id` = '\" . Session::getLoginUserID() . \"')\";\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR (`glpi_projects`.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \"))\";\n $condition .= \" OR (`$teamtable`.`itemtype` = 'Group'\n AND `$teamtable`.`items_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \"))\";\n }\n $condition .= \") \";\n }\n break;", " case 'Ticket':\n // Same structure in addDefaultJoin\n $condition = '';\n if (!Session::haveRight(\"ticket\", Ticket::READALL)) {\n $searchopt\n = &self::getOptions($itemtype);\n $requester_table\n = '`glpi_tickets_users_' .\n self::computeComplexJoinID($searchopt[4]['joinparams']['beforejoin']\n ['joinparams']) . '`';\n $requestergroup_table\n = '`glpi_groups_tickets_' .\n self::computeComplexJoinID($searchopt[71]['joinparams']['beforejoin']\n ['joinparams']) . '`';", " $assign_table\n = '`glpi_tickets_users_' .\n self::computeComplexJoinID($searchopt[5]['joinparams']['beforejoin']\n ['joinparams']) . '`';\n $assigngroup_table\n = '`glpi_groups_tickets_' .\n self::computeComplexJoinID($searchopt[8]['joinparams']['beforejoin']\n ['joinparams']) . '`';", " $observer_table\n = '`glpi_tickets_users_' .\n self::computeComplexJoinID($searchopt[66]['joinparams']['beforejoin']\n ['joinparams']) . '`';\n $observergroup_table\n = '`glpi_groups_tickets_' .\n self::computeComplexJoinID($searchopt[65]['joinparams']['beforejoin']\n ['joinparams']) . '`';", " $condition = \"(\";", " if (Session::haveRight(\"ticket\", Ticket::READMY)) {\n $condition .= \" $requester_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR $observer_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR `glpi_tickets`.`users_id_recipient` = '\" . Session::getLoginUserID() . \"'\";\n } else {\n $condition .= \"0=1\";\n }", " if (Session::haveRight(\"ticket\", Ticket::READGROUP)) {\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR $requestergroup_table.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \")\";\n $condition .= \" OR $observergroup_table.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \")\";\n }\n }", " if (Session::haveRight(\"ticket\", Ticket::OWN)) {// Can own ticket : show assign to me\n $condition .= \" OR $assign_table.users_id = '\" . Session::getLoginUserID() . \"' \";\n }", " if (Session::haveRight(\"ticket\", Ticket::READASSIGN)) { // assign to me\n $condition .= \" OR $assign_table.`users_id` = '\" . Session::getLoginUserID() . \"'\";\n if (count($_SESSION['glpigroups'])) {\n $condition .= \" OR $assigngroup_table.`groups_id`\n IN (\" . implode(\",\", $_SESSION['glpigroups']) . \")\";\n }\n if (Session::haveRight('ticket', Ticket::ASSIGN)) {\n $condition .= \" OR `glpi_tickets`.`status`='\" . CommonITILObject::INCOMING . \"'\";\n }\n }", " if (\n Session::haveRightsOr(\n 'ticketvalidation',\n [TicketValidation::VALIDATEINCIDENT,\n TicketValidation::VALIDATEREQUEST\n ]\n )\n ) {\n $condition .= \" OR `glpi_ticketvalidations`.`users_id_validate`\n = '\" . Session::getLoginUserID() . \"'\";\n }\n $condition .= \") \";\n }\n break;", " case 'Change':\n case 'Problem':\n if ($itemtype == 'Change') {\n $right = 'change';\n $table = 'changes';\n $groupetable = \"`glpi_changes_groups_\";\n } else if ($itemtype == 'Problem') {\n $right = 'problem';\n $table = 'problems';\n $groupetable = \"`glpi_groups_problems_\";\n }\n // Same structure in addDefaultJoin\n $condition = '';\n if (!Session::haveRight(\"$right\", $itemtype::READALL)) {\n $searchopt = &self::getOptions($itemtype);\n if (Session::haveRight(\"$right\", $itemtype::READMY)) {\n $requester_table = '`glpi_' . $table . '_users_' .\n self::computeComplexJoinID($searchopt[4]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n $requestergroup_table = $groupetable .\n self::computeComplexJoinID($searchopt[71]['joinparams']\n ['beforejoin']['joinparams']) . '`';", " $observer_table = '`glpi_' . $table . '_users_' .\n self::computeComplexJoinID($searchopt[66]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n $observergroup_table = $groupetable .\n self::computeComplexJoinID($searchopt[65]['joinparams']\n ['beforejoin']['joinparams']) . '`';", " $assign_table = '`glpi_' . $table . '_users_' .\n self::computeComplexJoinID($searchopt[5]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n $assigngroup_table = $groupetable .\n self::computeComplexJoinID($searchopt[8]['joinparams']\n ['beforejoin']['joinparams']) . '`';\n }\n $condition = \"(\";", " if (Session::haveRight(\"$right\", $itemtype::READMY)) {\n $condition .= \" $requester_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR $observer_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR $assign_table.users_id = '\" . Session::getLoginUserID() . \"'\n OR `glpi_\" . $table . \"`.`users_id_recipient` = '\" . Session::getLoginUserID() . \"'\";\n if (count($_SESSION['glpigroups'])) {\n $my_groups_keys = \"'\" . implode(\"','\", $_SESSION['glpigroups']) . \"'\";\n $condition .= \" OR $requestergroup_table.groups_id IN ($my_groups_keys)\n OR $observergroup_table.groups_id IN ($my_groups_keys)\n OR $assigngroup_table.groups_id IN ($my_groups_keys)\";\n }\n } else {\n $condition .= \"0=1\";\n }", " $condition .= \") \";\n }\n break;", " case 'Config':\n $availableContexts = ['core'] + Plugin::getPlugins();\n $availableContexts = implode(\"', '\", $availableContexts);\n $condition = \"`context` IN ('$availableContexts')\";\n break;", " case 'SavedSearch':\n $condition = SavedSearch::addVisibilityRestrict();\n break;", " case 'TicketTask':\n // Filter on is_private\n $allowed_is_private = [];\n if (Session::haveRight(TicketTask::$rightname, CommonITILTask::SEEPRIVATE)) {\n $allowed_is_private[] = 1;\n }\n if (Session::haveRight(TicketTask::$rightname, CommonITILTask::SEEPUBLIC)) {\n $allowed_is_private[] = 0;\n }", " // If the user can't see public and private\n if (!count($allowed_is_private)) {\n $condition = \"0 = 1\";\n break;\n }", " $in = \"IN ('\" . implode(\"','\", $allowed_is_private) . \"')\";\n $condition = \"(`glpi_tickettasks`.`is_private` $in \";", " // Check for assigned or created tasks\n $condition .= \"OR `glpi_tickettasks`.`users_id` = \" . Session::getLoginUserID() . \" \";\n $condition .= \"OR `glpi_tickettasks`.`users_id_tech` = \" . Session::getLoginUserID() . \" \";", " // Check for parent item visibility unless the user can see all the\n // possible parents\n if (!Session::haveRight('ticket', Ticket::READALL)) {\n $condition .= \"AND \" . TicketTask::buildParentCondition();\n }", " $condition .= \")\";", " break;", " case 'ITILFollowup':\n // Filter on is_private\n $allowed_is_private = [];\n if (Session::haveRight(ITILFollowup::$rightname, ITILFollowup::SEEPRIVATE)) {\n $allowed_is_private[] = 1;\n }\n if (Session::haveRight(ITILFollowup::$rightname, ITILFollowup::SEEPUBLIC)) {\n $allowed_is_private[] = 0;\n }", " // If the user can't see public and private\n if (!count($allowed_is_private)) {\n $condition = \"0 = 1\";\n break;\n }", " $in = \"IN ('\" . implode(\"','\", $allowed_is_private) . \"')\";\n $condition = \"(`glpi_itilfollowups`.`is_private` $in \";", " // Now filter on parent item visiblity\n $condition .= \"AND (\";", " // Filter for \"ticket\" parents\n $condition .= ITILFollowup::buildParentCondition(\\Ticket::getType());\n $condition .= \"OR \";", " // Filter for \"change\" parents\n $condition .= ITILFollowup::buildParentCondition(\n \\Change::getType(),\n 'changes_id',\n \"glpi_changes_users\",\n \"glpi_changes_groups\"\n );\n $condition .= \"OR \";", " // Fitler for \"problem\" parents\n $condition .= ITILFollowup::buildParentCondition(\n \\Problem::getType(),\n 'problems_id',\n \"glpi_problems_users\",\n \"glpi_groups_problems\"\n );\n $condition .= \"))\";", " break;", " default:\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $condition = Plugin::doOneHook($plug['plugin'], 'addDefaultWhere', $itemtype);\n }\n break;\n }", " /* Hook to restrict user right on current itemtype */\n list($itemtype, $condition) = Plugin::doHookFunction('add_default_where', [$itemtype, $condition]);\n return $condition;\n }", " /**\n * Generic Function to add where to a request\n *\n * @param string $link Link string\n * @param boolean $nott Is it a negative search ?\n * @param string $itemtype Item type\n * @param integer $ID ID of the item to search\n * @param string $searchtype Searchtype used (equals or contains)\n * @param string $val Item num in the request\n * @param integer $meta Is a meta search (meta=2 in search.class.php) (default 0)\n *\n * @return string Where string\n **/\n public static function addWhere($link, $nott, $itemtype, $ID, $searchtype, $val, $meta = 0)\n {", " global $DB;", " $searchopt = &self::getOptions($itemtype);\n if (!isset($searchopt[$ID]['table'])) {\n return false;\n }\n $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];", " $inittable = $table;\n $addtable = '';\n $is_fkey_composite_on_self = getTableNameForForeignKeyField($searchopt[$ID][\"linkfield\"]) == $table\n && $searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table);\n $orig_table = self::getOrigTableName($itemtype);\n if (\n ($table != 'asset_types')\n && ($is_fkey_composite_on_self || $table != $orig_table)\n && ($searchopt[$ID][\"linkfield\"] != getForeignKeyFieldForTable($table))\n ) {\n $addtable = \"_\" . $searchopt[$ID][\"linkfield\"];\n $table .= $addtable;\n }", " if (isset($searchopt[$ID]['joinparams'])) {\n $complexjoin = self::computeComplexJoinID($searchopt[$ID]['joinparams']);", " if (!empty($complexjoin)) {\n $table .= \"_\" . $complexjoin;\n }\n }", " $addmeta = \"\";\n if (\n $meta\n && ($itemtype::getTable() != $inittable)\n ) {\n $addmeta = \"_\" . $itemtype;\n $table .= $addmeta;\n }", " // Hack to allow search by ID on every sub-table\n if (preg_match('/^\\$\\$\\$\\$([0-9]+)$/', $val, $regs)) {\n return $link . \" (`$table`.`id` \" . ($nott ? \"<>\" : \"=\") . $regs[1] . \" \" .\n (($regs[1] == 0) ? \" OR `$table`.`id` IS NULL\" : '') . \") \";\n }", " // Preparse value\n if (isset($searchopt[$ID][\"datatype\"])) {\n switch ($searchopt[$ID][\"datatype\"]) {\n case \"datetime\":\n case \"date\":\n case \"date_delay\":\n $force_day = true;\n if (\n $searchopt[$ID][\"datatype\"] == 'datetime'\n && !(strstr($val, 'BEGIN') || strstr($val, 'LAST') || strstr($val, 'DAY'))\n ) {\n $force_day = false;\n }", " $val = Html::computeGenericDateTimeSearch($val, $force_day);", " break;\n }\n }\n switch ($searchtype) {\n case \"notcontains\":\n $nott = !$nott;\n //negated, use contains case\n case \"contains\":\n if (isset($searchopt[$ID][\"datatype\"]) && ($searchopt[$ID][\"datatype\"] === 'decimal')) {\n $matches = [];\n if (preg_match('/^(\\d+.?\\d?)/', $val, $matches)) {\n $val = $matches[1];\n if (!str_contains($val, '.')) {\n $val .= '.';\n }\n }\n }\n $SEARCH = self::makeTextSearch($val, $nott);\n break;", " case \"equals\":\n if ($nott) {\n $SEARCH = \" <> \" . DBmysql::quoteValue($val);\n } else {\n $SEARCH = \" = \" . DBmysql::quoteValue($val);\n }\n break;", " case \"notequals\":\n if ($nott) {\n $SEARCH = \" = \" . DBmysql::quoteValue($val);\n } else {\n $SEARCH = \" <> \" . DBmysql::quoteValue($val);\n }\n break;", " case \"under\":\n if ($nott) {\n $SEARCH = \" NOT IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n } else {\n $SEARCH = \" IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n }\n break;", " case \"notunder\":\n if ($nott) {\n $SEARCH = \" IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n } else {\n $SEARCH = \" NOT IN ('\" . implode(\"','\", getSonsOf($inittable, $val)) . \"')\";\n }\n break;\n }", " //Check in current item if a specific where is defined\n if (method_exists($itemtype, 'addWhere')) {\n $out = $itemtype::addWhere($link, $nott, $itemtype, $ID, $searchtype, $val);\n if (!empty($out)) {\n return $out;\n }\n }", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'addWhere',\n $link,\n $nott,\n $itemtype,\n $ID,\n $val,\n $searchtype\n );\n if (!empty($out)) {\n return $out;\n }\n }", " switch ($inittable . \".\" . $field) {\n // case \"glpi_users_validation.name\" :", " case \"glpi_users.name\":\n if ($val == 'myself') {\n switch ($searchtype) {\n case 'equals':\n return \" $link (`$table`.`id` = \" . $DB->quoteValue($_SESSION['glpiID']) . \") \";", " case 'notequals':\n return \" $link (`$table`.`id` <> \" . $DB->quoteValue($_SESSION['glpiID']) . \") \";\n }\n }", " if ($itemtype == 'User') { // glpi_users case / not link table\n if (in_array($searchtype, ['equals', 'notequals'])) {\n $search_str = \"`$table`.`id`\" . $SEARCH;", " if ($searchtype == 'notequals') {\n $nott = !$nott;\n }", " // Add NULL if $val = 0 and not negative search\n // Or negative search on real value\n if ((!$nott && ($val == 0)) || ($nott && ($val != 0))) {\n $search_str .= \" OR `$table`.`id` IS NULL\";\n }", " return \" $link ($search_str)\";\n }\n return self::makeTextCriteria(\"`$table`.`$field`\", $val, $nott, $link);\n }\n if ($_SESSION[\"glpinames_format\"] == User::FIRSTNAME_BEFORE) {\n $name1 = 'firstname';\n $name2 = 'realname';\n } else {\n $name1 = 'realname';\n $name2 = 'firstname';\n }", " if (in_array($searchtype, ['equals', 'notequals'])) {\n return \" $link (`$table`.`id`\" . $SEARCH .\n (($val == 0) ? \" OR `$table`.`id` IS\" .\n (($searchtype == \"notequals\") ? \" NOT\" : \"\") . \" NULL\" : '') . ') ';\n }\n $toadd = '';", " $tmplink = 'OR';\n if ($nott) {\n $tmplink = 'AND';\n }", " if (is_a($itemtype, CommonITILObject::class, true)) {\n if (\n isset($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"])\n && isset($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"joinparams\"])\n && (($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"]\n == 'glpi_tickets_users')\n || ($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"]\n == 'glpi_problems_users')\n || ($searchopt[$ID][\"joinparams\"][\"beforejoin\"][\"table\"]\n == 'glpi_changes_users'))\n ) {\n $bj = $searchopt[$ID][\"joinparams\"][\"beforejoin\"];\n $linktable = $bj['table'] . '_' . self::computeComplexJoinID($bj['joinparams']) . $addmeta;\n //$toadd = \"`$linktable`.`alternative_email` $SEARCH $tmplink \";\n $toadd = self::makeTextCriteria(\n \"`$linktable`.`alternative_email`\",\n $val,\n $nott,\n $tmplink\n );\n if ($val == '^$') {\n return $link . \" ((`$linktable`.`users_id` IS NULL)\n OR `$linktable`.`alternative_email` IS NULL)\";\n }\n }\n }\n $toadd2 = '';\n if (\n $nott\n && ($val != 'NULL') && ($val != 'null')\n ) {\n $toadd2 = \" OR `$table`.`$field` IS NULL\";\n }\n return $link . \" (((`$table`.`$name1` $SEARCH\n $tmplink `$table`.`$name2` $SEARCH\n $tmplink `$table`.`$field` $SEARCH\n $tmplink CONCAT(`$table`.`$name1`, ' ', `$table`.`$name2`) $SEARCH )\n $toadd2) $toadd)\";", " case \"glpi_groups.completename\":\n if ($val == 'mygroups') {\n switch ($searchtype) {\n case 'equals':\n return \" $link (`$table`.`id` IN ('\" . implode(\n \"','\",\n $_SESSION['glpigroups']\n ) . \"')) \";", " case 'notequals':\n return \" $link (`$table`.`id` NOT IN ('\" . implode(\n \"','\",\n $_SESSION['glpigroups']\n ) . \"')) \";", " case 'under':\n $groups = $_SESSION['glpigroups'];\n foreach ($_SESSION['glpigroups'] as $g) {\n $groups += getSonsOf($inittable, $g);\n }\n $groups = array_unique($groups);\n return \" $link (`$table`.`id` IN ('\" . implode(\"','\", $groups) . \"')) \";", " case 'notunder':\n $groups = $_SESSION['glpigroups'];\n foreach ($_SESSION['glpigroups'] as $g) {\n $groups += getSonsOf($inittable, $g);\n }\n $groups = array_unique($groups);\n return \" $link (`$table`.`id` NOT IN ('\" . implode(\"','\", $groups) . \"')) \";\n }\n }\n break;", " case \"glpi_auth_tables.name\":\n $user_searchopt = self::getOptions('User');\n $tmplink = 'OR';\n if ($nott) {\n $tmplink = 'AND';\n }\n return $link . \" (`glpi_authmails\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[31]['joinparams']) . $addmeta . \"`.`name`\n $SEARCH\n $tmplink `glpi_authldaps\" . $addtable . \"_\" .\n self::computeComplexJoinID($user_searchopt[30]['joinparams']) . $addmeta . \"`.`name`\n $SEARCH ) \";", " case \"glpi_ipaddresses.name\":\n $search = [\"/\\&lt;/\",\"/\\&gt;/\"];\n $replace = [\"<\",\">\"];\n $val = preg_replace($search, $replace, $val);\n if (preg_match(\"/^\\s*([<>])([=]*)[[:space:]]*([0-9\\.]+)/\", $val, $regs)) {\n if ($nott) {\n if ($regs[1] == '<') {\n $regs[1] = '>';\n } else {\n $regs[1] = '<';\n }\n }\n $regs[1] .= $regs[2];\n return $link . \" (INET_ATON(`$table`.`$field`) \" . $regs[1] . \" INET_ATON('\" . $regs[3] . \"')) \";\n }\n break;", " case \"glpi_tickets.status\":\n case \"glpi_problems.status\":\n case \"glpi_changes.status\":\n $tocheck = [];\n if ($item = getItemForItemtype($itemtype)) {\n switch ($val) {\n case 'process':\n $tocheck = $item->getProcessStatusArray();\n break;", " case 'notclosed':\n $tocheck = $item->getAllStatusArray();\n foreach ($item->getClosedStatusArray() as $status) {\n if (isset($tocheck[$status])) {\n unset($tocheck[$status]);\n }\n }\n $tocheck = array_keys($tocheck);\n break;", " case 'old':\n $tocheck = array_merge(\n $item->getSolvedStatusArray(),\n $item->getClosedStatusArray()\n );\n break;", " case 'notold':\n $tocheck = $item::getNotSolvedStatusArray();\n break;", " case 'all':\n $tocheck = array_keys($item->getAllStatusArray());\n break;\n }\n }", " if (count($tocheck) == 0) {\n $statuses = $item->getAllStatusArray();\n if (isset($statuses[$val])) {\n $tocheck = [$val];\n }\n }", " if (count($tocheck)) {\n if ($nott) {\n return $link . \" `$table`.`$field` NOT IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n return $link . \" `$table`.`$field` IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n break;", " case \"glpi_tickets_tickets.tickets_id_1\":\n $tmplink = 'OR';\n $compare = '=';\n if ($nott) {\n $tmplink = 'AND';\n $compare = '<>';\n }\n $toadd2 = '';\n if (\n $nott\n && ($val != 'NULL') && ($val != 'null')\n ) {\n $toadd2 = \" OR `$table`.`$field` IS NULL\";\n }", " return $link . \" (((`$table`.`tickets_id_1` $compare '$val'\n $tmplink `$table`.`tickets_id_2` $compare '$val')\n AND `glpi_tickets`.`id` <> '$val')\n $toadd2)\";", " case \"glpi_tickets.priority\":\n case \"glpi_tickets.impact\":\n case \"glpi_tickets.urgency\":\n case \"glpi_problems.priority\":\n case \"glpi_problems.impact\":\n case \"glpi_problems.urgency\":\n case \"glpi_changes.priority\":\n case \"glpi_changes.impact\":\n case \"glpi_changes.urgency\":\n case \"glpi_projects.priority\":\n if (is_numeric($val)) {\n if ($val > 0) {\n $compare = ($nott ? '<>' : '=');\n return $link . \" `$table`.`$field` $compare '$val'\";\n }\n if ($val < 0) {\n $compare = ($nott ? '<' : '>=');\n return $link . \" `$table`.`$field` $compare '\" . abs($val) . \"'\";\n }\n // Show all\n $compare = ($nott ? '<' : '>=');\n return $link . \" `$table`.`$field` $compare '0' \";\n }\n return \"\";", " case \"glpi_tickets.global_validation\":\n case \"glpi_ticketvalidations.status\":\n case \"glpi_changes.global_validation\":\n case \"glpi_changevalidations.status\":\n if ($val == 'all') {\n return \"\";\n }\n $tocheck = [];\n switch ($val) {\n case 'can':\n $tocheck = CommonITILValidation::getCanValidationStatusArray();\n break;", " case 'all':\n $tocheck = CommonITILValidation::getAllValidationStatusArray();\n break;\n }\n if (count($tocheck) == 0) {\n $tocheck = [$val];\n }\n if (count($tocheck)) {\n if ($nott) {\n return $link . \" `$table`.`$field` NOT IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n return $link . \" `$table`.`$field` IN ('\" . implode(\"','\", $tocheck) . \"')\";\n }\n break;", " case \"glpi_notifications.event\":\n if (in_array($searchtype, ['equals', 'notequals']) && strpos($val, self::SHORTSEP)) {\n $not = 'notequals' === $searchtype ? 'NOT' : '';\n list($itemtype_val, $event_val) = explode(self::SHORTSEP, $val);\n return \" $link $not(`$table`.`event` = '$event_val'\n AND `$table`.`itemtype` = '$itemtype_val')\";\n }\n break;\n }", " //// Default cases", " // Link with plugin tables\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $inittable, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'addWhere',\n $link,\n $nott,\n $itemtype,\n $ID,\n $val,\n $searchtype\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }", " $tocompute = \"`$table`.`$field`\";\n $tocomputetrans = \"`\" . $table . \"_trans_\" . $field . \"`.`value`\";\n if (isset($searchopt[$ID][\"computation\"])) {\n $tocompute = $searchopt[$ID][\"computation\"];\n $tocompute = str_replace($DB->quoteName('TABLE'), 'TABLE', $tocompute);\n $tocompute = str_replace(\"TABLE\", $DB->quoteName(\"$table\"), $tocompute);\n }", " // Preformat items\n if (isset($searchopt[$ID][\"datatype\"])) {\n if ($searchopt[$ID][\"datatype\"] == \"mio\") {\n // Parse value as it may contain a few different formats\n $val = Toolbox::getMioSizeFromString($val);\n }", " switch ($searchopt[$ID][\"datatype\"]) {\n case \"itemtypename\":\n if (in_array($searchtype, ['equals', 'notequals'])) {\n return \" $link (`$table`.`$field`\" . $SEARCH . ') ';\n }\n break;", " case \"itemlink\":\n if (in_array($searchtype, ['equals', 'notequals', 'under', 'notunder'])) {\n return \" $link (`$table`.`id`\" . $SEARCH . ') ';\n }\n break;", " case \"datetime\":\n case \"date\":\n case \"date_delay\":\n if ($searchopt[$ID][\"datatype\"] == 'datetime') {\n // Specific search for datetime\n if (in_array($searchtype, ['equals', 'notequals'])) {\n $val = preg_replace(\"/:00$/\", '', $val);\n $val = '^' . $val;\n if ($searchtype == 'notequals') {\n $nott = !$nott;\n }\n return self::makeTextCriteria(\"`$table`.`$field`\", $val, $nott, $link);\n }\n }\n if ($searchtype == 'lessthan') {\n $val = '<' . $val;\n }\n if ($searchtype == 'morethan') {\n $val = '>' . $val;\n }\n if ($searchtype) {\n $date_computation = $tocompute;\n }\n if (in_array($searchtype, [\"contains\", \"notcontains\"])) {\n $default_charset = DBConnection::getDefaultCharset();\n $date_computation = \"CONVERT($date_computation USING {$default_charset})\";\n }\n $search_unit = ' MONTH ';\n if (isset($searchopt[$ID]['searchunit'])) {\n $search_unit = $searchopt[$ID]['searchunit'];\n }\n if ($searchopt[$ID][\"datatype\"] == \"date_delay\") {\n $delay_unit = ' MONTH ';\n if (isset($searchopt[$ID]['delayunit'])) {\n $delay_unit = $searchopt[$ID]['delayunit'];\n }\n $add_minus = '';\n if (isset($searchopt[$ID][\"datafields\"][3])) {\n $add_minus = \"-`$table`.`\" . $searchopt[$ID][\"datafields\"][3] . \"`\";\n }\n $date_computation = \"ADDDATE(`$table`.\" . $searchopt[$ID][\"datafields\"][1] . \",\n INTERVAL (`$table`.\" . $searchopt[$ID][\"datafields\"][2] . \"\n $add_minus)\n $delay_unit)\";\n }\n if (in_array($searchtype, ['equals', 'notequals'])) {\n return \" $link ($date_computation \" . $SEARCH . ') ';\n }\n $search = [\"/\\&lt;/\",\"/\\&gt;/\"];\n $replace = [\"<\",\">\"];\n $val = preg_replace($search, $replace, $val);\n if (preg_match(\"/^\\s*([<>=]+)(.*)/\", $val, $regs)) {\n if (is_numeric($regs[2])) {\n return $link . \" $date_computation \" . $regs[1] . \"\n ADDDATE(NOW(), INTERVAL \" . $regs[2] . \" $search_unit) \";\n }\n // ELSE Reformat date if needed\n $regs[2] = preg_replace(\n '@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@',\n '\\5-\\3-\\1',\n $regs[2]\n );\n if (preg_match('/[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/', $regs[2])) {\n $ret = $link;\n if ($nott) {\n $ret .= \" NOT(\";\n }\n $ret .= \" $date_computation {$regs[1]} '{$regs[2]}'\";\n if ($nott) {\n $ret .= \")\";\n }\n return $ret;\n }\n return \"\";\n }\n // ELSE standard search\n // Date format modification if needed\n $val = preg_replace('@(\\d{1,2})(-|/)(\\d{1,2})(-|/)(\\d{4})@', '\\5-\\3-\\1', $val);\n if ($date_computation) {\n return self::makeTextCriteria($date_computation, $val, $nott, $link);\n }\n return '';", " case \"right\":\n if ($searchtype == 'notequals') {\n $nott = !$nott;\n }\n return $link . ($nott ? ' NOT' : '') . \" ($tocompute & '$val') \";", " case \"bool\":\n if (!is_numeric($val)) {\n if (strcasecmp($val, __('No')) == 0) {\n $val = 0;\n } else if (strcasecmp($val, __('Yes')) == 0) {\n $val = 1;\n }\n }\n // No break here : use number comparaison case", " case \"count\":\n case \"mio\":\n case \"number\":\n case \"decimal\":\n case \"timestamp\":\n case \"progressbar\":\n $decimal_contains = $searchopt[$ID][\"datatype\"] === 'decimal' && $searchtype === 'contains';\n $search = [\"/\\&lt;/\", \"/\\&gt;/\"];\n $replace = [\"<\", \">\"];\n $val = preg_replace($search, $replace, $val);", " if (preg_match(\"/([<>])([=]*)[[:space:]]*([0-9]+)/\", $val, $regs)) {\n if (in_array($searchtype, [\"notequals\", \"notcontains\"])) {\n $nott = !$nott;\n }\n if ($nott) {\n if ($regs[1] == '<') {\n $regs[1] = '>';\n } else {\n $regs[1] = '<';\n }\n }\n $regs[1] .= $regs[2];\n return $link . \" ($tocompute \" . $regs[1] . \" \" . $regs[3] . \") \";\n }", " if (is_numeric($val) && !$decimal_contains) {\n $numeric_val = floatval($val);", " if (in_array($searchtype, [\"notequals\", \"notcontains\"])) {\n $nott = !$nott;\n }", " if (isset($searchopt[$ID][\"width\"])) {\n $ADD = \"\";\n if (\n $nott\n && ($val != 'NULL') && ($val != 'null')\n ) {\n $ADD = \" OR $tocompute IS NULL\";\n }\n if ($nott) {\n return $link . \" ($tocompute < \" . ($numeric_val - $searchopt[$ID][\"width\"]) . \"\n OR $tocompute > \" . ($numeric_val + $searchopt[$ID][\"width\"]) . \"\n $ADD) \";\n }\n return $link . \" (($tocompute >= \" . ($numeric_val - $searchopt[$ID][\"width\"]) . \"\n AND $tocompute <= \" . ($numeric_val + $searchopt[$ID][\"width\"]) . \")\n $ADD) \";\n }\n if (!$nott) {\n return \" $link ($tocompute = $numeric_val) \";\n }\n return \" $link ($tocompute <> $numeric_val) \";\n }\n break;\n }\n }", " // Default case\n if (in_array($searchtype, ['equals', 'notequals','under', 'notunder'])) {\n if (\n (!isset($searchopt[$ID]['searchequalsonfield'])\n || !$searchopt[$ID]['searchequalsonfield'])\n && ($itemtype == AllAssets::getType()\n || $table != $itemtype::getTable())\n ) {\n $out = \" $link (`$table`.`id`\" . $SEARCH;\n } else {\n $out = \" $link (`$table`.`$field`\" . $SEARCH;\n }\n if ($searchtype == 'notequals') {\n $nott = !$nott;\n }\n // Add NULL if $val = 0 and not negative search\n // Or negative search on real value\n if (\n (!$nott && ($val == 0))\n || ($nott && ($val != 0))\n ) {\n $out .= \" OR `$table`.`id` IS NULL\";\n }\n $out .= ')';\n return $out;\n }\n $transitemtype = getItemTypeForTable($inittable);\n if (Session::haveTranslations($transitemtype, $field)) {\n return \" $link (\" . self::makeTextCriteria($tocompute, $val, $nott, '') . \"\n OR \" . self::makeTextCriteria($tocomputetrans, $val, $nott, '') . \")\";\n }", " return self::makeTextCriteria($tocompute, $val, $nott, $link);\n }", "\n /**\n * Generic Function to add Default left join to a request\n *\n * @param class-string<CommonDBTM> $itemtype Reference item type\n * @param string $ref_table Reference table\n * @param array &$already_link_tables Array of tables already joined\n *\n * @return string Left join string\n **/\n public static function addDefaultJoin($itemtype, $ref_table, array &$already_link_tables)\n {\n $out = '';", " switch ($itemtype) {\n // No link\n case 'User':\n $out = self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_profiles_users\",\n \"profiles_users_id\",\n 0,\n 0,\n ['jointype' => 'child']\n );\n break;", " case 'Reservation':\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n ReservationItem::getTable(),\n ReservationItem::getForeignKeyField(),\n );\n break;", " case 'Reminder':\n $out = Reminder::addVisibilityJoins();\n break;", " case 'RSSFeed':\n $out = RSSFeed::addVisibilityJoins();\n break;", " case 'ProjectTask':\n // Same structure in addDefaultWhere\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_projects\",\n \"projects_id\"\n );\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_projecttaskteams\",\n \"projecttaskteams_id\",\n 0,\n 0,\n ['jointype' => 'child']\n );\n break;", " case 'Project':\n // Same structure in addDefaultWhere\n if (!Session::haveRight(\"project\", Project::READALL)) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_projectteams\",\n \"projectteams_id\",\n 0,\n 0,\n ['jointype' => 'child']\n );\n }\n break;", " case 'Ticket':\n // Same structure in addDefaultWhere\n if (!Session::haveRight(\"ticket\", Ticket::READALL)) {\n $searchopt = &self::getOptions($itemtype);", " // show mine : requester\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[4]['joinparams']['beforejoin']['joinparams']\n );", " if (Session::haveRight(\"ticket\", Ticket::READGROUP)) {\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_groups_tickets\",\n \"groups_tickets_id\",\n 0,\n 0,\n $searchopt[71]['joinparams']['beforejoin']\n ['joinparams']\n );\n }\n }", " // show mine : observer\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[66]['joinparams']['beforejoin']['joinparams']\n );", " if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_groups_tickets\",\n \"groups_tickets_id\",\n 0,\n 0,\n $searchopt[65]['joinparams']['beforejoin']['joinparams']\n );\n }", " if (Session::haveRight(\"ticket\", Ticket::OWN)) { // Can own ticket : show assign to me\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[5]['joinparams']['beforejoin']['joinparams']\n );\n }", " if (Session::haveRightsOr(\"ticket\", [Ticket::READMY, Ticket::READASSIGN])) { // show mine + assign to me\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_tickets_users\",\n \"tickets_users_id\",\n 0,\n 0,\n $searchopt[5]['joinparams']['beforejoin']['joinparams']\n );", " if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_groups_tickets\",\n \"groups_tickets_id\",\n 0,\n 0,\n $searchopt[8]['joinparams']['beforejoin']\n ['joinparams']\n );\n }\n }", " if (\n Session::haveRightsOr(\n 'ticketvalidation',\n [TicketValidation::VALIDATEINCIDENT,\n TicketValidation::VALIDATEREQUEST\n ]\n )\n ) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_ticketvalidations\",\n \"ticketvalidations_id\",\n 0,\n 0,\n $searchopt[58]['joinparams']['beforejoin']['joinparams']\n );\n }\n }\n break;", " case 'Change':\n case 'Problem':\n if ($itemtype == 'Change') {\n $right = 'change';\n $table = 'changes';\n $groupetable = \"glpi_changes_groups\";\n $linkfield = \"changes_groups_id\";\n } else if ($itemtype == 'Problem') {\n $right = 'problem';\n $table = 'problems';\n $groupetable = \"glpi_groups_problems\";\n $linkfield = \"groups_problems_id\";\n }", " // Same structure in addDefaultWhere\n $out = '';\n if (!Session::haveRight(\"$right\", $itemtype::READALL)) {\n $searchopt = &self::getOptions($itemtype);", " if (Session::haveRight(\"$right\", $itemtype::READMY)) {\n // show mine : requester\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_\" . $table . \"_users\",\n $table . \"_users_id\",\n 0,\n 0,\n $searchopt[4]['joinparams']['beforejoin']['joinparams']\n );\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $groupetable,\n $linkfield,\n 0,\n 0,\n $searchopt[71]['joinparams']['beforejoin']['joinparams']\n );\n }", " // show mine : observer\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_\" . $table . \"_users\",\n $table . \"_users_id\",\n 0,\n 0,\n $searchopt[66]['joinparams']['beforejoin']['joinparams']\n );\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $groupetable,\n $linkfield,\n 0,\n 0,\n $searchopt[65]['joinparams']['beforejoin']['joinparams']\n );\n }", " // show mine : assign\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n \"glpi_\" . $table . \"_users\",\n $table . \"_users_id\",\n 0,\n 0,\n $searchopt[5]['joinparams']['beforejoin']['joinparams']\n );\n if (count($_SESSION['glpigroups'])) {\n $out .= self::addLeftJoin(\n $itemtype,\n $ref_table,\n $already_link_tables,\n $groupetable,\n $linkfield,\n 0,\n 0,\n $searchopt[8]['joinparams']['beforejoin']['joinparams']\n );\n }\n }\n }\n break;", " default:\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $plugin_name = $plug['plugin'];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addDefaultJoin';\n $hook_closure = function () use ($hook_function, $itemtype, $ref_table, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $already_link_tables);\n }\n };\n $out = Plugin::doOneHook($plugin_name, $hook_closure);\n }\n break;\n }", " list($itemtype, $out) = Plugin::doHookFunction('add_default_join', [$itemtype, $out]);\n return $out;\n }", "\n /**\n * Generic Function to add left join to a request\n *\n * @param string $itemtype Item type\n * @param string $ref_table Reference table\n * @param array $already_link_tables Array of tables already joined\n * @param string $new_table New table to join\n * @param string $linkfield Linkfield for LeftJoin\n * @param boolean $meta Is it a meta item ? (default 0)\n * @param integer $meta_type Meta type table (default 0)\n * @param array $joinparams Array join parameters (condition / joinbefore...)\n * @param string $field Field to display (needed for translation join) (default '')\n *\n * @return string Left join string\n **/\n public static function addLeftJoin(\n $itemtype,\n $ref_table,\n array &$already_link_tables,\n $new_table,\n $linkfield,\n $meta = 0,\n $meta_type = 0,\n $joinparams = [],\n $field = ''\n ) {", " // Rename table for meta left join\n $AS = \"\";\n $nt = $new_table;\n $cleannt = $nt;", " // Virtual field no link\n if (strpos($linkfield, '_virtual') === 0) {\n return '';\n }", " $complexjoin = self::computeComplexJoinID($joinparams);", " $is_fkey_composite_on_self = getTableNameForForeignKeyField($linkfield) == $ref_table\n && $linkfield != getForeignKeyFieldForTable($ref_table);", " // Auto link\n if (\n ($ref_table == $new_table)\n && empty($complexjoin)\n && !$is_fkey_composite_on_self\n ) {\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n return self::joinDropdownTranslations(\n $transAS,\n $nt,\n $transitemtype,\n $field\n );\n }\n return \"\";\n }", " // Multiple link possibilies case\n if (!empty($linkfield) && ($linkfield != getForeignKeyFieldForTable($new_table))) {\n $nt .= \"_\" . $linkfield;\n $AS = \" AS `$nt`\";\n }", " if (!empty($complexjoin)) {\n $nt .= \"_\" . $complexjoin;\n $AS = \" AS `$nt`\";\n }", " $addmetanum = \"\";\n $rt = $ref_table;\n $cleanrt = $rt;\n if ($meta && $meta_type::getTable() != $new_table) {\n $addmetanum = \"_\" . $meta_type;\n $AS = \" AS `$nt$addmetanum`\";\n $nt = $nt . $addmetanum;\n }", " // Do not take into account standard linkfield\n $tocheck = $nt . \".\" . $linkfield;\n if ($linkfield == getForeignKeyFieldForTable($new_table)) {\n $tocheck = $nt;\n }", " if (in_array($tocheck, $already_link_tables)) {\n return \"\";\n }\n array_push($already_link_tables, $tocheck);", " $specific_leftjoin = '';", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $plugin_name = $plug['plugin'];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addLeftJoin';\n $hook_closure = function () use ($hook_function, $itemtype, $ref_table, $new_table, $linkfield, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $new_table, $linkfield, $already_link_tables);\n }\n };\n $specific_leftjoin = Plugin::doOneHook($plugin_name, $hook_closure);\n }", " // Link with plugin tables : need to know left join structure\n if (\n empty($specific_leftjoin)\n && preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $new_table, $matches)\n ) {\n if (count($matches) == 2) {\n $plugin_name = $matches[1];\n $hook_function = 'plugin_' . strtolower($plugin_name) . '_addLeftJoin';\n $hook_closure = function () use ($hook_function, $itemtype, $ref_table, $new_table, $linkfield, &$already_link_tables) {\n if (is_callable($hook_function)) {\n return $hook_function($itemtype, $ref_table, $new_table, $linkfield, $already_link_tables);\n }\n };\n $specific_leftjoin = Plugin::doOneHook($plugin_name, $hook_closure);\n }\n }\n if (!empty($linkfield)) {\n $before = '';", " if (isset($joinparams['beforejoin']) && is_array($joinparams['beforejoin'])) {\n if (isset($joinparams['beforejoin']['table'])) {\n $joinparams['beforejoin'] = [$joinparams['beforejoin']];\n }", " foreach ($joinparams['beforejoin'] as $tab) {\n if (isset($tab['table'])) {\n $intertable = $tab['table'];\n if (isset($tab['linkfield'])) {\n $interlinkfield = $tab['linkfield'];\n } else {\n $interlinkfield = getForeignKeyFieldForTable($intertable);\n }", " $interjoinparams = [];\n if (isset($tab['joinparams'])) {\n $interjoinparams = $tab['joinparams'];\n }\n $before .= self::addLeftJoin(\n $itemtype,\n $rt,\n $already_link_tables,\n $intertable,\n $interlinkfield,\n $meta,\n $meta_type,\n $interjoinparams\n );\n }", " // No direct link with the previous joins\n if (!isset($tab['joinparams']['nolink']) || !$tab['joinparams']['nolink']) {\n $cleanrt = $intertable;\n $complexjoin = self::computeComplexJoinID($interjoinparams);\n if (!empty($interlinkfield) && ($interlinkfield != getForeignKeyFieldForTable($intertable))) {\n $intertable .= \"_\" . $interlinkfield;\n }\n if (!empty($complexjoin)) {\n $intertable .= \"_\" . $complexjoin;\n }\n if ($meta && $meta_type::getTable() != $cleanrt) {\n $intertable .= \"_\" . $meta_type;\n }\n $rt = $intertable;\n }\n }\n }", " $addcondition = '';\n if (isset($joinparams['condition'])) {\n $condition = $joinparams['condition'];\n if (is_array($condition)) {\n $it = new DBmysqlIterator(null);\n $condition = ' AND ' . $it->analyseCrit($condition);\n }\n $from = [\"`REFTABLE`\", \"REFTABLE\", \"`NEWTABLE`\", \"NEWTABLE\"];\n $to = [\"`$rt`\", \"`$rt`\", \"`$nt`\", \"`$nt`\"];\n $addcondition = str_replace($from, $to, $condition);\n $addcondition = $addcondition . \" \";\n }", " if (!isset($joinparams['jointype'])) {\n $joinparams['jointype'] = 'standard';\n }", " if (empty($specific_leftjoin)) {\n switch ($new_table) {\n // No link\n case \"glpi_auth_tables\":\n $user_searchopt = self::getOptions('User');", " $specific_leftjoin = self::addLeftJoin(\n $itemtype,\n $rt,\n $already_link_tables,\n \"glpi_authldaps\",\n 'auths_id',\n 0,\n 0,\n $user_searchopt[30]['joinparams']\n );\n $specific_leftjoin .= self::addLeftJoin(\n $itemtype,\n $rt,\n $already_link_tables,\n \"glpi_authmails\",\n 'auths_id',\n 0,\n 0,\n $user_searchopt[31]['joinparams']\n );\n break;\n }\n }", " if (empty($specific_leftjoin)) {\n switch ($joinparams['jointype']) {\n case 'child':\n $linkfield = getForeignKeyFieldForTable($cleanrt);\n if (isset($joinparams['linkfield'])) {\n $linkfield = $joinparams['linkfield'];\n }", " // Child join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$rt`.`id` = `$nt`.`$linkfield`\n $addcondition)\";\n break;", " case 'item_item':\n // Item_Item join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON ((`$rt`.`id`\n = `$nt`.`\" . getForeignKeyFieldForTable($cleanrt) . \"_1`\n OR `$rt`.`id`\n = `$nt`.`\" . getForeignKeyFieldForTable($cleanrt) . \"_2`)\n $addcondition)\";\n break;", " case 'item_item_revert':\n // Item_Item join reverting previous item_item\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON ((`$nt`.`id`\n = `$rt`.`\" . getForeignKeyFieldForTable($cleannt) . \"_1`\n OR `$nt`.`id`\n = `$rt`.`\" . getForeignKeyFieldForTable($cleannt) . \"_2`)\n $addcondition)\";\n break;", " case \"mainitemtype_mainitem\":\n $addmain = 'main';\n //addmain defined to be used in itemtype_item case", " case \"itemtype_item\":\n if (!isset($addmain)) {\n $addmain = '';\n }\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$rt`.`id` = `$nt`.`\" . $addmain . \"items_id`\n AND `$nt`.`\" . $addmain . \"itemtype` = '$used_itemtype'\n $addcondition) \";\n break;", " case \"itemtype_item_revert\":\n if (!isset($addmain)) {\n $addmain = '';\n }\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$nt`.`id` = `$rt`.`\" . $addmain . \"items_id`\n AND `$rt`.`\" . $addmain . \"itemtype` = '$used_itemtype'\n $addcondition) \";\n break;", " case \"itemtypeonly\":\n $used_itemtype = $itemtype;\n if (\n isset($joinparams['specific_itemtype'])\n && !empty($joinparams['specific_itemtype'])\n ) {\n $used_itemtype = $joinparams['specific_itemtype'];\n }\n // Itemtype join\n $specific_leftjoin = \" LEFT JOIN `$new_table` $AS\n ON (`$nt`.`itemtype` = '$used_itemtype'\n $addcondition) \";\n break;", " default:\n // Standard join\n $specific_leftjoin = \"LEFT JOIN `$new_table` $AS\n ON (`$rt`.`$linkfield` = `$nt`.`id`\n $addcondition)\";\n $transitemtype = getItemTypeForTable($new_table);\n if (Session::haveTranslations($transitemtype, $field)) {\n $transAS = $nt . '_trans_' . $field;\n $specific_leftjoin .= self::joinDropdownTranslations(\n $transAS,\n $nt,\n $transitemtype,\n $field\n );\n }\n break;\n }\n }\n return $before . $specific_leftjoin;\n }", " return '';\n }", "\n /**\n * Generic Function to add left join for meta items\n *\n * @param string $from_type Reference item type ID\n * @param string $to_type Item type to add\n * @param array $already_link_tables2 Array of tables already joined\n *showGenericSearch\n * @return string Meta Left join string\n **/\n public static function addMetaLeftJoin(\n $from_type,\n $to_type,\n array &$already_link_tables2,\n $joinparams = []\n ) {\n global $CFG_GLPI;", " $from_referencetype = self::getMetaReferenceItemtype($from_type);", " $LINK = \" LEFT JOIN \";", " $from_table = $from_type::getTable();\n $from_fk = getForeignKeyFieldForTable($from_table);\n $to_table = $to_type::getTable();\n $to_fk = getForeignKeyFieldForTable($to_table);", " $to_obj = getItemForItemtype($to_type);\n $to_entity_restrict = $to_obj->isField('entities_id') ? getEntitiesRestrictRequest('AND', $to_table) : '';", " $complexjoin = self::computeComplexJoinID($joinparams);\n $alias_suffix = ($complexjoin != '' ? '_' . $complexjoin : '') . '_' . $to_type;", " $JOIN = \"\";", " // Specific JOIN\n if ($from_referencetype === 'Software' && in_array($to_type, $CFG_GLPI['software_types'])) {\n // From Software to software_types\n $softwareversions_table = \"glpi_softwareversions{$alias_suffix}\";\n if (!in_array($softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $softwareversions_table);\n $JOIN .= \"$LINK `glpi_softwareversions` AS `$softwareversions_table`\n ON (`$softwareversions_table`.`softwares_id` = `$from_table`.`id`) \";\n }\n $items_softwareversions_table = \"glpi_items_softwareversions_{$alias_suffix}\";\n if (!in_array($items_softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $items_softwareversions_table);\n $JOIN .= \"$LINK `glpi_items_softwareversions` AS `$items_softwareversions_table`\n ON (`$items_softwareversions_table`.`softwareversions_id` = `$softwareversions_table`.`id`\n AND `$items_softwareversions_table`.`itemtype` = '$to_type'\n AND `$items_softwareversions_table`.`is_deleted` = 0) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$items_softwareversions_table`.`items_id` = `$to_table`.`id`\n AND `$items_softwareversions_table`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($to_type === 'Software' && in_array($from_referencetype, $CFG_GLPI['software_types'])) {\n // From software_types to Software\n $items_softwareversions_table = \"glpi_items_softwareversions{$alias_suffix}\";\n if (!in_array($items_softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $items_softwareversions_table);\n $JOIN .= \"$LINK `glpi_items_softwareversions` AS `$items_softwareversions_table`\n ON (`$items_softwareversions_table`.`items_id` = `$from_table`.`id`\n AND `$items_softwareversions_table`.`itemtype` = '$from_type'\n AND `$items_softwareversions_table`.`is_deleted` = 0) \";\n }\n $softwareversions_table = \"glpi_softwareversions{$alias_suffix}\";\n if (!in_array($softwareversions_table, $already_link_tables2)) {\n array_push($already_link_tables2, $softwareversions_table);\n $JOIN .= \"$LINK `glpi_softwareversions` AS `$softwareversions_table`\n ON (`$items_softwareversions_table`.`softwareversions_id` = `$softwareversions_table`.`id`) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$softwareversions_table`.`softwares_id` = `$to_table`.`id`) \";\n }\n $softwarelicenses_table = \"glpi_softwarelicenses{$alias_suffix}\";\n if (!in_array($softwarelicenses_table, $already_link_tables2)) {\n array_push($already_link_tables2, $softwarelicenses_table);\n $JOIN .= \"$LINK `glpi_softwarelicenses` AS `$softwarelicenses_table`\n ON ($to_table.`id` = `$softwarelicenses_table`.`softwares_id`\"\n . getEntitiesRestrictRequest(' AND', $softwarelicenses_table, '', '', true) . \") \";\n }\n return $JOIN;\n }", " if ($from_referencetype === 'Budget' && in_array($to_type, $CFG_GLPI['infocom_types'])) {\n // From Budget to infocom_types\n $infocom_alias = \"glpi_infocoms{$alias_suffix}\";\n if (!in_array($infocom_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $infocom_alias);\n $JOIN .= \"$LINK `glpi_infocoms` AS `$infocom_alias`\n ON (`$from_table`.`id` = `$infocom_alias`.`budgets_id`) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$to_table`.`id` = `$infocom_alias`.`items_id`\n AND `$infocom_alias`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($to_type === 'Budget' && in_array($from_referencetype, $CFG_GLPI['infocom_types'])) {\n // From infocom_types to Budget\n $infocom_alias = \"glpi_infocoms{$alias_suffix}\";\n if (!in_array($infocom_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $infocom_alias);\n $JOIN .= \"$LINK `glpi_infocoms` AS `$infocom_alias`\n ON (`$from_table`.`id` = `$infocom_alias`.`items_id`\n AND `$infocom_alias`.`itemtype` = '$from_type') \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$infocom_alias`.`$to_fk` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($from_referencetype === 'Reservation' && in_array($to_type, $CFG_GLPI['reservation_types'])) {\n // From Reservation to reservation_types\n $reservationitems_alias = \"glpi_reservationitems{$alias_suffix}\";\n if (!in_array($reservationitems_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $reservationitems_alias);\n $JOIN .= \"$LINK `glpi_reservationitems` AS `$reservationitems_alias`\n ON (`$from_table`.`reservationitems_id` = `$reservationitems_alias`.`id`) \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$to_table`.`id` = `$reservationitems_alias`.`items_id`\n AND `$reservationitems_alias`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " if ($to_type === 'Reservation' && in_array($from_referencetype, $CFG_GLPI['reservation_types'])) {\n // From reservation_types to Reservation\n $reservationitems_alias = \"glpi_reservationitems{$alias_suffix}\";\n if (!in_array($reservationitems_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $reservationitems_alias);\n $JOIN .= \"$LINK `glpi_reservationitems` AS `$reservationitems_alias`\n ON (`$from_table`.`id` = `$reservationitems_alias`.`items_id`\n AND `$reservationitems_alias`.`itemtype` = '$from_type') \";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$reservationitems_alias`.`id` = `$to_table`.`reservationitems_id`\n $to_entity_restrict) \";\n }\n return $JOIN;\n }", " // Generic JOIN\n $from_obj = getItemForItemtype($from_referencetype);\n $from_item_obj = null;\n $to_obj = getItemForItemtype($to_type);\n $to_item_obj = null;\n if (self::isPossibleMetaSubitemOf($from_referencetype, $to_type)) {\n $from_item_obj = getItemForItemtype($from_referencetype . '_Item');\n if (!$from_item_obj) {\n $from_item_obj = getItemForItemtype('Item_' . $from_referencetype);\n }\n }\n if (self::isPossibleMetaSubitemOf($to_type, $from_referencetype)) {\n $to_item_obj = getItemForItemtype($to_type . '_Item');\n if (!$to_item_obj) {\n $to_item_obj = getItemForItemtype('Item_' . $to_type);\n }\n }", " if ($from_obj && $from_obj->isField($to_fk)) {\n // $from_table has a foreign key corresponding to $to_table\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`$to_fk` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n } else if ($to_obj && $to_obj->isField($from_fk)) {\n // $to_table has a foreign key corresponding to $from_table\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`id` = `$to_table`.`$from_fk`\n $to_entity_restrict) \";\n }\n } else if ($from_obj && $from_obj->isField('itemtype') && $from_obj->isField('items_id')) {\n // $from_table has items_id/itemtype fields\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`items_id` = `$to_table`.`id`\n AND `$from_table`.`itemtype` = '$to_type'\n $to_entity_restrict) \";\n }\n } else if ($to_obj && $to_obj->isField('itemtype') && $to_obj->isField('items_id')) {\n // $to_table has items_id/itemtype fields\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$from_table`.`id` = `$to_table`.`items_id`\n AND `$to_table`.`itemtype` = '$from_type'\n $to_entity_restrict) \";\n }\n } else if ($from_item_obj && $from_item_obj->isField($from_fk)) {\n // glpi_$from_items table exists and has a foreign key corresponding to $to_table\n $items_table = $from_item_obj::getTable();\n $items_table_alias = $items_table . $alias_suffix;\n if (!in_array($items_table_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $items_table_alias);\n $deleted = $from_item_obj->isField('is_deleted') ? \"AND `$items_table_alias`.`is_deleted` = 0\" : \"\";\n $JOIN .= \"$LINK `$items_table` AS `$items_table_alias`\n ON (`$items_table_alias`.`$from_fk` = `$from_table`.`id`\n AND `$items_table_alias`.`itemtype` = '$to_type'\n $deleted)\";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$items_table_alias`.`items_id` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n } else if ($to_item_obj && $to_item_obj->isField($to_fk)) {\n // glpi_$to_items table exists and has a foreign key corresponding to $from_table\n $items_table = $to_item_obj::getTable();\n $items_table_alias = $items_table . $alias_suffix;\n if (!in_array($items_table_alias, $already_link_tables2)) {\n array_push($already_link_tables2, $items_table_alias);\n $deleted = $to_item_obj->isField('is_deleted') ? \"AND `$items_table_alias`.`is_deleted` = 0\" : \"\";\n $JOIN .= \"$LINK `$items_table` AS `$items_table_alias`\n ON (`$items_table_alias`.`items_id` = `$from_table`.`id`\n AND `$items_table_alias`.`itemtype` = '$from_type'\n $deleted)\";\n }\n if (!in_array($to_table, $already_link_tables2)) {\n array_push($already_link_tables2, $to_table);\n $JOIN .= \"$LINK `$to_table`\n ON (`$items_table_alias`.`$to_fk` = `$to_table`.`id`\n $to_entity_restrict) \";\n }\n }", " return $JOIN;\n }", "\n /**\n * Generic Function to display Items\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $itemtype item type\n * @param integer $ID ID of the SEARCH_OPTION item\n * @param array $data array retrieved data array\n *\n * @return string String to print\n **/\n public static function displayConfigItem($itemtype, $ID, $data = [])\n {", " $searchopt = &self::getOptions($itemtype);", " $table = $searchopt[$ID][\"table\"];\n $field = $searchopt[$ID][\"field\"];", " // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'displayConfigItem',\n $itemtype,\n $ID,\n $data,\n \"{$itemtype}_{$ID}\"\n );\n if (!empty($out)) {\n return $out;\n }\n }", " $out = \"\";\n $NAME = \"{$itemtype}_{$ID}\";", " switch ($table . \".\" . $field) {\n case \"glpi_tickets.time_to_resolve\":\n case \"glpi_tickets.internal_time_to_resolve\":\n case \"glpi_problems.time_to_resolve\":\n case \"glpi_changes.time_to_resolve\":\n if (in_array($ID, [151, 181])) {\n break; // Skip \"TTR + progress\" search options\n }", " $value = $data[$NAME][0]['name'];\n $status = $data[$NAME][0]['status'];\n $solve_date = $data[$NAME][0]['solvedate'];", " $is_late = !empty($value)\n && $status != CommonITILObject::WAITING\n && (\n $solve_date > $value\n || ($solve_date == null && $value < $_SESSION['glpi_currenttime'])\n );", " if ($is_late) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: #cf9b9b\\\" \";\n }\n break;\n case \"glpi_tickets.time_to_own\":\n case \"glpi_tickets.internal_time_to_own\":\n if (in_array($ID, [158, 186])) {\n break; // Skip \"TTO + progress\" search options\n }", " $value = $data[$NAME][0]['name'];\n $status = $data[$NAME][0]['status'];\n $opening_date = $data[$NAME][0]['date'];\n $tia_time = $data[$NAME][0]['takeintoaccount_delay_stat'];", " $is_late = !empty($value)\n && $status != CommonITILObject::WAITING\n && (\n $tia_time > strtotime($opening_date) - strtotime($value)\n || ($tia_time == 0 && $value < $_SESSION['glpi_currenttime'])\n );", " if ($is_late) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: #cf9b9b\\\" \";\n }\n break;", " case \"glpi_projectstates.color\":\n case \"glpi_cables.color\":\n $bg_color = $data[$NAME][0]['name'];\n if (!empty($bg_color)) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: $bg_color;\\\" \";\n }\n break;", " case \"glpi_projectstates.name\":\n if (array_key_exists('color', $data[$NAME][0])) {\n $bg_color = $data[$NAME][0]['color'];\n if (!empty($bg_color)) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: $bg_color;\\\" \";\n }\n }\n break;", " case \"glpi_domains.date_expiration\":\n case \"glpi_certificates.date_expiration\":\n if (\n !empty($data[$NAME][0]['name'])\n && ($data[$NAME][0]['name'] < $_SESSION['glpi_currenttime'])\n ) {\n $out = \" class=\\\"shadow-none\\\" style=\\\"background-color: #cf9b9b\\\" \";\n }\n break;\n }", " return $out;\n }", "\n /**\n * Generic Function to display Items\n *\n * @since 9.4: $num param has been dropped\n *\n * @param string $itemtype item type\n * @param integer $ID ID of the SEARCH_OPTION item\n * @param array $data array containing data results\n * @param boolean $meta is a meta item ? (default 0)\n * @param array $addobjectparams array added parameters for union search\n * @param string $orig_itemtype Original itemtype, used for union_search_type\n *\n * @return string String to print\n **/\n public static function giveItem(\n $itemtype,\n $ID,\n array $data,\n $meta = 0,\n array $addobjectparams = [],\n $orig_itemtype = null\n ) {\n global $CFG_GLPI;", " $searchopt = &self::getOptions($itemtype);\n if (\n isset($CFG_GLPI[\"union_search_type\"][$itemtype])\n && ($CFG_GLPI[\"union_search_type\"][$itemtype] == $searchopt[$ID][\"table\"])\n ) {\n $oparams = [];\n if (\n isset($searchopt[$ID]['addobjectparams'])\n && $searchopt[$ID]['addobjectparams']\n ) {\n $oparams = $searchopt[$ID]['addobjectparams'];\n }", " // Search option may not exists in subtype\n // This is the case for \"Inventory number\" for a Software listed from ReservationItem search\n $subtype_so = &self::getOptions($data[\"TYPE\"]);\n if (!array_key_exists($ID, $subtype_so)) {\n return '';\n }", " return self::giveItem($data[\"TYPE\"], $ID, $data, $meta, $oparams, $itemtype);\n }\n $so = $searchopt[$ID];\n $orig_id = $ID;\n $ID = ($orig_itemtype !== null ? $orig_itemtype : $itemtype) . '_' . $ID;", " if (count($addobjectparams)) {\n $so = array_merge($so, $addobjectparams);\n }\n // Plugin can override core definition for its type\n if ($plug = isPluginItemType($itemtype)) {\n $out = Plugin::doOneHook(\n $plug['plugin'],\n 'giveItem',\n $itemtype,\n $orig_id,\n $data,\n $ID\n );\n if (!empty($out)) {\n return $out;\n }\n }", "\n $html_output = in_array(\n self::$output_type,\n [\n self::HTML_OUTPUT,\n self::GLOBAL_SEARCH, // For a global search, output will be done in HTML context\n ]\n );", "\n if (isset($so[\"table\"])) {\n $table = $so[\"table\"];\n $field = $so[\"field\"];\n $linkfield = $so[\"linkfield\"];", " /// TODO try to clean all specific cases using SpecificToDisplay", " switch ($table . '.' . $field) {\n case \"glpi_users.name\":\n // USER search case\n if (\n ($itemtype != 'User')\n && isset($so[\"forcegroupby\"]) && $so[\"forcegroupby\"]\n ) {\n $out = \"\";\n $count_display = 0;\n $added = [];", " $showuserlink = 0;\n if (Session::haveRight('user', READ)) {\n $showuserlink = 1;\n }", " for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n (isset($data[$ID][$k]['name']) && ($data[$ID][$k]['name'] > 0))\n || (isset($data[$ID][$k][2]) && ($data[$ID][$k][2] != ''))\n ) {\n if ($count_display) {\n $out .= self::LBBR;\n }", " if ($itemtype == 'Ticket') {\n if (\n isset($data[$ID][$k]['name'])\n && $data[$ID][$k]['name'] > 0\n ) {\n if (\n Session::getCurrentInterface() == 'helpdesk'\n && $orig_id == 5 // -> Assigned user\n && !empty($anon_name = User::getAnonymizedNameForUser(\n $data[$ID][$k]['name'],\n $itemtype::getById($data['id'])->getEntityId()\n ))\n ) {\n $out .= $anon_name;\n } else {\n $userdata = getUserName($data[$ID][$k]['name'], 2);\n $tooltip = \"\";\n if (Session::haveRight('user', READ)) {\n $tooltip = Html::showToolTip(\n $userdata[\"comment\"],\n ['link' => $userdata[\"link\"],\n 'display' => false\n ]\n );\n }\n $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);\n }", " $count_display++;\n }\n } else {\n $out .= getUserName($data[$ID][$k]['name'], $showuserlink);\n $count_display++;\n }", " // Manage alternative_email for tickets_users\n if (\n ($itemtype == 'Ticket')\n && isset($data[$ID][$k][2])\n ) {\n $split = explode(self::LONGSEP, $data[$ID][$k][2]);\n for ($l = 0; $l < count($split); $l++) {\n $split2 = explode(\" \", $split[$l]);\n if ((count($split2) == 2) && ($split2[0] == 0) && !empty($split2[1])) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= \"<a href='mailto:\" . $split2[1] . \"'>\" . $split2[1] . \"</a>\";\n }\n }\n }\n }\n }\n return $out;\n }\n if ($itemtype != 'User') {\n $toadd = '';\n if (\n ($itemtype == 'Ticket')\n && ($data[$ID][0]['id'] > 0)\n ) {\n $userdata = getUserName($data[$ID][0]['id'], 2);\n $toadd = Html::showToolTip(\n $userdata[\"comment\"],\n ['link' => $userdata[\"link\"],\n 'display' => false\n ]\n );\n }\n $usernameformat = formatUserName(\n $data[$ID][0]['id'],\n $data[$ID][0]['name'],\n $data[$ID][0]['realname'],\n $data[$ID][0]['firstname'],\n 1\n );\n return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);\n }", " $current_users_id = $data[$ID][0]['id'] ?? 0;\n if ($current_users_id > 0) {\n return TemplateRenderer::getInstance()->render('components/user/picture.html.twig', [\n 'users_id' => $current_users_id,\n 'display_login' => true,\n 'force_login' => true,\n 'avatar_size' => \"avatar-sm\",\n ]);\n }\n break;", " case \"glpi_profiles.name\":\n if (\n ($itemtype == 'User')\n && ($orig_id == 20)\n ) {\n $out = \"\";", " $count_display = 0;\n $added = [];\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n strlen(trim($data[$ID][$k]['name'])) > 0\n && !in_array(\n $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['entities_id'],\n $added\n )\n ) {\n $text = sprintf(\n __('%1$s - %2$s'),\n $data[$ID][$k]['name'],\n Dropdown::getDropdownName(\n 'glpi_entities',\n $data[$ID][$k]['entities_id']\n )\n );\n $comp = '';\n if ($data[$ID][$k]['is_recursive']) {\n $comp = __('R');\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, \", \");\n }\n }\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));\n }\n if (!empty($comp)) {\n $text = sprintf(__('%1$s %2$s'), $text, \"(\" . $comp . \")\");\n }\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= $text;\n $added[] = $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['entities_id'];\n }\n }\n return $out;\n }\n break;", " case \"glpi_entities.completename\":\n if ($itemtype == 'User') {\n $out = \"\";\n $added = [];\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n isset($data[$ID][$k]['name'])\n && (strlen(trim($data[$ID][$k]['name'])) > 0)\n && !in_array(\n $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['profiles_id'],\n $added\n )\n ) {\n $text = sprintf(\n __('%1$s - %2$s'),\n Entity::badgeCompletename($data[$ID][$k]['name']),\n Dropdown::getDropdownName(\n 'glpi_profiles',\n $data[$ID][$k]['profiles_id']\n )\n );\n $comp = '';\n if ($data[$ID][$k]['is_recursive']) {\n $comp = __('R');\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, \", \");\n }\n }\n if ($data[$ID][$k]['is_dynamic']) {\n $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));\n }\n if (!empty($comp)) {\n $text = sprintf(__('%1$s %2$s'), $text, \"(\" . $comp . \")\");\n }\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= $text;\n $added[] = $data[$ID][$k]['name'] . \"-\" . $data[$ID][$k]['profiles_id'];\n }\n }\n return $out;\n } else if (($so[\"datatype\"] ?? \"\") != \"itemlink\" && !empty($data[$ID][0]['name'])) {\n return Entity::badgeCompletename($data[$ID][0]['name']);\n }\n break;", " case \"glpi_documenttypes.icon\":\n if (!empty($data[$ID][0]['name'])) {\n return \"<img class='middle' alt='' src='\" . $CFG_GLPI[\"typedoc_icon_dir\"] . \"/\" .\n $data[$ID][0]['name'] . \"'>\";\n }\n return \"&nbsp;\";", " case \"glpi_documents.filename\":\n $doc = new Document();\n if ($doc->getFromDB($data['id'])) {\n return $doc->getDownloadLink();\n }\n return NOT_AVAILABLE;", " case \"glpi_tickets_tickets.tickets_id_1\":\n $out = \"\";\n $displayed = [];\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n $linkid = ($data[$ID][$k]['tickets_id_2'] == $data['id'])\n ? $data[$ID][$k]['name']\n : $data[$ID][$k]['tickets_id_2'];", " // If link ID is int or integer string, force conversion to int. Coversion to int and then string to compare is needed to ensure it isn't a decimal\n if (is_numeric($linkid) && ((string)(int)$linkid === (string)$linkid)) {\n $linkid = (int) $linkid;\n }\n if ((is_int($linkid) && $linkid > 0) && !isset($displayed[$linkid])) {\n $text = \"<a \";\n $text .= \"href=\\\"\" . Ticket::getFormURLWithID($linkid) . \"\\\">\";\n $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . \"</a>\";\n if (count($displayed)) {\n $out .= self::LBBR;\n }\n $displayed[$linkid] = $linkid;\n $out .= $text;\n }\n }\n return $out;", " case \"glpi_problems.id\":\n if ($so[\"datatype\"] == 'count') {\n if (\n ($data[$ID][0]['name'] > 0)\n && Session::haveRight(\"problem\", Problem::READALL)\n ) {\n if ($itemtype == 'ITILCategory') {\n $options['criteria'][0]['field'] = 7;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n } else {\n $options['criteria'][0]['field'] = 12;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = 'all';\n $options['criteria'][0]['link'] = 'AND';", " $options['metacriteria'][0]['itemtype'] = $itemtype;\n $options['metacriteria'][0]['field'] = self::getOptionNumber(\n $itemtype,\n 'name'\n );\n $options['metacriteria'][0]['searchtype'] = 'equals';\n $options['metacriteria'][0]['value'] = $data['id'];\n $options['metacriteria'][0]['link'] = 'AND';\n }", " $options['reset'] = 'reset';", " $out = \"<a id='problem$itemtype\" . $data['id'] . \"' \";\n $out .= \"href=\\\"\" . $CFG_GLPI[\"root_doc\"] . \"/front/problem.php?\" .\n Toolbox::append_params($options, '&amp;') . \"\\\">\";\n $out .= $data[$ID][0]['name'] . \"</a>\";\n return $out;\n }\n }\n break;", " case \"glpi_tickets.id\":\n if ($so[\"datatype\"] == 'count') {\n if (\n ($data[$ID][0]['name'] > 0)\n && Session::haveRight(\"ticket\", Ticket::READALL)\n ) {\n if ($itemtype == 'User') {\n // Requester\n if ($ID == 'User_60') {\n $options['criteria'][0]['field'] = 4;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n }", " // Writer\n if ($ID == 'User_61') {\n $options['criteria'][0]['field'] = 22;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n }\n // Assign\n if ($ID == 'User_64') {\n $options['criteria'][0]['field'] = 5;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n }\n } else if ($itemtype == 'ITILCategory') {\n $options['criteria'][0]['field'] = 7;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = $data['id'];\n $options['criteria'][0]['link'] = 'AND';\n } else {\n $options['criteria'][0]['field'] = 12;\n $options['criteria'][0]['searchtype'] = 'equals';\n $options['criteria'][0]['value'] = 'all';\n $options['criteria'][0]['link'] = 'AND';", " $options['metacriteria'][0]['itemtype'] = $itemtype;\n $options['metacriteria'][0]['field'] = self::getOptionNumber(\n $itemtype,\n 'name'\n );\n $options['metacriteria'][0]['searchtype'] = 'equals';\n $options['metacriteria'][0]['value'] = $data['id'];\n $options['metacriteria'][0]['link'] = 'AND';\n }", " $options['reset'] = 'reset';", " $out = \"<a id='ticket$itemtype\" . $data['id'] . \"' \";\n $out .= \"href=\\\"\" . $CFG_GLPI[\"root_doc\"] . \"/front/ticket.php?\" .\n Toolbox::append_params($options, '&amp;') . \"\\\">\";\n $out .= $data[$ID][0]['name'] . \"</a>\";\n return $out;\n }\n }\n break;", " case \"glpi_tickets.time_to_resolve\":\n case \"glpi_problems.time_to_resolve\":\n case \"glpi_changes.time_to_resolve\":\n case \"glpi_tickets.time_to_own\":\n case \"glpi_tickets.internal_time_to_own\":\n case \"glpi_tickets.internal_time_to_resolve\":\n // Due date + progress\n if (in_array($orig_id, [151, 158, 181, 186])) {\n $out = Html::convDateTime($data[$ID][0]['name']);", " // No due date in waiting status\n if ($data[$ID][0]['status'] == CommonITILObject::WAITING) {\n return '';\n }\n if (empty($data[$ID][0]['name'])) {\n return '';\n }\n if (\n ($data[$ID][0]['status'] == Ticket::SOLVED)\n || ($data[$ID][0]['status'] == Ticket::CLOSED)\n ) {\n return $out;\n }", " $itemtype = getItemTypeForTable($table);\n $item = new $itemtype();\n $item->getFromDB($data['id']);\n $percentage = 0;\n $totaltime = 0;\n $currenttime = 0;\n $slaField = 'slas_id';", " // define correct sla field\n switch ($table . '.' . $field) {\n case \"glpi_tickets.time_to_resolve\":\n $slaField = 'slas_id_ttr';\n $sla_class = 'SLA';\n break;\n case \"glpi_tickets.time_to_own\":\n $slaField = 'slas_id_tto';\n $sla_class = 'SLA';\n break;\n case \"glpi_tickets.internal_time_to_own\":\n $slaField = 'olas_id_tto';\n $sla_class = 'OLA';\n break;\n case \"glpi_tickets.internal_time_to_resolve\":\n $slaField = 'olas_id_ttr';\n $sla_class = 'OLA';\n break;\n }", " switch ($table . '.' . $field) {\n // If ticket has been taken into account : no progression display\n case \"glpi_tickets.time_to_own\":\n case \"glpi_tickets.internal_time_to_own\":\n if (($item->fields['takeintoaccount_delay_stat'] > 0)) {\n return $out;\n }\n break;\n }", " if ($item->isField($slaField) && $item->fields[$slaField] != 0) { // Have SLA\n $sla = new $sla_class();\n $sla->getFromDB($item->fields[$slaField]);\n $currenttime = $sla->getActiveTimeBetween(\n $item->fields['date'],\n date('Y-m-d H:i:s')\n );\n $totaltime = $sla->getActiveTimeBetween(\n $item->fields['date'],\n $data[$ID][0]['name']\n );\n } else {\n $calendars_id = Entity::getUsedConfig(\n 'calendars_strategy',\n $item->fields['entities_id'],\n 'calendars_id',\n 0\n );\n $calendar = new Calendar();\n if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { // Ticket entity have calendar\n $currenttime = $calendar->getActiveTimeBetween(\n $item->fields['date'],\n date('Y-m-d H:i:s')\n );\n $totaltime = $calendar->getActiveTimeBetween(\n $item->fields['date'],\n $data[$ID][0]['name']\n );\n } else { // No calendar\n $currenttime = strtotime(date('Y-m-d H:i:s'))\n - strtotime($item->fields['date']);\n $totaltime = strtotime($data[$ID][0]['name'])\n - strtotime($item->fields['date']);\n }\n }\n if ($totaltime != 0) {\n $percentage = round((100 * $currenttime) / $totaltime);\n } else {\n // Total time is null : no active time\n $percentage = 100;\n }\n if ($percentage > 100) {\n $percentage = 100;\n }\n $percentage_text = $percentage;", " if ($_SESSION['glpiduedatewarning_unit'] == '%') {\n $less_warn_limit = $_SESSION['glpiduedatewarning_less'];\n $less_warn = (100 - $percentage);\n } else if ($_SESSION['glpiduedatewarning_unit'] == 'hour') {\n $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;\n $less_warn = ($totaltime - $currenttime);\n } else if ($_SESSION['glpiduedatewarning_unit'] == 'day') {\n $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;\n $less_warn = ($totaltime - $currenttime);\n }", " if ($_SESSION['glpiduedatecritical_unit'] == '%') {\n $less_crit_limit = $_SESSION['glpiduedatecritical_less'];\n $less_crit = (100 - $percentage);\n } else if ($_SESSION['glpiduedatecritical_unit'] == 'hour') {\n $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;\n $less_crit = ($totaltime - $currenttime);\n } else if ($_SESSION['glpiduedatecritical_unit'] == 'day') {\n $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;\n $less_crit = ($totaltime - $currenttime);\n }", " $color = $_SESSION['glpiduedateok_color'];\n if ($less_crit < $less_crit_limit) {\n $color = $_SESSION['glpiduedatecritical_color'];\n } else if ($less_warn < $less_warn_limit) {\n $color = $_SESSION['glpiduedatewarning_color'];\n }", " if (!isset($so['datatype'])) {\n $so['datatype'] = 'progressbar';\n }", " $progressbar_data = [\n 'text' => Html::convDateTime($data[$ID][0]['name']),\n 'percent' => $percentage,\n 'percent_text' => $percentage_text,\n 'color' => $color\n ];\n }\n break;", " case \"glpi_softwarelicenses.number\":\n if ($data[$ID][0]['min'] == -1) {\n return __('Unlimited');\n }\n if (empty($data[$ID][0]['name'])) {\n return 0;\n }\n return $data[$ID][0]['name'];", " case \"glpi_auth_tables.name\":\n return Auth::getMethodName(\n $data[$ID][0]['name'],\n $data[$ID][0]['auths_id'],\n 1,\n $data[$ID][0]['ldapname'] . $data[$ID][0]['mailname']\n );", " case \"glpi_reservationitems.comment\":\n if (empty($data[$ID][0]['name'])) {\n $text = __('None');\n } else {\n $text = Html::resume_text($data[$ID][0]['name']);\n }\n if (Session::haveRight('reservation', UPDATE)) {\n return \"<a title=\\\"\" . __s('Modify the comment') . \"\\\"\n href='\" . ReservationItem::getFormURLWithID($data['refID']) . \"' >\" . $text . \"</a>\";\n }\n return $text;", " case 'glpi_crontasks.description':\n $tmp = new CronTask();\n return $tmp->getDescription($data[$ID][0]['name']);", " case 'glpi_changes.status':\n $status = Change::getStatus($data[$ID][0]['name']);\n return \"<span class='text-nowrap'>\" .\n Change::getStatusIcon($data[$ID][0]['name']) . \"&nbsp;$status\" .\n \"</span>\";", " case 'glpi_problems.status':\n $status = Problem::getStatus($data[$ID][0]['name']);\n return \"<span class='text-nowrap'>\" .\n Problem::getStatusIcon($data[$ID][0]['name']) . \"&nbsp;$status\" .\n \"</span>\";", " case 'glpi_tickets.status':\n $status = Ticket::getStatus($data[$ID][0]['name']);\n return \"<span class='text-nowrap'>\" .\n Ticket::getStatusIcon($data[$ID][0]['name']) . \"&nbsp;$status\" .\n \"</span>\";", " case 'glpi_projectstates.name':\n $out = '';\n $name = $data[$ID][0]['name'];\n if (isset($data[$ID][0]['trans'])) {\n $name = $data[$ID][0]['trans'];\n }\n if ($itemtype == 'ProjectState') {\n $out = \"<a href='\" . ProjectState::getFormURLWithID($data[$ID][0][\"id\"]) . \"'>\" . $name . \"</a></div>\";\n } else {\n $out = $name;\n }\n return $out;", " case 'glpi_items_tickets.items_id':\n case 'glpi_items_problems.items_id':\n case 'glpi_changes_items.items_id':\n case 'glpi_certificates_items.items_id':\n case 'glpi_appliances_items.items_id':\n if (!empty($data[$ID])) {\n $items = [];\n foreach ($data[$ID] as $key => $val) {\n if (is_numeric($key)) {\n if (\n !empty($val['itemtype'])\n && ($item = getItemForItemtype($val['itemtype']))\n ) {\n if ($item->getFromDB($val['name'])) {\n $items[] = $item->getLink(['comments' => true]);\n }\n }\n }\n }\n if (!empty($items)) {\n return implode(\"<br>\", $items);\n }\n }\n return '&nbsp;';", " case 'glpi_items_tickets.itemtype':\n case 'glpi_items_problems.itemtype':\n if (!empty($data[$ID])) {\n $itemtypes = [];\n foreach ($data[$ID] as $key => $val) {\n if (is_numeric($key)) {\n if (\n !empty($val['name'])\n && ($item = getItemForItemtype($val['name']))\n ) {\n $item = new $val['name']();\n $name = $item->getTypeName();\n $itemtypes[] = __($name);\n }\n }\n }\n if (!empty($itemtypes)) {\n return implode(\"<br>\", $itemtypes);\n }\n }", " return '&nbsp;';", " case 'glpi_tickets.name':\n case 'glpi_problems.name':\n case 'glpi_changes.name':\n if (\n isset($data[$ID][0]['content'])\n && isset($data[$ID][0]['id'])\n && isset($data[$ID][0]['status'])\n ) {\n $link = $itemtype::getFormURLWithID($data[$ID][0]['id']);", " $out = \"<a id='$itemtype\" . $data[$ID][0]['id'] . \"' href=\\\"\" . $link;\n // Force solution tab if solved\n if ($item = getItemForItemtype($itemtype)) {\n if (in_array($data[$ID][0]['status'], $item->getSolvedStatusArray())) {\n $out .= \"&amp;forcetab=$itemtype$2\";\n }\n }\n $out .= \"\\\">\";\n $name = $data[$ID][0]['name'];\n if (\n $_SESSION[\"glpiis_ids_visible\"]\n || empty($data[$ID][0]['name'])\n ) {\n $name = sprintf(__('%1$s (%2$s)'), $name, $data[$ID][0]['id']);\n }\n $out .= $name . \"</a>\";\n $out = sprintf(\n __('%1$s %2$s'),\n $out,\n Html::showToolTip(\n RichText::getEnhancedHtml($data[$ID][0]['content']),\n [\n 'applyto' => $itemtype . $data[$ID][0]['id'],\n 'display' => false,\n 'images_gallery' => false, // don't show photoswipe gallery in tooltips\n ]\n )\n );\n return $out;\n }\n break;", " case 'glpi_ticketvalidations.status':\n $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if ($data[$ID][$k]['name']) {\n $status = TicketValidation::getStatus($data[$ID][$k]['name']);\n $bgcolor = TicketValidation::getStatusColor($data[$ID][$k]['name']);\n $out .= (empty($out) ? '' : self::LBBR) .\n \"<div style=\\\"background-color:\" . $bgcolor . \";\\\">\" . $status . '</div>';\n }\n }\n return $out;", " case 'glpi_cables.color':\n //do not display 'real' value (#.....)\n return \"\";", " case 'glpi_ticketsatisfactions.satisfaction':", " if ($html_output) {", " return TicketSatisfaction::displaySatisfaction($data[$ID][0]['name']);\n }\n break;", " case 'glpi_projects._virtual_planned_duration':\n return Html::timestampToString(\n ProjectTask::getTotalPlannedDurationForProject($data[\"id\"]),\n false\n );", " case 'glpi_projects._virtual_effective_duration':\n return Html::timestampToString(\n ProjectTask::getTotalEffectiveDurationForProject($data[\"id\"]),\n false\n );", " case 'glpi_cartridgeitems._virtual':\n return Cartridge::getCount(\n $data[\"id\"],\n $data[$ID][0]['alarm_threshold'],", " !$html_output", " );", " case 'glpi_printers._virtual':\n return Cartridge::getCountForPrinter(\n $data[\"id\"],", " !$html_output", " );", " case 'glpi_consumableitems._virtual':\n return Consumable::getCount(\n $data[\"id\"],\n $data[$ID][0]['alarm_threshold'],", " !$html_output", " );", " case 'glpi_links._virtual':\n $out = '';\n $link = new Link();\n if (\n ($item = getItemForItemtype($itemtype))\n && $item->getFromDB($data['id'])\n ) {\n $data = Link::getLinksDataForItem($item);\n $count_display = 0;\n foreach ($data as $val) {\n $links = Link::getAllLinksFor($item, $val);\n foreach ($links as $link) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $out .= $link;\n $count_display++;\n }\n }\n }\n return $out;", " case 'glpi_reservationitems._virtual':\n if ($data[$ID][0]['is_active']) {\n return \"<a href='reservation.php?reservationitems_id=\" .\n $data[\"refID\"] . \"' title=\\\"\" . __s('See planning') . \"\\\">\" .\n \"<i class='far fa-calendar-alt'></i><span class='sr-only'>\" . __('See planning') . \"</span></a>\";\n } else {\n return \"&nbsp;\";\n }", " case \"glpi_tickets.priority\":\n case \"glpi_problems.priority\":\n case \"glpi_changes.priority\":\n case \"glpi_projects.priority\":\n $index = $data[$ID][0]['name'];\n $color = $_SESSION[\"glpipriority_$index\"];\n $name = CommonITILObject::getPriorityName($index);\n return \"<div class='priority_block' style='border-color: $color'>\n <span style='background: $color'></span>&nbsp;$name\n </div>\";\n }\n }", " //// Default case", " if (\n $itemtype == 'Ticket'\n && Session::getCurrentInterface() == 'helpdesk'\n && $orig_id == 8\n && !empty($anon_name = Group::getAnonymizedName(\n $itemtype::getById($data['id'])->getEntityId()\n ))\n ) {\n // Assigned groups\n return $anon_name;\n }", " // Link with plugin tables : need to know left join structure\n if (isset($table)) {\n if (preg_match(\"/^glpi_plugin_([a-z0-9]+)/\", $table . '.' . $field, $matches)) {\n if (count($matches) == 2) {\n $plug = $matches[1];\n $out = Plugin::doOneHook(\n $plug,\n 'giveItem',\n $itemtype,\n $orig_id,\n $data,\n $ID\n );\n if (!empty($out)) {\n return $out;\n }\n }\n }\n }\n $unit = '';\n if (isset($so['unit'])) {\n $unit = $so['unit'];\n }", " // Preformat items\n if (isset($so[\"datatype\"])) {\n switch ($so[\"datatype\"]) {\n case \"itemlink\":\n $linkitemtype = getItemTypeForTable($so[\"table\"]);", " $out = \"\";\n $count_display = 0;\n $separate = self::LBBR;\n if (isset($so['splititems']) && $so['splititems']) {\n $separate = self::LBHR;\n }", " for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (isset($data[$ID][$k]['id'])) {\n if ($count_display) {\n $out .= $separate;\n }\n $count_display++;\n $page = $linkitemtype::getFormURLWithID($data[$ID][$k]['id']);\n $name = $data[$ID][$k]['name'];\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($data[$ID][$k]['name'])) {\n $name = sprintf(__('%1$s (%2$s)'), $name, $data[$ID][$k]['id']);\n }\n if ($field === 'completename') {\n $chunks = preg_split('/ > /', $name);\n $completename = '';\n foreach ($chunks as $key => $element_name) {\n $class = $key === array_key_last($chunks) ? '' : 'class=\"text-muted\"';\n $separator = $key === array_key_last($chunks) ? '' : ' &gt; ';\n $completename .= sprintf('<span %s>%s</span>%s', $class, $element_name, $separator);\n }\n $name = $completename;\n }", " $out .= \"<a id='\" . $linkitemtype . \"_\" . $data['id'] . \"_\" .\n $data[$ID][$k]['id'] . \"' href='$page'>\" .\n $name . \"</a>\";\n }\n }\n return $out;", " case \"text\":\n $separate = self::LBBR;\n if (isset($so['splititems']) && $so['splititems']) {\n $separate = self::LBHR;\n }", " $out = '';\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= $separate;\n }\n $count_display++;\n", " $plaintext = RichText::getTextFromHtml($data[$ID][$k]['name'], false, true, $html_output);", " if ($html_output && (Toolbox::strlen($plaintext) > $CFG_GLPI['cut'])) {", " $rand = mt_rand();\n $popup_params = [\n 'display' => false,\n 'awesome-class' => 'fa-comments',\n 'autoclose' => false,\n 'onclick' => true,\n ];\n $out .= sprintf(\n __('%1$s %2$s'),\n \"<span id='text$rand'>\" . Html::resume_text($plaintext, $CFG_GLPI['cut']) . '</span>',\n Html::showToolTip(\n '<div class=\"fup-popup\">' . RichText::getEnhancedHtml($data[$ID][$k]['name']) . '</div>',\n $popup_params\n )\n );\n } else {\n $out .= $plaintext;\n }\n }\n }\n return $out;", " case \"date\":\n case \"date_delay\":\n $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n is_null($data[$ID][$k]['name'])\n && isset($so['emptylabel']) && $so['emptylabel']\n ) {\n $out .= (empty($out) ? '' : self::LBBR) . $so['emptylabel'];\n } else {\n $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$ID][$k]['name']);\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"datetime\":\n $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (\n is_null($data[$ID][$k]['name'])\n && isset($so['emptylabel']) && $so['emptylabel']\n ) {\n $out .= (empty($out) ? '' : self::LBBR) . $so['emptylabel'];\n } else {\n $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$ID][$k]['name']);\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"timestamp\":\n $withseconds = false;\n if (isset($so['withseconds'])) {\n $withseconds = $so['withseconds'];\n }\n $withdays = true;\n if (isset($so['withdays'])) {\n $withdays = $so['withdays'];\n }", " $out = '';\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n $out .= (empty($out) ? '' : '<br>') . Html::timestampToString(\n $data[$ID][$k]['name'],\n $withseconds,\n $withdays\n );\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"email\":\n $out = '';\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n if (!empty($data[$ID][$k]['name'])) {\n $out .= (empty($out) ? '' : self::LBBR);\n $out .= \"<a href='mailto:\" . Html::entities_deep($data[$ID][$k]['name']) . \"'>\" . $data[$ID][$k]['name'];\n $out .= \"</a>\";\n }\n }\n return (empty($out) ? \"&nbsp;\" : $out);", " case \"weblink\":\n $orig_link = trim((string)$data[$ID][0]['name']);\n if (!empty($orig_link) && Toolbox::isValidWebUrl($orig_link)) {\n // strip begin of link\n $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);\n $link = preg_replace('/\\/$/', '', $link);\n if (Toolbox::strlen($link) > $CFG_GLPI[\"url_maxlength\"]) {\n $link = Toolbox::substr($link, 0, $CFG_GLPI[\"url_maxlength\"]) . \"...\";\n }\n return \"<a href=\\\"\" . Toolbox::formatOutputWebLink($orig_link) . \"\\\" target='_blank'>$link</a>\";\n }\n return \"&nbsp;\";", " case \"count\":\n case \"number\":\n case \"mio\":\n $out = \"\";\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n if (\n isset($so['toadd'])\n && isset($so['toadd'][$data[$ID][$k]['name']])\n ) {\n $out .= $so['toadd'][$data[$ID][$k]['name']];\n } else {\n $out .= Dropdown::getValueWithUnit($data[$ID][$k]['name'], $unit);\n }\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"decimal\":\n $out = \"\";\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n if (\n isset($so['toadd'])\n && isset($so['toadd'][$data[$ID][$k]['name']])\n ) {\n $out .= $so['toadd'][$data[$ID][$k]['name']];\n } else {\n $out .= Dropdown::getValueWithUnit($data[$ID][$k]['name'], $unit, $CFG_GLPI[\"decimal_number\"]);\n }\n }\n }\n $out = \"<span class='text-nowrap'>$out</span>\";\n return $out;", " case \"bool\":\n $out = \"\";\n $count_display = 0;\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if (strlen(trim((string)$data[$ID][$k]['name'])) > 0) {\n if ($count_display) {\n $out .= self::LBBR;\n }\n $count_display++;\n $out .= Dropdown::getYesNo($data[$ID][$k]['name']);\n }\n }\n return $out;", " case \"itemtypename\":\n if ($obj = getItemForItemtype($data[$ID][0]['name'])) {\n return $obj->getTypeName();\n }\n return \"\";", " case \"language\":\n if (isset($CFG_GLPI['languages'][$data[$ID][0]['name']])) {\n return $CFG_GLPI['languages'][$data[$ID][0]['name']][0];\n }\n return __('Default value');\n case 'progressbar':\n if (!isset($progressbar_data)) {\n $bar_color = 'green';\n $percent = ltrim(($data[$ID][0]['name'] ?? \"\"), 0);\n $progressbar_data = [\n 'percent' => $percent,\n 'percent_text' => $percent,\n 'color' => $bar_color,\n 'text' => ''\n ];\n }", " $out = \"\";\n if ($progressbar_data['percent'] !== null) {\n $out = <<<HTML\n <span class='text-nowrap'>\n {$progressbar_data['text']}\n </span>\n <div class=\"progress\" style=\"height: 16px\">\n <div class=\"progress-bar progress-bar-striped\" role=\"progressbar\"\n style=\"width: {$progressbar_data['percent']}%; background-color: {$progressbar_data['color']};\"\n aria-valuenow=\"{$progressbar_data['percent']}\"\n aria-valuemin=\"0\" aria-valuemax=\"100\">\n {$progressbar_data['percent_text']}%\n </div>\n </div>\nHTML;\n }", " return $out;\n break;\n }\n }\n // Manage items with need group by / group_concat\n $out = \"\";\n $count_display = 0;\n $separate = self::LBBR;\n if (isset($so['splititems']) && $so['splititems']) {\n $separate = self::LBHR;\n }\n for ($k = 0; $k < $data[$ID]['count']; $k++) {\n if ($count_display) {\n $out .= $separate;\n }\n $count_display++;\n // Get specific display if available\n if (isset($table)) {\n $itemtype = getItemTypeForTable($table);\n if ($item = getItemForItemtype($itemtype)) {\n $tmpdata = $data[$ID][$k];\n // Copy name to real field\n $tmpdata[$field] = $data[$ID][$k]['name'] ?? '';", " $specific = $item->getSpecificValueToDisplay(\n $field,\n $tmpdata,\n [\n 'html' => true,\n 'searchopt' => $so,\n 'raw_data' => $data\n ]\n );\n }\n }\n if (!empty($specific)) {\n $out .= $specific;\n } else {\n if (\n isset($so['toadd'])\n && isset($so['toadd'][$data[$ID][$k]['name']])\n ) {\n $out .= $so['toadd'][$data[$ID][$k]['name']];\n } else {\n // Empty is 0 or empty\n if (empty($split[0]) && isset($so['emptylabel'])) {\n $out .= $so['emptylabel'];\n } else {\n // Trans field exists\n if (isset($data[$ID][$k]['trans']) && !empty($data[$ID][$k]['trans'])) {\n $out .= $data[$ID][$k]['trans'];\n } else {\n $value = $data[$ID][$k]['name'];\n $out .= $so['field'] === 'completename'\n ? CommonTreeDropdown::sanitizeSeparatorInCompletename($value)\n : $value;\n }\n }\n }\n }\n }\n return $out;\n }", "\n /**\n * Reset save searches\n *\n * @return void\n **/\n public static function resetSaveSearch()\n {", " unset($_SESSION['glpisearch']);\n $_SESSION['glpisearch'] = [];\n }", "\n /**\n * Completion of the URL $_GET values with the $_SESSION values or define default values\n *\n * @param string $itemtype Item type to manage\n * @param array $params Params to parse\n * @param boolean $usesession Use datas save in session (true by default)\n * @param boolean $forcebookmark Force trying to load parameters from default bookmark:\n * used for global search (false by default)\n *\n * @return array parsed params\n **/\n public static function manageParams(\n $itemtype,\n $params = [],\n $usesession = true,\n $forcebookmark = false\n ) {\n $default_values = [];", " $default_values[\"start\"] = 0;\n $default_values[\"order\"] = \"ASC\";\n $default_values[\"sort\"] = 1;\n $default_values[\"is_deleted\"] = 0;\n $default_values[\"as_map\"] = 0;\n $default_values[\"browse\"] = 0;", " if (isset($params['start'])) {\n $params['start'] = (int)$params['start'];\n }", " $default_values[\"criteria\"] = self::getDefaultCriteria($itemtype);\n $default_values[\"metacriteria\"] = [];", " // Reorg search array\n // start\n // order\n // sort\n // is_deleted\n // itemtype\n // criteria : array (0 => array (link =>\n // field =>\n // searchtype =>\n // value => (contains)\n // metacriteria : array (0 => array (itemtype =>\n // link =>\n // field =>\n // searchtype =>\n // value => (contains)", " if ($itemtype != AllAssets::getType() && class_exists($itemtype)) {\n // retrieve default values for current itemtype\n $itemtype_default_values = [];\n if (method_exists($itemtype, 'getDefaultSearchRequest')) {\n $itemtype_default_values = call_user_func([$itemtype, 'getDefaultSearchRequest']);\n }", " // retrieve default values for the current user\n $user_default_values = SavedSearch_User::getDefault(Session::getLoginUserID(), $itemtype);\n if ($user_default_values === false) {\n $user_default_values = [];\n }", " // we construct default values in this order:\n // - general default\n // - itemtype default\n // - user default\n //\n // The last ones erase values or previous\n // So, we can combine each part (order from itemtype, criteria from user, etc)\n $default_values = array_merge(\n $default_values,\n $itemtype_default_values,\n $user_default_values\n );\n }", " // First view of the page or force bookmark : try to load a bookmark\n if (\n $forcebookmark\n || ($usesession\n && !isset($params[\"reset\"])\n && !isset($_SESSION['glpisearch'][$itemtype]))\n ) {\n $user_default_values = SavedSearch_User::getDefault(Session::getLoginUserID(), $itemtype);\n if ($user_default_values) {\n $_SESSION['glpisearch'][$itemtype] = [];\n // Only get datas for bookmarks\n if ($forcebookmark) {\n $params = $user_default_values;\n } else {\n $bookmark = new SavedSearch();\n $bookmark->load($user_default_values['savedsearches_id'], false);\n }\n }\n }\n // Force reorder criterias\n if (\n isset($params[\"criteria\"])\n && is_array($params[\"criteria\"])\n && count($params[\"criteria\"])\n ) {\n $tmp = $params[\"criteria\"];\n $params[\"criteria\"] = [];\n foreach ($tmp as $val) {\n $params[\"criteria\"][] = $val;\n }\n }", " // transform legacy meta-criteria in criteria (with flag meta=true)\n // at the end of the array, as before there was only at the end of the query\n if (\n isset($params[\"metacriteria\"])\n && is_array($params[\"metacriteria\"])\n ) {\n // as we will append meta to criteria, check the key exists\n if (!isset($params[\"criteria\"])) {\n $params[\"criteria\"] = [];\n }\n foreach ($params[\"metacriteria\"] as $val) {\n $params[\"criteria\"][] = $val + ['meta' => 1];\n }\n $params[\"metacriteria\"] = [];\n }", " if (\n $usesession\n && isset($params[\"reset\"])\n ) {\n if (isset($_SESSION['glpisearch'][$itemtype])) {\n unset($_SESSION['glpisearch'][$itemtype]);\n }\n }", " if (\n isset($params) && is_array($params)\n && $usesession\n ) {\n foreach ($params as $key => $val) {\n $_SESSION['glpisearch'][$itemtype][$key] = $val;\n }\n }", " $saved_params = $params;\n foreach ($default_values as $key => $val) {\n if (!isset($params[$key])) {\n if (\n $usesession\n && ($key == 'is_deleted' || $key == 'as_map' || $key == 'browse' || !isset($saved_params['criteria'])) // retrieve session only if not a new request\n && isset($_SESSION['glpisearch'][$itemtype][$key])\n ) {\n $params[$key] = $_SESSION['glpisearch'][$itemtype][$key];\n } else {\n $params[$key] = $val;\n $_SESSION['glpisearch'][$itemtype][$key] = $val;\n }\n }\n }", " return $params;\n }", "\n /**\n * Clean search options depending of user active profile\n *\n * @param string $itemtype Item type to manage\n * @param integer $action Action which is used to manupulate searchoption\n * (default READ)\n * @param boolean $withplugins Get plugins options (true by default)\n *\n * @return array Clean $SEARCH_OPTION array\n **/\n public static function getCleanedOptions($itemtype, $action = READ, $withplugins = true)\n {\n global $CFG_GLPI;", " $options = &self::getOptions($itemtype, $withplugins);\n $todel = [];", " if (\n !Session::haveRight('infocom', $action)\n && Infocom::canApplyOn($itemtype)\n ) {\n $itemstodel = Infocom::getSearchOptionsToAdd($itemtype);\n $todel = array_merge($todel, array_keys($itemstodel));\n }", " if (\n !Session::haveRight('contract', $action)\n && in_array($itemtype, $CFG_GLPI[\"contract_types\"])\n ) {\n $itemstodel = Contract::getSearchOptionsToAdd();\n $todel = array_merge($todel, array_keys($itemstodel));\n }", " if (\n !Session::haveRight('document', $action)\n && Document::canApplyOn($itemtype)\n ) {\n $itemstodel = Document::getSearchOptionsToAdd();\n $todel = array_merge($todel, array_keys($itemstodel));\n }", " // do not show priority if you don't have right in profile\n if (\n ($itemtype == 'Ticket')\n && ($action == UPDATE)\n && !Session::haveRight('ticket', Ticket::CHANGEPRIORITY)\n ) {\n $todel[] = 3;\n }", " if ($itemtype == 'Computer') {\n if (!Session::haveRight('networking', $action)) {\n $itemstodel = NetworkPort::getSearchOptionsToAdd($itemtype);\n $todel = array_merge($todel, array_keys($itemstodel));\n }\n }\n if (!Session::haveRight(strtolower($itemtype), READNOTE)) {\n $todel[] = 90;\n }", " if (count($todel)) {\n foreach ($todel as $ID) {\n if (isset($options[$ID])) {\n unset($options[$ID]);\n }\n }\n }", " return $options;\n }", "\n /**\n *\n * Get an option number in the SEARCH_OPTION array\n *\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param string $field Name\n *\n * @return integer\n **/\n public static function getOptionNumber($itemtype, $field)\n {", " $table = $itemtype::getTable();\n $opts = &self::getOptions($itemtype);", " foreach ($opts as $num => $opt) {\n if (\n is_array($opt) && isset($opt['table'])\n && ($opt['table'] == $table)\n && ($opt['field'] == $field)\n ) {\n return $num;\n }\n }\n return 0;\n }", "\n /**\n * Get the SEARCH_OPTION array\n *\n * @param string $itemtype Item type\n * @param boolean $withplugins Get search options from plugins (true by default)\n *\n * @return array The reference to the array of search options for the given item type\n **/\n public static function &getOptions($itemtype, $withplugins = true)\n {\n global $CFG_GLPI;", " $item = null;", " if (!isset(self::$search[$itemtype])) {\n // standard type first\n switch ($itemtype) {\n case 'Internet':\n self::$search[$itemtype]['common'] = __('Characteristics');", " self::$search[$itemtype][1]['table'] = 'networkport_types';\n self::$search[$itemtype][1]['field'] = 'name';\n self::$search[$itemtype][1]['name'] = __('Name');\n self::$search[$itemtype][1]['datatype'] = 'itemlink';\n self::$search[$itemtype][1]['searchtype'] = 'contains';", " self::$search[$itemtype][2]['table'] = 'networkport_types';\n self::$search[$itemtype][2]['field'] = 'id';\n self::$search[$itemtype][2]['name'] = __('ID');\n self::$search[$itemtype][2]['searchtype'] = 'contains';", " self::$search[$itemtype][31]['table'] = 'glpi_states';\n self::$search[$itemtype][31]['field'] = 'completename';\n self::$search[$itemtype][31]['name'] = __('Status');", " self::$search[$itemtype] += NetworkPort::getSearchOptionsToAdd('networkport_types');\n break;", " case AllAssets::getType():\n self::$search[$itemtype]['common'] = __('Characteristics');", " self::$search[$itemtype][1]['table'] = 'asset_types';\n self::$search[$itemtype][1]['field'] = 'name';\n self::$search[$itemtype][1]['name'] = __('Name');\n self::$search[$itemtype][1]['datatype'] = 'itemlink';\n self::$search[$itemtype][1]['searchtype'] = 'contains';", " self::$search[$itemtype][2]['table'] = 'asset_types';\n self::$search[$itemtype][2]['field'] = 'id';\n self::$search[$itemtype][2]['name'] = __('ID');\n self::$search[$itemtype][2]['searchtype'] = 'contains';", " self::$search[$itemtype][31]['table'] = 'glpi_states';\n self::$search[$itemtype][31]['field'] = 'completename';\n self::$search[$itemtype][31]['name'] = __('Status');", " self::$search[$itemtype] += Location::getSearchOptionsToAdd();", " self::$search[$itemtype][5]['table'] = 'asset_types';\n self::$search[$itemtype][5]['field'] = 'serial';\n self::$search[$itemtype][5]['name'] = __('Serial number');", " self::$search[$itemtype][6]['table'] = 'asset_types';\n self::$search[$itemtype][6]['field'] = 'otherserial';\n self::$search[$itemtype][6]['name'] = __('Inventory number');", " self::$search[$itemtype][16]['table'] = 'asset_types';\n self::$search[$itemtype][16]['field'] = 'comment';\n self::$search[$itemtype][16]['name'] = __('Comments');\n self::$search[$itemtype][16]['datatype'] = 'text';", " self::$search[$itemtype][70]['table'] = 'glpi_users';\n self::$search[$itemtype][70]['field'] = 'name';\n self::$search[$itemtype][70]['name'] = User::getTypeName(1);", " self::$search[$itemtype][7]['table'] = 'asset_types';\n self::$search[$itemtype][7]['field'] = 'contact';\n self::$search[$itemtype][7]['name'] = __('Alternate username');\n self::$search[$itemtype][7]['datatype'] = 'string';", " self::$search[$itemtype][8]['table'] = 'asset_types';\n self::$search[$itemtype][8]['field'] = 'contact_num';\n self::$search[$itemtype][8]['name'] = __('Alternate username number');\n self::$search[$itemtype][8]['datatype'] = 'string';", " self::$search[$itemtype][71]['table'] = 'glpi_groups';\n self::$search[$itemtype][71]['field'] = 'completename';\n self::$search[$itemtype][71]['name'] = Group::getTypeName(1);", " self::$search[$itemtype][19]['table'] = 'asset_types';\n self::$search[$itemtype][19]['field'] = 'date_mod';\n self::$search[$itemtype][19]['name'] = __('Last update');\n self::$search[$itemtype][19]['datatype'] = 'datetime';\n self::$search[$itemtype][19]['massiveaction'] = false;", " self::$search[$itemtype][23]['table'] = 'glpi_manufacturers';\n self::$search[$itemtype][23]['field'] = 'name';\n self::$search[$itemtype][23]['name'] = Manufacturer::getTypeName(1);", " self::$search[$itemtype][24]['table'] = 'glpi_users';\n self::$search[$itemtype][24]['field'] = 'name';\n self::$search[$itemtype][24]['linkfield'] = 'users_id_tech';\n self::$search[$itemtype][24]['name'] = __('Technician in charge of the hardware');\n self::$search[$itemtype][24]['condition'] = ['is_assign' => 1];", " self::$search[$itemtype][49]['table'] = 'glpi_groups';\n self::$search[$itemtype][49]['field'] = 'completename';\n self::$search[$itemtype][49]['linkfield'] = 'groups_id_tech';\n self::$search[$itemtype][49]['name'] = __('Group in charge of the hardware');\n self::$search[$itemtype][49]['condition'] = ['is_assign' => 1];\n self::$search[$itemtype][49]['datatype'] = 'dropdown';", " self::$search[$itemtype][80]['table'] = 'glpi_entities';\n self::$search[$itemtype][80]['field'] = 'completename';\n self::$search[$itemtype][80]['name'] = Entity::getTypeName(1);\n break;", " default:\n if ($item = getItemForItemtype($itemtype)) {\n self::$search[$itemtype] = $item->searchOptions();\n }\n break;\n }", " if (\n Session::getLoginUserID()\n && in_array($itemtype, $CFG_GLPI[\"ticket_types\"])\n ) {\n self::$search[$itemtype]['tracking'] = __('Assistance');", " self::$search[$itemtype][60]['table'] = 'glpi_tickets';\n self::$search[$itemtype][60]['field'] = 'id';\n self::$search[$itemtype][60]['datatype'] = 'count';\n self::$search[$itemtype][60]['name'] = _x('quantity', 'Number of tickets');\n self::$search[$itemtype][60]['forcegroupby'] = true;\n self::$search[$itemtype][60]['usehaving'] = true;\n self::$search[$itemtype][60]['massiveaction'] = false;\n self::$search[$itemtype][60]['joinparams'] = ['beforejoin'\n => ['table'\n => 'glpi_items_tickets',\n 'joinparams'\n => ['jointype'\n => 'itemtype_item'\n ]\n ],\n 'condition'\n => getEntitiesRestrictRequest(\n 'AND',\n 'NEWTABLE'\n )\n ];", " self::$search[$itemtype][140]['table'] = 'glpi_problems';\n self::$search[$itemtype][140]['field'] = 'id';\n self::$search[$itemtype][140]['datatype'] = 'count';\n self::$search[$itemtype][140]['name'] = _x('quantity', 'Number of problems');\n self::$search[$itemtype][140]['forcegroupby'] = true;\n self::$search[$itemtype][140]['usehaving'] = true;\n self::$search[$itemtype][140]['massiveaction'] = false;\n self::$search[$itemtype][140]['joinparams'] = ['beforejoin'\n => ['table'\n => 'glpi_items_problems',\n 'joinparams'\n => ['jointype'\n => 'itemtype_item'\n ]\n ],\n 'condition'\n => getEntitiesRestrictRequest(\n 'AND',\n 'NEWTABLE'\n )\n ];\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"networkport_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += NetworkPort::getSearchOptionsToAdd($itemtype);\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"contract_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Contract::getSearchOptionsToAdd();\n }", " if (\n Document::canApplyOn($itemtype)\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Document::getSearchOptionsToAdd();\n }", " if (\n Infocom::canApplyOn($itemtype)\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Infocom::getSearchOptionsToAdd($itemtype);\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"domain_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Domain::getSearchOptionsToAdd($itemtype);\n }", " if (\n in_array($itemtype, $CFG_GLPI[\"appliance_types\"])\n || ($itemtype == AllAssets::getType())\n ) {\n self::$search[$itemtype] += Appliance::getSearchOptionsToAdd($itemtype);\n }", " if (in_array($itemtype, $CFG_GLPI[\"link_types\"])) {\n self::$search[$itemtype]['link'] = Link::getTypeName(Session::getPluralNumber());\n self::$search[$itemtype] += Link::getSearchOptionsToAdd($itemtype);\n self::$search[$itemtype]['manuallink'] = ManualLink::getTypeName(Session::getPluralNumber());\n self::$search[$itemtype] += ManualLink::getSearchOptionsToAdd($itemtype);\n }", " if ($withplugins) {\n // Search options added by plugins\n $plugsearch = Plugin::getAddSearchOptions($itemtype);\n $plugsearch = $plugsearch + Plugin::getAddSearchOptionsNew($itemtype);\n if (count($plugsearch)) {\n self::$search[$itemtype] += ['plugins' => _n('Plugin', 'Plugins', Session::getPluralNumber())];\n self::$search[$itemtype] += $plugsearch;\n }\n }", " // Complete linkfield if not define\n if (is_null($item)) { // Special union type\n $itemtable = $CFG_GLPI['union_search_type'][$itemtype];\n } else {\n if ($item = getItemForItemtype($itemtype)) {\n $itemtable = $item->getTable();\n }\n }", " foreach (self::$search[$itemtype] as $key => $val) {\n if (!is_array($val) || count($val) == 1) {\n // skip sub-menu\n continue;\n }\n // Compatibility before 0.80 : Force massive action to false if linkfield is empty :\n if (isset($val['linkfield']) && empty($val['linkfield'])) {\n self::$search[$itemtype][$key]['massiveaction'] = false;\n }", " // Set default linkfield\n if (!isset($val['linkfield']) || empty($val['linkfield'])) {\n if (\n (strcmp($itemtable, $val['table']) == 0)\n && (!isset($val['joinparams']) || (count($val['joinparams']) == 0))\n ) {\n self::$search[$itemtype][$key]['linkfield'] = $val['field'];\n } else {\n self::$search[$itemtype][$key]['linkfield'] = getForeignKeyFieldForTable($val['table']);\n }\n }\n // Add default joinparams\n if (!isset($val['joinparams'])) {\n self::$search[$itemtype][$key]['joinparams'] = [];\n }\n }\n }", " return self::$search[$itemtype];\n }", " /**\n * Is the search item related to infocoms\n *\n * @param string $itemtype Item type\n * @param integer $searchID ID of the element in $SEARCHOPTION\n *\n * @return boolean\n **/\n public static function isInfocomOption($itemtype, $searchID)\n {\n if (!Infocom::canApplyOn($itemtype)) {\n return false;\n }", " $infocom_options = Infocom::rawSearchOptionsToAdd($itemtype);\n $found_infocoms = array_filter($infocom_options, function ($option) use ($searchID) {\n return isset($option['id']) && $searchID == $option['id'];\n });", " return (count($found_infocoms) > 0);\n }", "\n /**\n * @param string $itemtype\n * @param integer $field_num\n **/\n public static function getActionsFor($itemtype, $field_num)\n {", " $searchopt = &self::getOptions($itemtype);\n $actions = [\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'searchopt' => []\n ];", " if (isset($searchopt[$field_num]) && isset($searchopt[$field_num]['table'])) {\n $actions['searchopt'] = $searchopt[$field_num];", " // Force search type\n if (isset($actions['searchopt']['searchtype'])) {\n // Reset search option\n $actions = [];\n $actions['searchopt'] = $searchopt[$field_num];\n if (!is_array($actions['searchopt']['searchtype'])) {\n $actions['searchopt']['searchtype'] = [$actions['searchopt']['searchtype']];\n }\n foreach ($actions['searchopt']['searchtype'] as $searchtype) {\n switch ($searchtype) {\n case \"equals\":\n $actions['equals'] = __('is');\n break;", " case \"notequals\":\n $actions['notequals'] = __('is not');\n break;", " case \"contains\":\n $actions['contains'] = __('contains');\n $actions['notcontains'] = __('not contains');\n break;", " case \"notcontains\":\n $actions['notcontains'] = __('not contains');\n break;", " case \"under\":\n $actions['under'] = __('under');\n break;", " case \"notunder\":\n $actions['notunder'] = __('not under');\n break;", " case \"lessthan\":\n $actions['lessthan'] = __('before');\n break;", " case \"morethan\":\n $actions['morethan'] = __('after');\n break;\n }\n }\n return $actions;\n }", " if (isset($searchopt[$field_num]['datatype'])) {\n switch ($searchopt[$field_num]['datatype']) {\n case 'mio':\n case 'count':\n case 'number':\n $opt = [\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];\n // No is / isnot if no limits defined\n if (\n !isset($searchopt[$field_num]['min'])\n && !isset($searchopt[$field_num]['max'])\n ) {\n unset($opt['equals']);\n unset($opt['notequals']);", " // https://github.com/glpi-project/glpi/issues/6917\n // change filter wording for numeric values to be more\n // obvious if the number dropdown will not be used\n $opt['contains'] = __('is');\n $opt['notcontains'] = __('is not');\n }\n return $opt;", " case 'bool':\n return [\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'right':\n return ['equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'itemtypename':\n return ['equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'date':\n case 'datetime':\n case 'date_delay':\n return [\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'lessthan' => __('before'),\n 'morethan' => __('after'),\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'searchopt' => $searchopt[$field_num]\n ];\n }\n }", " // switch ($searchopt[$field_num]['table']) {\n // case 'glpi_users_validation' :\n // return array('equals' => __('is'),\n // 'notequals' => __('is not'),\n // 'searchopt' => $searchopt[$field_num]);\n // }", " switch ($searchopt[$field_num]['field']) {\n case 'id':\n return ['equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " case 'name':\n case 'completename':\n $actions = [\n 'contains' => __('contains'),\n 'notcontains' => __('not contains'),\n 'equals' => __('is'),\n 'notequals' => __('is not'),\n 'searchopt' => $searchopt[$field_num]\n ];", " // Specific case of TreeDropdown : add under\n $itemtype_linked = getItemTypeForTable($searchopt[$field_num]['table']);\n if ($itemlinked = getItemForItemtype($itemtype_linked)) {\n if ($itemlinked instanceof CommonTreeDropdown) {\n $actions['under'] = __('under');\n $actions['notunder'] = __('not under');\n }\n return $actions;\n }\n }\n }\n return $actions;\n }", "\n /**\n * Print generic Header Column\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $value Value to display\n * @param integer &$num Column number\n * @param string $linkto Link display element (HTML specific) (default '')\n * @param boolean|integer $issort Is the sort column ? (default 0)\n * @param string $order Order type ASC or DESC (defaut '')\n * @param string $options Options to add (default '')\n *\n * @return string HTML to display\n **/\n public static function showHeaderItem(\n $type,\n $value,\n &$num,\n $linkto = \"\",\n $issort = 0,\n $order = \"\",\n $options = \"\"\n ) {\n $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE:\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= \"<th $options>\";\n $PDF_TABLE .= htmlspecialchars($value);\n $PDF_TABLE .= \"</th>\";\n break;", " case self::SYLK_OUTPUT: //sylk\n global $SYLK_HEADER,$SYLK_SIZE;\n $SYLK_HEADER[$num] = self::sylk_clean($value);\n $SYLK_SIZE[$num] = Toolbox::strlen($SYLK_HEADER[$num]);\n break;", " case self::CSV_OUTPUT: //CSV\n $out = \"\\\"\" . self::csv_clean($value) . \"\\\"\" . $_SESSION[\"glpicsv_delimiter\"];\n break;", " case self::NAMES_OUTPUT:\n $out = \"\";\n break;", " default:\n $class = \"\";\n if ($issort) {\n $class = \"order_$order\";\n }\n $out = \"<th $options class='$class'>\";\n if (!empty($linkto)) {\n $out .= \"<a href=\\\"$linkto\\\">\";\n }\n $out .= $value;\n if (!empty($linkto)) {\n $out .= \"</a>\";\n }\n $out .= \"</th>\\n\";\n }\n $num++;\n return $out;\n }", "\n /**\n * Print generic normal Item Cell\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $value Value to display\n * @param integer &$num Column number\n * @param integer $row Row number\n * @param string $extraparam Extra parameters for display (default '')\n *\n * @return string HTML to display\n **/\n public static function showItem($type, $value, &$num, $row, $extraparam = '')\n {", " $out = \"\";\n // Handle null values\n if ($value === null) {\n $value = '';\n }", " switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $value = DataExport::normalizeValueForTextExport($value ?? '');\n $value = htmlspecialchars($value);\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $PDF_TABLE .= \"<td $extraparam valign='top'>\";\n $PDF_TABLE .= $value;\n $PDF_TABLE .= \"</td>\";", " break;", " case self::SYLK_OUTPUT: //sylk\n global $SYLK_ARRAY,$SYLK_SIZE;\n $value = DataExport::normalizeValueForTextExport($value);\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $SYLK_ARRAY[$row][$num] = self::sylk_clean($value);\n $SYLK_SIZE[$num] = max(\n $SYLK_SIZE[$num],\n Toolbox::strlen($SYLK_ARRAY[$row][$num])\n );\n break;", " case self::CSV_OUTPUT: //csv\n $value = DataExport::normalizeValueForTextExport($value);\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $out = \"\\\"\" . self::csv_clean($value) . \"\\\"\" . $_SESSION[\"glpicsv_delimiter\"];\n break;", " case self::NAMES_OUTPUT:\n // We only want to display one column (the name of the item).\n // The name field is always the first column expect for tickets\n // which have their ids as the first column instead, thus moving the\n // name to the second column.\n // We don't have access to the itemtype so we must rely on data\n // types to figure which column to use :\n // - Ticket will have a numeric first column (id) and an HTML\n // link containing the name as the second column.\n // - Other items will have an HTML link containing the name as\n // the first column and a simple string containing the entity\n // name as the second column.\n // -> We can check that the column is the first or second AND is html\n if (\n strip_tags($value) !== $value\n && ($num == 1 || $num == 2)\n ) {\n // Use a regex to keep only the link, there may be other content\n // after that we don't need (script, tooltips, ...)\n if (preg_match('/<a.*<\\/a>/', $value, $matches)) {\n $out = html_entity_decode(strip_tags($matches[0]));\n }\n }\n break;", " default:\n global $CFG_GLPI;\n $out = \"<td $extraparam valign='top'>\";", " if (!preg_match('/' . self::LBHR . '/', $value)) {\n $values = preg_split('/' . self::LBBR . '/i', $value);\n $line_delimiter = '<br>';\n } else {\n $values = preg_split('/' . self::LBHR . '/i', $value);\n $line_delimiter = '<hr>';\n }", " if (\n count($values) > 1\n && Toolbox::strlen($value) > $CFG_GLPI['cut']\n ) {\n $value = '';\n foreach ($values as $v) {\n $value .= $v . $line_delimiter;\n }\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $value = '<div class=\"fup-popup\">' . $value . '</div>';\n $valTip = \"&nbsp;\" . Html::showToolTip(\n $value,\n [\n 'awesome-class' => 'fa-comments',\n 'display' => false,\n 'autoclose' => false,\n 'onclick' => true\n ]\n );\n $out .= $values[0] . $valTip;\n } else {\n $value = preg_replace('/' . self::LBBR . '/', '<br>', $value);\n $value = preg_replace('/' . self::LBHR . '/', '<hr>', $value);\n $out .= $value;\n }\n $out .= \"</td>\\n\";\n }\n $num++;\n return $out;\n }", "\n /**\n * Print generic error\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $message Message to display, if empty \"no item found\" will be displayed\n *\n * @return string HTML to display\n **/\n public static function showError($type, $message = \"\")\n {\n if (strlen($message) == 0) {\n $message = __('No item found');\n }", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n break;", " default:\n $out = \"<div class='center b'>$message</div>\\n\";\n }\n return $out;\n }", "\n /**\n * Print generic footer\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param string $title title of file : used for PDF (default '')\n * @param integer $count Total number of results\n *\n * @return string HTML to display\n **/\n public static function showFooter($type, $title = \"\", $count = null)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;", " $font = 'helvetica';\n $fontsize = 8;\n if (isset($_SESSION['glpipdffont']) && $_SESSION['glpipdffont']) {\n $font = $_SESSION['glpipdffont'];\n }", " $pdf = new GLPIPDF(\n [\n 'font_size' => $fontsize,\n 'font' => $font,\n 'orientation' => $type == self::PDF_OUTPUT_LANDSCAPE ? 'L' : 'P',\n ],\n $count,\n $title,\n );", " $PDF_TABLE .= '</table>';\n $pdf->writeHTML($PDF_TABLE, true, false, true);\n $pdf->Output('glpi.pdf', 'I');\n break;", " case self::SYLK_OUTPUT: //sylk\n global $SYLK_HEADER,$SYLK_ARRAY,$SYLK_SIZE;\n // largeurs des colonnes\n foreach ($SYLK_SIZE as $num => $val) {\n $out .= \"F;W\" . $num . \" \" . $num . \" \" . min(50, $val) . \"\\n\";\n }\n $out .= \"\\n\";\n // Header\n foreach ($SYLK_HEADER as $num => $val) {\n $out .= \"F;SDM4;FG0C;\" . ($num == 1 ? \"Y1;\" : \"\") . \"X$num\\n\";\n $out .= \"C;N;K\\\"$val\\\"\\n\";\n $out .= \"\\n\";\n }\n // Datas\n foreach ($SYLK_ARRAY as $row => $tab) {\n foreach ($tab as $num => $val) {\n $out .= \"F;P3;FG0L;\" . ($num == 1 ? \"Y\" . $row . \";\" : \"\") . \"X$num\\n\";\n $out .= \"C;N;K\\\"$val\\\"\\n\";\n }\n }\n $out .= \"E\\n\";\n break;", " case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $out = \"</table></div>\\n\";\n }\n return $out;\n }", "\n /**\n * Print generic footer\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param integer $rows Number of rows\n * @param integer $cols Number of columns\n * @param boolean|integer $fixed Used tab_cadre_fixe table for HTML export ? (default 0)\n *\n * @return string HTML to display\n **/\n public static function showHeader($type, $rows, $cols, $fixed = 0)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE = \"<table cellspacing=\\\"0\\\" cellpadding=\\\"1\\\" border=\\\"1\\\" >\";\n break;", " case self::SYLK_OUTPUT: // Sylk\n global $SYLK_ARRAY, $SYLK_HEADER, $SYLK_SIZE;\n $SYLK_ARRAY = [];\n $SYLK_HEADER = [];\n $SYLK_SIZE = [];\n // entetes HTTP\n header(\"Expires: Mon, 26 Nov 1962 00:00:00 GMT\");\n header('Pragma: private'); /// IE BUG + SSL\n header('Cache-control: private, must-revalidate'); /// IE BUG + SSL\n header(\"Content-disposition: filename=glpi.slk\");\n header('Content-type: application/octetstream');\n // entete du fichier\n echo \"ID;PGLPI_EXPORT\\n\"; // ID;Pappli\n echo \"\\n\";\n // formats\n echo \"P;PGeneral\\n\";\n echo \"P;P#,##0.00\\n\"; // P;Pformat_1 (reels)\n echo \"P;P#,##0\\n\"; // P;Pformat_2 (entiers)\n echo \"P;P@\\n\"; // P;Pformat_3 (textes)\n echo \"\\n\";\n // polices\n echo \"P;EArial;M200\\n\";\n echo \"P;EArial;M200\\n\";\n echo \"P;EArial;M200\\n\";\n echo \"P;FArial;M200;SB\\n\";\n echo \"\\n\";\n // nb lignes * nb colonnes\n echo \"B;Y\" . $rows;\n echo \";X\" . $cols . \"\\n\"; // B;Yligmax;Xcolmax\n echo \"\\n\";\n break;", " case self::CSV_OUTPUT: // csv\n header(\"Expires: Mon, 26 Nov 1962 00:00:00 GMT\");\n header('Pragma: private'); /// IE BUG + SSL\n header('Cache-control: private, must-revalidate'); /// IE BUG + SSL\n header(\"Content-disposition: filename=glpi.csv\");\n header('Content-type: text/csv');\n // zero width no break space (for excel)\n echo\"\\xEF\\xBB\\xBF\";\n break;", " case self::NAMES_OUTPUT:\n header(\"Content-disposition: filename=glpi.txt\");\n header('Content-type: file/txt');\n break;", " default:\n if ($fixed) {\n $out = \"<div class='center'><table border='0' class='table'>\";\n } else {\n $out = \"<div class='center'><table border='0' class='table card-table table-hover'>\";\n }\n }\n return $out;\n }", "\n /**\n * Print begin of header part\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n *\n * @since 0.85\n *\n * @return string HTML to display\n **/\n public static function showBeginHeader($type)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= \"<thead>\";\n break;", " case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $out = \"<thead>\";\n }\n return $out;\n }", "\n /**\n * Print end of header part\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n *\n * @since 0.85\n *\n * @return string to display\n **/\n public static function showEndHeader($type)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= \"</thead>\";\n break;", " case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $out = \"</thead>\";\n }\n return $out;\n }", "\n /**\n * Print generic new line\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n * @param boolean $odd Is it a new odd line ? (false by default)\n * @param boolean $is_deleted Is it a deleted search ? (false by default)\n *\n * @return string HTML to display\n **/\n public static function showNewLine($type, $odd = false, $is_deleted = false)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $style = \"\";\n if ($odd) {\n $style = \" style=\\\"background-color:#DDDDDD;\\\" \";\n }\n $PDF_TABLE .= \"<tr $style nobr=\\\"true\\\">\";\n break;", " case self::SYLK_OUTPUT: //sylk\n case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n break;", " default:\n $class = \" class='tab_bg_2\" . ($is_deleted ? '_2' : '') . \"' \";\n if ($odd) {\n $class = \" class='tab_bg_1\" . ($is_deleted ? '_2' : '') . \"' \";\n }\n $out = \"<tr $class>\";\n }\n return $out;\n }", "\n /**\n * Print generic end line\n *\n * @param integer $type Display type (0=HTML, 1=Sylk, 2=PDF, 3=CSV)\n *\n * @return string HTML to display\n **/\n public static function showEndLine($type, bool $is_header_line = false)\n {", " $out = \"\";\n switch ($type) {\n case self::PDF_OUTPUT_LANDSCAPE: //pdf\n case self::PDF_OUTPUT_PORTRAIT:\n global $PDF_TABLE;\n $PDF_TABLE .= '</tr>';\n break;", " case self::SYLK_OUTPUT: //sylk\n break;", " case self::CSV_OUTPUT: //csv\n case self::NAMES_OUTPUT:\n // NAMES_OUTPUT has no output on header lines\n $newline = $type != self::NAMES_OUTPUT || !$is_header_line;\n if ($newline) {\n $out = \"\\n\";\n }\n break;", " default:\n $out = \"</tr>\";\n }\n return $out;\n }", "\n /**\n * @param array $joinparams\n */\n public static function computeComplexJoinID(array $joinparams)\n {", " $complexjoin = '';", " if (isset($joinparams['condition'])) {\n if (!is_array($joinparams['condition'])) {\n $complexjoin .= $joinparams['condition'];\n } else {\n global $DB;\n $dbi = new DBmysqlIterator($DB);\n $sql_clause = $dbi->analyseCrit($joinparams['condition']);\n $complexjoin .= ' AND ' . $sql_clause; //TODO: and should came from conf\n }\n }", " // For jointype == child\n if (\n isset($joinparams['jointype']) && ($joinparams['jointype'] == 'child')\n && isset($joinparams['linkfield'])\n ) {\n $complexjoin .= $joinparams['linkfield'];\n }", " if (isset($joinparams['beforejoin'])) {\n if (isset($joinparams['beforejoin']['table'])) {\n $joinparams['beforejoin'] = [$joinparams['beforejoin']];\n }\n foreach ($joinparams['beforejoin'] as $tab) {\n if (isset($tab['table'])) {\n $complexjoin .= $tab['table'];\n }\n if (isset($tab['joinparams']) && isset($tab['joinparams']['condition'])) {\n if (!is_array($tab['joinparams']['condition'])) {\n $complexjoin .= $tab['joinparams']['condition'];\n } else {\n global $DB;\n $dbi = new DBmysqlIterator($DB);\n $sql_clause = $dbi->analyseCrit($tab['joinparams']['condition']);\n $complexjoin .= ' AND ' . $sql_clause; //TODO: and should came from conf\n }\n }\n }\n }", " if (!empty($complexjoin)) {\n $complexjoin = md5($complexjoin);\n }\n return $complexjoin;\n }", "\n /**\n * Clean display value for csv export\n *\n * @param string $value value\n *\n * @return string Clean value\n **/\n public static function csv_clean($value)\n {", " $value = str_replace(\"\\\"\", \"''\", $value);", " return $value;\n }", "\n /**\n * Clean display value for sylk export\n *\n * @param string $value value\n *\n * @return string Clean value\n **/\n public static function sylk_clean($value)\n {", " $value = preg_replace('/\\x0A/', ' ', $value);\n $value = preg_replace('/\\x0D/', '', $value);\n $value = str_replace(\"\\\"\", \"''\", $value);\n $value = str_replace(\"\\n\", \" | \", $value);", " return $value;\n }", "\n /**\n * Create SQL search condition\n *\n * @param string $field Nname (should be ` protected)\n * @param string $val Value to search\n * @param boolean $not Is a negative search ? (false by default)\n * @param string $link With previous criteria (default 'AND')\n *\n * @return search SQL string\n **/\n public static function makeTextCriteria($field, $val, $not = false, $link = 'AND')\n {", " $sql = $field . self::makeTextSearch($val, $not);\n // mange empty field (string with length = 0)\n $sql_or = \"\";\n if (strtolower($val) == \"null\") {\n $sql_or = \"OR $field = ''\";\n }", " if (\n ($not && ($val != 'NULL') && ($val != 'null') && ($val != '^$')) // Not something\n || (!$not && ($val == '^$'))\n ) { // Empty\n $sql = \"($sql OR $field IS NULL)\";\n }\n return \" $link ($sql $sql_or)\";\n }", " /**\n * Create SQL search value\n *\n * @since 9.4\n *\n * @param string $val value to search\n *\n * @return string|null\n **/\n public static function makeTextSearchValue($val)\n {\n // `$val` will mostly comes from sanitized input, but may also be raw value.\n // 1. Unsanitize value to be sure to use raw value.\n // 2. Escape raw value to protect SQL special chars.\n $val = Sanitizer::dbEscape(Sanitizer::unsanitize($val));", " // escape _ char used as wildcard in mysql likes\n $val = str_replace('_', '\\\\_', $val);", " if ($val === 'NULL' || $val === 'null') {\n return null;\n }", " $val = trim($val);", " if ($val === '^') {\n // Special case, searching \"^\" means we are searching for a non empty/null field\n return '%';\n }", " if ($val === '' || $val === '^$' || $val === '$') {\n return '';\n }", " if (preg_match('/^\\^/', $val)) {\n // Remove leading `^`\n $val = ltrim(preg_replace('/^\\^/', '', $val));\n } else {\n // Add % wildcard before searched string if not begining by a `^`\n $val = '%' . $val;\n }", " if (preg_match('/\\$$/', $val)) {\n // Remove trailing `$`\n $val = rtrim(preg_replace('/\\$$/', '', $val));\n } else {\n // Add % wildcard after searched string if not ending by a `$`\n $val = $val . '%';\n }", " return $val;\n }", "\n /**\n * Create SQL search condition\n *\n * @param string $val Value to search\n * @param boolean $not Is a negative search ? (false by default)\n *\n * @return string Search string\n **/\n public static function makeTextSearch($val, $not = false)\n {", " $NOT = \"\";\n if ($not) {\n $NOT = \"NOT\";\n }", " $val = self::makeTextSearchValue($val);\n if ($val == null) {\n $SEARCH = \" IS $NOT NULL \";\n } else {\n $SEARCH = \" $NOT LIKE \" . DBmysql::quoteValue($val) . \" \";\n }\n return $SEARCH;\n }", "\n /**\n * @since 0.84\n *\n * @param string $pattern\n * @param string $subject\n **/\n public static function explodeWithID($pattern, $subject)\n {", " $tab = explode($pattern, $subject);", " if (isset($tab[1]) && !is_numeric($tab[1])) {\n // Report $ to tab[0]\n if (preg_match('/^(\\\\$*)(.*)/', $tab[1], $matchs)) {\n if (isset($matchs[2]) && is_numeric($matchs[2])) {\n $tab[1] = $matchs[2];\n $tab[0] .= $matchs[1];\n }\n }\n }\n // Manage NULL value\n if ($tab[0] == self::NULLVALUE) {\n $tab[0] = null;\n }\n return $tab;\n }", " /**\n * Add join for dropdown translations\n *\n * @param string $alias Alias for translation table\n * @param string $table Table to join on\n * @param class-string<CommonDBTM> $itemtype Item type\n * @param string $field Field name\n *\n * @return string\n */\n public static function joinDropdownTranslations($alias, $table, $itemtype, $field)\n {\n return \"LEFT JOIN `glpi_dropdowntranslations` AS `$alias`\n ON (`$alias`.`itemtype` = '$itemtype'\n AND `$alias`.`items_id` = `$table`.`id`\n AND `$alias`.`language` = '\" .\n $_SESSION['glpilanguage'] . \"'\n AND `$alias`.`field` = '$field')\";\n }", " /**\n * Get table name for item type\n *\n * @param class-string<CommonDBTM> $itemtype\n *\n * @return string\n */\n public static function getOrigTableName(string $itemtype): string\n {\n return (is_a($itemtype, CommonDBTM::class, true)) ? $itemtype::getTable() : getTableForItemType($itemtype);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [7171], "buggy_code_start_loc": [6308], "filenames": ["src/Search.php"], "fixing_code_end_loc": [7178], "fixing_code_start_loc": [6309], "message": "GLPI stands for Gestionnaire Libre de Parc Informatique and is a Free Asset and IT Management Software package, that provides ITIL Service Desk features, licenses tracking and software auditing. Affected versions were found to not properly neutralize HTML tags in the global search context. Users are advised to upgrade to version 10.0.3 to resolve this issue. Users unable to upgrade should disable global search.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "F1118A51-CFED-4D17-8344-EA94C8F77EAD", "versionEndExcluding": "10.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI stands for Gestionnaire Libre de Parc Informatique and is a Free Asset and IT Management Software package, that provides ITIL Service Desk features, licenses tracking and software auditing. Affected versions were found to not properly neutralize HTML tags in the global search context. Users are advised to upgrade to version 10.0.3 to resolve this issue. Users unable to upgrade should disable global search."}, {"lang": "es", "value": "GLPI son las siglas de Gestionnaire Libre de Parc Informatique y es un Paquete de Software Libre de Administraci\u00f3n de Activos y TI, que proporciona funciones de Service Desk de ITIL, seguimiento de licencias y auditor\u00eda de software. Se ha detectado que las versiones afectadas no neutralizan correctamente las etiquetas HTML en el contexto de la b\u00fasqueda global. Es recomendado a usuarios actualizar a versi\u00f3n 10.0.3 para resolver este problema. Los usuarios que no puedan actualizarse deber\u00e1n deshabilitar la b\u00fasqueda global"}], "evaluatorComment": null, "id": "CVE-2022-31187", "lastModified": "2022-09-19T14:08:43.310", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:H", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-09-14T18:15:10.437", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/e248ed5649d267c0f61a17d99b7bd6be4074aadb"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-43j5-xhvj-9236"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/e248ed5649d267c0f61a17d99b7bd6be4074aadb"}, "type": "CWE-79"}
282
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\nimport re", "import sys", "from setuptools import setup\nfrom setuptools.command.test import test as TestCommand", "install_requires = [\n # core dependencies\n 'decorator',\n 'requests >= 1.0.0',\n 'future',\n 'paste',\n 'zope.interface',\n 'repoze.who',\n 'pycryptodomex',\n 'pytz',\n 'pyOpenSSL',\n 'python-dateutil',", "", " 'six'\n]", "version = ''\nwith open('src/saml2/__init__.py', 'r') as fd:\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]',\n fd.read(), re.MULTILINE).group(1)", "setup(\n name='pysaml2',\n version=version,\n description='Python implementation of SAML Version 2',\n # long_description = read(\"README\"),\n author='Roland Hedberg',\n author_email='roland.hedberg@adm.umu.se',\n license='Apache 2.0',\n url='https://github.com/rohe/pysaml2',", " packages=['saml2', 'saml2/xmldsig', 'saml2/xmlenc', 'saml2/s2repoze',\n 'saml2/s2repoze.plugins', \"saml2/profile\", \"saml2/schema\",\n \"saml2/extension\", \"saml2/attributemaps\", \"saml2/authn_context\",\n \"saml2/entity_category\", \"saml2/userinfo\", \"saml2/ws\"],", " package_dir={'': 'src'},\n package_data={'': ['xml/*.xml']},\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\"\n ],", " scripts=[\"tools/parse_xsd2.py\", \"tools/make_metadata.py\",\n \"tools/mdexport.py\", \"tools/merge_metadata.py\"],\n install_requires=install_requires,\n zip_safe=False,\n)" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\nimport re", "import sys", "from setuptools import setup\nfrom setuptools.command.test import test as TestCommand", "install_requires = [\n # core dependencies\n 'decorator',\n 'requests >= 1.0.0',\n 'future',\n 'paste',\n 'zope.interface',\n 'repoze.who',\n 'pycryptodomex',\n 'pytz',\n 'pyOpenSSL',\n 'python-dateutil',", " 'defusedxml',", " 'six'\n]", "version = ''\nwith open('src/saml2/__init__.py', 'r') as fd:\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]',\n fd.read(), re.MULTILINE).group(1)", "setup(\n name='pysaml2',\n version=version,\n description='Python implementation of SAML Version 2',\n # long_description = read(\"README\"),\n author='Roland Hedberg',\n author_email='roland.hedberg@adm.umu.se',\n license='Apache 2.0',\n url='https://github.com/rohe/pysaml2',", " packages=['saml2', 'saml2/xmldsig', 'saml2/xmlenc', 'saml2/s2repoze',\n 'saml2/s2repoze.plugins', \"saml2/profile\", \"saml2/schema\",\n \"saml2/extension\", \"saml2/attributemaps\", \"saml2/authn_context\",\n \"saml2/entity_category\", \"saml2/userinfo\", \"saml2/ws\"],", " package_dir={'': 'src'},\n package_data={'': ['xml/*.xml']},\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\"\n ],", " scripts=[\"tools/parse_xsd2.py\", \"tools/make_metadata.py\",\n \"tools/mdexport.py\", \"tools/merge_metadata.py\"],\n install_requires=install_requires,\n zip_safe=False,\n)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-", "\"\"\"Contains base classes representing SAML elements.", " These codes were originally written by Jeffrey Scudder for\n representing Saml elements. Takashi Matsuo had added some codes, and\n changed some. Roland Hedberg rewrote the whole thing from bottom up so\n barely anything but the original structures remained.", " Module objective: provide data classes for SAML constructs. These\n classes hide the XML-ness of SAML and provide a set of native Python\n classes to interact with.", " Conversions to and from XML should only be necessary when the SAML classes\n \"touch the wire\" and are sent over HTTP. For this reason this module\n provides methods and functions to convert SAML classes to and from strings.\n\"\"\"", "__version__ = \"4.4.0\"", "import logging\nimport six\nfrom saml2.validate import valid_instance", "try:\n from xml.etree import cElementTree as ElementTree", " if ElementTree.VERSION < '1.3.0':\n # cElementTree has no support for register_namespace\n # neither _namespace_map, thus we sacrify performance\n # for correctness\n from xml.etree import ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "", "\nroot_logger = logging.getLogger(__name__)\nroot_logger.level = logging.NOTSET", "NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion'\n# TEMPLATE = '{urn:oasis:names:tc:SAML:2.0:assertion}%s'\n# XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance'", "NAMEID_FORMAT_EMAILADDRESS = (\n \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\")", "# These are defined in saml2.saml\n# NAME_FORMAT_UNSPECIFIED = (\n# \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\")\n# NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"\n# NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\"", "DECISION_TYPE_PERMIT = \"Permit\"\nDECISION_TYPE_DENY = \"Deny\"\nDECISION_TYPE_INDETERMINATE = \"Indeterminate\"", "VERSION = \"2.0\"", "BINDING_SOAP = 'urn:oasis:names:tc:SAML:2.0:bindings:SOAP'\nBINDING_PAOS = 'urn:oasis:names:tc:SAML:2.0:bindings:PAOS'\nBINDING_HTTP_REDIRECT = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'\nBINDING_HTTP_POST = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'\nBINDING_HTTP_ARTIFACT = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'\nBINDING_URI = 'urn:oasis:names:tc:SAML:2.0:bindings:URI'", "\ndef class_name(instance):\n return \"%s:%s\" % (instance.c_namespace, instance.c_tag)", "\ndef create_class_from_xml_string(target_class, xml_string):\n \"\"\"Creates an instance of the target class from a string.", " :param target_class: The class which will be instantiated and populated\n with the contents of the XML. This class must have a c_tag and a\n c_namespace class variable.\n :param xml_string: A string which contains valid XML. The root element\n of the XML string should match the tag and namespace of the desired\n class.", " :return: An instance of the target class with members assigned according to\n the contents of the XML - or None if the root XML tag and namespace did\n not match those of the target class.\n \"\"\"\n if not isinstance(xml_string, six.binary_type):\n xml_string = xml_string.encode('utf-8')", " tree = ElementTree.fromstring(xml_string)", " return create_class_from_element_tree(target_class, tree)", "\ndef create_class_from_element_tree(target_class, tree, namespace=None,\n tag=None):\n \"\"\"Instantiates the class and populates members according to the tree.", " Note: Only use this function with classes that have c_namespace and c_tag\n class members.", " :param target_class: The class which will be instantiated and populated\n with the contents of the XML.\n :param tree: An element tree whose contents will be converted into\n members of the new target_class instance.\n :param namespace: The namespace which the XML tree's root node must\n match. If omitted, the namespace defaults to the c_namespace of the\n target class.\n :param tag: The tag which the XML tree's root node must match. If\n omitted, the tag defaults to the c_tag class member of the target\n class.", " :return: An instance of the target class - or None if the tag and namespace\n of the XML tree's root node did not match the desired namespace and tag.\n \"\"\"\n if namespace is None:\n namespace = target_class.c_namespace\n if tag is None:\n tag = target_class.c_tag\n if tree.tag == '{%s}%s' % (namespace, tag):\n target = target_class()\n target.harvest_element_tree(tree)\n return target\n else:\n return None", "\nclass Error(Exception):\n \"\"\"Exception class thrown by this module.\"\"\"\n pass", "\nclass SAMLError(Exception):\n pass", "\nclass ExtensionElement(object):\n \"\"\"XML which is not part of the SAML specification,\n these are called extension elements. If a classes parser\n encounters an unexpected XML construct, it is translated into an\n ExtensionElement instance. ExtensionElement is designed to fully\n capture the information in the XML. Child nodes in an XML\n extension are turned into ExtensionElements as well.\n \"\"\"", " def __init__(self, tag, namespace=None, attributes=None,\n children=None, text=None):\n \"\"\"Constructor for ExtensionElement", " :param namespace: The XML namespace for this element.\n :param tag: The tag (without the namespace qualifier) for\n this element. To reconstruct the full qualified name of the\n element, combine this tag with the namespace.\n :param attributes: The attribute value string pairs for the XML\n attributes of this element.\n :param children: list (optional) A list of ExtensionElements which\n represent the XML child nodes of this element.\n \"\"\"", " self.namespace = namespace\n self.tag = tag\n self.attributes = attributes or {}\n self.children = children or []\n self.text = text", " def to_string(self):\n \"\"\" Serialize the object into a XML string \"\"\"\n element_tree = self.transfer_to_element_tree()\n return ElementTree.tostring(element_tree, encoding=\"UTF-8\")", " def transfer_to_element_tree(self):\n if self.tag is None:\n return None", " element_tree = ElementTree.Element('')", " if self.namespace is not None:\n element_tree.tag = '{%s}%s' % (self.namespace, self.tag)\n else:\n element_tree.tag = self.tag", " for key, value in iter(self.attributes.items()):\n element_tree.attrib[key] = value", " for child in self.children:\n child.become_child_element_of(element_tree)", " element_tree.text = self.text", " return element_tree", " def become_child_element_of(self, element_tree):\n \"\"\"Converts this object into an etree element and adds it as a child\n node in an etree element.", " Adds self to the ElementTree. This method is required to avoid verbose\n XML which constantly redefines the namespace.", " :param element_tree: ElementTree._Element The element to which this\n object's XML will be added.\n \"\"\"\n new_element = self.transfer_to_element_tree()\n element_tree.append(new_element)", " def find_children(self, tag=None, namespace=None):\n \"\"\"Searches child nodes for objects with the desired tag/namespace.", " Returns a list of extension elements within this object whose tag\n and/or namespace match those passed in. To find all children in\n a particular namespace, specify the namespace but not the tag name.\n If you specify only the tag, the result list may contain extension\n elements in multiple namespaces.", " :param tag: str (optional) The desired tag\n :param namespace: str (optional) The desired namespace", " :return: A list of elements whose tag and/or namespace match the\n parameters values\n \"\"\"", " results = []", " if tag and namespace:\n for element in self.children:\n if element.tag == tag and element.namespace == namespace:\n results.append(element)\n elif tag and not namespace:\n for element in self.children:\n if element.tag == tag:\n results.append(element)\n elif namespace and not tag:\n for element in self.children:\n if element.namespace == namespace:\n results.append(element)\n else:\n for element in self.children:\n results.append(element)", " return results", " def loadd(self, ava):\n \"\"\" expects a special set of keys \"\"\"", " if \"attributes\" in ava:\n for key, val in ava[\"attributes\"].items():\n self.attributes[key] = val", " try:\n self.tag = ava[\"tag\"]\n except KeyError:\n if not self.tag:\n raise KeyError(\"ExtensionElement must have a tag\")", " try:\n self.namespace = ava[\"namespace\"]\n except KeyError:\n if not self.namespace:\n raise KeyError(\"ExtensionElement must belong to a namespace\")", " try:\n self.text = ava[\"text\"]\n except KeyError:\n pass", " if \"children\" in ava:\n for item in ava[\"children\"]:\n self.children.append(ExtensionElement(item[\"tag\"]).loadd(item))", " return self", "\ndef extension_element_from_string(xml_string):", " element_tree = ElementTree.fromstring(xml_string)", " return _extension_element_from_element_tree(element_tree)", "\ndef _extension_element_from_element_tree(element_tree):\n elementc_tag = element_tree.tag\n if '}' in elementc_tag:\n namespace = elementc_tag[1:elementc_tag.index('}')]\n tag = elementc_tag[elementc_tag.index('}') + 1:]\n else:\n namespace = None\n tag = elementc_tag\n extension = ExtensionElement(namespace=namespace, tag=tag)\n for key, value in iter(element_tree.attrib.items()):\n extension.attributes[key] = value\n for child in element_tree:\n extension.children.append(_extension_element_from_element_tree(child))\n extension.text = element_tree.text\n return extension", "\nclass ExtensionContainer(object):\n c_tag = \"\"\n c_namespace = \"\"", " def __init__(self, text=None, extension_elements=None,\n extension_attributes=None):", " self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n self.encrypted_assertion = None", " # Three methods to create an object from an ElementTree\n def harvest_element_tree(self, tree):\n # Fill in the instance members from the contents of the XML tree.\n for child in tree:\n self._convert_element_tree_to_member(child)\n for attribute, value in iter(tree.attrib.items()):\n self._convert_element_attribute_to_member(attribute, value)\n self.text = tree.text", " def _convert_element_tree_to_member(self, child_tree):\n self.extension_elements.append(_extension_element_from_element_tree(\n child_tree))", " def _convert_element_attribute_to_member(self, attribute, value):\n self.extension_attributes[attribute] = value", " # One method to create an ElementTree from an object\n def _add_members_to_element_tree(self, tree):\n for child in self.extension_elements:\n child.become_child_element_of(tree)\n for attribute, value in iter(self.extension_attributes.items()):\n tree.attrib[attribute] = value\n tree.text = self.text", " def find_extensions(self, tag=None, namespace=None):\n \"\"\"Searches extension elements for child nodes with the desired name.", " Returns a list of extension elements within this object whose tag\n and/or namespace match those passed in. To find all extensions in\n a particular namespace, specify the namespace but not the tag name.\n If you specify only the tag, the result list may contain extension\n elements in multiple namespaces.", " :param tag: str (optional) The desired tag\n :param namespace: str (optional) The desired namespace", " :Return: A list of elements whose tag and/or namespace match the\n parameters values\n \"\"\"", " results = []", " if tag and namespace:\n for element in self.extension_elements:\n if element.tag == tag and element.namespace == namespace:\n results.append(element)\n elif tag and not namespace:\n for element in self.extension_elements:\n if element.tag == tag:\n results.append(element)\n elif namespace and not tag:\n for element in self.extension_elements:\n if element.namespace == namespace:\n results.append(element)\n else:\n for element in self.extension_elements:\n results.append(element)", " return results", " def extensions_as_elements(self, tag, schema):\n \"\"\" Return extensions that has the given tag and belongs to the\n given schema as native elements of that schema.", " :param tag: The tag of the element\n :param schema: Which schema the element should originate from\n :return: a list of native elements\n \"\"\"\n result = []\n for ext in self.find_extensions(tag, schema.NAMESPACE):\n ets = schema.ELEMENT_FROM_STRING[tag]\n result.append(ets(ext.to_string()))\n return result", " def add_extension_elements(self, items):\n for item in items:\n self.extension_elements.append(element_to_extension_element(item))", " def add_extension_element(self, item):\n self.extension_elements.append(element_to_extension_element(item))", " def add_extension_attribute(self, name, value):\n self.extension_attributes[name] = value", "\ndef make_vals(val, klass, klass_inst=None, prop=None, part=False,\n base64encode=False):\n \"\"\"\n Creates a class instance with a specified value, the specified\n class instance may be a value on a property in a defined class instance.", " :param val: The value\n :param klass: The value class\n :param klass_inst: The class instance which has a property on which\n what this function returns is a value.\n :param prop: The property which the value should be assigned to.\n :param part: If the value is one of a possible list of values it should be\n handled slightly different compared to if it isn't.\n :return: Value class instance\n \"\"\"\n cinst = None", " # print(\"make_vals(%s, %s)\" % (val, klass))", " if isinstance(val, dict):\n cinst = klass().loadd(val, base64encode=base64encode)\n else:\n try:\n cinst = klass().set_text(val)\n except ValueError:\n if not part:\n cis = [make_vals(sval, klass, klass_inst, prop, True,\n base64encode) for sval in val]\n setattr(klass_inst, prop, cis)\n else:\n raise", " if part:\n return cinst\n else:\n if cinst:\n cis = [cinst]\n setattr(klass_inst, prop, cis)", "\ndef make_instance(klass, spec, base64encode=False):\n \"\"\"\n Constructs a class instance containing the specified information", " :param klass: The class\n :param spec: Information to be placed in the instance (a dictionary)\n :return: The instance\n \"\"\"", " return klass().loadd(spec, base64encode)", "\nclass SamlBase(ExtensionContainer):\n \"\"\"A foundation class on which SAML classes are built. It\n handles the parsing of attributes and children which are common to all\n SAML classes. By default, the SamlBase class translates all XML child\n nodes into ExtensionElements.\n \"\"\"", " c_children = {}\n c_attributes = {}\n c_attribute_type = {}\n c_child_order = []\n c_cardinality = {}\n c_any = None\n c_any_attribute = None\n c_value_type = None\n c_ns_prefix = None", " def _get_all_c_children_with_order(self):\n if len(self.c_child_order) > 0:\n for child in self.c_child_order:\n yield child\n else:\n for _, values in iter(self.__class__.c_children.items()):\n yield values[0]", " def _convert_element_tree_to_member(self, child_tree):\n # Find the element's tag in this class's list of child members\n if child_tree.tag in self.__class__.c_children:\n member_name = self.__class__.c_children[child_tree.tag][0]\n member_class = self.__class__.c_children[child_tree.tag][1]\n # If the class member is supposed to contain a list, make sure the\n # matching member is set to a list, then append the new member\n # instance to the list.\n if isinstance(member_class, list):\n if getattr(self, member_name) is None:\n setattr(self, member_name, [])\n getattr(self, member_name).append(\n create_class_from_element_tree(member_class[0], child_tree))\n else:\n setattr(self, member_name,\n create_class_from_element_tree(member_class,\n child_tree))\n else:\n ExtensionContainer._convert_element_tree_to_member(self, child_tree)", " def _convert_element_attribute_to_member(self, attribute, value):\n # Find the attribute in this class's list of attributes.\n if attribute in self.__class__.c_attributes:\n # Find the member of this class which corresponds to the XML\n # attribute(lookup in current_class.c_attributes) and set this\n # member to the desired value (using self.__dict__).\n setattr(self, self.__class__.c_attributes[attribute][0], value)\n else:\n # If it doesn't appear in the attribute list it's an extension\n ExtensionContainer._convert_element_attribute_to_member(\n self, attribute, value)", " # Three methods to create an ElementTree from an object\n def _add_members_to_element_tree(self, tree):\n # Convert the members of this class which are XML child nodes.\n # This uses the class's c_children dictionary to find the members which\n # should become XML child nodes.\n for member_name in self._get_all_c_children_with_order():\n member = getattr(self, member_name)\n if member is None:\n pass\n elif isinstance(member, list):\n for instance in member:\n instance.become_child_element_of(tree)\n else:\n member.become_child_element_of(tree)\n # Convert the members of this class which are XML attributes.\n for xml_attribute, attribute_info in \\\n iter(self.__class__.c_attributes.items()):\n (member_name, member_type, required) = attribute_info\n member = getattr(self, member_name)\n if member is not None:\n tree.attrib[xml_attribute] = member", " # Lastly, call the ExtensionContainers's _add_members_to_element_tree\n # to convert any extension attributes.\n ExtensionContainer._add_members_to_element_tree(self, tree)", " def become_child_element_of(self, node):\n \"\"\"\n Note: Only for use with classes that have a c_tag and c_namespace class\n member. It is in SamlBase so that it can be inherited but it should\n not be called on instances of SamlBase.", " :param node: The node to which this instance should be a child\n \"\"\"\n new_child = self._to_element_tree()\n node.append(new_child)", " def _to_element_tree(self):\n \"\"\"", " Note, this method is designed to be used only with classes that have a\n c_tag and c_namespace. It is placed in SamlBase for inheritance but\n should not be called on in this class.", " \"\"\"\n new_tree = ElementTree.Element('{%s}%s' % (self.__class__.c_namespace,\n self.__class__.c_tag))\n self._add_members_to_element_tree(new_tree)\n return new_tree", " def register_prefix(self, nspair):\n \"\"\"\n Register with ElementTree a set of namespaces", " :param nspair: A dictionary of prefixes and uris to use when\n constructing the text representation.\n :return:\n \"\"\"\n for prefix, uri in nspair.items():\n try:\n ElementTree.register_namespace(prefix, uri)\n except AttributeError:\n # Backwards compatibility with ET < 1.3\n ElementTree._namespace_map[uri] = prefix\n except ValueError:\n pass", " def get_ns_map_attribute(self, attributes, uri_set):\n for attribute in attributes:\n if attribute[0] == \"{\":\n uri, tag = attribute[1:].split(\"}\")\n uri_set.add(uri)\n return uri_set", " def tag_get_uri(self, elem):\n if elem.tag[0] == \"{\":\n uri, tag = elem.tag[1:].split(\"}\")\n return uri\n return None", " def get_ns_map(self, elements, uri_set):", " for elem in elements:\n uri_set = self.get_ns_map_attribute(elem.attrib, uri_set)\n uri_set = self.get_ns_map(elem.getchildren(), uri_set)\n uri = self.tag_get_uri(elem)\n if uri is not None:\n uri_set.add(uri)\n return uri_set", " def get_prefix_map(self, elements):\n uri_set = self.get_ns_map(elements, set())\n prefix_map = {}\n for uri in sorted(uri_set):\n prefix_map[\"encas%d\" % len(prefix_map)] = uri\n return prefix_map", " def get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n self, assertion_tag, advice_tag):\n for tmp_encrypted_assertion in \\\n self.assertion.advice.encrypted_assertion:\n if tmp_encrypted_assertion.encrypted_data is None:\n prefix_map = self.get_prefix_map([\n tmp_encrypted_assertion._to_element_tree().find(\n assertion_tag)])\n tree = self._to_element_tree()\n encs = tree.find(assertion_tag).find(advice_tag).findall(\n tmp_encrypted_assertion._to_element_tree().tag)\n for enc in encs:\n assertion = enc.find(assertion_tag)\n if assertion is not None:\n self.set_prefixes(assertion, prefix_map)", " return ElementTree.tostring(tree, encoding=\"UTF-8\").decode('utf-8')", " def get_xml_string_with_self_contained_assertion_within_encrypted_assertion(\n self, assertion_tag):\n \"\"\" Makes a encrypted assertion only containing self contained\n namespaces.", " :param assertion_tag: Tag for the assertion to be transformed.\n :return: A new samlp.Resonse in string representation.\n \"\"\"\n prefix_map = self.get_prefix_map(\n [self.encrypted_assertion._to_element_tree().find(assertion_tag)])", " tree = self._to_element_tree()", " self.set_prefixes(\n tree.find(\n self.encrypted_assertion._to_element_tree().tag).find(\n assertion_tag), prefix_map)", " return ElementTree.tostring(tree, encoding=\"UTF-8\").decode('utf-8')", " def set_prefixes(self, elem, prefix_map):", " # check if this is a tree wrapper\n if not ElementTree.iselement(elem):\n elem = elem.getroot()", " # build uri map and add to root element\n uri_map = {}\n for prefix, uri in prefix_map.items():\n uri_map[uri] = prefix\n elem.set(\"xmlns:\" + prefix, uri)", " # fixup all elements in the tree\n memo = {}\n for elem in elem.getiterator():\n self.fixup_element_prefixes(elem, uri_map, memo)", " def fixup_element_prefixes(self, elem, uri_map, memo):\n def fixup(name):\n try:\n return memo[name]\n except KeyError:\n if name[0] != \"{\":\n return\n uri, tag = name[1:].split(\"}\")\n if uri in uri_map:\n new_name = uri_map[uri] + \":\" + tag\n memo[name] = new_name\n return new_name", " # fix element name\n name = fixup(elem.tag)\n if name:\n elem.tag = name\n # fix attribute names\n for key, value in elem.items():\n name = fixup(key)\n if name:\n elem.set(name, value)\n del elem.attrib[key]", " def to_string_force_namespace(self, nspair):", " elem = self._to_element_tree()", " self.set_prefixes(elem, nspair)", " return ElementTree.tostring(elem, encoding=\"UTF-8\")", " def to_string(self, nspair=None):\n \"\"\"Converts the Saml object to a string containing XML.", " :param nspair: A dictionary of prefixes and uris to use when\n constructing the text representation.\n :return: String representation of the object\n \"\"\"\n if not nspair and self.c_ns_prefix:\n nspair = self.c_ns_prefix", " if nspair:\n self.register_prefix(nspair)", " return ElementTree.tostring(self._to_element_tree(), encoding=\"UTF-8\")", " def __str__(self):\n # Yes this is confusing. http://bugs.python.org/issue10942\n x = self.to_string()\n if not isinstance(x, six.string_types):\n x = x.decode('utf-8')\n return x", " def keyswv(self):\n \"\"\" Return the keys of attributes or children that has values", " :return: list of keys\n \"\"\"\n return [key for key, val in self.__dict__.items() if val]", " def keys(self):\n \"\"\" Return all the keys that represent possible attributes and\n children.", " :return: list of keys\n \"\"\"\n keys = ['text']\n keys.extend([n for (n, t, r) in self.c_attributes.values()])\n keys.extend([v[0] for v in self.c_children.values()])\n return keys", " def children_with_values(self):\n \"\"\" Returns all children that has values", " :return: Possibly empty list of children.\n \"\"\"\n childs = []\n for attribute in self._get_all_c_children_with_order():\n member = getattr(self, attribute)\n if member is None or member == []:\n pass\n elif isinstance(member, list):\n for instance in member:\n childs.append(instance)\n else:\n childs.append(member)\n return childs", " # noinspection PyUnusedLocal\n def set_text(self, val, base64encode=False):\n \"\"\" Sets the text property of this instance.", " :param val: The value of the text property\n :param base64encode: Whether the value should be base64encoded\n :return: The instance\n \"\"\"", " # print(\"set_text: %s\" % (val,))\n if isinstance(val, bool):\n if val:\n setattr(self, \"text\", \"true\")\n else:\n setattr(self, \"text\", \"false\")\n elif isinstance(val, int):\n setattr(self, \"text\", \"%d\" % val)\n elif isinstance(val, six.string_types):\n setattr(self, \"text\", val)\n elif val is None:\n pass\n else:\n raise ValueError(\"Type shouldn't be '%s'\" % (val,))", " return self", " def loadd(self, ava, base64encode=False):\n \"\"\"\n Sets attributes, children, extension elements and extension\n attributes of this element instance depending on what is in\n the given dictionary. If there are already values on properties\n those will be overwritten. If the keys in the dictionary does\n not correspond to known attributes/children/.. they are ignored.", " :param ava: The dictionary\n :param base64encode: Whether the values on attributes or texts on\n children shoule be base64encoded.\n :return: The instance\n \"\"\"", " for prop, _typ, _req in self.c_attributes.values():\n # print(\"# %s\" % (prop))\n if prop in ava:\n if isinstance(ava[prop], bool):\n setattr(self, prop, \"%s\" % ava[prop])\n elif isinstance(ava[prop], int):\n setattr(self, prop, \"%d\" % ava[prop])\n else:\n setattr(self, prop, ava[prop])", " if \"text\" in ava:\n self.set_text(ava[\"text\"], base64encode)", " for prop, klassdef in self.c_children.values():\n # print(\"## %s, %s\" % (prop, klassdef))\n if prop in ava:\n # print(\"### %s\" % ava[prop])\n # means there can be a list of values\n if isinstance(klassdef, list):\n make_vals(ava[prop], klassdef[0], self, prop,\n base64encode=base64encode)\n else:\n cis = make_vals(ava[prop], klassdef, self, prop, True,\n base64encode)\n setattr(self, prop, cis)", " if \"extension_elements\" in ava:\n for item in ava[\"extension_elements\"]:\n self.extension_elements.append(ExtensionElement(\n item[\"tag\"]).loadd(item))", " if \"extension_attributes\" in ava:\n for key, val in ava[\"extension_attributes\"].items():\n self.extension_attributes[key] = val", " return self", " def clear_text(self):\n if self.text:\n _text = self.text.strip()\n if _text == \"\":\n self.text = None", " def __eq__(self, other):\n try:\n assert isinstance(other, SamlBase)\n except AssertionError:\n return False", " self.clear_text()\n other.clear_text()\n if len(self.keyswv()) != len(other.keyswv()):\n return False", " for key in self.keyswv():\n if key in [\"_extatt\"]:\n continue\n svals = self.__dict__[key]\n ovals = other.__dict__[key]\n if isinstance(svals, six.string_types):\n if svals != ovals:\n return False\n elif isinstance(svals, list):\n for sval in svals:\n try:\n for oval in ovals:\n if sval == oval:\n break\n else:\n return False\n except TypeError:\n # ovals isn't iterable\n return False\n else:\n if svals == ovals: # Since I only support '=='\n pass\n else:\n return False\n return True", " def child_class(self, child):\n \"\"\" Return the class a child element should be an instance of", " :param child: The name of the child element\n :return: The class\n \"\"\"\n for prop, klassdef in self.c_children.values():\n if child == prop:\n if isinstance(klassdef, list):\n return klassdef[0]\n else:\n return klassdef\n return None", " def child_cardinality(self, child):\n \"\"\" Return the cardinality of a child element", " :param child: The name of the child element\n :return: The cardinality as a 2-tuple (min, max).\n The max value is either a number or the string \"unbounded\".\n The min value is always a number.\n \"\"\"\n for prop, klassdef in self.c_children.values():\n if child == prop:\n if isinstance(klassdef, list):\n try:\n _min = self.c_cardinality[\"min\"]\n except KeyError:\n _min = 1\n try:\n _max = self.c_cardinality[\"max\"]\n except KeyError:\n _max = \"unbounded\"", " return _min, _max\n else:\n return 1, 1\n return None", " def verify(self):\n return valid_instance(self)", " def empty(self):\n for prop, _typ, _req in self.c_attributes.values():\n if getattr(self, prop, None):\n return False", " for prop, klassdef in self.c_children.values():\n if getattr(self, prop):\n return False", " for param in [\"text\", \"extension_elements\", \"extension_attributes\"]:\n if getattr(self, param):\n return False", " return True", "\n# ----------------------------------------------------------------------------", "\ndef element_to_extension_element(element):\n \"\"\"\n Convert an element into a extension element", " :param element: The element instance\n :return: An extension element instance\n \"\"\"", " exel = ExtensionElement(element.c_tag, element.c_namespace,\n text=element.text)", " exel.attributes.update(element.extension_attributes)\n exel.children.extend(element.extension_elements)", " for xml_attribute, (member_name, typ, req) in \\\n iter(element.c_attributes.items()):\n member_value = getattr(element, member_name)\n if member_value is not None:\n exel.attributes[xml_attribute] = member_value", " exel.children.extend([element_to_extension_element(c) for c in\n element.children_with_values()])", " return exel", "\ndef extension_element_to_element(extension_element, translation_functions,\n namespace=None):\n \"\"\" Convert an extension element to a normal element.\n In order to do this you need to have an idea of what type of\n element it is. Or rather which module it belongs to.", " :param extension_element: The extension element\n :param translation_functions: A dictionary with class identifiers\n as keys and string-to-element translations functions as values\n :param namespace: The namespace of the translation functions.\n :return: An element instance or None\n \"\"\"", " try:\n element_namespace = extension_element.namespace\n except AttributeError:\n element_namespace = extension_element.c_namespace\n if element_namespace == namespace:\n try:\n try:\n ets = translation_functions[extension_element.tag]\n except AttributeError:\n ets = translation_functions[extension_element.c_tag]\n return ets(extension_element.to_string())\n except KeyError:\n pass", " return None", "\ndef extension_elements_to_elements(extension_elements, schemas):\n \"\"\" Create a list of elements each one matching one of the\n given extension elements. This is of course dependent on the access\n to schemas that describe the extension elements.", " :param extension_elements: The list of extension elements\n :param schemas: Imported Python modules that represent the different\n known schemas used for the extension elements\n :return: A list of elements, representing the set of extension elements\n that was possible to match against a Class in the given schemas.\n The elements returned are the native representation of the elements\n according to the schemas.\n \"\"\"\n res = []", " if isinstance(schemas, list):\n pass\n elif isinstance(schemas, dict):\n schemas = list(schemas.values())\n else:\n return res", " for extension_element in extension_elements:\n for schema in schemas:\n inst = extension_element_to_element(extension_element,\n schema.ELEMENT_FROM_STRING,\n schema.NAMESPACE)\n if inst:\n res.append(inst)\n break", " return res", "\ndef extension_elements_as_dict(extension_elements, onts):\n ees_ = extension_elements_to_elements(extension_elements, onts)\n res = {}\n for elem in ees_:\n try:\n res[elem.c_tag].append(elem)\n except KeyError:\n res[elem.c_tag] = [elem]\n return res" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-", "\"\"\"Contains base classes representing SAML elements.", " These codes were originally written by Jeffrey Scudder for\n representing Saml elements. Takashi Matsuo had added some codes, and\n changed some. Roland Hedberg rewrote the whole thing from bottom up so\n barely anything but the original structures remained.", " Module objective: provide data classes for SAML constructs. These\n classes hide the XML-ness of SAML and provide a set of native Python\n classes to interact with.", " Conversions to and from XML should only be necessary when the SAML classes\n \"touch the wire\" and are sent over HTTP. For this reason this module\n provides methods and functions to convert SAML classes to and from strings.\n\"\"\"", "__version__ = \"4.4.0\"", "import logging\nimport six\nfrom saml2.validate import valid_instance", "try:\n from xml.etree import cElementTree as ElementTree", " if ElementTree.VERSION < '1.3.0':\n # cElementTree has no support for register_namespace\n # neither _namespace_map, thus we sacrify performance\n # for correctness\n from xml.etree import ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "import defusedxml.ElementTree", "\nroot_logger = logging.getLogger(__name__)\nroot_logger.level = logging.NOTSET", "NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion'\n# TEMPLATE = '{urn:oasis:names:tc:SAML:2.0:assertion}%s'\n# XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance'", "NAMEID_FORMAT_EMAILADDRESS = (\n \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\")", "# These are defined in saml2.saml\n# NAME_FORMAT_UNSPECIFIED = (\n# \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\")\n# NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"\n# NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\"", "DECISION_TYPE_PERMIT = \"Permit\"\nDECISION_TYPE_DENY = \"Deny\"\nDECISION_TYPE_INDETERMINATE = \"Indeterminate\"", "VERSION = \"2.0\"", "BINDING_SOAP = 'urn:oasis:names:tc:SAML:2.0:bindings:SOAP'\nBINDING_PAOS = 'urn:oasis:names:tc:SAML:2.0:bindings:PAOS'\nBINDING_HTTP_REDIRECT = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'\nBINDING_HTTP_POST = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'\nBINDING_HTTP_ARTIFACT = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'\nBINDING_URI = 'urn:oasis:names:tc:SAML:2.0:bindings:URI'", "\ndef class_name(instance):\n return \"%s:%s\" % (instance.c_namespace, instance.c_tag)", "\ndef create_class_from_xml_string(target_class, xml_string):\n \"\"\"Creates an instance of the target class from a string.", " :param target_class: The class which will be instantiated and populated\n with the contents of the XML. This class must have a c_tag and a\n c_namespace class variable.\n :param xml_string: A string which contains valid XML. The root element\n of the XML string should match the tag and namespace of the desired\n class.", " :return: An instance of the target class with members assigned according to\n the contents of the XML - or None if the root XML tag and namespace did\n not match those of the target class.\n \"\"\"\n if not isinstance(xml_string, six.binary_type):\n xml_string = xml_string.encode('utf-8')", " tree = defusedxml.ElementTree.fromstring(xml_string)", " return create_class_from_element_tree(target_class, tree)", "\ndef create_class_from_element_tree(target_class, tree, namespace=None,\n tag=None):\n \"\"\"Instantiates the class and populates members according to the tree.", " Note: Only use this function with classes that have c_namespace and c_tag\n class members.", " :param target_class: The class which will be instantiated and populated\n with the contents of the XML.\n :param tree: An element tree whose contents will be converted into\n members of the new target_class instance.\n :param namespace: The namespace which the XML tree's root node must\n match. If omitted, the namespace defaults to the c_namespace of the\n target class.\n :param tag: The tag which the XML tree's root node must match. If\n omitted, the tag defaults to the c_tag class member of the target\n class.", " :return: An instance of the target class - or None if the tag and namespace\n of the XML tree's root node did not match the desired namespace and tag.\n \"\"\"\n if namespace is None:\n namespace = target_class.c_namespace\n if tag is None:\n tag = target_class.c_tag\n if tree.tag == '{%s}%s' % (namespace, tag):\n target = target_class()\n target.harvest_element_tree(tree)\n return target\n else:\n return None", "\nclass Error(Exception):\n \"\"\"Exception class thrown by this module.\"\"\"\n pass", "\nclass SAMLError(Exception):\n pass", "\nclass ExtensionElement(object):\n \"\"\"XML which is not part of the SAML specification,\n these are called extension elements. If a classes parser\n encounters an unexpected XML construct, it is translated into an\n ExtensionElement instance. ExtensionElement is designed to fully\n capture the information in the XML. Child nodes in an XML\n extension are turned into ExtensionElements as well.\n \"\"\"", " def __init__(self, tag, namespace=None, attributes=None,\n children=None, text=None):\n \"\"\"Constructor for ExtensionElement", " :param namespace: The XML namespace for this element.\n :param tag: The tag (without the namespace qualifier) for\n this element. To reconstruct the full qualified name of the\n element, combine this tag with the namespace.\n :param attributes: The attribute value string pairs for the XML\n attributes of this element.\n :param children: list (optional) A list of ExtensionElements which\n represent the XML child nodes of this element.\n \"\"\"", " self.namespace = namespace\n self.tag = tag\n self.attributes = attributes or {}\n self.children = children or []\n self.text = text", " def to_string(self):\n \"\"\" Serialize the object into a XML string \"\"\"\n element_tree = self.transfer_to_element_tree()\n return ElementTree.tostring(element_tree, encoding=\"UTF-8\")", " def transfer_to_element_tree(self):\n if self.tag is None:\n return None", " element_tree = ElementTree.Element('')", " if self.namespace is not None:\n element_tree.tag = '{%s}%s' % (self.namespace, self.tag)\n else:\n element_tree.tag = self.tag", " for key, value in iter(self.attributes.items()):\n element_tree.attrib[key] = value", " for child in self.children:\n child.become_child_element_of(element_tree)", " element_tree.text = self.text", " return element_tree", " def become_child_element_of(self, element_tree):\n \"\"\"Converts this object into an etree element and adds it as a child\n node in an etree element.", " Adds self to the ElementTree. This method is required to avoid verbose\n XML which constantly redefines the namespace.", " :param element_tree: ElementTree._Element The element to which this\n object's XML will be added.\n \"\"\"\n new_element = self.transfer_to_element_tree()\n element_tree.append(new_element)", " def find_children(self, tag=None, namespace=None):\n \"\"\"Searches child nodes for objects with the desired tag/namespace.", " Returns a list of extension elements within this object whose tag\n and/or namespace match those passed in. To find all children in\n a particular namespace, specify the namespace but not the tag name.\n If you specify only the tag, the result list may contain extension\n elements in multiple namespaces.", " :param tag: str (optional) The desired tag\n :param namespace: str (optional) The desired namespace", " :return: A list of elements whose tag and/or namespace match the\n parameters values\n \"\"\"", " results = []", " if tag and namespace:\n for element in self.children:\n if element.tag == tag and element.namespace == namespace:\n results.append(element)\n elif tag and not namespace:\n for element in self.children:\n if element.tag == tag:\n results.append(element)\n elif namespace and not tag:\n for element in self.children:\n if element.namespace == namespace:\n results.append(element)\n else:\n for element in self.children:\n results.append(element)", " return results", " def loadd(self, ava):\n \"\"\" expects a special set of keys \"\"\"", " if \"attributes\" in ava:\n for key, val in ava[\"attributes\"].items():\n self.attributes[key] = val", " try:\n self.tag = ava[\"tag\"]\n except KeyError:\n if not self.tag:\n raise KeyError(\"ExtensionElement must have a tag\")", " try:\n self.namespace = ava[\"namespace\"]\n except KeyError:\n if not self.namespace:\n raise KeyError(\"ExtensionElement must belong to a namespace\")", " try:\n self.text = ava[\"text\"]\n except KeyError:\n pass", " if \"children\" in ava:\n for item in ava[\"children\"]:\n self.children.append(ExtensionElement(item[\"tag\"]).loadd(item))", " return self", "\ndef extension_element_from_string(xml_string):", " element_tree = defusedxml.ElementTree.fromstring(xml_string)", " return _extension_element_from_element_tree(element_tree)", "\ndef _extension_element_from_element_tree(element_tree):\n elementc_tag = element_tree.tag\n if '}' in elementc_tag:\n namespace = elementc_tag[1:elementc_tag.index('}')]\n tag = elementc_tag[elementc_tag.index('}') + 1:]\n else:\n namespace = None\n tag = elementc_tag\n extension = ExtensionElement(namespace=namespace, tag=tag)\n for key, value in iter(element_tree.attrib.items()):\n extension.attributes[key] = value\n for child in element_tree:\n extension.children.append(_extension_element_from_element_tree(child))\n extension.text = element_tree.text\n return extension", "\nclass ExtensionContainer(object):\n c_tag = \"\"\n c_namespace = \"\"", " def __init__(self, text=None, extension_elements=None,\n extension_attributes=None):", " self.text = text\n self.extension_elements = extension_elements or []\n self.extension_attributes = extension_attributes or {}\n self.encrypted_assertion = None", " # Three methods to create an object from an ElementTree\n def harvest_element_tree(self, tree):\n # Fill in the instance members from the contents of the XML tree.\n for child in tree:\n self._convert_element_tree_to_member(child)\n for attribute, value in iter(tree.attrib.items()):\n self._convert_element_attribute_to_member(attribute, value)\n self.text = tree.text", " def _convert_element_tree_to_member(self, child_tree):\n self.extension_elements.append(_extension_element_from_element_tree(\n child_tree))", " def _convert_element_attribute_to_member(self, attribute, value):\n self.extension_attributes[attribute] = value", " # One method to create an ElementTree from an object\n def _add_members_to_element_tree(self, tree):\n for child in self.extension_elements:\n child.become_child_element_of(tree)\n for attribute, value in iter(self.extension_attributes.items()):\n tree.attrib[attribute] = value\n tree.text = self.text", " def find_extensions(self, tag=None, namespace=None):\n \"\"\"Searches extension elements for child nodes with the desired name.", " Returns a list of extension elements within this object whose tag\n and/or namespace match those passed in. To find all extensions in\n a particular namespace, specify the namespace but not the tag name.\n If you specify only the tag, the result list may contain extension\n elements in multiple namespaces.", " :param tag: str (optional) The desired tag\n :param namespace: str (optional) The desired namespace", " :Return: A list of elements whose tag and/or namespace match the\n parameters values\n \"\"\"", " results = []", " if tag and namespace:\n for element in self.extension_elements:\n if element.tag == tag and element.namespace == namespace:\n results.append(element)\n elif tag and not namespace:\n for element in self.extension_elements:\n if element.tag == tag:\n results.append(element)\n elif namespace and not tag:\n for element in self.extension_elements:\n if element.namespace == namespace:\n results.append(element)\n else:\n for element in self.extension_elements:\n results.append(element)", " return results", " def extensions_as_elements(self, tag, schema):\n \"\"\" Return extensions that has the given tag and belongs to the\n given schema as native elements of that schema.", " :param tag: The tag of the element\n :param schema: Which schema the element should originate from\n :return: a list of native elements\n \"\"\"\n result = []\n for ext in self.find_extensions(tag, schema.NAMESPACE):\n ets = schema.ELEMENT_FROM_STRING[tag]\n result.append(ets(ext.to_string()))\n return result", " def add_extension_elements(self, items):\n for item in items:\n self.extension_elements.append(element_to_extension_element(item))", " def add_extension_element(self, item):\n self.extension_elements.append(element_to_extension_element(item))", " def add_extension_attribute(self, name, value):\n self.extension_attributes[name] = value", "\ndef make_vals(val, klass, klass_inst=None, prop=None, part=False,\n base64encode=False):\n \"\"\"\n Creates a class instance with a specified value, the specified\n class instance may be a value on a property in a defined class instance.", " :param val: The value\n :param klass: The value class\n :param klass_inst: The class instance which has a property on which\n what this function returns is a value.\n :param prop: The property which the value should be assigned to.\n :param part: If the value is one of a possible list of values it should be\n handled slightly different compared to if it isn't.\n :return: Value class instance\n \"\"\"\n cinst = None", " # print(\"make_vals(%s, %s)\" % (val, klass))", " if isinstance(val, dict):\n cinst = klass().loadd(val, base64encode=base64encode)\n else:\n try:\n cinst = klass().set_text(val)\n except ValueError:\n if not part:\n cis = [make_vals(sval, klass, klass_inst, prop, True,\n base64encode) for sval in val]\n setattr(klass_inst, prop, cis)\n else:\n raise", " if part:\n return cinst\n else:\n if cinst:\n cis = [cinst]\n setattr(klass_inst, prop, cis)", "\ndef make_instance(klass, spec, base64encode=False):\n \"\"\"\n Constructs a class instance containing the specified information", " :param klass: The class\n :param spec: Information to be placed in the instance (a dictionary)\n :return: The instance\n \"\"\"", " return klass().loadd(spec, base64encode)", "\nclass SamlBase(ExtensionContainer):\n \"\"\"A foundation class on which SAML classes are built. It\n handles the parsing of attributes and children which are common to all\n SAML classes. By default, the SamlBase class translates all XML child\n nodes into ExtensionElements.\n \"\"\"", " c_children = {}\n c_attributes = {}\n c_attribute_type = {}\n c_child_order = []\n c_cardinality = {}\n c_any = None\n c_any_attribute = None\n c_value_type = None\n c_ns_prefix = None", " def _get_all_c_children_with_order(self):\n if len(self.c_child_order) > 0:\n for child in self.c_child_order:\n yield child\n else:\n for _, values in iter(self.__class__.c_children.items()):\n yield values[0]", " def _convert_element_tree_to_member(self, child_tree):\n # Find the element's tag in this class's list of child members\n if child_tree.tag in self.__class__.c_children:\n member_name = self.__class__.c_children[child_tree.tag][0]\n member_class = self.__class__.c_children[child_tree.tag][1]\n # If the class member is supposed to contain a list, make sure the\n # matching member is set to a list, then append the new member\n # instance to the list.\n if isinstance(member_class, list):\n if getattr(self, member_name) is None:\n setattr(self, member_name, [])\n getattr(self, member_name).append(\n create_class_from_element_tree(member_class[0], child_tree))\n else:\n setattr(self, member_name,\n create_class_from_element_tree(member_class,\n child_tree))\n else:\n ExtensionContainer._convert_element_tree_to_member(self, child_tree)", " def _convert_element_attribute_to_member(self, attribute, value):\n # Find the attribute in this class's list of attributes.\n if attribute in self.__class__.c_attributes:\n # Find the member of this class which corresponds to the XML\n # attribute(lookup in current_class.c_attributes) and set this\n # member to the desired value (using self.__dict__).\n setattr(self, self.__class__.c_attributes[attribute][0], value)\n else:\n # If it doesn't appear in the attribute list it's an extension\n ExtensionContainer._convert_element_attribute_to_member(\n self, attribute, value)", " # Three methods to create an ElementTree from an object\n def _add_members_to_element_tree(self, tree):\n # Convert the members of this class which are XML child nodes.\n # This uses the class's c_children dictionary to find the members which\n # should become XML child nodes.\n for member_name in self._get_all_c_children_with_order():\n member = getattr(self, member_name)\n if member is None:\n pass\n elif isinstance(member, list):\n for instance in member:\n instance.become_child_element_of(tree)\n else:\n member.become_child_element_of(tree)\n # Convert the members of this class which are XML attributes.\n for xml_attribute, attribute_info in \\\n iter(self.__class__.c_attributes.items()):\n (member_name, member_type, required) = attribute_info\n member = getattr(self, member_name)\n if member is not None:\n tree.attrib[xml_attribute] = member", " # Lastly, call the ExtensionContainers's _add_members_to_element_tree\n # to convert any extension attributes.\n ExtensionContainer._add_members_to_element_tree(self, tree)", " def become_child_element_of(self, node):\n \"\"\"\n Note: Only for use with classes that have a c_tag and c_namespace class\n member. It is in SamlBase so that it can be inherited but it should\n not be called on instances of SamlBase.", " :param node: The node to which this instance should be a child\n \"\"\"\n new_child = self._to_element_tree()\n node.append(new_child)", " def _to_element_tree(self):\n \"\"\"", " Note, this method is designed to be used only with classes that have a\n c_tag and c_namespace. It is placed in SamlBase for inheritance but\n should not be called on in this class.", " \"\"\"\n new_tree = ElementTree.Element('{%s}%s' % (self.__class__.c_namespace,\n self.__class__.c_tag))\n self._add_members_to_element_tree(new_tree)\n return new_tree", " def register_prefix(self, nspair):\n \"\"\"\n Register with ElementTree a set of namespaces", " :param nspair: A dictionary of prefixes and uris to use when\n constructing the text representation.\n :return:\n \"\"\"\n for prefix, uri in nspair.items():\n try:\n ElementTree.register_namespace(prefix, uri)\n except AttributeError:\n # Backwards compatibility with ET < 1.3\n ElementTree._namespace_map[uri] = prefix\n except ValueError:\n pass", " def get_ns_map_attribute(self, attributes, uri_set):\n for attribute in attributes:\n if attribute[0] == \"{\":\n uri, tag = attribute[1:].split(\"}\")\n uri_set.add(uri)\n return uri_set", " def tag_get_uri(self, elem):\n if elem.tag[0] == \"{\":\n uri, tag = elem.tag[1:].split(\"}\")\n return uri\n return None", " def get_ns_map(self, elements, uri_set):", " for elem in elements:\n uri_set = self.get_ns_map_attribute(elem.attrib, uri_set)\n uri_set = self.get_ns_map(elem.getchildren(), uri_set)\n uri = self.tag_get_uri(elem)\n if uri is not None:\n uri_set.add(uri)\n return uri_set", " def get_prefix_map(self, elements):\n uri_set = self.get_ns_map(elements, set())\n prefix_map = {}\n for uri in sorted(uri_set):\n prefix_map[\"encas%d\" % len(prefix_map)] = uri\n return prefix_map", " def get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n self, assertion_tag, advice_tag):\n for tmp_encrypted_assertion in \\\n self.assertion.advice.encrypted_assertion:\n if tmp_encrypted_assertion.encrypted_data is None:\n prefix_map = self.get_prefix_map([\n tmp_encrypted_assertion._to_element_tree().find(\n assertion_tag)])\n tree = self._to_element_tree()\n encs = tree.find(assertion_tag).find(advice_tag).findall(\n tmp_encrypted_assertion._to_element_tree().tag)\n for enc in encs:\n assertion = enc.find(assertion_tag)\n if assertion is not None:\n self.set_prefixes(assertion, prefix_map)", " return ElementTree.tostring(tree, encoding=\"UTF-8\").decode('utf-8')", " def get_xml_string_with_self_contained_assertion_within_encrypted_assertion(\n self, assertion_tag):\n \"\"\" Makes a encrypted assertion only containing self contained\n namespaces.", " :param assertion_tag: Tag for the assertion to be transformed.\n :return: A new samlp.Resonse in string representation.\n \"\"\"\n prefix_map = self.get_prefix_map(\n [self.encrypted_assertion._to_element_tree().find(assertion_tag)])", " tree = self._to_element_tree()", " self.set_prefixes(\n tree.find(\n self.encrypted_assertion._to_element_tree().tag).find(\n assertion_tag), prefix_map)", " return ElementTree.tostring(tree, encoding=\"UTF-8\").decode('utf-8')", " def set_prefixes(self, elem, prefix_map):", " # check if this is a tree wrapper\n if not ElementTree.iselement(elem):\n elem = elem.getroot()", " # build uri map and add to root element\n uri_map = {}\n for prefix, uri in prefix_map.items():\n uri_map[uri] = prefix\n elem.set(\"xmlns:\" + prefix, uri)", " # fixup all elements in the tree\n memo = {}\n for elem in elem.getiterator():\n self.fixup_element_prefixes(elem, uri_map, memo)", " def fixup_element_prefixes(self, elem, uri_map, memo):\n def fixup(name):\n try:\n return memo[name]\n except KeyError:\n if name[0] != \"{\":\n return\n uri, tag = name[1:].split(\"}\")\n if uri in uri_map:\n new_name = uri_map[uri] + \":\" + tag\n memo[name] = new_name\n return new_name", " # fix element name\n name = fixup(elem.tag)\n if name:\n elem.tag = name\n # fix attribute names\n for key, value in elem.items():\n name = fixup(key)\n if name:\n elem.set(name, value)\n del elem.attrib[key]", " def to_string_force_namespace(self, nspair):", " elem = self._to_element_tree()", " self.set_prefixes(elem, nspair)", " return ElementTree.tostring(elem, encoding=\"UTF-8\")", " def to_string(self, nspair=None):\n \"\"\"Converts the Saml object to a string containing XML.", " :param nspair: A dictionary of prefixes and uris to use when\n constructing the text representation.\n :return: String representation of the object\n \"\"\"\n if not nspair and self.c_ns_prefix:\n nspair = self.c_ns_prefix", " if nspair:\n self.register_prefix(nspair)", " return ElementTree.tostring(self._to_element_tree(), encoding=\"UTF-8\")", " def __str__(self):\n # Yes this is confusing. http://bugs.python.org/issue10942\n x = self.to_string()\n if not isinstance(x, six.string_types):\n x = x.decode('utf-8')\n return x", " def keyswv(self):\n \"\"\" Return the keys of attributes or children that has values", " :return: list of keys\n \"\"\"\n return [key for key, val in self.__dict__.items() if val]", " def keys(self):\n \"\"\" Return all the keys that represent possible attributes and\n children.", " :return: list of keys\n \"\"\"\n keys = ['text']\n keys.extend([n for (n, t, r) in self.c_attributes.values()])\n keys.extend([v[0] for v in self.c_children.values()])\n return keys", " def children_with_values(self):\n \"\"\" Returns all children that has values", " :return: Possibly empty list of children.\n \"\"\"\n childs = []\n for attribute in self._get_all_c_children_with_order():\n member = getattr(self, attribute)\n if member is None or member == []:\n pass\n elif isinstance(member, list):\n for instance in member:\n childs.append(instance)\n else:\n childs.append(member)\n return childs", " # noinspection PyUnusedLocal\n def set_text(self, val, base64encode=False):\n \"\"\" Sets the text property of this instance.", " :param val: The value of the text property\n :param base64encode: Whether the value should be base64encoded\n :return: The instance\n \"\"\"", " # print(\"set_text: %s\" % (val,))\n if isinstance(val, bool):\n if val:\n setattr(self, \"text\", \"true\")\n else:\n setattr(self, \"text\", \"false\")\n elif isinstance(val, int):\n setattr(self, \"text\", \"%d\" % val)\n elif isinstance(val, six.string_types):\n setattr(self, \"text\", val)\n elif val is None:\n pass\n else:\n raise ValueError(\"Type shouldn't be '%s'\" % (val,))", " return self", " def loadd(self, ava, base64encode=False):\n \"\"\"\n Sets attributes, children, extension elements and extension\n attributes of this element instance depending on what is in\n the given dictionary. If there are already values on properties\n those will be overwritten. If the keys in the dictionary does\n not correspond to known attributes/children/.. they are ignored.", " :param ava: The dictionary\n :param base64encode: Whether the values on attributes or texts on\n children shoule be base64encoded.\n :return: The instance\n \"\"\"", " for prop, _typ, _req in self.c_attributes.values():\n # print(\"# %s\" % (prop))\n if prop in ava:\n if isinstance(ava[prop], bool):\n setattr(self, prop, \"%s\" % ava[prop])\n elif isinstance(ava[prop], int):\n setattr(self, prop, \"%d\" % ava[prop])\n else:\n setattr(self, prop, ava[prop])", " if \"text\" in ava:\n self.set_text(ava[\"text\"], base64encode)", " for prop, klassdef in self.c_children.values():\n # print(\"## %s, %s\" % (prop, klassdef))\n if prop in ava:\n # print(\"### %s\" % ava[prop])\n # means there can be a list of values\n if isinstance(klassdef, list):\n make_vals(ava[prop], klassdef[0], self, prop,\n base64encode=base64encode)\n else:\n cis = make_vals(ava[prop], klassdef, self, prop, True,\n base64encode)\n setattr(self, prop, cis)", " if \"extension_elements\" in ava:\n for item in ava[\"extension_elements\"]:\n self.extension_elements.append(ExtensionElement(\n item[\"tag\"]).loadd(item))", " if \"extension_attributes\" in ava:\n for key, val in ava[\"extension_attributes\"].items():\n self.extension_attributes[key] = val", " return self", " def clear_text(self):\n if self.text:\n _text = self.text.strip()\n if _text == \"\":\n self.text = None", " def __eq__(self, other):\n try:\n assert isinstance(other, SamlBase)\n except AssertionError:\n return False", " self.clear_text()\n other.clear_text()\n if len(self.keyswv()) != len(other.keyswv()):\n return False", " for key in self.keyswv():\n if key in [\"_extatt\"]:\n continue\n svals = self.__dict__[key]\n ovals = other.__dict__[key]\n if isinstance(svals, six.string_types):\n if svals != ovals:\n return False\n elif isinstance(svals, list):\n for sval in svals:\n try:\n for oval in ovals:\n if sval == oval:\n break\n else:\n return False\n except TypeError:\n # ovals isn't iterable\n return False\n else:\n if svals == ovals: # Since I only support '=='\n pass\n else:\n return False\n return True", " def child_class(self, child):\n \"\"\" Return the class a child element should be an instance of", " :param child: The name of the child element\n :return: The class\n \"\"\"\n for prop, klassdef in self.c_children.values():\n if child == prop:\n if isinstance(klassdef, list):\n return klassdef[0]\n else:\n return klassdef\n return None", " def child_cardinality(self, child):\n \"\"\" Return the cardinality of a child element", " :param child: The name of the child element\n :return: The cardinality as a 2-tuple (min, max).\n The max value is either a number or the string \"unbounded\".\n The min value is always a number.\n \"\"\"\n for prop, klassdef in self.c_children.values():\n if child == prop:\n if isinstance(klassdef, list):\n try:\n _min = self.c_cardinality[\"min\"]\n except KeyError:\n _min = 1\n try:\n _max = self.c_cardinality[\"max\"]\n except KeyError:\n _max = \"unbounded\"", " return _min, _max\n else:\n return 1, 1\n return None", " def verify(self):\n return valid_instance(self)", " def empty(self):\n for prop, _typ, _req in self.c_attributes.values():\n if getattr(self, prop, None):\n return False", " for prop, klassdef in self.c_children.values():\n if getattr(self, prop):\n return False", " for param in [\"text\", \"extension_elements\", \"extension_attributes\"]:\n if getattr(self, param):\n return False", " return True", "\n# ----------------------------------------------------------------------------", "\ndef element_to_extension_element(element):\n \"\"\"\n Convert an element into a extension element", " :param element: The element instance\n :return: An extension element instance\n \"\"\"", " exel = ExtensionElement(element.c_tag, element.c_namespace,\n text=element.text)", " exel.attributes.update(element.extension_attributes)\n exel.children.extend(element.extension_elements)", " for xml_attribute, (member_name, typ, req) in \\\n iter(element.c_attributes.items()):\n member_value = getattr(element, member_name)\n if member_value is not None:\n exel.attributes[xml_attribute] = member_value", " exel.children.extend([element_to_extension_element(c) for c in\n element.children_with_values()])", " return exel", "\ndef extension_element_to_element(extension_element, translation_functions,\n namespace=None):\n \"\"\" Convert an extension element to a normal element.\n In order to do this you need to have an idea of what type of\n element it is. Or rather which module it belongs to.", " :param extension_element: The extension element\n :param translation_functions: A dictionary with class identifiers\n as keys and string-to-element translations functions as values\n :param namespace: The namespace of the translation functions.\n :return: An element instance or None\n \"\"\"", " try:\n element_namespace = extension_element.namespace\n except AttributeError:\n element_namespace = extension_element.c_namespace\n if element_namespace == namespace:\n try:\n try:\n ets = translation_functions[extension_element.tag]\n except AttributeError:\n ets = translation_functions[extension_element.c_tag]\n return ets(extension_element.to_string())\n except KeyError:\n pass", " return None", "\ndef extension_elements_to_elements(extension_elements, schemas):\n \"\"\" Create a list of elements each one matching one of the\n given extension elements. This is of course dependent on the access\n to schemas that describe the extension elements.", " :param extension_elements: The list of extension elements\n :param schemas: Imported Python modules that represent the different\n known schemas used for the extension elements\n :return: A list of elements, representing the set of extension elements\n that was possible to match against a Class in the given schemas.\n The elements returned are the native representation of the elements\n according to the schemas.\n \"\"\"\n res = []", " if isinstance(schemas, list):\n pass\n elif isinstance(schemas, dict):\n schemas = list(schemas.values())\n else:\n return res", " for extension_element in extension_elements:\n for schema in schemas:\n inst = extension_element_to_element(extension_element,\n schema.ELEMENT_FROM_STRING,\n schema.NAMESPACE)\n if inst:\n res.append(inst)\n break", " return res", "\ndef extension_elements_as_dict(extension_elements, onts):\n ees_ = extension_elements_to_elements(extension_elements, onts)\n res = {}\n for elem in ees_:\n try:\n res[elem.c_tag].append(elem)\n except KeyError:\n res[elem.c_tag] = [elem]\n return res" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#", "\"\"\"Contains classes and functions that are necessary to implement\ndifferent bindings.", "Bindings normally consists of three parts:\n- rules about what to send\n- how to package the information\n- which protocol to use\n\"\"\"\nfrom six.moves.urllib.parse import urlparse, urlencode\nimport saml2\nimport base64\nfrom saml2.s_utils import deflate_and_base64_encode\nfrom saml2.s_utils import Unsupported\nimport logging\nfrom saml2.sigver import REQ_ORDER\nfrom saml2.sigver import RESP_ORDER\nfrom saml2.sigver import SIGNER_ALGS\nimport six\nfrom saml2.xmldsig import SIG_ALLOWED_ALG", "logger = logging.getLogger(__name__)", "try:\n from xml.etree import cElementTree as ElementTree", " if ElementTree.VERSION < '1.3.0':\n # cElementTree has no support for register_namespace\n # neither _namespace_map, thus we sacrify performance\n # for correctness\n from xml.etree import ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "", "\nNAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\"\nFORM_SPEC = \"\"\"<form method=\"post\" action=\"%s\">\n <input type=\"hidden\" name=\"%s\" value=\"%s\" />\n <input type=\"hidden\" name=\"RelayState\" value=\"%s\" />\n <input type=\"submit\" value=\"Submit\" />\n</form>\"\"\"", "\ndef http_form_post_message(message, location, relay_state=\"\",\n typ=\"SAMLRequest\", **kwargs):\n \"\"\"The HTTP POST binding defines a mechanism by which SAML protocol\n messages may be transmitted within the base64-encoded content of a\n HTML form control.", " :param message: The message\n :param location: Where the form should be posted to\n :param relay_state: for preserving and conveying state information\n :return: A tuple containing header information and a HTML message.\n \"\"\"\n response = [\"<head>\", \"\"\"<title>SAML 2.0 POST</title>\"\"\", \"</head><body>\"]", " if not isinstance(message, six.string_types):\n message = str(message)\n if not isinstance(message, six.binary_type):\n message = message.encode('utf-8')", " if typ == \"SAMLRequest\" or typ == \"SAMLResponse\":\n _msg = base64.b64encode(message)\n else:\n _msg = message\n _msg = _msg.decode('ascii')", " response.append(FORM_SPEC % (location, typ, _msg, relay_state))", " response.append(\"\"\"<script type=\"text/javascript\">\"\"\")\n response.append(\" window.onload = function ()\")\n response.append(\" { document.forms[0].submit(); }\")\n response.append(\"\"\"</script>\"\"\")\n response.append(\"</body>\")", " return {\"headers\": [(\"Content-type\", \"text/html\")], \"data\": response}", "\ndef http_post_message(message, relay_state=\"\", typ=\"SAMLRequest\", **kwargs):\n \"\"\"", " :param message: The message\n :param relay_state: for preserving and conveying state information\n :return: A tuple containing header information and a HTML message.\n \"\"\"\n if not isinstance(message, six.string_types):\n message = str(message)\n if not isinstance(message, six.binary_type):\n message = message.encode('utf-8')", " if typ == \"SAMLRequest\" or typ == \"SAMLResponse\":\n _msg = base64.b64encode(message)\n else:\n _msg = message\n _msg = _msg.decode('ascii')", " part = {typ: _msg}\n if relay_state:\n part[\"RelayState\"] = relay_state", " return {\"headers\": [(\"Content-type\", 'application/x-www-form-urlencoded')],\n \"data\": urlencode(part)}", "\ndef http_redirect_message(message, location, relay_state=\"\", typ=\"SAMLRequest\",\n sigalg='', signer=None, **kwargs):\n \"\"\"The HTTP Redirect binding defines a mechanism by which SAML protocol\n messages can be transmitted within URL parameters.\n Messages are encoded for use with this binding using a URL encoding\n technique, and transmitted using the HTTP GET method.", " The DEFLATE Encoding is used in this function.", " :param message: The message\n :param location: Where the message should be posted to\n :param relay_state: for preserving and conveying state information\n :param typ: What type of message it is SAMLRequest/SAMLResponse/SAMLart\n :param sigalg: Which algorithm the signature function will use to sign\n the message\n :param signer: A signature function that can be used to sign the message\n :return: A tuple containing header information and a HTML message.\n \"\"\"", " if not isinstance(message, six.string_types):\n message = \"%s\" % (message,)", " _order = None\n if typ in [\"SAMLRequest\", \"SAMLResponse\"]:\n if typ == \"SAMLRequest\":\n _order = REQ_ORDER\n else:\n _order = RESP_ORDER\n args = {typ: deflate_and_base64_encode(message)}\n elif typ == \"SAMLart\":\n args = {typ: message}\n else:\n raise Exception(\"Unknown message type: %s\" % typ)", " if relay_state:\n args[\"RelayState\"] = relay_state", " if signer:\n # sigalgs, should be one defined in xmldsig\n assert sigalg in [b for a, b in SIG_ALLOWED_ALG]\n args[\"SigAlg\"] = sigalg", " string = \"&\".join([urlencode({k: args[k]})\n for k in _order if k in args]).encode('ascii')\n args[\"Signature\"] = base64.b64encode(signer.sign(string))\n string = urlencode(args)\n else:\n string = urlencode(args)", " glue_char = \"&\" if urlparse(location).query else \"?\"\n login_url = glue_char.join([location, string])\n headers = [('Location', str(login_url))]\n body = []", " return {\"headers\": headers, \"data\": body}", "\nDUMMY_NAMESPACE = \"http://example.org/\"\nPREFIX = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", "\ndef make_soap_enveloped_saml_thingy(thingy, header_parts=None):\n \"\"\" Returns a soap envelope containing a SAML request\n as a text string.", " :param thingy: The SAML thingy\n :return: The SOAP envelope as a string\n \"\"\"\n envelope = ElementTree.Element('')\n envelope.tag = '{%s}Envelope' % NAMESPACE", " if header_parts:\n header = ElementTree.Element('')\n header.tag = '{%s}Header' % NAMESPACE\n envelope.append(header)\n for part in header_parts:\n # This doesn't work if the headers are signed\n part.become_child_element_of(header)", " body = ElementTree.Element('')\n body.tag = '{%s}Body' % NAMESPACE\n envelope.append(body)", " if isinstance(thingy, six.string_types):\n # remove the first XML version/encoding line\n if thingy[0:5].lower() == '<?xml':\n logger.debug(\"thingy0: %s\", thingy)\n _part = thingy.split(\"\\n\")\n thingy = \"\".join(_part[1:])\n thingy = thingy.replace(PREFIX, \"\")\n logger.debug(\"thingy: %s\", thingy)\n _child = ElementTree.Element('')\n _child.tag = '{%s}FuddleMuddle' % DUMMY_NAMESPACE\n body.append(_child)\n _str = ElementTree.tostring(envelope, encoding=\"UTF-8\")\n if isinstance(_str, six.binary_type):\n _str = _str.decode('utf-8')\n logger.debug(\"SOAP precursor: %s\", _str)\n # find an remove the namespace definition\n i = _str.find(DUMMY_NAMESPACE)\n j = _str.rfind(\"xmlns:\", 0, i)\n cut1 = _str[j:i + len(DUMMY_NAMESPACE) + 1]\n _str = _str.replace(cut1, \"\")\n first = _str.find(\"<%s:FuddleMuddle\" % (cut1[6:9],))\n last = _str.find(\">\", first + 14)\n cut2 = _str[first:last + 1]\n return _str.replace(cut2, thingy)\n else:\n thingy.become_child_element_of(body)\n return ElementTree.tostring(envelope, encoding=\"UTF-8\")", "\ndef http_soap_message(message):\n return {\"headers\": [(\"Content-type\", \"application/soap+xml\")],\n \"data\": make_soap_enveloped_saml_thingy(message)}", "\ndef http_paos(message, extra=None):\n return {\"headers\": [(\"Content-type\", \"application/soap+xml\")],\n \"data\": make_soap_enveloped_saml_thingy(message, extra)}", "\ndef parse_soap_enveloped_saml(text, body_class, header_class=None):\n \"\"\"Parses a SOAP enveloped SAML thing and returns header parts and body", " :param text: The SOAP object as XML\n :return: header parts and body as saml.samlbase instances\n \"\"\"", " envelope = ElementTree.fromstring(text)", " assert envelope.tag == '{%s}Envelope' % NAMESPACE", " # print(len(envelope))\n body = None\n header = {}\n for part in envelope:\n # print(\">\",part.tag)\n if part.tag == '{%s}Body' % NAMESPACE:\n for sub in part:\n try:\n body = saml2.create_class_from_element_tree(body_class, sub)\n except Exception:\n raise Exception(\n \"Wrong body type (%s) in SOAP envelope\" % sub.tag)\n elif part.tag == '{%s}Header' % NAMESPACE:\n if not header_class:\n raise Exception(\"Header where I didn't expect one\")\n # print(\"--- HEADER ---\")\n for sub in part:\n # print(\">>\",sub.tag)\n for klass in header_class:\n # print(\"?{%s}%s\" % (klass.c_namespace,klass.c_tag))\n if sub.tag == \"{%s}%s\" % (klass.c_namespace, klass.c_tag):\n header[sub.tag] = \\\n saml2.create_class_from_element_tree(klass, sub)\n break", " return body, header", "\n# -----------------------------------------------------------------------------", "PACKING = {\n saml2.BINDING_HTTP_REDIRECT: http_redirect_message,\n saml2.BINDING_HTTP_POST: http_form_post_message,\n}", "\ndef packager(identifier):\n try:\n return PACKING[identifier]\n except KeyError:\n raise Exception(\"Unknown binding type: %s\" % identifier)", "\ndef factory(binding, message, location, relay_state=\"\", typ=\"SAMLRequest\",\n **kwargs):\n return PACKING[binding](message, location, relay_state, typ, **kwargs)" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#", "\"\"\"Contains classes and functions that are necessary to implement\ndifferent bindings.", "Bindings normally consists of three parts:\n- rules about what to send\n- how to package the information\n- which protocol to use\n\"\"\"\nfrom six.moves.urllib.parse import urlparse, urlencode\nimport saml2\nimport base64\nfrom saml2.s_utils import deflate_and_base64_encode\nfrom saml2.s_utils import Unsupported\nimport logging\nfrom saml2.sigver import REQ_ORDER\nfrom saml2.sigver import RESP_ORDER\nfrom saml2.sigver import SIGNER_ALGS\nimport six\nfrom saml2.xmldsig import SIG_ALLOWED_ALG", "logger = logging.getLogger(__name__)", "try:\n from xml.etree import cElementTree as ElementTree", " if ElementTree.VERSION < '1.3.0':\n # cElementTree has no support for register_namespace\n # neither _namespace_map, thus we sacrify performance\n # for correctness\n from xml.etree import ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "import defusedxml.ElementTree", "\nNAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\"\nFORM_SPEC = \"\"\"<form method=\"post\" action=\"%s\">\n <input type=\"hidden\" name=\"%s\" value=\"%s\" />\n <input type=\"hidden\" name=\"RelayState\" value=\"%s\" />\n <input type=\"submit\" value=\"Submit\" />\n</form>\"\"\"", "\ndef http_form_post_message(message, location, relay_state=\"\",\n typ=\"SAMLRequest\", **kwargs):\n \"\"\"The HTTP POST binding defines a mechanism by which SAML protocol\n messages may be transmitted within the base64-encoded content of a\n HTML form control.", " :param message: The message\n :param location: Where the form should be posted to\n :param relay_state: for preserving and conveying state information\n :return: A tuple containing header information and a HTML message.\n \"\"\"\n response = [\"<head>\", \"\"\"<title>SAML 2.0 POST</title>\"\"\", \"</head><body>\"]", " if not isinstance(message, six.string_types):\n message = str(message)\n if not isinstance(message, six.binary_type):\n message = message.encode('utf-8')", " if typ == \"SAMLRequest\" or typ == \"SAMLResponse\":\n _msg = base64.b64encode(message)\n else:\n _msg = message\n _msg = _msg.decode('ascii')", " response.append(FORM_SPEC % (location, typ, _msg, relay_state))", " response.append(\"\"\"<script type=\"text/javascript\">\"\"\")\n response.append(\" window.onload = function ()\")\n response.append(\" { document.forms[0].submit(); }\")\n response.append(\"\"\"</script>\"\"\")\n response.append(\"</body>\")", " return {\"headers\": [(\"Content-type\", \"text/html\")], \"data\": response}", "\ndef http_post_message(message, relay_state=\"\", typ=\"SAMLRequest\", **kwargs):\n \"\"\"", " :param message: The message\n :param relay_state: for preserving and conveying state information\n :return: A tuple containing header information and a HTML message.\n \"\"\"\n if not isinstance(message, six.string_types):\n message = str(message)\n if not isinstance(message, six.binary_type):\n message = message.encode('utf-8')", " if typ == \"SAMLRequest\" or typ == \"SAMLResponse\":\n _msg = base64.b64encode(message)\n else:\n _msg = message\n _msg = _msg.decode('ascii')", " part = {typ: _msg}\n if relay_state:\n part[\"RelayState\"] = relay_state", " return {\"headers\": [(\"Content-type\", 'application/x-www-form-urlencoded')],\n \"data\": urlencode(part)}", "\ndef http_redirect_message(message, location, relay_state=\"\", typ=\"SAMLRequest\",\n sigalg='', signer=None, **kwargs):\n \"\"\"The HTTP Redirect binding defines a mechanism by which SAML protocol\n messages can be transmitted within URL parameters.\n Messages are encoded for use with this binding using a URL encoding\n technique, and transmitted using the HTTP GET method.", " The DEFLATE Encoding is used in this function.", " :param message: The message\n :param location: Where the message should be posted to\n :param relay_state: for preserving and conveying state information\n :param typ: What type of message it is SAMLRequest/SAMLResponse/SAMLart\n :param sigalg: Which algorithm the signature function will use to sign\n the message\n :param signer: A signature function that can be used to sign the message\n :return: A tuple containing header information and a HTML message.\n \"\"\"", " if not isinstance(message, six.string_types):\n message = \"%s\" % (message,)", " _order = None\n if typ in [\"SAMLRequest\", \"SAMLResponse\"]:\n if typ == \"SAMLRequest\":\n _order = REQ_ORDER\n else:\n _order = RESP_ORDER\n args = {typ: deflate_and_base64_encode(message)}\n elif typ == \"SAMLart\":\n args = {typ: message}\n else:\n raise Exception(\"Unknown message type: %s\" % typ)", " if relay_state:\n args[\"RelayState\"] = relay_state", " if signer:\n # sigalgs, should be one defined in xmldsig\n assert sigalg in [b for a, b in SIG_ALLOWED_ALG]\n args[\"SigAlg\"] = sigalg", " string = \"&\".join([urlencode({k: args[k]})\n for k in _order if k in args]).encode('ascii')\n args[\"Signature\"] = base64.b64encode(signer.sign(string))\n string = urlencode(args)\n else:\n string = urlencode(args)", " glue_char = \"&\" if urlparse(location).query else \"?\"\n login_url = glue_char.join([location, string])\n headers = [('Location', str(login_url))]\n body = []", " return {\"headers\": headers, \"data\": body}", "\nDUMMY_NAMESPACE = \"http://example.org/\"\nPREFIX = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", "\ndef make_soap_enveloped_saml_thingy(thingy, header_parts=None):\n \"\"\" Returns a soap envelope containing a SAML request\n as a text string.", " :param thingy: The SAML thingy\n :return: The SOAP envelope as a string\n \"\"\"\n envelope = ElementTree.Element('')\n envelope.tag = '{%s}Envelope' % NAMESPACE", " if header_parts:\n header = ElementTree.Element('')\n header.tag = '{%s}Header' % NAMESPACE\n envelope.append(header)\n for part in header_parts:\n # This doesn't work if the headers are signed\n part.become_child_element_of(header)", " body = ElementTree.Element('')\n body.tag = '{%s}Body' % NAMESPACE\n envelope.append(body)", " if isinstance(thingy, six.string_types):\n # remove the first XML version/encoding line\n if thingy[0:5].lower() == '<?xml':\n logger.debug(\"thingy0: %s\", thingy)\n _part = thingy.split(\"\\n\")\n thingy = \"\".join(_part[1:])\n thingy = thingy.replace(PREFIX, \"\")\n logger.debug(\"thingy: %s\", thingy)\n _child = ElementTree.Element('')\n _child.tag = '{%s}FuddleMuddle' % DUMMY_NAMESPACE\n body.append(_child)\n _str = ElementTree.tostring(envelope, encoding=\"UTF-8\")\n if isinstance(_str, six.binary_type):\n _str = _str.decode('utf-8')\n logger.debug(\"SOAP precursor: %s\", _str)\n # find an remove the namespace definition\n i = _str.find(DUMMY_NAMESPACE)\n j = _str.rfind(\"xmlns:\", 0, i)\n cut1 = _str[j:i + len(DUMMY_NAMESPACE) + 1]\n _str = _str.replace(cut1, \"\")\n first = _str.find(\"<%s:FuddleMuddle\" % (cut1[6:9],))\n last = _str.find(\">\", first + 14)\n cut2 = _str[first:last + 1]\n return _str.replace(cut2, thingy)\n else:\n thingy.become_child_element_of(body)\n return ElementTree.tostring(envelope, encoding=\"UTF-8\")", "\ndef http_soap_message(message):\n return {\"headers\": [(\"Content-type\", \"application/soap+xml\")],\n \"data\": make_soap_enveloped_saml_thingy(message)}", "\ndef http_paos(message, extra=None):\n return {\"headers\": [(\"Content-type\", \"application/soap+xml\")],\n \"data\": make_soap_enveloped_saml_thingy(message, extra)}", "\ndef parse_soap_enveloped_saml(text, body_class, header_class=None):\n \"\"\"Parses a SOAP enveloped SAML thing and returns header parts and body", " :param text: The SOAP object as XML\n :return: header parts and body as saml.samlbase instances\n \"\"\"", " envelope = defusedxml.ElementTree.fromstring(text)", " assert envelope.tag == '{%s}Envelope' % NAMESPACE", " # print(len(envelope))\n body = None\n header = {}\n for part in envelope:\n # print(\">\",part.tag)\n if part.tag == '{%s}Body' % NAMESPACE:\n for sub in part:\n try:\n body = saml2.create_class_from_element_tree(body_class, sub)\n except Exception:\n raise Exception(\n \"Wrong body type (%s) in SOAP envelope\" % sub.tag)\n elif part.tag == '{%s}Header' % NAMESPACE:\n if not header_class:\n raise Exception(\"Header where I didn't expect one\")\n # print(\"--- HEADER ---\")\n for sub in part:\n # print(\">>\",sub.tag)\n for klass in header_class:\n # print(\"?{%s}%s\" % (klass.c_namespace,klass.c_tag))\n if sub.tag == \"{%s}%s\" % (klass.c_namespace, klass.c_tag):\n header[sub.tag] = \\\n saml2.create_class_from_element_tree(klass, sub)\n break", " return body, header", "\n# -----------------------------------------------------------------------------", "PACKING = {\n saml2.BINDING_HTTP_REDIRECT: http_redirect_message,\n saml2.BINDING_HTTP_POST: http_form_post_message,\n}", "\ndef packager(identifier):\n try:\n return PACKING[identifier]\n except KeyError:\n raise Exception(\"Unknown binding type: %s\" % identifier)", "\ndef factory(binding, message, location, relay_state=\"\", typ=\"SAMLRequest\",\n **kwargs):\n return PACKING[binding](message, location, relay_state, typ, **kwargs)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#", "\"\"\"\nSuppport for the client part of the SAML2.0 SOAP binding.\n\"\"\"\nimport logging", "from saml2 import create_class_from_element_tree\nfrom saml2.samlp import NAMESPACE as SAMLP_NAMESPACE\nfrom saml2.schema import soapenv", "try:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n #noinspection PyUnresolvedReferences\n from elementtree import ElementTree", "", "", "logger = logging.getLogger(__name__)", "\nclass XmlParseError(Exception):\n pass", "\nclass WrongMessageType(Exception):\n pass", "\ndef parse_soap_enveloped_saml_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}LogoutResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_logout_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}LogoutResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_attribute_query(text):\n expected_tag = '{%s}AttributeQuery' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_attribute_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}AttributeResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_logout_request(text):\n expected_tag = '{%s}LogoutRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_authn_request(text):\n expected_tag = '{%s}AuthnRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_artifact_resolve(text):\n expected_tag = '{%s}ArtifactResolve' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_artifact_response(text):\n expected_tag = '{%s}ArtifactResponse' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_name_id_mapping_request(text):\n expected_tag = '{%s}NameIDMappingRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_name_id_mapping_response(text):\n expected_tag = '{%s}NameIDMappingResponse' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_manage_name_id_request(text):\n expected_tag = '{%s}ManageNameIDRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_manage_name_id_response(text):\n expected_tag = '{%s}ManageNameIDResponse' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_assertion_id_request(text):\n expected_tag = '{%s}AssertionIDRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_assertion_id_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}AssertionIDResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_authn_query(text):\n expected_tag = '{%s}AuthnQuery' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_authn_query_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_authn_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\n#def parse_soap_enveloped_saml_logout_response(text):\n# expected_tag = '{%s}LogoutResponse' % SAMLP_NAMESPACE\n# return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "def parse_soap_enveloped_saml_thingy(text, expected_tags):\n \"\"\"Parses a SOAP enveloped SAML thing and returns the thing as\n a string.", " :param text: The SOAP object as XML string\n :param expected_tags: What the tag of the SAML thingy is expected to be.\n :return: SAML thingy as a string\n \"\"\"", " envelope = ElementTree.fromstring(text)", "\n # Make sure it's a SOAP message\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE", " assert len(envelope) >= 1\n body = None\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n body = part\n break", " if body is None:\n return \"\"", " saml_part = body[0]\n if saml_part.tag in expected_tags:\n return ElementTree.tostring(saml_part, encoding=\"UTF-8\")\n else:\n raise WrongMessageType(\"Was '%s' expected one of %s\" % (saml_part.tag,\n expected_tags))", "import re", "NS_AND_TAG = re.compile(\"\\{([^}]+)\\}(.*)\")", "\ndef instanciate_class(item, modules):\n m = NS_AND_TAG.match(item.tag)\n ns, tag = m.groups()\n for module in modules:\n if module.NAMESPACE == ns:\n try:\n target = module.ELEMENT_BY_TAG[tag]\n return create_class_from_element_tree(target, item)\n except KeyError:\n continue\n raise Exception(\"Unknown class: ns='%s', tag='%s'\" % (ns, tag))", "\ndef 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.", " :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:", " envelope = ElementTree.fromstring(text)", " except Exception as exc:\n raise XmlParseError(\"%s\" % exc)", " assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n env = {\"header\": [], \"body\": None}", " 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))", " return env", "\ndef open_soap_envelope(text):\n \"\"\"", " :param text: SOAP message\n :return: dictionary with two keys \"body\"/\"header\"\n \"\"\"\n try:", " envelope = ElementTree.fromstring(text)", " except Exception as exc:\n raise XmlParseError(\"%s\" % exc)", " assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n content = {\"header\": [], \"body\": None}", " for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n content[\"body\"] = ElementTree.tostring(part[0], encoding=\"UTF-8\")\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n _str = ElementTree.tostring(item, encoding=\"UTF-8\")\n content[\"header\"].append(_str)", " return content", "\ndef make_soap_enveloped_saml_thingy(thingy, headers=None):\n \"\"\" Returns a soap envelope containing a SAML request\n as a text string.", " :param thingy: The SAML thingy\n :return: The SOAP envelope as a string\n \"\"\"\n soap_envelope = soapenv.Envelope()", " if headers:\n _header = soapenv.Header()\n _header.add_extension_elements(headers)\n soap_envelope.header = _header", " soap_envelope.body = soapenv.Body()\n soap_envelope.body.add_extension_element(thingy)", " return \"%s\" % soap_envelope", "\ndef soap_fault(message=None, actor=None, code=None, detail=None):\n \"\"\" Create a SOAP Fault message", " :param message: Human readable error message\n :param actor: Who discovered the error\n :param code: Error code\n :param detail: More specific error message\n :return: A SOAP Fault message as a string\n \"\"\"\n _string = _actor = _code = _detail = None", " if message:\n _string = soapenv.Fault_faultstring(text=message)\n if actor:\n _actor = soapenv.Fault_faultactor(text=actor)\n if code:\n _code = soapenv.Fault_faultcode(text=code)\n if detail:\n _detail = soapenv.Fault_detail(text=detail)", " fault = soapenv.Fault(\n faultcode=_code,\n faultstring=_string,\n faultactor=_actor,\n detail=_detail,\n )", " return \"%s\" % fault" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#", "\"\"\"\nSuppport for the client part of the SAML2.0 SOAP binding.\n\"\"\"\nimport logging", "from saml2 import create_class_from_element_tree\nfrom saml2.samlp import NAMESPACE as SAMLP_NAMESPACE\nfrom saml2.schema import soapenv", "try:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n #noinspection PyUnresolvedReferences\n from elementtree import ElementTree", "import defusedxml.ElementTree", "", "logger = logging.getLogger(__name__)", "\nclass XmlParseError(Exception):\n pass", "\nclass WrongMessageType(Exception):\n pass", "\ndef parse_soap_enveloped_saml_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}LogoutResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_logout_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}LogoutResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_attribute_query(text):\n expected_tag = '{%s}AttributeQuery' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_attribute_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}AttributeResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_logout_request(text):\n expected_tag = '{%s}LogoutRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_authn_request(text):\n expected_tag = '{%s}AuthnRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_artifact_resolve(text):\n expected_tag = '{%s}ArtifactResolve' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_artifact_response(text):\n expected_tag = '{%s}ArtifactResponse' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_name_id_mapping_request(text):\n expected_tag = '{%s}NameIDMappingRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_name_id_mapping_response(text):\n expected_tag = '{%s}NameIDMappingResponse' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_manage_name_id_request(text):\n expected_tag = '{%s}ManageNameIDRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_manage_name_id_response(text):\n expected_tag = '{%s}ManageNameIDResponse' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_assertion_id_request(text):\n expected_tag = '{%s}AssertionIDRequest' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_assertion_id_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE,\n '{%s}AssertionIDResponse' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_authn_query(text):\n expected_tag = '{%s}AuthnQuery' % SAMLP_NAMESPACE\n return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "\ndef parse_soap_enveloped_saml_authn_query_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\ndef parse_soap_enveloped_saml_authn_response(text):\n tags = ['{%s}Response' % SAMLP_NAMESPACE]\n return parse_soap_enveloped_saml_thingy(text, tags)", "\n#def parse_soap_enveloped_saml_logout_response(text):\n# expected_tag = '{%s}LogoutResponse' % SAMLP_NAMESPACE\n# return parse_soap_enveloped_saml_thingy(text, [expected_tag])", "def parse_soap_enveloped_saml_thingy(text, expected_tags):\n \"\"\"Parses a SOAP enveloped SAML thing and returns the thing as\n a string.", " :param text: The SOAP object as XML string\n :param expected_tags: What the tag of the SAML thingy is expected to be.\n :return: SAML thingy as a string\n \"\"\"", " envelope = defusedxml.ElementTree.fromstring(text)", "\n # Make sure it's a SOAP message\n assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE", " assert len(envelope) >= 1\n body = None\n for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n body = part\n break", " if body is None:\n return \"\"", " saml_part = body[0]\n if saml_part.tag in expected_tags:\n return ElementTree.tostring(saml_part, encoding=\"UTF-8\")\n else:\n raise WrongMessageType(\"Was '%s' expected one of %s\" % (saml_part.tag,\n expected_tags))", "import re", "NS_AND_TAG = re.compile(\"\\{([^}]+)\\}(.*)\")", "\ndef instanciate_class(item, modules):\n m = NS_AND_TAG.match(item.tag)\n ns, tag = m.groups()\n for module in modules:\n if module.NAMESPACE == ns:\n try:\n target = module.ELEMENT_BY_TAG[tag]\n return create_class_from_element_tree(target, item)\n except KeyError:\n continue\n raise Exception(\"Unknown class: ns='%s', tag='%s'\" % (ns, tag))", "\ndef 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.", " :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:", " envelope = defusedxml.ElementTree.fromstring(text)", " except Exception as exc:\n raise XmlParseError(\"%s\" % exc)", " assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n env = {\"header\": [], \"body\": None}", " 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))", " return env", "\ndef open_soap_envelope(text):\n \"\"\"", " :param text: SOAP message\n :return: dictionary with two keys \"body\"/\"header\"\n \"\"\"\n try:", " envelope = defusedxml.ElementTree.fromstring(text)", " except Exception as exc:\n raise XmlParseError(\"%s\" % exc)", " assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n assert len(envelope) >= 1\n content = {\"header\": [], \"body\": None}", " for part in envelope:\n if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n assert len(part) == 1\n content[\"body\"] = ElementTree.tostring(part[0], encoding=\"UTF-8\")\n elif part.tag == \"{%s}Header\" % soapenv.NAMESPACE:\n for item in part:\n _str = ElementTree.tostring(item, encoding=\"UTF-8\")\n content[\"header\"].append(_str)", " return content", "\ndef make_soap_enveloped_saml_thingy(thingy, headers=None):\n \"\"\" Returns a soap envelope containing a SAML request\n as a text string.", " :param thingy: The SAML thingy\n :return: The SOAP envelope as a string\n \"\"\"\n soap_envelope = soapenv.Envelope()", " if headers:\n _header = soapenv.Header()\n _header.add_extension_elements(headers)\n soap_envelope.header = _header", " soap_envelope.body = soapenv.Body()\n soap_envelope.body.add_extension_element(thingy)", " return \"%s\" % soap_envelope", "\ndef soap_fault(message=None, actor=None, code=None, detail=None):\n \"\"\" Create a SOAP Fault message", " :param message: Human readable error message\n :param actor: Who discovered the error\n :param code: Error code\n :param detail: More specific error message\n :return: A SOAP Fault message as a string\n \"\"\"\n _string = _actor = _code = _detail = None", " if message:\n _string = soapenv.Fault_faultstring(text=message)\n if actor:\n _actor = soapenv.Fault_faultactor(text=actor)\n if code:\n _code = soapenv.Fault_faultcode(text=code)\n if detail:\n _detail = soapenv.Fault_detail(text=detail)", " fault = soapenv.Fault(\n faultcode=_code,\n faultstring=_string,\n faultactor=_actor,\n detail=_detail,\n )", " return \"%s\" % fault" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python", "import saml2", "from saml2 import create_class_from_xml_string, class_name, make_vals, md\nfrom saml2.saml import NameID, Issuer, SubjectLocality, AuthnContextClassRef\nfrom saml2.saml import SubjectConfirmationData, SubjectConfirmation\nfrom saml2.saml import Attribute", "from py.test import raises\nimport saml2_data", "try:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "", "\nITEMS = {\n NameID: [\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n SPProvidedID=\"sp provided id\">\n roland@example.com\n</NameID>\n\"\"\", \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n SPNameQualifier=\"https://foo.example.com/sp\" \n Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\">_1632879f09d08ea5ede2dc667cbed7e429ebc4335c</NameID>\n\"\"\", \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nFormat=\"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\"\nNameQualifier=\"http://authentic.example.com/saml/metadata\"\nSPNameQualifier=\"http://auth.example.com/saml/metadata\">test\n</NameID>\"\"\"],\n Issuer: \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Issuer xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\">\n http://www.example.com/test\n</Issuer>\n\"\"\",\n SubjectLocality: \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectLocality xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n Address=\"127.0.0.1\" DNSName=\"localhost\"/>\n\"\"\",\n SubjectConfirmationData:\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectConfirmationData xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nInResponseTo=\"_1683146e27983964fbe7bf8f08961108d166a652e5\" \nNotOnOrAfter=\"2010-02-18T13:52:13.959Z\" \nNotBefore=\"2010-01-16T12:00:00Z\" \nRecipient=\"http://192.168.0.10/saml/sp\" />\"\"\",\n SubjectConfirmation:\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectConfirmation xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nMethod=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\"><NameID\nFormat=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\nNameQualifier=\"http://authentic.example.com/saml/metadata\">test@example.com\n</NameID>\n<SubjectConfirmationData\nNotOnOrAfter=\"2010-02-17T17:02:38Z\"\nRecipient=\"http://auth.example.com/saml/proxySingleSignOnRedirect\"\nInResponseTo=\"_59B3A01B03334032C31E434C63F89E3E\"/></SubjectConfirmation>\"\"\"\n}", "#def pytest_generate_tests(metafunc):\n# if \"target_class\" in metafunc.funcargnames:\n# for tcl,xml in ITEMS.items():\n# metafunc.addcall(funcargs={\"target_class\":tcl,\"xml_string\":xml})", "def _eq(l1, l2):\n return set(l1) == set(l2)", "\ndef test_create_class_from_xml_string_nameid():\n kl = create_class_from_xml_string(NameID, ITEMS[NameID][0])\n assert kl != None\n assert kl.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert kl.sp_provided_id == \"sp provided id\"\n assert kl.text.strip() == \"roland@example.com\"\n assert _eq(kl.keyswv(), ['sp_provided_id', 'format', 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"\n assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier',\n 'name_qualifier', 'format', 'text'])", " kl = create_class_from_xml_string(NameID, ITEMS[NameID][1])\n assert kl != None\n assert kl.format == \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\"\n assert kl.sp_name_qualifier == \"https://foo.example.com/sp\"\n assert kl.text.strip() == \"_1632879f09d08ea5ede2dc667cbed7e429ebc4335c\"\n assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"", " kl = create_class_from_xml_string(NameID, ITEMS[NameID][2])\n assert kl != None\n assert kl.format == \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\"\n assert kl.name_qualifier == \"http://authentic.example.com/saml/metadata\"\n assert kl.sp_name_qualifier == \"http://auth.example.com/saml/metadata\"\n assert kl.text.strip() == \"test\"\n assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'name_qualifier',\n 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"", "\ndef test_create_class_from_xml_string_issuer():\n kl = create_class_from_xml_string(Issuer, ITEMS[Issuer])\n assert kl != None\n assert kl.text.strip() == \"http://www.example.com/test\"\n assert _eq(kl.keyswv(), ['text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:Issuer\"", "\ndef test_create_class_from_xml_string_subject_locality():\n kl = create_class_from_xml_string(SubjectLocality, ITEMS[SubjectLocality])\n assert kl != None\n assert _eq(kl.keyswv(), ['address', \"dns_name\"])\n assert kl.address == \"127.0.0.1\"\n assert kl.dns_name == \"localhost\"\n assert class_name(\n kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality\"", "\ndef test_create_class_from_xml_string_subject_confirmation_data():\n kl = create_class_from_xml_string(SubjectConfirmationData,\n ITEMS[SubjectConfirmationData])\n assert kl != None\n assert _eq(kl.keyswv(), ['in_response_to', 'not_on_or_after',\n 'not_before', 'recipient'])\n assert kl.in_response_to == \"_1683146e27983964fbe7bf8f08961108d166a652e5\"\n assert kl.not_on_or_after == \"2010-02-18T13:52:13.959Z\"\n assert kl.not_before == \"2010-01-16T12:00:00Z\"\n assert kl.recipient == \"http://192.168.0.10/saml/sp\"\n assert class_name(kl) == \\\n \"urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData\"", "\ndef test_create_class_from_xml_string_subject_confirmation():\n kl = create_class_from_xml_string(SubjectConfirmation,\n ITEMS[SubjectConfirmation])\n assert kl != None\n assert _eq(kl.keyswv(), ['method', 'name_id',\n 'subject_confirmation_data'])\n assert kl.method == \"urn:oasis:names:tc:SAML:2.0:cm:bearer\"\n name_id = kl.name_id\n assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text'])\n assert name_id.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert name_id.name_qualifier == \"http://authentic.example.com/saml/metadata\"\n assert name_id.text.strip() == \"test@example.com\"\n subject_confirmation_data = kl.subject_confirmation_data\n assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after',\n 'recipient',\n 'in_response_to'])\n assert subject_confirmation_data.recipient == \\\n \"http://auth.example.com/saml/proxySingleSignOnRedirect\"\n assert subject_confirmation_data.not_on_or_after == \"2010-02-17T17:02:38Z\"\n assert subject_confirmation_data.in_response_to == \\\n \"_59B3A01B03334032C31E434C63F89E3E\"\n assert class_name(kl) == \\\n \"urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation\"", "\ndef test_create_class_from_xml_string_wrong_class_spec():\n kl = create_class_from_xml_string(SubjectConfirmationData,\n ITEMS[SubjectConfirmation])\n assert kl == None", "", "", "def test_ee_1():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?><foo>bar</foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {}\n assert ee.tag == \"foo\"\n assert ee.namespace == None\n assert ee.children == []\n assert ee.text == \"bar\"", "\ndef test_ee_2():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?><foo id=\"xyz\">bar</foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {\"id\": \"xyz\"}\n assert ee.tag == \"foo\"\n assert ee.namespace == None\n assert ee.children == []\n assert ee.text == \"bar\"", "\ndef test_ee_3():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\" \n id=\"xyz\">bar</foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {\"id\": \"xyz\"}\n assert ee.tag == \"foo\"\n assert ee.namespace == \"urn:mace:example.com:saml:ns\"\n assert ee.children == []\n assert ee.text == \"bar\"", "\ndef test_ee_4():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\">\n <id>xyz</id><bar>tre</bar></foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {}\n assert ee.tag == \"foo\"\n assert ee.namespace == \"urn:mace:example.com:saml:ns\"\n assert len(ee.children) == 2\n assert ee.text.strip() == \"\"\n cid = ee.find_children(\"id\", \"urn:mace:example.com:saml:namespace\")\n assert cid == []\n ids = ee.find_children(\"id\", \"urn:mace:example.com:saml:ns\")\n assert ids != []\n cid = ids[0]\n print(cid.__dict__)\n assert cid.attributes == {}\n assert cid.tag == \"id\"\n assert cid.namespace == \"urn:mace:example.com:saml:ns\"\n assert cid.children == []\n assert cid.text.strip() == \"xyz\"", "\ndef test_ee_5():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\">bar</foo>\"\"\")", " ce = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <educause xmlns=\"urn:mace:example.com:saml:cu\">rev</educause>\"\"\")", " ee.children.append(ce)", " assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {}\n assert ee.tag == \"foo\"\n assert ee.namespace == \"urn:mace:example.com:saml:ns\"\n assert len(ee.children) == 1\n assert ee.text.strip() == \"bar\"", " c = ee.children[0]\n print(c.__dict__)", " child = ee.find_children(namespace=\"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = ee.find_children(namespace=\"urn:mace:example.com:saml:ns\")\n assert len(child) == 0\n child = ee.find_children(\"educause\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = ee.find_children(\"edugain\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 0\n print(ee.to_string())", "\ndef test_ee_6():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\">bar</foo>\"\"\")", " ce = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <educause xmlns=\"urn:mace:example.com:saml:cu\">rev</educause>\"\"\")", " et = ee.transfer_to_element_tree()\n ce.become_child_element_of(et)", " pee = saml2._extension_element_from_element_tree(et)", " assert pee != None\n print(pee.__dict__)\n assert pee.attributes == {}\n assert pee.tag == \"foo\"\n assert pee.namespace == \"urn:mace:example.com:saml:ns\"\n assert len(pee.children) == 1\n assert pee.text.strip() == \"bar\"", " c = pee.children[0]\n print(c.__dict__)", " child = pee.find_children(namespace=\"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = pee.find_children(namespace=\"urn:mace:example.com:saml:ns\")\n assert len(child) == 0\n child = pee.find_children(\"educause\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = pee.find_children(\"edugain\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 0\n print(pee.to_string())", "\nNAMEID_WITH_ATTRIBUTE_EXTENSION = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n xmlns:local=\"urn:mace:example.com:saml:assertion\"\n Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n SPProvidedID=\"sp provided id\"\n local:Foo=\"BAR\">\n roland@example.com\n</NameID>\n\"\"\"", "\ndef test_nameid_with_extension():\n kl = create_class_from_xml_string(NameID, NAMEID_WITH_ATTRIBUTE_EXTENSION)\n assert kl != None\n print(kl.__dict__)\n assert kl.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert kl.sp_provided_id == \"sp provided id\"\n assert kl.text.strip() == \"roland@example.com\"\n assert _eq(kl.keyswv(), ['sp_provided_id', 'format',\n 'extension_attributes', 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"\n assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier',\n 'name_qualifier', 'format', 'text'])\n assert kl.extension_attributes == {\n '{urn:mace:example.com:saml:assertion}Foo': 'BAR'}", "\nSUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectConfirmation xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nMethod=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">\n<NameID\nFormat=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\nNameQualifier=\"http://authentic.example.com/saml/metadata\">test@example.com\n</NameID>\n<SubjectConfirmationData\nNotOnOrAfter=\"2010-02-17T17:02:38Z\"\nRecipient=\"http://auth.example.com/saml/proxySingleSignOnRedirect\"\nInResponseTo=\"_59B3A01B03334032C31E434C63F89E3E\"/>\n<local:Trustlevel xmlns:local=\"urn:mace:example.com:saml:assertion\">\nExcellent\n</local:Trustlevel>\n</SubjectConfirmation>\"\"\"", "\ndef test_subject_confirmation_with_extension():\n kl = create_class_from_xml_string(SubjectConfirmation,\n SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION)\n assert kl != None\n print(kl.__dict__)\n assert kl.extension_attributes == {}\n assert kl.method == \"urn:oasis:names:tc:SAML:2.0:cm:bearer\"\n name_id = kl.name_id\n assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text'])\n assert name_id.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert name_id.name_qualifier == \"http://authentic.example.com/saml/metadata\"\n assert name_id.text.strip() == \"test@example.com\"\n subject_confirmation_data = kl.subject_confirmation_data\n assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after',\n 'recipient',\n 'in_response_to'])\n assert subject_confirmation_data.recipient == \\\n \"http://auth.example.com/saml/proxySingleSignOnRedirect\"\n assert subject_confirmation_data.not_on_or_after == \"2010-02-17T17:02:38Z\"\n assert subject_confirmation_data.in_response_to == \\\n \"_59B3A01B03334032C31E434C63F89E3E\"\n assert len(kl.extension_elements) == 1\n ee = kl.extension_elements[0]\n assert ee.tag == \"Trustlevel\"\n assert ee.namespace == \"urn:mace:example.com:saml:assertion\"\n assert ee.text.strip() == \"Excellent\"", "\ndef test_to_fro_string_1():\n kl = create_class_from_xml_string(SubjectConfirmation,\n SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION)\n txt = kl.to_string()\n cpy = create_class_from_xml_string(SubjectConfirmation, txt)", " print(kl.__dict__)\n print(cpy.__dict__)", " assert kl.text.strip() == cpy.text.strip()\n assert _eq(kl.keyswv(), cpy.keyswv())\n assert len(kl.extension_elements) == len(cpy.extension_elements)\n klee = kl.extension_elements[0]\n cpyee = cpy.extension_elements[0]\n assert klee.text.strip() == cpyee.text.strip()\n assert klee.tag == cpyee.tag\n assert klee.namespace == cpyee.namespace", "\ndef test_make_vals_str():\n kl = make_vals(\"Jeter\", md.GivenName, part=True)\n assert isinstance(kl, md.GivenName)\n assert kl.text == \"Jeter\"", "\ndef test_make_vals_list_of_strs():\n cp = md.ContactPerson()\n make_vals([\"Derek\", \"Sanderson\"], md.GivenName, cp, \"given_name\")\n assert len(cp.given_name) == 2\n assert _eq([i.text for i in cp.given_name], [\"Sanderson\", \"Derek\"])", "\ndef test_attribute_element_to_extension_element():\n attr = create_class_from_xml_string(Attribute, saml2_data.TEST_ATTRIBUTE)\n ee = saml2.element_to_extension_element(attr)\n print(ee.__dict__)\n assert ee.tag == \"Attribute\"\n assert ee.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion'\n assert _eq(ee.attributes.keys(), ['FriendlyName', 'Name', 'NameFormat'])\n assert ee.attributes[\"FriendlyName\"] == 'test attribute'\n assert ee.attributes[\"Name\"] == \"testAttribute\"\n assert ee.attributes[\"NameFormat\"] == \\\n 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified'\n assert len(ee.children) == 2\n for child in ee.children:\n # children are also extension element instances\n assert child.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion'\n assert child.tag == \"AttributeValue\"", "\ndef test_ee_7():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <ExternalEntityAttributeAuthority\n xmlns=\"urn:oasis:names:tc:SAML:metadata:dynamicsaml\">\n <AssertingEntity>\n <NameID Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">\n http://federationX.org\n </NameID>\n </AssertingEntity>\n <RetrievalEndpoint>\n https://federationX.org/?ID=a87s76a5765da76576a57as\n </RetrievalEndpoint>\n </ExternalEntityAttributeAuthority>\n\"\"\")", " print(ee.__dict__)\n assert len(ee.children) == 2\n for child in ee.children:\n assert child.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert _eq([\"AssertingEntity\", \"RetrievalEndpoint\"],\n [c.tag for c in ee.children])\n aes = [c for c in ee.children if c.tag == \"AssertingEntity\"]\n assert len(aes) == 1\n assert len(aes[0].children) == 1\n assert _eq(aes[0].attributes.keys(), [])\n nid = aes[0].children[0]\n assert nid.tag == \"NameID\"\n assert nid.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert len(nid.children) == 0\n assert _eq(nid.attributes.keys(), [\"Format\"])\n assert nid.text.strip() == \"http://federationX.org\"", "", "", "def test_extension_element_loadd():\n ava = {'attributes': {},\n 'tag': 'ExternalEntityAttributeAuthority',\n 'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml',\n 'children': [{\n \"tag\": \"AssertingEntity\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",", " \"children\": [{\n \"tag\": \"NameID\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"text\": \"http://federationX.org\",\n \"attributes\": {\n \"Format\": \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\"\n },\n }]\n }, {\n \"tag\": \"RetrievalEndpoint\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata\"\n \":dynamicsaml\",\n \"text\": \"https://federationX.org/?ID=a87s76a5765da76576a57as\",\n }],\n }", " ee = saml2.ExtensionElement(ava[\"tag\"]).loadd(ava)\n print(ee.__dict__)\n assert len(ee.children) == 2\n for child in ee.children:\n assert child.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert _eq([\"AssertingEntity\", \"RetrievalEndpoint\"],\n [c.tag for c in ee.children])\n aes = [c for c in ee.children if c.tag == \"AssertingEntity\"]\n assert len(aes) == 1\n assert len(aes[0].children) == 1\n assert _eq(aes[0].attributes.keys(), [])\n nid = aes[0].children[0]\n assert nid.tag == \"NameID\"\n assert nid.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert len(nid.children) == 0\n assert _eq(nid.attributes.keys(), [\"Format\"])\n assert nid.text.strip() == \"http://federationX.org\"", "\ndef test_extensions_loadd():\n ava = {\"extension_elements\": [\n {\n 'attributes': {},\n 'tag': 'ExternalEntityAttributeAuthority',\n 'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml',\n 'children': [\n {\"tag\": \"AssertingEntity\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"children\": [\n {\"tag\": \"NameID\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"text\": \"http://federationX.org\",\n \"attributes\": {\n \"Format\": \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\"\n },\n }]\n },\n {\n \"tag\": \"RetrievalEndpoint\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"text\": \"https://federationX.org/?ID=a87s76a5765da76576a57as\",\n }],\n }],\n \"extension_attributes\": {\n \"foo\": \"bar\",\n }\n }", " extension = saml2.SamlBase()\n extension.loadd(ava)", " print(extension.__dict__)\n assert len(extension.extension_elements) == 1\n ee = extension.extension_elements[0]\n assert len(ee.children) == 2\n for child in ee.children:\n assert child.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert _eq([\"AssertingEntity\", \"RetrievalEndpoint\"],\n [c.tag for c in ee.children])\n aes = [c for c in ee.children if c.tag == \"AssertingEntity\"]\n assert len(aes) == 1\n assert len(aes[0].children) == 1\n assert _eq(aes[0].attributes.keys(), [])\n nid = aes[0].children[0]\n assert nid.tag == \"NameID\"\n assert nid.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert len(nid.children) == 0\n assert _eq(nid.attributes.keys(), [\"Format\"])\n assert nid.text.strip() == \"http://federationX.org\"", " assert list(extension.extension_attributes.keys()) == [\"foo\"]\n assert extension.extension_attributes[\"foo\"] == \"bar\"" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python", "import saml2", "from saml2 import create_class_from_xml_string, class_name, make_vals, md\nfrom saml2.saml import NameID, Issuer, SubjectLocality, AuthnContextClassRef\nfrom saml2.saml import SubjectConfirmationData, SubjectConfirmation\nfrom saml2.saml import Attribute", "from py.test import raises\nimport saml2_data", "try:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "from defusedxml.common import EntitiesForbidden", "\nITEMS = {\n NameID: [\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n SPProvidedID=\"sp provided id\">\n roland@example.com\n</NameID>\n\"\"\", \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n SPNameQualifier=\"https://foo.example.com/sp\" \n Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\">_1632879f09d08ea5ede2dc667cbed7e429ebc4335c</NameID>\n\"\"\", \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nFormat=\"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\"\nNameQualifier=\"http://authentic.example.com/saml/metadata\"\nSPNameQualifier=\"http://auth.example.com/saml/metadata\">test\n</NameID>\"\"\"],\n Issuer: \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Issuer xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\">\n http://www.example.com/test\n</Issuer>\n\"\"\",\n SubjectLocality: \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectLocality xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n Address=\"127.0.0.1\" DNSName=\"localhost\"/>\n\"\"\",\n SubjectConfirmationData:\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectConfirmationData xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nInResponseTo=\"_1683146e27983964fbe7bf8f08961108d166a652e5\" \nNotOnOrAfter=\"2010-02-18T13:52:13.959Z\" \nNotBefore=\"2010-01-16T12:00:00Z\" \nRecipient=\"http://192.168.0.10/saml/sp\" />\"\"\",\n SubjectConfirmation:\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectConfirmation xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nMethod=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\"><NameID\nFormat=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\nNameQualifier=\"http://authentic.example.com/saml/metadata\">test@example.com\n</NameID>\n<SubjectConfirmationData\nNotOnOrAfter=\"2010-02-17T17:02:38Z\"\nRecipient=\"http://auth.example.com/saml/proxySingleSignOnRedirect\"\nInResponseTo=\"_59B3A01B03334032C31E434C63F89E3E\"/></SubjectConfirmation>\"\"\"\n}", "#def pytest_generate_tests(metafunc):\n# if \"target_class\" in metafunc.funcargnames:\n# for tcl,xml in ITEMS.items():\n# metafunc.addcall(funcargs={\"target_class\":tcl,\"xml_string\":xml})", "def _eq(l1, l2):\n return set(l1) == set(l2)", "\ndef test_create_class_from_xml_string_nameid():\n kl = create_class_from_xml_string(NameID, ITEMS[NameID][0])\n assert kl != None\n assert kl.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert kl.sp_provided_id == \"sp provided id\"\n assert kl.text.strip() == \"roland@example.com\"\n assert _eq(kl.keyswv(), ['sp_provided_id', 'format', 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"\n assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier',\n 'name_qualifier', 'format', 'text'])", " kl = create_class_from_xml_string(NameID, ITEMS[NameID][1])\n assert kl != None\n assert kl.format == \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\"\n assert kl.sp_name_qualifier == \"https://foo.example.com/sp\"\n assert kl.text.strip() == \"_1632879f09d08ea5ede2dc667cbed7e429ebc4335c\"\n assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"", " kl = create_class_from_xml_string(NameID, ITEMS[NameID][2])\n assert kl != None\n assert kl.format == \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\"\n assert kl.name_qualifier == \"http://authentic.example.com/saml/metadata\"\n assert kl.sp_name_qualifier == \"http://auth.example.com/saml/metadata\"\n assert kl.text.strip() == \"test\"\n assert _eq(kl.keyswv(), ['sp_name_qualifier', 'format', 'name_qualifier',\n 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"", "\ndef test_create_class_from_xml_string_issuer():\n kl = create_class_from_xml_string(Issuer, ITEMS[Issuer])\n assert kl != None\n assert kl.text.strip() == \"http://www.example.com/test\"\n assert _eq(kl.keyswv(), ['text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:Issuer\"", "\ndef test_create_class_from_xml_string_subject_locality():\n kl = create_class_from_xml_string(SubjectLocality, ITEMS[SubjectLocality])\n assert kl != None\n assert _eq(kl.keyswv(), ['address', \"dns_name\"])\n assert kl.address == \"127.0.0.1\"\n assert kl.dns_name == \"localhost\"\n assert class_name(\n kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality\"", "\ndef test_create_class_from_xml_string_subject_confirmation_data():\n kl = create_class_from_xml_string(SubjectConfirmationData,\n ITEMS[SubjectConfirmationData])\n assert kl != None\n assert _eq(kl.keyswv(), ['in_response_to', 'not_on_or_after',\n 'not_before', 'recipient'])\n assert kl.in_response_to == \"_1683146e27983964fbe7bf8f08961108d166a652e5\"\n assert kl.not_on_or_after == \"2010-02-18T13:52:13.959Z\"\n assert kl.not_before == \"2010-01-16T12:00:00Z\"\n assert kl.recipient == \"http://192.168.0.10/saml/sp\"\n assert class_name(kl) == \\\n \"urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData\"", "\ndef test_create_class_from_xml_string_subject_confirmation():\n kl = create_class_from_xml_string(SubjectConfirmation,\n ITEMS[SubjectConfirmation])\n assert kl != None\n assert _eq(kl.keyswv(), ['method', 'name_id',\n 'subject_confirmation_data'])\n assert kl.method == \"urn:oasis:names:tc:SAML:2.0:cm:bearer\"\n name_id = kl.name_id\n assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text'])\n assert name_id.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert name_id.name_qualifier == \"http://authentic.example.com/saml/metadata\"\n assert name_id.text.strip() == \"test@example.com\"\n subject_confirmation_data = kl.subject_confirmation_data\n assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after',\n 'recipient',\n 'in_response_to'])\n assert subject_confirmation_data.recipient == \\\n \"http://auth.example.com/saml/proxySingleSignOnRedirect\"\n assert subject_confirmation_data.not_on_or_after == \"2010-02-17T17:02:38Z\"\n assert subject_confirmation_data.in_response_to == \\\n \"_59B3A01B03334032C31E434C63F89E3E\"\n assert class_name(kl) == \\\n \"urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation\"", "\ndef test_create_class_from_xml_string_wrong_class_spec():\n kl = create_class_from_xml_string(SubjectConfirmationData,\n ITEMS[SubjectConfirmation])\n assert kl == None", "", "def test_create_class_from_xml_string_xxe():\n xml = \"\"\"<?xml version=\"1.0\"?>\n <!DOCTYPE lolz [\n <!ENTITY lol \"lol\">\n <!ELEMENT lolz (#PCDATA)>\n <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n ]>\n <lolz>&lol1;</lolz>\n \"\"\"\n with raises(EntitiesForbidden) as err:\n create_class_from_xml_string(NameID, xml)", "", "def test_ee_1():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?><foo>bar</foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {}\n assert ee.tag == \"foo\"\n assert ee.namespace == None\n assert ee.children == []\n assert ee.text == \"bar\"", "\ndef test_ee_2():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?><foo id=\"xyz\">bar</foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {\"id\": \"xyz\"}\n assert ee.tag == \"foo\"\n assert ee.namespace == None\n assert ee.children == []\n assert ee.text == \"bar\"", "\ndef test_ee_3():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\" \n id=\"xyz\">bar</foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {\"id\": \"xyz\"}\n assert ee.tag == \"foo\"\n assert ee.namespace == \"urn:mace:example.com:saml:ns\"\n assert ee.children == []\n assert ee.text == \"bar\"", "\ndef test_ee_4():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\">\n <id>xyz</id><bar>tre</bar></foo>\"\"\")\n assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {}\n assert ee.tag == \"foo\"\n assert ee.namespace == \"urn:mace:example.com:saml:ns\"\n assert len(ee.children) == 2\n assert ee.text.strip() == \"\"\n cid = ee.find_children(\"id\", \"urn:mace:example.com:saml:namespace\")\n assert cid == []\n ids = ee.find_children(\"id\", \"urn:mace:example.com:saml:ns\")\n assert ids != []\n cid = ids[0]\n print(cid.__dict__)\n assert cid.attributes == {}\n assert cid.tag == \"id\"\n assert cid.namespace == \"urn:mace:example.com:saml:ns\"\n assert cid.children == []\n assert cid.text.strip() == \"xyz\"", "\ndef test_ee_5():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\">bar</foo>\"\"\")", " ce = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <educause xmlns=\"urn:mace:example.com:saml:cu\">rev</educause>\"\"\")", " ee.children.append(ce)", " assert ee != None\n print(ee.__dict__)\n assert ee.attributes == {}\n assert ee.tag == \"foo\"\n assert ee.namespace == \"urn:mace:example.com:saml:ns\"\n assert len(ee.children) == 1\n assert ee.text.strip() == \"bar\"", " c = ee.children[0]\n print(c.__dict__)", " child = ee.find_children(namespace=\"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = ee.find_children(namespace=\"urn:mace:example.com:saml:ns\")\n assert len(child) == 0\n child = ee.find_children(\"educause\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = ee.find_children(\"edugain\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 0\n print(ee.to_string())", "\ndef test_ee_6():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <foo xmlns=\"urn:mace:example.com:saml:ns\">bar</foo>\"\"\")", " ce = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <educause xmlns=\"urn:mace:example.com:saml:cu\">rev</educause>\"\"\")", " et = ee.transfer_to_element_tree()\n ce.become_child_element_of(et)", " pee = saml2._extension_element_from_element_tree(et)", " assert pee != None\n print(pee.__dict__)\n assert pee.attributes == {}\n assert pee.tag == \"foo\"\n assert pee.namespace == \"urn:mace:example.com:saml:ns\"\n assert len(pee.children) == 1\n assert pee.text.strip() == \"bar\"", " c = pee.children[0]\n print(c.__dict__)", " child = pee.find_children(namespace=\"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = pee.find_children(namespace=\"urn:mace:example.com:saml:ns\")\n assert len(child) == 0\n child = pee.find_children(\"educause\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 1\n child = pee.find_children(\"edugain\", \"urn:mace:example.com:saml:cu\")\n assert len(child) == 0\n print(pee.to_string())", "\nNAMEID_WITH_ATTRIBUTE_EXTENSION = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<NameID xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\n xmlns:local=\"urn:mace:example.com:saml:assertion\"\n Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n SPProvidedID=\"sp provided id\"\n local:Foo=\"BAR\">\n roland@example.com\n</NameID>\n\"\"\"", "\ndef test_nameid_with_extension():\n kl = create_class_from_xml_string(NameID, NAMEID_WITH_ATTRIBUTE_EXTENSION)\n assert kl != None\n print(kl.__dict__)\n assert kl.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert kl.sp_provided_id == \"sp provided id\"\n assert kl.text.strip() == \"roland@example.com\"\n assert _eq(kl.keyswv(), ['sp_provided_id', 'format',\n 'extension_attributes', 'text'])\n assert class_name(kl) == \"urn:oasis:names:tc:SAML:2.0:assertion:NameID\"\n assert _eq(kl.keys(), ['sp_provided_id', 'sp_name_qualifier',\n 'name_qualifier', 'format', 'text'])\n assert kl.extension_attributes == {\n '{urn:mace:example.com:saml:assertion}Foo': 'BAR'}", "\nSUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<SubjectConfirmation xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\"\nMethod=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">\n<NameID\nFormat=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\nNameQualifier=\"http://authentic.example.com/saml/metadata\">test@example.com\n</NameID>\n<SubjectConfirmationData\nNotOnOrAfter=\"2010-02-17T17:02:38Z\"\nRecipient=\"http://auth.example.com/saml/proxySingleSignOnRedirect\"\nInResponseTo=\"_59B3A01B03334032C31E434C63F89E3E\"/>\n<local:Trustlevel xmlns:local=\"urn:mace:example.com:saml:assertion\">\nExcellent\n</local:Trustlevel>\n</SubjectConfirmation>\"\"\"", "\ndef test_subject_confirmation_with_extension():\n kl = create_class_from_xml_string(SubjectConfirmation,\n SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION)\n assert kl != None\n print(kl.__dict__)\n assert kl.extension_attributes == {}\n assert kl.method == \"urn:oasis:names:tc:SAML:2.0:cm:bearer\"\n name_id = kl.name_id\n assert _eq(name_id.keyswv(), ['format', 'name_qualifier', 'text'])\n assert name_id.format == \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\n assert name_id.name_qualifier == \"http://authentic.example.com/saml/metadata\"\n assert name_id.text.strip() == \"test@example.com\"\n subject_confirmation_data = kl.subject_confirmation_data\n assert _eq(subject_confirmation_data.keyswv(), ['not_on_or_after',\n 'recipient',\n 'in_response_to'])\n assert subject_confirmation_data.recipient == \\\n \"http://auth.example.com/saml/proxySingleSignOnRedirect\"\n assert subject_confirmation_data.not_on_or_after == \"2010-02-17T17:02:38Z\"\n assert subject_confirmation_data.in_response_to == \\\n \"_59B3A01B03334032C31E434C63F89E3E\"\n assert len(kl.extension_elements) == 1\n ee = kl.extension_elements[0]\n assert ee.tag == \"Trustlevel\"\n assert ee.namespace == \"urn:mace:example.com:saml:assertion\"\n assert ee.text.strip() == \"Excellent\"", "\ndef test_to_fro_string_1():\n kl = create_class_from_xml_string(SubjectConfirmation,\n SUBJECT_CONFIRMATION_WITH_MEMBER_EXTENSION)\n txt = kl.to_string()\n cpy = create_class_from_xml_string(SubjectConfirmation, txt)", " print(kl.__dict__)\n print(cpy.__dict__)", " assert kl.text.strip() == cpy.text.strip()\n assert _eq(kl.keyswv(), cpy.keyswv())\n assert len(kl.extension_elements) == len(cpy.extension_elements)\n klee = kl.extension_elements[0]\n cpyee = cpy.extension_elements[0]\n assert klee.text.strip() == cpyee.text.strip()\n assert klee.tag == cpyee.tag\n assert klee.namespace == cpyee.namespace", "\ndef test_make_vals_str():\n kl = make_vals(\"Jeter\", md.GivenName, part=True)\n assert isinstance(kl, md.GivenName)\n assert kl.text == \"Jeter\"", "\ndef test_make_vals_list_of_strs():\n cp = md.ContactPerson()\n make_vals([\"Derek\", \"Sanderson\"], md.GivenName, cp, \"given_name\")\n assert len(cp.given_name) == 2\n assert _eq([i.text for i in cp.given_name], [\"Sanderson\", \"Derek\"])", "\ndef test_attribute_element_to_extension_element():\n attr = create_class_from_xml_string(Attribute, saml2_data.TEST_ATTRIBUTE)\n ee = saml2.element_to_extension_element(attr)\n print(ee.__dict__)\n assert ee.tag == \"Attribute\"\n assert ee.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion'\n assert _eq(ee.attributes.keys(), ['FriendlyName', 'Name', 'NameFormat'])\n assert ee.attributes[\"FriendlyName\"] == 'test attribute'\n assert ee.attributes[\"Name\"] == \"testAttribute\"\n assert ee.attributes[\"NameFormat\"] == \\\n 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified'\n assert len(ee.children) == 2\n for child in ee.children:\n # children are also extension element instances\n assert child.namespace == 'urn:oasis:names:tc:SAML:2.0:assertion'\n assert child.tag == \"AttributeValue\"", "\ndef test_ee_7():\n ee = saml2.extension_element_from_string(\n \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n <ExternalEntityAttributeAuthority\n xmlns=\"urn:oasis:names:tc:SAML:metadata:dynamicsaml\">\n <AssertingEntity>\n <NameID Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">\n http://federationX.org\n </NameID>\n </AssertingEntity>\n <RetrievalEndpoint>\n https://federationX.org/?ID=a87s76a5765da76576a57as\n </RetrievalEndpoint>\n </ExternalEntityAttributeAuthority>\n\"\"\")", " print(ee.__dict__)\n assert len(ee.children) == 2\n for child in ee.children:\n assert child.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert _eq([\"AssertingEntity\", \"RetrievalEndpoint\"],\n [c.tag for c in ee.children])\n aes = [c for c in ee.children if c.tag == \"AssertingEntity\"]\n assert len(aes) == 1\n assert len(aes[0].children) == 1\n assert _eq(aes[0].attributes.keys(), [])\n nid = aes[0].children[0]\n assert nid.tag == \"NameID\"\n assert nid.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert len(nid.children) == 0\n assert _eq(nid.attributes.keys(), [\"Format\"])\n assert nid.text.strip() == \"http://federationX.org\"", "", "def test_ee_xxe():\n xml = \"\"\"<?xml version=\"1.0\"?>\n <!DOCTYPE lolz [\n <!ENTITY lol \"lol\">\n <!ELEMENT lolz (#PCDATA)>\n <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n ]>\n <lolz>&lol1;</lolz>\n \"\"\"\n with raises(EntitiesForbidden):\n saml2.extension_element_from_string(xml)", "", "def test_extension_element_loadd():\n ava = {'attributes': {},\n 'tag': 'ExternalEntityAttributeAuthority',\n 'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml',\n 'children': [{\n \"tag\": \"AssertingEntity\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",", " \"children\": [{\n \"tag\": \"NameID\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"text\": \"http://federationX.org\",\n \"attributes\": {\n \"Format\": \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\"\n },\n }]\n }, {\n \"tag\": \"RetrievalEndpoint\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata\"\n \":dynamicsaml\",\n \"text\": \"https://federationX.org/?ID=a87s76a5765da76576a57as\",\n }],\n }", " ee = saml2.ExtensionElement(ava[\"tag\"]).loadd(ava)\n print(ee.__dict__)\n assert len(ee.children) == 2\n for child in ee.children:\n assert child.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert _eq([\"AssertingEntity\", \"RetrievalEndpoint\"],\n [c.tag for c in ee.children])\n aes = [c for c in ee.children if c.tag == \"AssertingEntity\"]\n assert len(aes) == 1\n assert len(aes[0].children) == 1\n assert _eq(aes[0].attributes.keys(), [])\n nid = aes[0].children[0]\n assert nid.tag == \"NameID\"\n assert nid.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert len(nid.children) == 0\n assert _eq(nid.attributes.keys(), [\"Format\"])\n assert nid.text.strip() == \"http://federationX.org\"", "\ndef test_extensions_loadd():\n ava = {\"extension_elements\": [\n {\n 'attributes': {},\n 'tag': 'ExternalEntityAttributeAuthority',\n 'namespace': 'urn:oasis:names:tc:SAML:metadata:dynamicsaml',\n 'children': [\n {\"tag\": \"AssertingEntity\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"children\": [\n {\"tag\": \"NameID\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"text\": \"http://federationX.org\",\n \"attributes\": {\n \"Format\": \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\"\n },\n }]\n },\n {\n \"tag\": \"RetrievalEndpoint\",\n \"namespace\": \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\",\n \"text\": \"https://federationX.org/?ID=a87s76a5765da76576a57as\",\n }],\n }],\n \"extension_attributes\": {\n \"foo\": \"bar\",\n }\n }", " extension = saml2.SamlBase()\n extension.loadd(ava)", " print(extension.__dict__)\n assert len(extension.extension_elements) == 1\n ee = extension.extension_elements[0]\n assert len(ee.children) == 2\n for child in ee.children:\n assert child.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert _eq([\"AssertingEntity\", \"RetrievalEndpoint\"],\n [c.tag for c in ee.children])\n aes = [c for c in ee.children if c.tag == \"AssertingEntity\"]\n assert len(aes) == 1\n assert len(aes[0].children) == 1\n assert _eq(aes[0].attributes.keys(), [])\n nid = aes[0].children[0]\n assert nid.tag == \"NameID\"\n assert nid.namespace == \"urn:oasis:names:tc:SAML:metadata:dynamicsaml\"\n assert len(nid.children) == 0\n assert _eq(nid.attributes.keys(), [\"Format\"])\n assert nid.text.strip() == \"http://federationX.org\"", " assert list(extension.extension_attributes.keys()) == [\"foo\"]\n assert extension.extension_attributes[\"foo\"] == \"bar\"" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python", "try:\n from xml.etree import cElementTree as ElementTree\n if ElementTree.VERSION < '1.3.0':\n # cElementTree has no support for register_namespace\n # neither _namespace_map, thus we sacrify performance\n # for correctness\n from xml.etree import ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "", "\nimport saml2.samlp as samlp\nfrom saml2.samlp import NAMESPACE as SAMLP_NAMESPACE", "", "\nNAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\"", "example = \"\"\"<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <Body>\n <samlp:Response xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" \n xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" \n ID=\"_6c3a4f8b9c2d\" Version=\"2.0\" IssueInstant=\"2004-03-27T08:42:00Z\">\n <saml:Issuer>https://www.example.com/SAML</saml:Issuer>\n <Status>\n <StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/>\n </Status>\n <saml:Assertion>\n <saml:Subject></saml:Subject>\n <saml:AttributeStatement></saml:AttributeStatement>\n </saml:Assertion>\n </samlp:Response>\n </Body>\n</Envelope>\n\"\"\"", "\ndef test_parse_soap_envelope():\n envelope = ElementTree.fromstring(example)\n assert envelope.tag == '{%s}Envelope' % NAMESPACE\n # How to check that it's the right type ?\n assert len(envelope) == 1\n body = envelope[0]\n assert body.tag == '{%s}Body' % NAMESPACE\n assert len(body) == 1\n saml_part = body[0]\n assert saml_part.tag == '{%s}Response' % SAMLP_NAMESPACE\n # {http://schemas.xmlsoap.org/soap/envelope/}Envelope", "\ndef test_make_soap_envelope():\n envelope = ElementTree.Element('')\n envelope.tag = '{%s}Envelope' % NAMESPACE\n body = ElementTree.Element('')\n body.tag = '{%s}Body' % NAMESPACE\n envelope.append(body) \n request = samlp.AuthnRequest()\n request.become_child_element_of(body)", " assert envelope.tag == '{%s}Envelope' % NAMESPACE\n assert len(envelope) == 1\n body = envelope[0]\n assert body.tag == '{%s}Body' % NAMESPACE\n assert len(body) == 1\n saml_part = body[0]\n assert saml_part.tag == '{%s}AuthnRequest' % SAMLP_NAMESPACE", "" ]
[ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python", "try:\n from xml.etree import cElementTree as ElementTree\n if ElementTree.VERSION < '1.3.0':\n # cElementTree has no support for register_namespace\n # neither _namespace_map, thus we sacrify performance\n # for correctness\n from xml.etree import ElementTree\nexcept ImportError:\n try:\n import cElementTree as ElementTree\n except ImportError:\n from elementtree import ElementTree", "from defusedxml.common import EntitiesForbidden", "from pytest import raises", "\nimport saml2.samlp as samlp\nfrom saml2.samlp import NAMESPACE as SAMLP_NAMESPACE", "from saml2 import soap", "\nNAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\"", "example = \"\"\"<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <Body>\n <samlp:Response xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" \n xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" \n ID=\"_6c3a4f8b9c2d\" Version=\"2.0\" IssueInstant=\"2004-03-27T08:42:00Z\">\n <saml:Issuer>https://www.example.com/SAML</saml:Issuer>\n <Status>\n <StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/>\n </Status>\n <saml:Assertion>\n <saml:Subject></saml:Subject>\n <saml:AttributeStatement></saml:AttributeStatement>\n </saml:Assertion>\n </samlp:Response>\n </Body>\n</Envelope>\n\"\"\"", "\ndef test_parse_soap_envelope():\n envelope = ElementTree.fromstring(example)\n assert envelope.tag == '{%s}Envelope' % NAMESPACE\n # How to check that it's the right type ?\n assert len(envelope) == 1\n body = envelope[0]\n assert body.tag == '{%s}Body' % NAMESPACE\n assert len(body) == 1\n saml_part = body[0]\n assert saml_part.tag == '{%s}Response' % SAMLP_NAMESPACE\n # {http://schemas.xmlsoap.org/soap/envelope/}Envelope", "\ndef test_make_soap_envelope():\n envelope = ElementTree.Element('')\n envelope.tag = '{%s}Envelope' % NAMESPACE\n body = ElementTree.Element('')\n body.tag = '{%s}Body' % NAMESPACE\n envelope.append(body) \n request = samlp.AuthnRequest()\n request.become_child_element_of(body)", " assert envelope.tag == '{%s}Envelope' % NAMESPACE\n assert len(envelope) == 1\n body = envelope[0]\n assert body.tag == '{%s}Body' % NAMESPACE\n assert len(body) == 1\n saml_part = body[0]\n assert saml_part.tag == '{%s}AuthnRequest' % SAMLP_NAMESPACE", "", "def test_parse_soap_enveloped_saml_thingy_xxe():\n xml = \"\"\"<?xml version=\"1.0\"?>\n <!DOCTYPE lolz [\n <!ENTITY lol \"lol\">\n <!ELEMENT lolz (#PCDATA)>\n <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n ]>\n <lolz>&lol1;</lolz>\n \"\"\"\n with raises(EntitiesForbidden):\n soap.parse_soap_enveloped_saml_thingy(xml, None)", "\ndef test_class_instances_from_soap_enveloped_saml_thingies_xxe():\n xml = \"\"\"<?xml version=\"1.0\"?>\n <!DOCTYPE lolz [\n <!ENTITY lol \"lol\">\n <!ELEMENT lolz (#PCDATA)>\n <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n ]>\n <lolz>&lol1;</lolz>\n \"\"\"\n with raises(soap.XmlParseError):\n soap.class_instances_from_soap_enveloped_saml_thingies(xml, None)", "\ndef test_open_soap_envelope_xxe():\n xml = \"\"\"<?xml version=\"1.0\"?>\n <!DOCTYPE lolz [\n <!ENTITY lol \"lol\">\n <!ELEMENT lolz (#PCDATA)>\n <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n ]>\n <lolz>&lol1;</lolz>\n \"\"\"\n with raises(soap.XmlParseError):\n soap.open_soap_envelope(xml)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-", "import base64\nimport uuid\nimport six\nfrom future.backports.urllib.parse import parse_qs\nfrom future.backports.urllib.parse import urlencode\nfrom future.backports.urllib.parse import urlparse", "", "\nfrom saml2.argtree import add_path\nfrom saml2.cert import OpenSSLWrapper\nfrom saml2.xmldsig import SIG_RSA_SHA256\nfrom saml2 import BINDING_HTTP_POST\nfrom saml2 import BINDING_HTTP_REDIRECT\nfrom saml2 import config\nfrom saml2 import class_name\nfrom saml2 import extension_elements_to_elements\nfrom saml2 import saml\nfrom saml2 import samlp\nfrom saml2 import sigver\nfrom saml2 import s_utils\nfrom saml2.assertion import Assertion", "from saml2.authn_context import INTERNETPROTOCOLPASSWORD\nfrom saml2.client import Saml2Client\nfrom saml2.config import SPConfig", "", "from saml2.response import LogoutResponse\nfrom saml2.saml import NAMEID_FORMAT_PERSISTENT, EncryptedAssertion, Advice\nfrom saml2.saml import NAMEID_FORMAT_TRANSIENT\nfrom saml2.saml import NameID\nfrom saml2.samlp import SessionIndex\nfrom saml2.server import Server\nfrom saml2.sigver import pre_encryption_part, make_temp, pre_encrypt_assertion\nfrom saml2.sigver import rm_xmltag\nfrom saml2.sigver import verify_redirect_signature\nfrom saml2.s_utils import do_attribute_statement\nfrom saml2.s_utils import factory\nfrom saml2.time_util import in_a_while, a_while_ago", "", "\nfrom fakeIDP import FakeIDP\nfrom fakeIDP import unpack_form\nfrom pathutils import full_path", "AUTHN = {\n \"class_ref\": INTERNETPROTOCOLPASSWORD,\n \"authn_auth\": \"http://www.example.com/login\"\n}", "\ndef generate_cert():\n sn = uuid.uuid4().urn\n cert_info = {\n \"cn\": \"localhost\",\n \"country_code\": \"se\",\n \"state\": \"ac\",\n \"city\": \"Umea\",\n \"organization\": \"ITS\",\n \"organization_unit\": \"DIRG\"\n }\n osw = OpenSSLWrapper()\n ca_cert_str = osw.read_str_from_file(\n full_path(\"root_cert/localhost.ca.crt\"))\n ca_key_str = osw.read_str_from_file(\n full_path(\"root_cert/localhost.ca.key\"))\n req_cert_str, req_key_str = osw.create_certificate(cert_info, request=True,\n sn=sn, key_length=2048)\n cert_str = osw.create_cert_signed_certificate(ca_cert_str, ca_key_str,\n req_cert_str)\n return cert_str, req_key_str", "\ndef add_subelement(xmldoc, node_name, subelem):\n s = xmldoc.find(node_name)\n if s > 0:\n x = xmldoc.rindex(\"<\", 0, s)\n tag = xmldoc[x + 1:s - 1]\n c = s + len(node_name)\n spaces = \"\"\n while xmldoc[c] == \" \":\n spaces += \" \"\n c += 1\n # Sometimes we get an xml header, sometimes we don't.\n subelem_str = str(subelem)\n if subelem_str[0:5].lower() == '<?xml':\n subelem_str = subelem_str.split(\"\\n\", 1)[1]\n xmldoc = xmldoc.replace(\n \"<%s:%s%s/>\" % (tag, node_name, spaces),\n \"<%s:%s%s>%s</%s:%s>\" % (tag, node_name, spaces, subelem_str, tag,\n node_name))", " return xmldoc", "\ndef for_me(condition, me):\n for restriction in condition.audience_restriction:\n audience = restriction.audience\n if audience.text.strip() == me:\n return True", "\ndef ava(attribute_statement):\n result = {}\n for attribute in attribute_statement.attribute:\n # Check name_format ??\n name = attribute.name.strip()\n result[name] = []\n for value in attribute.attribute_value:\n result[name].append(value.text.strip())\n return result", "\ndef _leq(l1, l2):\n return set(l1) == set(l2)", "\n# def test_parse_3():\n# xml_response = open(XML_RESPONSE_FILE3).read()\n# response = samlp.response_from_string(xml_response)\n# client = Saml2Client({})\n# (ava, name_id, real_uri) = \\\n# client.do_response(response, \"xenosmilus.umdc.umu.se\")\n# print(40*\"=\")\n# print(ava)\n# print(40*\",\")\n# print(name_id)\n# assert False", "REQ1 = {\"1.2.14\": \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n<ns0:AttributeQuery Destination=\"https://idp.example.com/idp/\" ID=\"id1\"\nIssueInstant=\"%s\" Version=\"2.0\" xmlns:ns0=\"urn:oasis:names:tc:SAML:2\n.0:protocol\"><ns1:Issuer Format=\"urn:oasis:names:tc:SAML:2\n.0:nameid-format:entity\" xmlns:ns1=\"urn:oasis:names:tc:SAML:2\n.0:assertion\">urn:mace:example.com:saml:roland:sp</ns1:Issuer><ns1:Subject\nxmlns:ns1=\"urn:oasis:names:tc:SAML:2.0:assertion\"><ns1:NameID\nFormat=\"urn:oasis:names:tc:SAML:2\n.0:nameid-format:persistent\">E8042FB4-4D5B-48C3-8E14-8EDD852790DD</ns1:NameID\n></ns1:Subject></ns0:AttributeQuery>\"\"\",\n \"1.2.16\": \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n<ns0:AttributeQuery xmlns:ns0=\"urn:oasis:names:tc:SAML:2.0:protocol\"\nxmlns:ns1=\"urn:oasis:names:tc:SAML:2.0:assertion\" Destination=\"https://idp\n.example.com/idp/\" ID=\"id1\" IssueInstant=\"%s\" Version=\"2.0\"><ns1:Issuer\nFormat=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">urn:mace:example\n.com:saml:roland:sp</ns1:Issuer><ns1:Subject><ns1:NameID\nFormat=\"urn:oasis:names:tc:SAML:2\n.0:nameid-format:persistent\">E8042FB4-4D5B-48C3-8E14-8EDD852790DD</ns1:NameID\n></ns1:Subject></ns0:AttributeQuery>\"\"\"}", "nid = NameID(name_qualifier=\"foo\", format=NAMEID_FORMAT_TRANSIENT,\n text=\"123456\")", "\ndef list_values2simpletons(_dict):\n return dict([(k, v[0]) for k, v in _dict.items()])", "\nclass TestClient:\n def setup_class(self):\n self.server = Server(\"idp_conf\")", " conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n self.client = Saml2Client(conf)", " def teardown_class(self):\n self.server.close()", " def test_create_attribute_query1(self):\n req_id, req = self.client.create_attribute_query(\n \"https://idp.example.com/idp/\",\n \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\",\n format=saml.NAMEID_FORMAT_PERSISTENT,\n message_id=\"id1\")\n reqstr = \"%s\" % req.to_string().decode('utf-8')", " assert req.destination == \"https://idp.example.com/idp/\"\n assert req.id == \"id1\"\n assert req.version == \"2.0\"\n subject = req.subject\n name_id = subject.name_id\n assert name_id.format == saml.NAMEID_FORMAT_PERSISTENT\n assert name_id.text == \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\"\n issuer = req.issuer\n assert issuer.text == \"urn:mace:example.com:saml:roland:sp\"", " attrq = samlp.attribute_query_from_string(reqstr)", " print(attrq.keyswv())\n assert _leq(attrq.keyswv(), ['destination', 'subject', 'issue_instant',\n 'version', 'id', 'issuer'])", " assert attrq.destination == req.destination\n assert attrq.id == req.id\n assert attrq.version == req.version\n assert attrq.issuer.text == issuer.text\n assert attrq.issue_instant == req.issue_instant\n assert attrq.subject.name_id.format == name_id.format\n assert attrq.subject.name_id.text == name_id.text", " def test_create_attribute_query2(self):\n req_id, req = self.client.create_attribute_query(\n \"https://idp.example.com/idp/\",\n \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\",\n attribute={\n (\"urn:oid:2.5.4.42\",\n \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\",\n \"givenName\"): None,\n (\"urn:oid:2.5.4.4\",\n \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\",\n \"surname\"): None,\n (\"urn:oid:1.2.840.113549.1.9.1\",\n \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"): None,\n },\n format=saml.NAMEID_FORMAT_PERSISTENT,\n message_id=\"id1\")", " print(req.to_string())\n assert req.destination == \"https://idp.example.com/idp/\"\n assert req.id == \"id1\"\n assert req.version == \"2.0\"\n subject = req.subject\n name_id = subject.name_id\n assert name_id.format == saml.NAMEID_FORMAT_PERSISTENT\n assert name_id.text == \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\"\n assert len(req.attribute) == 3\n # one is givenName\n seen = []\n for attribute in req.attribute:\n if attribute.name == \"urn:oid:2.5.4.42\":\n assert attribute.name_format == saml.NAME_FORMAT_URI\n assert attribute.friendly_name == \"givenName\"\n seen.append(\"givenName\")\n elif attribute.name == \"urn:oid:2.5.4.4\":\n assert attribute.name_format == saml.NAME_FORMAT_URI\n assert attribute.friendly_name == \"surname\"\n seen.append(\"surname\")\n elif attribute.name == \"urn:oid:1.2.840.113549.1.9.1\":\n assert attribute.name_format == saml.NAME_FORMAT_URI\n if getattr(attribute, \"friendly_name\"):\n assert False\n seen.append(\"email\")\n assert _leq(seen, [\"givenName\", \"surname\", \"email\"])", " def test_create_attribute_query_3(self):\n req_id, req = self.client.create_attribute_query(\n \"https://aai-demo-idp.switch.ch/idp/shibboleth\",\n \"_e7b68a04488f715cda642fbdd90099f5\",\n format=saml.NAMEID_FORMAT_TRANSIENT,\n message_id=\"id1\")", " assert isinstance(req, samlp.AttributeQuery)\n assert req.destination == \"https://aai-demo-idp.switch\" \\\n \".ch/idp/shibboleth\"\n assert req.id == \"id1\"\n assert req.version == \"2.0\"\n assert req.issue_instant\n assert req.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n nameid = req.subject.name_id\n assert nameid.format == saml.NAMEID_FORMAT_TRANSIENT\n assert nameid.text == \"_e7b68a04488f715cda642fbdd90099f5\"", " def test_create_auth_request_0(self):\n ar_str = \"%s\" % self.client.create_authn_request(\n \"http://www.example.com/sso\", message_id=\"id1\")[1]", " ar = samlp.authn_request_from_string(ar_str)\n print(ar)\n assert ar.assertion_consumer_service_url == (\"http://lingon.catalogix\"\n \".se:8087/\")\n assert ar.destination == \"http://www.example.com/sso\"\n assert ar.protocol_binding == BINDING_HTTP_POST\n assert ar.version == \"2.0\"\n assert ar.provider_name == \"urn:mace:example.com:saml:roland:sp\"\n assert ar.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n nid_policy = ar.name_id_policy\n assert nid_policy.allow_create == \"false\"\n assert nid_policy.format == saml.NAMEID_FORMAT_TRANSIENT", " def test_create_auth_request_vo(self):\n assert list(self.client.config.vorg.keys()) == [\n \"urn:mace:example.com:it:tek\"]", " ar_str = \"%s\" % self.client.create_authn_request(\n \"http://www.example.com/sso\",\n \"urn:mace:example.com:it:tek\", # vo\n nameid_format=NAMEID_FORMAT_PERSISTENT,\n message_id=\"666\")[1]", " ar = samlp.authn_request_from_string(ar_str)\n print(ar)\n assert ar.id == \"666\"\n assert ar.assertion_consumer_service_url == \"http://lingon.catalogix\" \\\n \".se:8087/\"\n assert ar.destination == \"http://www.example.com/sso\"\n assert ar.protocol_binding == BINDING_HTTP_POST\n assert ar.version == \"2.0\"\n assert ar.provider_name == \"urn:mace:example.com:saml:roland:sp\"\n assert ar.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n nid_policy = ar.name_id_policy\n assert nid_policy.allow_create == \"false\"\n assert nid_policy.format == saml.NAMEID_FORMAT_PERSISTENT\n assert nid_policy.sp_name_qualifier == \"urn:mace:example.com:it:tek\"", " def test_sign_auth_request_0(self):\n # print(self.client.config)", " req_id, areq = self.client.create_authn_request(\n \"http://www.example.com/sso\", sign=True, message_id=\"id1\")", " ar_str = \"%s\" % areq\n ar = samlp.authn_request_from_string(ar_str)", " assert ar\n assert ar.signature\n assert ar.signature.signature_value\n signed_info = ar.signature.signed_info\n # print(signed_info)\n assert len(signed_info.reference) == 1\n assert signed_info.reference[0].uri == \"#id1\"\n assert signed_info.reference[0].digest_value\n print(\"------------------------------------------------\")\n try:\n assert self.client.sec.correctly_signed_authn_request(\n ar_str, self.client.config.xmlsec_binary,\n self.client.config.metadata)\n except Exception: # missing certificate\n self.client.sec.verify_signature(ar_str, node_name=class_name(ar))", " def test_create_logout_request(self):\n req_id, req = self.client.create_logout_request(\n \"http://localhost:8088/slo\", \"urn:mace:example.com:saml:roland:idp\",\n name_id=nid, reason=\"Tired\", expire=in_a_while(minutes=15),\n session_indexes=[\"_foo\"])", " assert req.destination == \"http://localhost:8088/slo\"\n assert req.reason == \"Tired\"\n assert req.version == \"2.0\"\n assert req.name_id == nid\n assert req.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n assert req.session_index == [SessionIndex(\"_foo\")]", " def test_response_1(self):\n IDP = \"urn:mace:example.com:saml:roland:idp\"", " ava = {\"givenName\": [\"Derek\"], \"surName\": [\"Jeter\"],\n \"mail\": [\"derek@nyy.mlb.com\"], \"title\": [\"The man\"]}", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id_policy=nameid_policy,\n userid=\"foba0001@example.com\",\n authn=AUTHN)", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " assert authn_response is not None\n assert authn_response.issuer() == IDP\n assert authn_response.response.assertion[0].issuer.text == IDP\n session_info = authn_response.session_info()", " print(session_info)\n assert session_info[\"ava\"] == {'mail': ['derek@nyy.mlb.com'],\n 'givenName': ['Derek'],\n 'sn': ['Jeter'],\n 'title': [\"The man\"]}\n assert session_info[\"issuer\"] == IDP\n assert session_info[\"came_from\"] == \"http://foo.example.com/service\"\n response = samlp.response_from_string(authn_response.xmlstr)\n assert response.destination == \"http://lingon.catalogix.se:8087/\"\n assert \"session_index\" in session_info", " # One person in the cache\n assert len(self.client.users.subjects()) == 1\n subject_id = self.client.users.subjects()[0]\n print(\"||||\", self.client.users.get_info_from(subject_id, IDP))\n # The information I have about the subject comes from one source\n assert self.client.users.issuers_of_info(subject_id) == [IDP]", " # --- authenticate another person", " ava = {\"givenName\": [\"Alfonson\"], \"surName\": [\"Soriano\"],\n \"mail\": [\"alfonson@chc.mlb.com\"], \"title\": [\"outfielder\"]}", " resp_str = \"%s\" % self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id2\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id_policy=nameid_policy,\n userid=\"also0001@example.com\",\n authn=AUTHN)", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id2\": \"http://foo.example.com/service\"})", " # Two persons in the cache\n assert len(self.client.users.subjects()) == 2\n issuers = [self.client.users.issuers_of_info(s) for s in\n self.client.users.subjects()]\n # The information I have about the subjects comes from the same source\n print(issuers)\n assert issuers == [[IDP], [IDP]]", " def test_response_2(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " cert_str, cert_key_str = generate_cert()", " cert = \\\n {\n \"cert\": cert_str,\n \"key\": cert_key_str\n }", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=False,\n encrypt_assertion_self_contained=True,\n pefim=True,\n encrypt_cert_advice=cert_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"}, {\"id1\": cert})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_3(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=False,\n encrypt_assertion_self_contained=True,\n pefim=True,\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_4(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n pefim=True,\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_5(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " cert_str, cert_key_str = generate_cert()", " cert = \\\n {\n \"cert\": cert_str,\n \"key\": cert_key_str\n }", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n pefim=True,\n encrypt_cert_assertion=cert_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"}, {\"id1\": cert})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_6(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " cert_assertion_str, cert_key_assertion_str = generate_cert()", " cert_assertion = \\\n {\n \"cert\": cert_assertion_str,\n \"key\": cert_key_assertion_str\n }", " cert_advice_str, cert_key_advice_str = generate_cert()", " cert_advice = \\\n {\n \"cert\": cert_advice_str,\n \"key\": cert_key_advice_str\n }", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n pefim=True,\n encrypt_cert_assertion=cert_assertion_str,\n encrypt_cert_advice=cert_advice_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"},\n {\"id1\": [cert_assertion, cert_advice]})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_7(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n encrypted_advice_attributes=True,\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_8(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " cert_str, cert_key_str = generate_cert()", " cert = \\\n {\n \"cert\": cert_str,\n \"key\": cert_key_str\n }", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n encrypt_cert_assertion=cert_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"}, {\"id1\": cert})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def setup_verify_authn_response(self):\n idp = \"urn:mace:example.com:saml:roland:idp\"\n ava = {\"givenName\": [\"Derek\"], \"surName\": [\"Jeter\"],\n \"mail\": [\"derek@nyy.mlb.com\"], \"title\": [\"The man\"]}\n ava_verify = {'mail': ['derek@nyy.mlb.com'], 'givenName': ['Derek'],\n 'sn': ['Jeter'], 'title': [\"The man\"]}\n nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)\n return idp, ava, ava_verify, nameid_policy", " def verify_authn_response(self, idp, authn_response, _client, ava_verify):\n assert authn_response is not None\n assert authn_response.issuer() == idp\n assert authn_response.assertion.issuer.text == idp\n session_info = authn_response.session_info()", " assert session_info[\"ava\"] == ava_verify\n assert session_info[\"issuer\"] == idp\n assert session_info[\"came_from\"] == \"http://foo.example.com/service\"\n response = samlp.response_from_string(authn_response.xmlstr)\n assert response.destination == \"http://lingon.catalogix.se:8087/\"", " # One person in the cache\n assert len(_client.users.subjects()) == 1\n subject_id = _client.users.subjects()[0]\n # The information I have about the subject comes from one source\n assert _client.users.issuers_of_info(subject_id) == [idp]", " def test_init_values(self):\n entityid = self.client.config.entityid\n print(entityid)\n assert entityid == \"urn:mace:example.com:saml:roland:sp\"\n print(self.client.metadata.with_descriptor(\"idpsso\"))\n location = self.client._sso_location()\n print(location)\n assert location == 'http://localhost:8088/sso'\n my_name = self.client._my_name()\n print(my_name)\n assert my_name == \"urn:mace:example.com:saml:roland:sp\"", " def test_sign_then_encrypt_assertion(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " assertion = s_utils.assertion_factory(\n subject=factory(saml.Subject, text=\"_aaa\",\n name_id=factory(\n saml.NameID,\n format=saml.NAMEID_FORMAT_TRANSIENT)),\n attribute_statement=do_attribute_statement(\n {\n (\"\", \"\", \"surName\"): (\"Jeter\", \"\"),\n (\"\", \"\", \"givenName\"): (\"Derek\", \"\"),\n }\n ),\n issuer=self.server._issuer(),\n )", " assertion.signature = sigver.pre_signature_part(\n assertion.id, _sec.my_cert, 1)", " sigass = _sec.sign_statement(assertion, class_name(assertion),\n key_file=full_path(\"test.key\"),\n node_id=assertion.id)\n # Create an Assertion instance from the signed assertion\n _ass = saml.assertion_from_string(sigass)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"https:#www.example.com\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer(),\n assertion=_ass\n )", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part())", " seresp = samlp.response_from_string(enctext)", " # Now over to the client side\n _csec = self.client.sec\n if seresp.encrypted_assertion:\n decr_text = _csec.decrypt(enctext)\n seresp = samlp.response_from_string(decr_text)\n resp_ass = []", " sign_cert_file = full_path(\"test.pem\")\n for enc_ass in seresp.encrypted_assertion:\n assers = extension_elements_to_elements(\n enc_ass.extension_elements, [saml, samlp])\n for ass in assers:\n if ass.signature:\n if not _csec.verify_signature(\"%s\" % ass,\n sign_cert_file,\n node_name=class_name(\n ass)):\n continue\n resp_ass.append(ass)", " seresp.assertion = resp_ass\n seresp.encrypted_assertion = None\n # print(_sresp)", " assert seresp.assertion", " def test_sign_then_encrypt_assertion2(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " asser = Assertion({\"givenName\": \"Derek\", \"surName\": \"Jeter\"})\n farg = add_path(\n {},\n ['assertion', 'subject', 'subject_confirmation', 'method',\n saml.SCM_BEARER])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'in_response_to',\n '_012345'])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'recipient',\n \"http://lingon.catalogix.se:8087/\"])", " assertion = asser.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n name_id=factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n farg=farg['assertion']\n )", " assertion.signature = sigver.pre_signature_part(\n assertion.id, _sec.my_cert, 1)", " sigass = _sec.sign_statement(assertion, class_name(assertion),\n key_file=self.client.sec.key_file,\n node_id=assertion.id)", " sigass = rm_xmltag(sigass)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"http://lingon.catalogix.se:8087/\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer(),\n encrypted_assertion=EncryptedAssertion()\n )", " xmldoc = \"%s\" % response\n # strangely enough I get different tags if I run this test separately\n # or as part of a bunch of tests.\n xmldoc = add_subelement(xmldoc, \"EncryptedAssertion\", sigass)", " enctext = _sec.crypto.encrypt_assertion(xmldoc,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part())", " # seresp = samlp.response_from_string(enctext)", " resp_str = base64.encodestring(enctext.encode('utf-8'))\n # Now over to the client side\n resp = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"_012345\": \"http://foo.example.com/service\"})", " # assert resp.encrypted_assertion == []\n assert resp.assertion\n assert resp.ava == {'givenName': ['Derek'], 'sn': ['Jeter']}", " def test_sign_then_encrypt_assertion_advice_1(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " asser = Assertion({\"givenName\": \"Derek\", \"surName\": \"Jeter\"})", " subject_confirmation_specs = {\n 'recipient': \"http://lingon.catalogix.se:8087/\",\n 'in_response_to': \"_012345\",\n 'subject_confirmation_method': saml.SCM_BEARER\n }\n name_id = factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT)", " farg = add_path(\n {},\n ['assertion', 'subject', 'subject_confirmation', 'method',\n saml.SCM_BEARER])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'in_response_to',\n '_012345'])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'recipient',\n \"http://lingon.catalogix.se:8087/\"])", " assertion = asser.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n name_id=name_id,\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n farg=farg['assertion'])", " a_asser = Assertion({\"uid\": \"test01\", \"email\": \"test.testsson@test.se\"})\n a_assertion = a_asser.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_assertion.signature = sigver.pre_signature_part(\n a_assertion.id, _sec.my_cert, 1)", " assertion.advice = Advice()", " assertion.advice.encrypted_assertion = []\n assertion.advice.encrypted_assertion.append(EncryptedAssertion())", " assertion.advice.encrypted_assertion[0].add_extension_element(\n a_assertion)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"http://lingon.catalogix.se:8087/\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer()\n )", " response.assertion.append(assertion)", " response = _sec.sign_statement(\"%s\" % response, class_name(a_assertion),\n key_file=self.client.sec.key_file,\n node_id=a_assertion.id)", " # xmldoc = \"%s\" % response\n # strangely enough I get different tags if I run this test separately\n # or as part of a bunch of tests.\n # xmldoc = add_subelement(xmldoc, \"EncryptedAssertion\", sigass)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " # seresp = samlp.response_from_string(enctext)", " resp_str = base64.encodestring(enctext.encode('utf-8'))\n # Now over to the client side\n resp = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"_012345\": \"http://foo.example.com/service\"})", " # assert resp.encrypted_assertion == []\n assert resp.assertion\n assert resp.assertion.advice\n assert resp.assertion.advice.assertion\n assert resp.ava == \\\n {'sn': ['Jeter'], 'givenName': ['Derek'], 'uid': ['test01'],\n 'email': ['test.testsson@test.se']}", " def test_sign_then_encrypt_assertion_advice_2(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " asser_1 = Assertion({\"givenName\": \"Derek\"})", " farg = add_path(\n {},\n ['assertion', 'subject', 'subject_confirmation', 'method',\n saml.SCM_BEARER])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'in_response_to',\n '_012345'])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'recipient',\n \"http://lingon.catalogix.se:8087/\"])\n name_id = factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT)", " assertion_1 = asser_1.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " asser_2 = Assertion({\"surName\": \"Jeter\"})", " assertion_2 = asser_2.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_1 = Assertion({\"uid\": \"test01\"})\n a_assertion_1 = a_asser_1.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_2 = Assertion({\"email\": \"test.testsson@test.se\"})\n a_assertion_2 = a_asser_2.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_3 = Assertion({\"street\": \"street\"})\n a_assertion_3 = a_asser_3.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_4 = Assertion({\"title\": \"title\"})\n a_assertion_4 = a_asser_4.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_assertion_1.signature = sigver.pre_signature_part(\n a_assertion_1.id, _sec.my_cert, 1)", " a_assertion_2.signature = sigver.pre_signature_part(\n a_assertion_2.id, _sec.my_cert, 1)", " a_assertion_3.signature = sigver.pre_signature_part(\n a_assertion_3.id, _sec.my_cert, 1)", " a_assertion_4.signature = sigver.pre_signature_part(\n a_assertion_4.id, _sec.my_cert, 1)", " assertion_1.signature = sigver.pre_signature_part(assertion_1.id,\n _sec.my_cert, 1)", " assertion_2.signature = sigver.pre_signature_part(assertion_2.id,\n _sec.my_cert, 1)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"http://lingon.catalogix.se:8087/\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer()\n )", " response.assertion = assertion_1", " response.assertion.advice = Advice()", " response.assertion.advice.encrypted_assertion = []\n response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())", " response.assertion.advice.encrypted_assertion[0].add_extension_element(\n a_assertion_1)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_1._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_1),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_1.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response.assertion = response.assertion[0]", " response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())\n response.assertion.advice.encrypted_assertion[1].add_extension_element(\n a_assertion_2)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_2._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_2),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_2.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response.assertion = response.assertion[0]", " assertion_tag = response.assertion._to_element_tree().tag\n response = pre_encrypt_assertion(response)\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_encrypted_assertion(\n assertion_tag)", " response = _sec.sign_statement(\"%s\" % response, class_name(assertion_1),\n key_file=self.server.sec.key_file,\n node_id=assertion_1.id)", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part())", " response = samlp.response_from_string(enctext)", " response.assertion = assertion_2", " response.assertion.advice = Advice()", " response.assertion.advice.encrypted_assertion = []\n response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())", " response.assertion.advice.encrypted_assertion[0].add_extension_element(\n a_assertion_3)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_3._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_3),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_3.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response.assertion = response.assertion[0]", " response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())", " response.assertion.advice.encrypted_assertion[1].add_extension_element(\n a_assertion_4)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_4._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_4),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_4.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(response.assertion[0]),\n key_file=self.server.sec.key_file,\n node_id=response.assertion[0].id)", " response = samlp.response_from_string(response)", " # seresp = samlp.response_from_string(enctext)", " resp_str = base64.encodestring(str(response).encode('utf-8'))\n # Now over to the client side\n resp = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"_012345\": \"http://foo.example.com/service\"})", " # assert resp.encrypted_assertion == []\n assert resp.assertion\n assert resp.assertion.advice\n assert resp.assertion.advice.assertion\n assert resp.ava == \\\n {'street': ['street'], 'uid': ['test01'], 'title': ['title'],\n 'givenName': ['Derek'], 'email':\n ['test.testsson@test.se'], 'sn': ['Jeter']}", " def test_signed_redirect(self):", " msg_str = \"%s\" % self.client.create_authn_request(\n \"http://localhost:8088/sso\", message_id=\"id1\")[1]", " info = self.client.apply_binding(\n BINDING_HTTP_REDIRECT, msg_str, destination=\"\",\n relay_state=\"relay2\", sigalg=SIG_RSA_SHA256)", " loc = info[\"headers\"][0][1]\n qs = parse_qs(loc[1:])\n assert _leq(qs.keys(),\n ['SigAlg', 'SAMLRequest', 'RelayState', 'Signature'])", " assert verify_redirect_signature(list_values2simpletons(qs),\n self.client.sec.sec_backend)", " res = self.server.parse_authn_request(qs[\"SAMLRequest\"][0],\n BINDING_HTTP_REDIRECT)\n print(res)", " def test_do_logout_signed_redirect(self):\n conf = config.SPConfig()\n conf.load_file(\"sp_slo_redirect_conf\")\n client = Saml2Client(conf)", " # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": in_a_while(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n }\n }\n client.users.add_information_about_person(session_info)\n entity_ids = client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]", " resp = client.do_logout(nid, entity_ids, \"Tired\", in_a_while(minutes=5),\n sign=True,\n expected_binding=BINDING_HTTP_REDIRECT)", " assert list(resp.keys()) == entity_ids\n binding, info = resp[entity_ids[0]]\n assert binding == BINDING_HTTP_REDIRECT", " loc = info[\"headers\"][0][1]\n _, _, _, _, qs, _ = urlparse(loc)\n qs = parse_qs(qs)\n assert _leq(qs.keys(),\n ['SigAlg', 'SAMLRequest', 'RelayState', 'Signature'])", " assert verify_redirect_signature(list_values2simpletons(qs),\n client.sec.sec_backend)", " res = self.server.parse_logout_request(qs[\"SAMLRequest\"][0],\n BINDING_HTTP_REDIRECT)\n print(res)", " def test_do_logout_post(self):\n # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": in_a_while(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n },\n \"session_index\": SessionIndex(\"_foo\")\n }\n self.client.users.add_information_about_person(session_info)\n entity_ids = self.client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]\n resp = self.client.do_logout(nid, entity_ids, \"Tired\",\n in_a_while(minutes=5), sign=True,\n expected_binding=BINDING_HTTP_POST)\n assert resp\n assert len(resp) == 1\n assert list(resp.keys()) == entity_ids\n binding, info = resp[entity_ids[0]]\n assert binding == BINDING_HTTP_POST", " _dic = unpack_form(info[\"data\"][3])\n res = self.server.parse_logout_request(_dic[\"SAMLRequest\"],\n BINDING_HTTP_POST)\n assert b'<ns0:SessionIndex>_foo</ns0:SessionIndex>' in res.xmlstr", " def test_do_logout_session_expired(self):\n # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": a_while_ago(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n },\n \"session_index\": SessionIndex(\"_foo\")\n }\n self.client.users.add_information_about_person(session_info)\n entity_ids = self.client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]\n resp = self.client.do_logout(nid, entity_ids, \"Tired\",\n in_a_while(minutes=5), sign=True,\n expected_binding=BINDING_HTTP_POST)\n assert resp\n assert len(resp) == 1\n assert list(resp.keys()) == entity_ids\n binding, info = resp[entity_ids[0]]\n assert binding == BINDING_HTTP_POST", " _dic = unpack_form(info[\"data\"][3])\n res = self.server.parse_logout_request(_dic[\"SAMLRequest\"],\n BINDING_HTTP_POST)\n assert b'<ns0:SessionIndex>_foo</ns0:SessionIndex>' in res.xmlstr", "\n# Below can only be done with dummy Server\nIDP = \"urn:mace:example.com:saml:roland:idp\"", "\nclass TestClientWithDummy():\n def setup_class(self):\n self.server = FakeIDP(\"idp_all_conf\")", " conf = SPConfig()\n conf.load_file(\"servera_conf\")\n self.client = Saml2Client(conf)", " self.client.send = self.server.receive", " def test_do_authn(self):\n binding = BINDING_HTTP_REDIRECT\n response_binding = BINDING_HTTP_POST\n sid, http_args = self.client.prepare_for_authenticate(\n IDP, \"http://www.example.com/relay_state\",\n binding=binding, response_binding=response_binding)", " assert isinstance(sid, six.string_types)\n assert len(http_args) == 4\n assert http_args[\"headers\"][0][0] == \"Location\"\n assert http_args[\"data\"] == []\n redirect_url = http_args[\"headers\"][0][1]\n _, _, _, _, qs, _ = urlparse(redirect_url)\n qs_dict = parse_qs(qs)\n req = self.server.parse_authn_request(qs_dict[\"SAMLRequest\"][0],\n binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " def test_do_negotiated_authn(self):\n binding = BINDING_HTTP_REDIRECT\n response_binding = BINDING_HTTP_POST\n sid, auth_binding, http_args = \\\n self.client.prepare_for_negotiated_authenticate(\n IDP, \"http://www.example.com/relay_state\",\n binding=binding, response_binding=response_binding)", " assert binding == auth_binding\n assert isinstance(sid, six.string_types)\n assert len(http_args) == 4\n assert http_args[\"headers\"][0][0] == \"Location\"\n assert http_args[\"data\"] == []\n redirect_url = http_args[\"headers\"][0][1]\n _, _, _, _, qs, _ = urlparse(redirect_url)\n qs_dict = parse_qs(qs)\n req = self.server.parse_authn_request(qs_dict[\"SAMLRequest\"][0],\n binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " def test_do_attribute_query(self):\n response = self.client.do_attribute_query(\n IDP, \"_e7b68a04488f715cda642fbdd90099f5\",\n attribute={\"eduPersonAffiliation\": None},\n nameid_format=NAMEID_FORMAT_TRANSIENT)", " def test_logout_1(self):\n \"\"\" one IdP/AA logout from\"\"\"", " # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": in_a_while(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n }\n }\n self.client.users.add_information_about_person(session_info)\n entity_ids = self.client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]\n resp = self.client.global_logout(nid, \"Tired\", in_a_while(minutes=5))\n print(resp)\n assert resp\n assert len(resp) == 1\n assert list(resp.keys()) == entity_ids\n response = resp[entity_ids[0]]\n assert isinstance(response, LogoutResponse)", " def test_post_sso(self):\n binding = BINDING_HTTP_POST\n response_binding = BINDING_HTTP_POST\n sid, http_args = self.client.prepare_for_authenticate(\n \"urn:mace:example.com:saml:roland:idp\", relay_state=\"really\",\n binding=binding, response_binding=response_binding)\n _dic = unpack_form(http_args[\"data\"][3])", " req = self.server.parse_authn_request(_dic[\"SAMLRequest\"], binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " # Normally a response would now be sent back to the users web client\n # Here I fake what the client will do\n # create the form post", " http_args[\"data\"] = urlencode(_dic)\n http_args[\"method\"] = \"POST\"\n http_args[\"dummy\"] = _dic[\"SAMLRequest\"]\n http_args[\"headers\"] = [('Content-type',\n 'application/x-www-form-urlencoded')]", " response = self.client.send(**http_args)\n print(response.text)\n _dic = unpack_form(response.text[3], \"SAMLResponse\")\n resp = self.client.parse_authn_request_response(_dic[\"SAMLResponse\"],\n BINDING_HTTP_POST,\n {sid: \"/\"})\n ac = resp.assertion.authn_statement[0].authn_context\n assert ac.authenticating_authority[0].text == \\\n 'http://www.example.com/login'\n assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD", " def test_negotiated_post_sso(self):\n binding = BINDING_HTTP_POST\n response_binding = BINDING_HTTP_POST\n sid, auth_binding, http_args = self.client.prepare_for_negotiated_authenticate(\n \"urn:mace:example.com:saml:roland:idp\", relay_state=\"really\",\n binding=binding, response_binding=response_binding)\n _dic = unpack_form(http_args[\"data\"][3])", " assert binding == auth_binding", " req = self.server.parse_authn_request(_dic[\"SAMLRequest\"], binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " # Normally a response would now be sent back to the users web client\n # Here I fake what the client will do\n # create the form post", " http_args[\"data\"] = urlencode(_dic)\n http_args[\"method\"] = \"POST\"\n http_args[\"dummy\"] = _dic[\"SAMLRequest\"]\n http_args[\"headers\"] = [('Content-type',\n 'application/x-www-form-urlencoded')]", " response = self.client.send(**http_args)\n print(response.text)\n _dic = unpack_form(response.text[3], \"SAMLResponse\")\n resp = self.client.parse_authn_request_response(_dic[\"SAMLResponse\"],\n BINDING_HTTP_POST,\n {sid: \"/\"})\n ac = resp.assertion.authn_statement[0].authn_context\n assert ac.authenticating_authority[0].text == \\\n 'http://www.example.com/login'\n assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD\n", "", "\n# if __name__ == \"__main__\":\n# tc = TestClient()\n# tc.setup_class()\n# tc.test_response()", "if __name__ == \"__main__\":\n tc = TestClient()\n tc.setup_class()\n tc.test_sign_then_encrypt_assertion()" ]
[ 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-", "import base64\nimport uuid\nimport six\nfrom future.backports.urllib.parse import parse_qs\nfrom future.backports.urllib.parse import urlencode\nfrom future.backports.urllib.parse import urlparse", "from pytest import raises", "\nfrom saml2.argtree import add_path\nfrom saml2.cert import OpenSSLWrapper\nfrom saml2.xmldsig import SIG_RSA_SHA256\nfrom saml2 import BINDING_HTTP_POST\nfrom saml2 import BINDING_HTTP_REDIRECT\nfrom saml2 import config\nfrom saml2 import class_name\nfrom saml2 import extension_elements_to_elements\nfrom saml2 import saml\nfrom saml2 import samlp\nfrom saml2 import sigver\nfrom saml2 import s_utils\nfrom saml2.assertion import Assertion", "from saml2.authn_context import INTERNETPROTOCOLPASSWORD\nfrom saml2.client import Saml2Client\nfrom saml2.config import SPConfig", "from saml2.pack import parse_soap_enveloped_saml", "from saml2.response import LogoutResponse\nfrom saml2.saml import NAMEID_FORMAT_PERSISTENT, EncryptedAssertion, Advice\nfrom saml2.saml import NAMEID_FORMAT_TRANSIENT\nfrom saml2.saml import NameID\nfrom saml2.samlp import SessionIndex\nfrom saml2.server import Server\nfrom saml2.sigver import pre_encryption_part, make_temp, pre_encrypt_assertion\nfrom saml2.sigver import rm_xmltag\nfrom saml2.sigver import verify_redirect_signature\nfrom saml2.s_utils import do_attribute_statement\nfrom saml2.s_utils import factory\nfrom saml2.time_util import in_a_while, a_while_ago", "\nfrom defusedxml.common import EntitiesForbidden", "\nfrom fakeIDP import FakeIDP\nfrom fakeIDP import unpack_form\nfrom pathutils import full_path", "AUTHN = {\n \"class_ref\": INTERNETPROTOCOLPASSWORD,\n \"authn_auth\": \"http://www.example.com/login\"\n}", "\ndef generate_cert():\n sn = uuid.uuid4().urn\n cert_info = {\n \"cn\": \"localhost\",\n \"country_code\": \"se\",\n \"state\": \"ac\",\n \"city\": \"Umea\",\n \"organization\": \"ITS\",\n \"organization_unit\": \"DIRG\"\n }\n osw = OpenSSLWrapper()\n ca_cert_str = osw.read_str_from_file(\n full_path(\"root_cert/localhost.ca.crt\"))\n ca_key_str = osw.read_str_from_file(\n full_path(\"root_cert/localhost.ca.key\"))\n req_cert_str, req_key_str = osw.create_certificate(cert_info, request=True,\n sn=sn, key_length=2048)\n cert_str = osw.create_cert_signed_certificate(ca_cert_str, ca_key_str,\n req_cert_str)\n return cert_str, req_key_str", "\ndef add_subelement(xmldoc, node_name, subelem):\n s = xmldoc.find(node_name)\n if s > 0:\n x = xmldoc.rindex(\"<\", 0, s)\n tag = xmldoc[x + 1:s - 1]\n c = s + len(node_name)\n spaces = \"\"\n while xmldoc[c] == \" \":\n spaces += \" \"\n c += 1\n # Sometimes we get an xml header, sometimes we don't.\n subelem_str = str(subelem)\n if subelem_str[0:5].lower() == '<?xml':\n subelem_str = subelem_str.split(\"\\n\", 1)[1]\n xmldoc = xmldoc.replace(\n \"<%s:%s%s/>\" % (tag, node_name, spaces),\n \"<%s:%s%s>%s</%s:%s>\" % (tag, node_name, spaces, subelem_str, tag,\n node_name))", " return xmldoc", "\ndef for_me(condition, me):\n for restriction in condition.audience_restriction:\n audience = restriction.audience\n if audience.text.strip() == me:\n return True", "\ndef ava(attribute_statement):\n result = {}\n for attribute in attribute_statement.attribute:\n # Check name_format ??\n name = attribute.name.strip()\n result[name] = []\n for value in attribute.attribute_value:\n result[name].append(value.text.strip())\n return result", "\ndef _leq(l1, l2):\n return set(l1) == set(l2)", "\n# def test_parse_3():\n# xml_response = open(XML_RESPONSE_FILE3).read()\n# response = samlp.response_from_string(xml_response)\n# client = Saml2Client({})\n# (ava, name_id, real_uri) = \\\n# client.do_response(response, \"xenosmilus.umdc.umu.se\")\n# print(40*\"=\")\n# print(ava)\n# print(40*\",\")\n# print(name_id)\n# assert False", "REQ1 = {\"1.2.14\": \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n<ns0:AttributeQuery Destination=\"https://idp.example.com/idp/\" ID=\"id1\"\nIssueInstant=\"%s\" Version=\"2.0\" xmlns:ns0=\"urn:oasis:names:tc:SAML:2\n.0:protocol\"><ns1:Issuer Format=\"urn:oasis:names:tc:SAML:2\n.0:nameid-format:entity\" xmlns:ns1=\"urn:oasis:names:tc:SAML:2\n.0:assertion\">urn:mace:example.com:saml:roland:sp</ns1:Issuer><ns1:Subject\nxmlns:ns1=\"urn:oasis:names:tc:SAML:2.0:assertion\"><ns1:NameID\nFormat=\"urn:oasis:names:tc:SAML:2\n.0:nameid-format:persistent\">E8042FB4-4D5B-48C3-8E14-8EDD852790DD</ns1:NameID\n></ns1:Subject></ns0:AttributeQuery>\"\"\",\n \"1.2.16\": \"\"\"<?xml version='1.0' encoding='UTF-8'?>\n<ns0:AttributeQuery xmlns:ns0=\"urn:oasis:names:tc:SAML:2.0:protocol\"\nxmlns:ns1=\"urn:oasis:names:tc:SAML:2.0:assertion\" Destination=\"https://idp\n.example.com/idp/\" ID=\"id1\" IssueInstant=\"%s\" Version=\"2.0\"><ns1:Issuer\nFormat=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">urn:mace:example\n.com:saml:roland:sp</ns1:Issuer><ns1:Subject><ns1:NameID\nFormat=\"urn:oasis:names:tc:SAML:2\n.0:nameid-format:persistent\">E8042FB4-4D5B-48C3-8E14-8EDD852790DD</ns1:NameID\n></ns1:Subject></ns0:AttributeQuery>\"\"\"}", "nid = NameID(name_qualifier=\"foo\", format=NAMEID_FORMAT_TRANSIENT,\n text=\"123456\")", "\ndef list_values2simpletons(_dict):\n return dict([(k, v[0]) for k, v in _dict.items()])", "\nclass TestClient:\n def setup_class(self):\n self.server = Server(\"idp_conf\")", " conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n self.client = Saml2Client(conf)", " def teardown_class(self):\n self.server.close()", " def test_create_attribute_query1(self):\n req_id, req = self.client.create_attribute_query(\n \"https://idp.example.com/idp/\",\n \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\",\n format=saml.NAMEID_FORMAT_PERSISTENT,\n message_id=\"id1\")\n reqstr = \"%s\" % req.to_string().decode('utf-8')", " assert req.destination == \"https://idp.example.com/idp/\"\n assert req.id == \"id1\"\n assert req.version == \"2.0\"\n subject = req.subject\n name_id = subject.name_id\n assert name_id.format == saml.NAMEID_FORMAT_PERSISTENT\n assert name_id.text == \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\"\n issuer = req.issuer\n assert issuer.text == \"urn:mace:example.com:saml:roland:sp\"", " attrq = samlp.attribute_query_from_string(reqstr)", " print(attrq.keyswv())\n assert _leq(attrq.keyswv(), ['destination', 'subject', 'issue_instant',\n 'version', 'id', 'issuer'])", " assert attrq.destination == req.destination\n assert attrq.id == req.id\n assert attrq.version == req.version\n assert attrq.issuer.text == issuer.text\n assert attrq.issue_instant == req.issue_instant\n assert attrq.subject.name_id.format == name_id.format\n assert attrq.subject.name_id.text == name_id.text", " def test_create_attribute_query2(self):\n req_id, req = self.client.create_attribute_query(\n \"https://idp.example.com/idp/\",\n \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\",\n attribute={\n (\"urn:oid:2.5.4.42\",\n \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\",\n \"givenName\"): None,\n (\"urn:oid:2.5.4.4\",\n \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\",\n \"surname\"): None,\n (\"urn:oid:1.2.840.113549.1.9.1\",\n \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"): None,\n },\n format=saml.NAMEID_FORMAT_PERSISTENT,\n message_id=\"id1\")", " print(req.to_string())\n assert req.destination == \"https://idp.example.com/idp/\"\n assert req.id == \"id1\"\n assert req.version == \"2.0\"\n subject = req.subject\n name_id = subject.name_id\n assert name_id.format == saml.NAMEID_FORMAT_PERSISTENT\n assert name_id.text == \"E8042FB4-4D5B-48C3-8E14-8EDD852790DD\"\n assert len(req.attribute) == 3\n # one is givenName\n seen = []\n for attribute in req.attribute:\n if attribute.name == \"urn:oid:2.5.4.42\":\n assert attribute.name_format == saml.NAME_FORMAT_URI\n assert attribute.friendly_name == \"givenName\"\n seen.append(\"givenName\")\n elif attribute.name == \"urn:oid:2.5.4.4\":\n assert attribute.name_format == saml.NAME_FORMAT_URI\n assert attribute.friendly_name == \"surname\"\n seen.append(\"surname\")\n elif attribute.name == \"urn:oid:1.2.840.113549.1.9.1\":\n assert attribute.name_format == saml.NAME_FORMAT_URI\n if getattr(attribute, \"friendly_name\"):\n assert False\n seen.append(\"email\")\n assert _leq(seen, [\"givenName\", \"surname\", \"email\"])", " def test_create_attribute_query_3(self):\n req_id, req = self.client.create_attribute_query(\n \"https://aai-demo-idp.switch.ch/idp/shibboleth\",\n \"_e7b68a04488f715cda642fbdd90099f5\",\n format=saml.NAMEID_FORMAT_TRANSIENT,\n message_id=\"id1\")", " assert isinstance(req, samlp.AttributeQuery)\n assert req.destination == \"https://aai-demo-idp.switch\" \\\n \".ch/idp/shibboleth\"\n assert req.id == \"id1\"\n assert req.version == \"2.0\"\n assert req.issue_instant\n assert req.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n nameid = req.subject.name_id\n assert nameid.format == saml.NAMEID_FORMAT_TRANSIENT\n assert nameid.text == \"_e7b68a04488f715cda642fbdd90099f5\"", " def test_create_auth_request_0(self):\n ar_str = \"%s\" % self.client.create_authn_request(\n \"http://www.example.com/sso\", message_id=\"id1\")[1]", " ar = samlp.authn_request_from_string(ar_str)\n print(ar)\n assert ar.assertion_consumer_service_url == (\"http://lingon.catalogix\"\n \".se:8087/\")\n assert ar.destination == \"http://www.example.com/sso\"\n assert ar.protocol_binding == BINDING_HTTP_POST\n assert ar.version == \"2.0\"\n assert ar.provider_name == \"urn:mace:example.com:saml:roland:sp\"\n assert ar.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n nid_policy = ar.name_id_policy\n assert nid_policy.allow_create == \"false\"\n assert nid_policy.format == saml.NAMEID_FORMAT_TRANSIENT", " def test_create_auth_request_vo(self):\n assert list(self.client.config.vorg.keys()) == [\n \"urn:mace:example.com:it:tek\"]", " ar_str = \"%s\" % self.client.create_authn_request(\n \"http://www.example.com/sso\",\n \"urn:mace:example.com:it:tek\", # vo\n nameid_format=NAMEID_FORMAT_PERSISTENT,\n message_id=\"666\")[1]", " ar = samlp.authn_request_from_string(ar_str)\n print(ar)\n assert ar.id == \"666\"\n assert ar.assertion_consumer_service_url == \"http://lingon.catalogix\" \\\n \".se:8087/\"\n assert ar.destination == \"http://www.example.com/sso\"\n assert ar.protocol_binding == BINDING_HTTP_POST\n assert ar.version == \"2.0\"\n assert ar.provider_name == \"urn:mace:example.com:saml:roland:sp\"\n assert ar.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n nid_policy = ar.name_id_policy\n assert nid_policy.allow_create == \"false\"\n assert nid_policy.format == saml.NAMEID_FORMAT_PERSISTENT\n assert nid_policy.sp_name_qualifier == \"urn:mace:example.com:it:tek\"", " def test_sign_auth_request_0(self):\n # print(self.client.config)", " req_id, areq = self.client.create_authn_request(\n \"http://www.example.com/sso\", sign=True, message_id=\"id1\")", " ar_str = \"%s\" % areq\n ar = samlp.authn_request_from_string(ar_str)", " assert ar\n assert ar.signature\n assert ar.signature.signature_value\n signed_info = ar.signature.signed_info\n # print(signed_info)\n assert len(signed_info.reference) == 1\n assert signed_info.reference[0].uri == \"#id1\"\n assert signed_info.reference[0].digest_value\n print(\"------------------------------------------------\")\n try:\n assert self.client.sec.correctly_signed_authn_request(\n ar_str, self.client.config.xmlsec_binary,\n self.client.config.metadata)\n except Exception: # missing certificate\n self.client.sec.verify_signature(ar_str, node_name=class_name(ar))", " def test_create_logout_request(self):\n req_id, req = self.client.create_logout_request(\n \"http://localhost:8088/slo\", \"urn:mace:example.com:saml:roland:idp\",\n name_id=nid, reason=\"Tired\", expire=in_a_while(minutes=15),\n session_indexes=[\"_foo\"])", " assert req.destination == \"http://localhost:8088/slo\"\n assert req.reason == \"Tired\"\n assert req.version == \"2.0\"\n assert req.name_id == nid\n assert req.issuer.text == \"urn:mace:example.com:saml:roland:sp\"\n assert req.session_index == [SessionIndex(\"_foo\")]", " def test_response_1(self):\n IDP = \"urn:mace:example.com:saml:roland:idp\"", " ava = {\"givenName\": [\"Derek\"], \"surName\": [\"Jeter\"],\n \"mail\": [\"derek@nyy.mlb.com\"], \"title\": [\"The man\"]}", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id_policy=nameid_policy,\n userid=\"foba0001@example.com\",\n authn=AUTHN)", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " assert authn_response is not None\n assert authn_response.issuer() == IDP\n assert authn_response.response.assertion[0].issuer.text == IDP\n session_info = authn_response.session_info()", " print(session_info)\n assert session_info[\"ava\"] == {'mail': ['derek@nyy.mlb.com'],\n 'givenName': ['Derek'],\n 'sn': ['Jeter'],\n 'title': [\"The man\"]}\n assert session_info[\"issuer\"] == IDP\n assert session_info[\"came_from\"] == \"http://foo.example.com/service\"\n response = samlp.response_from_string(authn_response.xmlstr)\n assert response.destination == \"http://lingon.catalogix.se:8087/\"\n assert \"session_index\" in session_info", " # One person in the cache\n assert len(self.client.users.subjects()) == 1\n subject_id = self.client.users.subjects()[0]\n print(\"||||\", self.client.users.get_info_from(subject_id, IDP))\n # The information I have about the subject comes from one source\n assert self.client.users.issuers_of_info(subject_id) == [IDP]", " # --- authenticate another person", " ava = {\"givenName\": [\"Alfonson\"], \"surName\": [\"Soriano\"],\n \"mail\": [\"alfonson@chc.mlb.com\"], \"title\": [\"outfielder\"]}", " resp_str = \"%s\" % self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id2\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id_policy=nameid_policy,\n userid=\"also0001@example.com\",\n authn=AUTHN)", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id2\": \"http://foo.example.com/service\"})", " # Two persons in the cache\n assert len(self.client.users.subjects()) == 2\n issuers = [self.client.users.issuers_of_info(s) for s in\n self.client.users.subjects()]\n # The information I have about the subjects comes from the same source\n print(issuers)\n assert issuers == [[IDP], [IDP]]", " def test_response_2(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " cert_str, cert_key_str = generate_cert()", " cert = \\\n {\n \"cert\": cert_str,\n \"key\": cert_key_str\n }", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=False,\n encrypt_assertion_self_contained=True,\n pefim=True,\n encrypt_cert_advice=cert_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"}, {\"id1\": cert})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_3(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=False,\n encrypt_assertion_self_contained=True,\n pefim=True,\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_4(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n pefim=True,\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_5(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " cert_str, cert_key_str = generate_cert()", " cert = \\\n {\n \"cert\": cert_str,\n \"key\": cert_key_str\n }", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n pefim=True,\n encrypt_cert_assertion=cert_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"}, {\"id1\": cert})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_6(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " cert_assertion_str, cert_key_assertion_str = generate_cert()", " cert_assertion = \\\n {\n \"cert\": cert_assertion_str,\n \"key\": cert_key_assertion_str\n }", " cert_advice_str, cert_key_advice_str = generate_cert()", " cert_advice = \\\n {\n \"cert\": cert_advice_str,\n \"key\": cert_key_advice_str\n }", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n pefim=True,\n encrypt_cert_assertion=cert_assertion_str,\n encrypt_cert_advice=cert_advice_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"},\n {\"id1\": [cert_assertion, cert_advice]})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_7(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n encrypted_advice_attributes=True,\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def test_response_8(self):\n conf = config.SPConfig()\n conf.load_file(\"server_conf\")\n _client = Saml2Client(conf)", " idp, ava, ava_verify, nameid_policy = self.setup_verify_authn_response()", " self.name_id = self.server.ident.transient_nameid(\n \"urn:mace:example.com:saml:roland:sp\", \"id1\")", " cert_str, cert_key_str = generate_cert()", " cert = \\\n {\n \"cert\": cert_str,\n \"key\": cert_key_str\n }", " resp = self.server.create_authn_response(\n identity=ava,\n in_response_to=\"id1\",\n destination=\"http://lingon.catalogix.se:8087/\",\n sp_entity_id=\"urn:mace:example.com:saml:roland:sp\",\n name_id=self.name_id,\n userid=\"foba0001@example.com\",\n authn=AUTHN,\n sign_response=True,\n sign_assertion=True,\n encrypt_assertion=True,\n encrypt_assertion_self_contained=True,\n encrypt_cert_assertion=cert_str\n )", " resp_str = \"%s\" % resp", " resp_str = base64.encodestring(resp_str.encode('utf-8'))", " authn_response = _client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"id1\": \"http://foo.example.com/service\"}, {\"id1\": cert})", " self.verify_authn_response(idp, authn_response, _client, ava_verify)", " def setup_verify_authn_response(self):\n idp = \"urn:mace:example.com:saml:roland:idp\"\n ava = {\"givenName\": [\"Derek\"], \"surName\": [\"Jeter\"],\n \"mail\": [\"derek@nyy.mlb.com\"], \"title\": [\"The man\"]}\n ava_verify = {'mail': ['derek@nyy.mlb.com'], 'givenName': ['Derek'],\n 'sn': ['Jeter'], 'title': [\"The man\"]}\n nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)\n return idp, ava, ava_verify, nameid_policy", " def verify_authn_response(self, idp, authn_response, _client, ava_verify):\n assert authn_response is not None\n assert authn_response.issuer() == idp\n assert authn_response.assertion.issuer.text == idp\n session_info = authn_response.session_info()", " assert session_info[\"ava\"] == ava_verify\n assert session_info[\"issuer\"] == idp\n assert session_info[\"came_from\"] == \"http://foo.example.com/service\"\n response = samlp.response_from_string(authn_response.xmlstr)\n assert response.destination == \"http://lingon.catalogix.se:8087/\"", " # One person in the cache\n assert len(_client.users.subjects()) == 1\n subject_id = _client.users.subjects()[0]\n # The information I have about the subject comes from one source\n assert _client.users.issuers_of_info(subject_id) == [idp]", " def test_init_values(self):\n entityid = self.client.config.entityid\n print(entityid)\n assert entityid == \"urn:mace:example.com:saml:roland:sp\"\n print(self.client.metadata.with_descriptor(\"idpsso\"))\n location = self.client._sso_location()\n print(location)\n assert location == 'http://localhost:8088/sso'\n my_name = self.client._my_name()\n print(my_name)\n assert my_name == \"urn:mace:example.com:saml:roland:sp\"", " def test_sign_then_encrypt_assertion(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " assertion = s_utils.assertion_factory(\n subject=factory(saml.Subject, text=\"_aaa\",\n name_id=factory(\n saml.NameID,\n format=saml.NAMEID_FORMAT_TRANSIENT)),\n attribute_statement=do_attribute_statement(\n {\n (\"\", \"\", \"surName\"): (\"Jeter\", \"\"),\n (\"\", \"\", \"givenName\"): (\"Derek\", \"\"),\n }\n ),\n issuer=self.server._issuer(),\n )", " assertion.signature = sigver.pre_signature_part(\n assertion.id, _sec.my_cert, 1)", " sigass = _sec.sign_statement(assertion, class_name(assertion),\n key_file=full_path(\"test.key\"),\n node_id=assertion.id)\n # Create an Assertion instance from the signed assertion\n _ass = saml.assertion_from_string(sigass)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"https:#www.example.com\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer(),\n assertion=_ass\n )", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part())", " seresp = samlp.response_from_string(enctext)", " # Now over to the client side\n _csec = self.client.sec\n if seresp.encrypted_assertion:\n decr_text = _csec.decrypt(enctext)\n seresp = samlp.response_from_string(decr_text)\n resp_ass = []", " sign_cert_file = full_path(\"test.pem\")\n for enc_ass in seresp.encrypted_assertion:\n assers = extension_elements_to_elements(\n enc_ass.extension_elements, [saml, samlp])\n for ass in assers:\n if ass.signature:\n if not _csec.verify_signature(\"%s\" % ass,\n sign_cert_file,\n node_name=class_name(\n ass)):\n continue\n resp_ass.append(ass)", " seresp.assertion = resp_ass\n seresp.encrypted_assertion = None\n # print(_sresp)", " assert seresp.assertion", " def test_sign_then_encrypt_assertion2(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " asser = Assertion({\"givenName\": \"Derek\", \"surName\": \"Jeter\"})\n farg = add_path(\n {},\n ['assertion', 'subject', 'subject_confirmation', 'method',\n saml.SCM_BEARER])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'in_response_to',\n '_012345'])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'recipient',\n \"http://lingon.catalogix.se:8087/\"])", " assertion = asser.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n name_id=factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n farg=farg['assertion']\n )", " assertion.signature = sigver.pre_signature_part(\n assertion.id, _sec.my_cert, 1)", " sigass = _sec.sign_statement(assertion, class_name(assertion),\n key_file=self.client.sec.key_file,\n node_id=assertion.id)", " sigass = rm_xmltag(sigass)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"http://lingon.catalogix.se:8087/\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer(),\n encrypted_assertion=EncryptedAssertion()\n )", " xmldoc = \"%s\" % response\n # strangely enough I get different tags if I run this test separately\n # or as part of a bunch of tests.\n xmldoc = add_subelement(xmldoc, \"EncryptedAssertion\", sigass)", " enctext = _sec.crypto.encrypt_assertion(xmldoc,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part())", " # seresp = samlp.response_from_string(enctext)", " resp_str = base64.encodestring(enctext.encode('utf-8'))\n # Now over to the client side\n resp = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"_012345\": \"http://foo.example.com/service\"})", " # assert resp.encrypted_assertion == []\n assert resp.assertion\n assert resp.ava == {'givenName': ['Derek'], 'sn': ['Jeter']}", " def test_sign_then_encrypt_assertion_advice_1(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " asser = Assertion({\"givenName\": \"Derek\", \"surName\": \"Jeter\"})", " subject_confirmation_specs = {\n 'recipient': \"http://lingon.catalogix.se:8087/\",\n 'in_response_to': \"_012345\",\n 'subject_confirmation_method': saml.SCM_BEARER\n }\n name_id = factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT)", " farg = add_path(\n {},\n ['assertion', 'subject', 'subject_confirmation', 'method',\n saml.SCM_BEARER])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'in_response_to',\n '_012345'])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'recipient',\n \"http://lingon.catalogix.se:8087/\"])", " assertion = asser.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n name_id=name_id,\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n farg=farg['assertion'])", " a_asser = Assertion({\"uid\": \"test01\", \"email\": \"test.testsson@test.se\"})\n a_assertion = a_asser.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_assertion.signature = sigver.pre_signature_part(\n a_assertion.id, _sec.my_cert, 1)", " assertion.advice = Advice()", " assertion.advice.encrypted_assertion = []\n assertion.advice.encrypted_assertion.append(EncryptedAssertion())", " assertion.advice.encrypted_assertion[0].add_extension_element(\n a_assertion)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"http://lingon.catalogix.se:8087/\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer()\n )", " response.assertion.append(assertion)", " response = _sec.sign_statement(\"%s\" % response, class_name(a_assertion),\n key_file=self.client.sec.key_file,\n node_id=a_assertion.id)", " # xmldoc = \"%s\" % response\n # strangely enough I get different tags if I run this test separately\n # or as part of a bunch of tests.\n # xmldoc = add_subelement(xmldoc, \"EncryptedAssertion\", sigass)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " # seresp = samlp.response_from_string(enctext)", " resp_str = base64.encodestring(enctext.encode('utf-8'))\n # Now over to the client side\n resp = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"_012345\": \"http://foo.example.com/service\"})", " # assert resp.encrypted_assertion == []\n assert resp.assertion\n assert resp.assertion.advice\n assert resp.assertion.advice.assertion\n assert resp.ava == \\\n {'sn': ['Jeter'], 'givenName': ['Derek'], 'uid': ['test01'],\n 'email': ['test.testsson@test.se']}", " def test_sign_then_encrypt_assertion_advice_2(self):\n # Begin with the IdPs side\n _sec = self.server.sec", " nameid_policy = samlp.NameIDPolicy(allow_create=\"false\",\n format=saml.NAMEID_FORMAT_PERSISTENT)", " asser_1 = Assertion({\"givenName\": \"Derek\"})", " farg = add_path(\n {},\n ['assertion', 'subject', 'subject_confirmation', 'method',\n saml.SCM_BEARER])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'in_response_to',\n '_012345'])\n add_path(\n farg['assertion']['subject']['subject_confirmation'],\n ['subject_confirmation_data', 'recipient',\n \"http://lingon.catalogix.se:8087/\"])\n name_id = factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT)", " assertion_1 = asser_1.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " asser_2 = Assertion({\"surName\": \"Jeter\"})", " assertion_2 = asser_2.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_1 = Assertion({\"uid\": \"test01\"})\n a_assertion_1 = a_asser_1.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_2 = Assertion({\"email\": \"test.testsson@test.se\"})\n a_assertion_2 = a_asser_2.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_3 = Assertion({\"street\": \"street\"})\n a_assertion_3 = a_asser_3.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_asser_4 = Assertion({\"title\": \"title\"})\n a_assertion_4 = a_asser_4.construct(\n self.client.config.entityid,\n self.server.config.attribute_converters,\n self.server.config.getattr(\"policy\", \"idp\"),\n issuer=self.server._issuer(),\n authn_class=INTERNETPROTOCOLPASSWORD,\n authn_auth=\"http://www.example.com/login\",\n name_id=name_id,\n farg=farg['assertion'])", " a_assertion_1.signature = sigver.pre_signature_part(\n a_assertion_1.id, _sec.my_cert, 1)", " a_assertion_2.signature = sigver.pre_signature_part(\n a_assertion_2.id, _sec.my_cert, 1)", " a_assertion_3.signature = sigver.pre_signature_part(\n a_assertion_3.id, _sec.my_cert, 1)", " a_assertion_4.signature = sigver.pre_signature_part(\n a_assertion_4.id, _sec.my_cert, 1)", " assertion_1.signature = sigver.pre_signature_part(assertion_1.id,\n _sec.my_cert, 1)", " assertion_2.signature = sigver.pre_signature_part(assertion_2.id,\n _sec.my_cert, 1)", " response = sigver.response_factory(\n in_response_to=\"_012345\",\n destination=\"http://lingon.catalogix.se:8087/\",\n status=s_utils.success_status_factory(),\n issuer=self.server._issuer()\n )", " response.assertion = assertion_1", " response.assertion.advice = Advice()", " response.assertion.advice.encrypted_assertion = []\n response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())", " response.assertion.advice.encrypted_assertion[0].add_extension_element(\n a_assertion_1)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_1._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_1),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_1.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response.assertion = response.assertion[0]", " response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())\n response.assertion.advice.encrypted_assertion[1].add_extension_element(\n a_assertion_2)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_2._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_2),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_2.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response.assertion = response.assertion[0]", " assertion_tag = response.assertion._to_element_tree().tag\n response = pre_encrypt_assertion(response)\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_encrypted_assertion(\n assertion_tag)", " response = _sec.sign_statement(\"%s\" % response, class_name(assertion_1),\n key_file=self.server.sec.key_file,\n node_id=assertion_1.id)", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part())", " response = samlp.response_from_string(enctext)", " response.assertion = assertion_2", " response.assertion.advice = Advice()", " response.assertion.advice.encrypted_assertion = []\n response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())", " response.assertion.advice.encrypted_assertion[0].add_extension_element(\n a_assertion_3)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_3._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_3),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_3.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 0][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response.assertion = response.assertion[0]", " response.assertion.advice.encrypted_assertion.append(\n EncryptedAssertion())", " response.assertion.advice.encrypted_assertion[1].add_extension_element(\n a_assertion_4)", " advice_tag = response.assertion.advice._to_element_tree().tag\n assertion_tag = a_assertion_4._to_element_tree().tag\n response = \\\n response.get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(\n assertion_tag, advice_tag)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(a_assertion_4),\n key_file=self.server.sec.key_file,\n node_id=a_assertion_4.id)", " node_xpath = ''.join([\"/*[local-name()=\\\"%s\\\"]\" % v for v in\n [\"Response\", \"Assertion\", \"Advice\",\n \"EncryptedAssertion\", \"Assertion\"]])", " enctext = _sec.crypto.encrypt_assertion(response,\n self.client.sec.encryption_keypairs[\n 1][\"cert_file\"],\n pre_encryption_part(),\n node_xpath=node_xpath)", " response = samlp.response_from_string(enctext)", " response = _sec.sign_statement(\"%s\" % response,\n class_name(response.assertion[0]),\n key_file=self.server.sec.key_file,\n node_id=response.assertion[0].id)", " response = samlp.response_from_string(response)", " # seresp = samlp.response_from_string(enctext)", " resp_str = base64.encodestring(str(response).encode('utf-8'))\n # Now over to the client side\n resp = self.client.parse_authn_request_response(\n resp_str, BINDING_HTTP_POST,\n {\"_012345\": \"http://foo.example.com/service\"})", " # assert resp.encrypted_assertion == []\n assert resp.assertion\n assert resp.assertion.advice\n assert resp.assertion.advice.assertion\n assert resp.ava == \\\n {'street': ['street'], 'uid': ['test01'], 'title': ['title'],\n 'givenName': ['Derek'], 'email':\n ['test.testsson@test.se'], 'sn': ['Jeter']}", " def test_signed_redirect(self):", " msg_str = \"%s\" % self.client.create_authn_request(\n \"http://localhost:8088/sso\", message_id=\"id1\")[1]", " info = self.client.apply_binding(\n BINDING_HTTP_REDIRECT, msg_str, destination=\"\",\n relay_state=\"relay2\", sigalg=SIG_RSA_SHA256)", " loc = info[\"headers\"][0][1]\n qs = parse_qs(loc[1:])\n assert _leq(qs.keys(),\n ['SigAlg', 'SAMLRequest', 'RelayState', 'Signature'])", " assert verify_redirect_signature(list_values2simpletons(qs),\n self.client.sec.sec_backend)", " res = self.server.parse_authn_request(qs[\"SAMLRequest\"][0],\n BINDING_HTTP_REDIRECT)\n print(res)", " def test_do_logout_signed_redirect(self):\n conf = config.SPConfig()\n conf.load_file(\"sp_slo_redirect_conf\")\n client = Saml2Client(conf)", " # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": in_a_while(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n }\n }\n client.users.add_information_about_person(session_info)\n entity_ids = client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]", " resp = client.do_logout(nid, entity_ids, \"Tired\", in_a_while(minutes=5),\n sign=True,\n expected_binding=BINDING_HTTP_REDIRECT)", " assert list(resp.keys()) == entity_ids\n binding, info = resp[entity_ids[0]]\n assert binding == BINDING_HTTP_REDIRECT", " loc = info[\"headers\"][0][1]\n _, _, _, _, qs, _ = urlparse(loc)\n qs = parse_qs(qs)\n assert _leq(qs.keys(),\n ['SigAlg', 'SAMLRequest', 'RelayState', 'Signature'])", " assert verify_redirect_signature(list_values2simpletons(qs),\n client.sec.sec_backend)", " res = self.server.parse_logout_request(qs[\"SAMLRequest\"][0],\n BINDING_HTTP_REDIRECT)\n print(res)", " def test_do_logout_post(self):\n # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": in_a_while(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n },\n \"session_index\": SessionIndex(\"_foo\")\n }\n self.client.users.add_information_about_person(session_info)\n entity_ids = self.client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]\n resp = self.client.do_logout(nid, entity_ids, \"Tired\",\n in_a_while(minutes=5), sign=True,\n expected_binding=BINDING_HTTP_POST)\n assert resp\n assert len(resp) == 1\n assert list(resp.keys()) == entity_ids\n binding, info = resp[entity_ids[0]]\n assert binding == BINDING_HTTP_POST", " _dic = unpack_form(info[\"data\"][3])\n res = self.server.parse_logout_request(_dic[\"SAMLRequest\"],\n BINDING_HTTP_POST)\n assert b'<ns0:SessionIndex>_foo</ns0:SessionIndex>' in res.xmlstr", " def test_do_logout_session_expired(self):\n # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": a_while_ago(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n },\n \"session_index\": SessionIndex(\"_foo\")\n }\n self.client.users.add_information_about_person(session_info)\n entity_ids = self.client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]\n resp = self.client.do_logout(nid, entity_ids, \"Tired\",\n in_a_while(minutes=5), sign=True,\n expected_binding=BINDING_HTTP_POST)\n assert resp\n assert len(resp) == 1\n assert list(resp.keys()) == entity_ids\n binding, info = resp[entity_ids[0]]\n assert binding == BINDING_HTTP_POST", " _dic = unpack_form(info[\"data\"][3])\n res = self.server.parse_logout_request(_dic[\"SAMLRequest\"],\n BINDING_HTTP_POST)\n assert b'<ns0:SessionIndex>_foo</ns0:SessionIndex>' in res.xmlstr", "\n# Below can only be done with dummy Server\nIDP = \"urn:mace:example.com:saml:roland:idp\"", "\nclass TestClientWithDummy():\n def setup_class(self):\n self.server = FakeIDP(\"idp_all_conf\")", " conf = SPConfig()\n conf.load_file(\"servera_conf\")\n self.client = Saml2Client(conf)", " self.client.send = self.server.receive", " def test_do_authn(self):\n binding = BINDING_HTTP_REDIRECT\n response_binding = BINDING_HTTP_POST\n sid, http_args = self.client.prepare_for_authenticate(\n IDP, \"http://www.example.com/relay_state\",\n binding=binding, response_binding=response_binding)", " assert isinstance(sid, six.string_types)\n assert len(http_args) == 4\n assert http_args[\"headers\"][0][0] == \"Location\"\n assert http_args[\"data\"] == []\n redirect_url = http_args[\"headers\"][0][1]\n _, _, _, _, qs, _ = urlparse(redirect_url)\n qs_dict = parse_qs(qs)\n req = self.server.parse_authn_request(qs_dict[\"SAMLRequest\"][0],\n binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " def test_do_negotiated_authn(self):\n binding = BINDING_HTTP_REDIRECT\n response_binding = BINDING_HTTP_POST\n sid, auth_binding, http_args = \\\n self.client.prepare_for_negotiated_authenticate(\n IDP, \"http://www.example.com/relay_state\",\n binding=binding, response_binding=response_binding)", " assert binding == auth_binding\n assert isinstance(sid, six.string_types)\n assert len(http_args) == 4\n assert http_args[\"headers\"][0][0] == \"Location\"\n assert http_args[\"data\"] == []\n redirect_url = http_args[\"headers\"][0][1]\n _, _, _, _, qs, _ = urlparse(redirect_url)\n qs_dict = parse_qs(qs)\n req = self.server.parse_authn_request(qs_dict[\"SAMLRequest\"][0],\n binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " def test_do_attribute_query(self):\n response = self.client.do_attribute_query(\n IDP, \"_e7b68a04488f715cda642fbdd90099f5\",\n attribute={\"eduPersonAffiliation\": None},\n nameid_format=NAMEID_FORMAT_TRANSIENT)", " def test_logout_1(self):\n \"\"\" one IdP/AA logout from\"\"\"", " # information about the user from an IdP\n session_info = {\n \"name_id\": nid,\n \"issuer\": \"urn:mace:example.com:saml:roland:idp\",\n \"not_on_or_after\": in_a_while(minutes=15),\n \"ava\": {\n \"givenName\": \"Anders\",\n \"surName\": \"Andersson\",\n \"mail\": \"anders.andersson@example.com\"\n }\n }\n self.client.users.add_information_about_person(session_info)\n entity_ids = self.client.users.issuers_of_info(nid)\n assert entity_ids == [\"urn:mace:example.com:saml:roland:idp\"]\n resp = self.client.global_logout(nid, \"Tired\", in_a_while(minutes=5))\n print(resp)\n assert resp\n assert len(resp) == 1\n assert list(resp.keys()) == entity_ids\n response = resp[entity_ids[0]]\n assert isinstance(response, LogoutResponse)", " def test_post_sso(self):\n binding = BINDING_HTTP_POST\n response_binding = BINDING_HTTP_POST\n sid, http_args = self.client.prepare_for_authenticate(\n \"urn:mace:example.com:saml:roland:idp\", relay_state=\"really\",\n binding=binding, response_binding=response_binding)\n _dic = unpack_form(http_args[\"data\"][3])", " req = self.server.parse_authn_request(_dic[\"SAMLRequest\"], binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " # Normally a response would now be sent back to the users web client\n # Here I fake what the client will do\n # create the form post", " http_args[\"data\"] = urlencode(_dic)\n http_args[\"method\"] = \"POST\"\n http_args[\"dummy\"] = _dic[\"SAMLRequest\"]\n http_args[\"headers\"] = [('Content-type',\n 'application/x-www-form-urlencoded')]", " response = self.client.send(**http_args)\n print(response.text)\n _dic = unpack_form(response.text[3], \"SAMLResponse\")\n resp = self.client.parse_authn_request_response(_dic[\"SAMLResponse\"],\n BINDING_HTTP_POST,\n {sid: \"/\"})\n ac = resp.assertion.authn_statement[0].authn_context\n assert ac.authenticating_authority[0].text == \\\n 'http://www.example.com/login'\n assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD", " def test_negotiated_post_sso(self):\n binding = BINDING_HTTP_POST\n response_binding = BINDING_HTTP_POST\n sid, auth_binding, http_args = self.client.prepare_for_negotiated_authenticate(\n \"urn:mace:example.com:saml:roland:idp\", relay_state=\"really\",\n binding=binding, response_binding=response_binding)\n _dic = unpack_form(http_args[\"data\"][3])", " assert binding == auth_binding", " req = self.server.parse_authn_request(_dic[\"SAMLRequest\"], binding)\n resp_args = self.server.response_args(req.message, [response_binding])\n assert resp_args[\"binding\"] == response_binding", " # Normally a response would now be sent back to the users web client\n # Here I fake what the client will do\n # create the form post", " http_args[\"data\"] = urlencode(_dic)\n http_args[\"method\"] = \"POST\"\n http_args[\"dummy\"] = _dic[\"SAMLRequest\"]\n http_args[\"headers\"] = [('Content-type',\n 'application/x-www-form-urlencoded')]", " response = self.client.send(**http_args)\n print(response.text)\n _dic = unpack_form(response.text[3], \"SAMLResponse\")\n resp = self.client.parse_authn_request_response(_dic[\"SAMLResponse\"],\n BINDING_HTTP_POST,\n {sid: \"/\"})\n ac = resp.assertion.authn_statement[0].authn_context\n assert ac.authenticating_authority[0].text == \\\n 'http://www.example.com/login'\n assert ac.authn_context_class_ref.text == INTERNETPROTOCOLPASSWORD\n", "def test_parse_soap_enveloped_saml_xxe():\n xml = \"\"\"<?xml version=\"1.0\"?>\n <!DOCTYPE lolz [\n <!ENTITY lol \"lol\">\n <!ELEMENT lolz (#PCDATA)>\n <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n ]>\n <lolz>&lol1;</lolz>\n \"\"\"\n with raises(EntitiesForbidden):\n parse_soap_enveloped_saml(xml, None)", "\n# if __name__ == \"__main__\":\n# tc = TestClient()\n# tc.setup_class()\n# tc.test_response()", "if __name__ == \"__main__\":\n tc = TestClient()\n tc.setup_class()\n tc.test_sign_then_encrypt_assertion()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 273, 239, 213, 454, 68, 1554], "buggy_code_start_loc": [20, 38, 39, 21, 19, 14, 9], "filenames": ["setup.py", "src/saml2/__init__.py", "src/saml2/pack.py", "src/saml2/soap.py", "tests/test_03_saml2.py", "tests/test_43_soap.py", "tests/test_51_client.py"], "fixing_code_end_loc": [22, 274, 240, 214, 482, 112, 1570], "fixing_code_start_loc": [21, 39, 40, 22, 20, 15, 10], "message": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pysaml2_project:pysaml2:*:*:*:*:*:*:*:*", "matchCriteriaId": "24F2FB4E-4F43-4B09-B01C-1B3FCB88AB2C", "versionEndExcluding": null, "versionEndIncluding": "4.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XML External Entity (XXE) vulnerability in PySAML2 4.4.0 and earlier allows remote attackers to read arbitrary files via a crafted SAML XML request or response."}, {"lang": "es", "value": "Vulnerabilidad de XXE en PySAML2 4.4.0 y versiones anteriores permite a atacantes remotos leer archivos arbitrarios a trav\u00e9s de una solicitud o respuesta SAMPL XML manipulada."}], "evaluatorComment": null, "id": "CVE-2016-10149", "lastModified": "2018-01-05T02:30:31.603", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-03-24T14:59:00.227", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2017/dsa-3759"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/01/19/5"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/97692"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0936"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0937"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2017:0938"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850716"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/issues/366"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/rohe/pysaml2/pull/379"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-611"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/rohe/pysaml2/commit/6e09a25d9b4b7aa7a506853210a9a14100b8bc9b"}, "type": "CWE-611"}
283
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* For licensing terms, see /license.txt */", "/**\n * @package chamilo.social\n *\n * @author Julio Montoya <gugli100@gmail.com>\n */\n$cidReset = true;", "require_once __DIR__.'/../inc/global.inc.php';\n$ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';\napi_block_anonymous_users();", "if (api_get_setting('allow_social_tool') != 'true') {\n api_not_allowed();\n}", "$this_section = SECTION_SOCIAL;\n$tool_name = get_lang('Search');\n$interbreadcrumb[] = [\n 'url' => api_get_path(WEB_CODE_PATH).'social/profile.php',\n 'name' => get_lang('SocialNetwork'),\n];\n", "$query = isset($_GET['q']) ? Security::remove_XSS($_GET['q']) : null;", "$queryNoFilter = isset($_GET['q']) ? $_GET['q'] : null;", "$query_search_type = isset($_GET['search_type']) && in_array($_GET['search_type'], ['0', '1', '2']) ? $_GET['search_type'] : null;\n$extra_fields = UserManager::getExtraFilterableFields();\n$query_vars = ['q' => $query, 'search_type' => $query_search_type];\nif (!empty($extra_fields)) {\n foreach ($extra_fields as $extra_field) {\n $field_name = 'field_'.$extra_field['variable'];\n if (isset($_GET[$field_name]) && $_GET[$field_name] != '0') {\n $query_vars[$field_name] = $_GET[$field_name];\n }\n }\n}", "//Block Social Menu\n$social_menu_block = SocialManager::show_social_menu('search');\n$block_search = '';", "$searchForm = UserManager::get_search_form($queryNoFilter);", "\n$groups = [];\n$totalGroups = [];\n$users = [];\n$totalUsers = [];\n$usergroup = new UserGroup();", "// I'm searching something\nif ($query != '' || ($query_vars['search_type'] == '1' && count($query_vars) > 2)) {\n $itemPerPage = 6;", " if ($_GET['search_type'] == '0' || $_GET['search_type'] == '1') {\n $page = isset($_GET['users_page_nr']) ? intval($_GET['users_page_nr']) : 1;\n $totalUsers = UserManager::get_all_user_tags(\n $_GET['q'],\n 0,\n 0,\n $itemPerPage,\n true\n );", " $from = intval(($page - 1) * $itemPerPage);\n // Get users from tags\n $users = UserManager::get_all_user_tags($_GET['q'], 0, $from, $itemPerPage);\n }", " if ($_GET['search_type'] == '0' || $_GET['search_type'] == '2') {\n $pageGroup = isset($_GET['groups_page_nr']) ? intval($_GET['groups_page_nr']) : 1;\n // Groups\n $fromGroups = intval(($pageGroup - 1) * $itemPerPage);\n $totalGroups = count($usergroup->get_all_group_tags($_GET['q'], 0, $itemPerPage, true));", " $groups = $usergroup->get_all_group_tags($_GET['q'], $fromGroups);\n }", " if (empty($users) && empty($groups)) {\n Display::addFlash(Display::return_message(get_lang('SorryNoResults')));\n }", " $results = '<div id=\"whoisonline\">';\n if (is_array($users) && count($users) > 0) {\n $results .= '<div class=\"row\">';\n $buttonClass = 'btn btn-default btn-sm';\n foreach ($users as $user) {\n $user_info = api_get_user_info($user['id'], true);\n $sendInvitation = '<button class=\"'.$buttonClass.' disabled \">\n <em class=\"fa fa-user\"></em> '.get_lang('SendInvitation').'</button>';\n $relation_type = SocialManager::get_relation_between_contacts(api_get_user_id(), $user_info['user_id']);\n $url = api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_info['user_id'];", " // Show send invitation icon if they are not friends yet\n if ($relation_type != 3 && $relation_type != 4 && $user_info['user_id'] != api_get_user_id()) {\n $sendInvitation = '<a href=\"#\" class=\"'.$buttonClass.' btn-to-send-invitation\" data-send-to=\"'.$user_info['user_id'].'\">\n <em class=\"fa fa-user\"></em> '.get_lang('SendInvitation').'</a>';\n }", " $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([\n 'a' => 'get_user_popup',\n 'user_id' => $user_info['user_id'],\n ]);", " $sendMessage = Display::toolbarButton(\n get_lang('SendMessage'),\n $sendMessageUrl,\n 'envelope',\n 'default',\n [\n 'class' => 'ajax btn-sm',\n 'data-title' => get_lang('SendMessage'),\n ]\n );", " if (!empty($user_info['user_is_online'])) {\n $status_icon = Display::return_icon('online.png', get_lang('OnLine'), null, ICON_SIZE_TINY);\n } else {\n $status_icon = Display::return_icon('offline.png', get_lang('Disconnected'), null, ICON_SIZE_TINY);\n }", " if ($user_info['status'] == 5) {\n $user_icon = Display::return_icon('user.png', get_lang('Student'), null, ICON_SIZE_TINY);\n } else {\n $user_icon = Display::return_icon('teacher.png', get_lang('Teacher'), null, ICON_SIZE_TINY);\n }", " $user_info['complete_name'] = Display::url($user_info['complete_name'], $url);\n $invitations = $sendInvitation.$sendMessage;", " $results .= Display::getUserCard(\n $user_info,\n $status_icon.$user_icon,\n $invitations\n );\n }\n $results .= '</div>';\n }\n $results .= '</div>';", " $visibility = [true, true, true, true, true];", " if (!empty($users)) {\n $results .= Display::return_sortable_grid(\n 'users',\n null,\n null,\n ['hide_navigation' => false, 'per_page' => $itemPerPage],\n $query_vars,\n false,\n $visibility,\n true,\n [],\n $totalUsers\n );\n $block_search .= Display::panelCollapse(\n get_lang('Users'),\n $results,\n 'search-friends',\n null,\n 'friends-accordion',\n 'friends-collapse'\n );\n }", " $grid_groups = [];\n $block_groups = '<div id=\"whoisonline\">';\n if (is_array($groups) && count($groups) > 0) {\n $block_groups .= '<div class=\"row\">';\n foreach ($groups as $group) {\n $group['name'] = Security::remove_XSS($group['name'], STUDENT, true);\n $group['description'] = Security::remove_XSS($group['description'], STUDENT, true);\n $id = $group['id'];\n $url_open = '<a href=\"group_view.php?id='.$id.'\">';\n $url_close = '</a>';\n $name = cut($group['name'], 60, true);\n $count_users_group = count($usergroup->get_all_users_by_group($id));\n if ($count_users_group == 1) {\n $count_users_group = $count_users_group;\n } else {\n $count_users_group = $count_users_group;\n }\n $picture = $usergroup->get_picture_group(\n $group['id'],\n $group['picture'],\n GROUP_IMAGE_SIZE_ORIGINAL\n );", " $tags = null;\n $group['picture'] = '<img class=\"img-responsive img-circle\" src=\"'.$picture['file'].'\" />';", " $members = Display::returnFontAwesomeIcon('user').'( '.$count_users_group.' )';\n $item_1 = Display::tag('p', $url_open.$name.$url_close);", " $block_groups .= '\n <div class=\"col-md-4\">\n <div class=\"items-user\">\n <div class=\"items-user-avatar\">\n '.$group['picture'].'\n </div>\n <div class=\"user-info\">\n '.$item_1.'", " <p>'.$members.'</p> ", " <p>'.$group['description'].'</p>\n <p>'.$tags.'</p>\n <p>'.$url_open.get_lang('SeeMore').$url_close.'</p>\n </div>\n </div>\n </div>';\n }\n $block_groups .= '</div>';\n }\n $block_groups .= '</div>';", " $visibility = [true, true, true, true, true];", " if (!empty($groups)) {\n $block_groups .= Display::return_sortable_grid(\n 'groups',\n null,\n $grid_groups,\n ['hide_navigation' => false, 'per_page' => $itemPerPage],\n $query_vars,\n false,\n $visibility,\n true,\n [],\n $totalGroups\n );\n $block_search .= Display:: panelCollapse(\n get_lang('Groups'),\n $block_groups,\n 'search-groups',\n null,\n 'groups-accordion',\n 'groups-collapse'\n );\n }\n}", "$tpl = new Template($tool_name);\n// Block Social Avatar\nSocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'search');\n$tpl->assign('social_menu_block', $social_menu_block);\n$tpl->assign('social_search', $block_search);\n$tpl->assign('search_form', $searchForm);", "$formModalTpl = new Template();\n$formModalTpl->assign('invitation_form', MessageManager::generate_invitation_form());\n$template = $formModalTpl->get_template('social/form_modals.tpl');\n$formModals = $formModalTpl->fetch($template);", "$tpl->assign('form_modals', $formModals);", "$social_layout = $tpl->get_template('social/search.tpl');\n$tpl->display($social_layout);" ]
[ 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [205], "buggy_code_start_loc": [26], "filenames": ["main/social/search.php"], "fixing_code_end_loc": [205], "fixing_code_start_loc": [26], "message": "A Chamilo LMS 1.11.14 reflected XSS vulnerability exists in main/social/search.php=q URI (social network search feature).", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:chamilo:chamilo_lms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F430146D-54FD-40CF-8199-CE337308440A", "versionEndExcluding": "1.11.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A Chamilo LMS 1.11.14 reflected XSS vulnerability exists in main/social/search.php=q URI (social network search feature)."}, {"lang": "es", "value": "Se presenta una vulnerabilidad de tipo XSS reflejado en Chamilo LMS versi\u00f3n 1.11.14, en la funci\u00f3n main/social/search.php=q URI (funcionalidad de b\u00fasqueda en redes sociales)"}], "evaluatorComment": null, "id": "CVE-2021-37390", "lastModified": "2021-08-17T15:36:33.400", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-08-10T20:15:08.647", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://gitbook.seguranca-informatica.pt/cve-and-exploits/cves/chamilo-lms-1.11.14-xss-vulnerabilities"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/chamilo/chamilo-lms/commit/3fcc751d5cc7da311532a8756fba5a8778f50ca0"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/chamilo/chamilo-lms/commit/3fcc751d5cc7da311532a8756fba5a8778f50ca0"}, "type": "CWE-79"}
284
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* For licensing terms, see /license.txt */", "/**\n * @package chamilo.social\n *\n * @author Julio Montoya <gugli100@gmail.com>\n */\n$cidReset = true;", "require_once __DIR__.'/../inc/global.inc.php';\n$ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';\napi_block_anonymous_users();", "if (api_get_setting('allow_social_tool') != 'true') {\n api_not_allowed();\n}", "$this_section = SECTION_SOCIAL;\n$tool_name = get_lang('Search');\n$interbreadcrumb[] = [\n 'url' => api_get_path(WEB_CODE_PATH).'social/profile.php',\n 'name' => get_lang('SocialNetwork'),\n];\n", "$query = isset($_GET['q']) ? htmlentities($_GET['q']) : null;", "$queryNoTags = isset($_GET['q']) ? strip_tags($_GET['q']) : null;", "$query_search_type = isset($_GET['search_type']) && in_array($_GET['search_type'], ['0', '1', '2']) ? $_GET['search_type'] : null;\n$extra_fields = UserManager::getExtraFilterableFields();\n$query_vars = ['q' => $query, 'search_type' => $query_search_type];\nif (!empty($extra_fields)) {\n foreach ($extra_fields as $extra_field) {\n $field_name = 'field_'.$extra_field['variable'];\n if (isset($_GET[$field_name]) && $_GET[$field_name] != '0') {\n $query_vars[$field_name] = $_GET[$field_name];\n }\n }\n}", "//Block Social Menu\n$social_menu_block = SocialManager::show_social_menu('search');\n$block_search = '';", "$searchForm = UserManager::get_search_form($queryNoTags);", "\n$groups = [];\n$totalGroups = [];\n$users = [];\n$totalUsers = [];\n$usergroup = new UserGroup();", "// I'm searching something\nif ($query != '' || ($query_vars['search_type'] == '1' && count($query_vars) > 2)) {\n $itemPerPage = 6;", " if ($_GET['search_type'] == '0' || $_GET['search_type'] == '1') {\n $page = isset($_GET['users_page_nr']) ? intval($_GET['users_page_nr']) : 1;\n $totalUsers = UserManager::get_all_user_tags(\n $_GET['q'],\n 0,\n 0,\n $itemPerPage,\n true\n );", " $from = intval(($page - 1) * $itemPerPage);\n // Get users from tags\n $users = UserManager::get_all_user_tags($_GET['q'], 0, $from, $itemPerPage);\n }", " if ($_GET['search_type'] == '0' || $_GET['search_type'] == '2') {\n $pageGroup = isset($_GET['groups_page_nr']) ? intval($_GET['groups_page_nr']) : 1;\n // Groups\n $fromGroups = intval(($pageGroup - 1) * $itemPerPage);\n $totalGroups = count($usergroup->get_all_group_tags($_GET['q'], 0, $itemPerPage, true));", " $groups = $usergroup->get_all_group_tags($_GET['q'], $fromGroups);\n }", " if (empty($users) && empty($groups)) {\n Display::addFlash(Display::return_message(get_lang('SorryNoResults')));\n }", " $results = '<div id=\"whoisonline\">';\n if (is_array($users) && count($users) > 0) {\n $results .= '<div class=\"row\">';\n $buttonClass = 'btn btn-default btn-sm';\n foreach ($users as $user) {\n $user_info = api_get_user_info($user['id'], true);\n $sendInvitation = '<button class=\"'.$buttonClass.' disabled \">\n <em class=\"fa fa-user\"></em> '.get_lang('SendInvitation').'</button>';\n $relation_type = SocialManager::get_relation_between_contacts(api_get_user_id(), $user_info['user_id']);\n $url = api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_info['user_id'];", " // Show send invitation icon if they are not friends yet\n if ($relation_type != 3 && $relation_type != 4 && $user_info['user_id'] != api_get_user_id()) {\n $sendInvitation = '<a href=\"#\" class=\"'.$buttonClass.' btn-to-send-invitation\" data-send-to=\"'.$user_info['user_id'].'\">\n <em class=\"fa fa-user\"></em> '.get_lang('SendInvitation').'</a>';\n }", " $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([\n 'a' => 'get_user_popup',\n 'user_id' => $user_info['user_id'],\n ]);", " $sendMessage = Display::toolbarButton(\n get_lang('SendMessage'),\n $sendMessageUrl,\n 'envelope',\n 'default',\n [\n 'class' => 'ajax btn-sm',\n 'data-title' => get_lang('SendMessage'),\n ]\n );", " if (!empty($user_info['user_is_online'])) {\n $status_icon = Display::return_icon('online.png', get_lang('OnLine'), null, ICON_SIZE_TINY);\n } else {\n $status_icon = Display::return_icon('offline.png', get_lang('Disconnected'), null, ICON_SIZE_TINY);\n }", " if ($user_info['status'] == 5) {\n $user_icon = Display::return_icon('user.png', get_lang('Student'), null, ICON_SIZE_TINY);\n } else {\n $user_icon = Display::return_icon('teacher.png', get_lang('Teacher'), null, ICON_SIZE_TINY);\n }", " $user_info['complete_name'] = Display::url($user_info['complete_name'], $url);\n $invitations = $sendInvitation.$sendMessage;", " $results .= Display::getUserCard(\n $user_info,\n $status_icon.$user_icon,\n $invitations\n );\n }\n $results .= '</div>';\n }\n $results .= '</div>';", " $visibility = [true, true, true, true, true];", " if (!empty($users)) {\n $results .= Display::return_sortable_grid(\n 'users',\n null,\n null,\n ['hide_navigation' => false, 'per_page' => $itemPerPage],\n $query_vars,\n false,\n $visibility,\n true,\n [],\n $totalUsers\n );\n $block_search .= Display::panelCollapse(\n get_lang('Users'),\n $results,\n 'search-friends',\n null,\n 'friends-accordion',\n 'friends-collapse'\n );\n }", " $grid_groups = [];\n $block_groups = '<div id=\"whoisonline\">';\n if (is_array($groups) && count($groups) > 0) {\n $block_groups .= '<div class=\"row\">';\n foreach ($groups as $group) {\n $group['name'] = Security::remove_XSS($group['name'], STUDENT, true);\n $group['description'] = Security::remove_XSS($group['description'], STUDENT, true);\n $id = $group['id'];\n $url_open = '<a href=\"group_view.php?id='.$id.'\">';\n $url_close = '</a>';\n $name = cut($group['name'], 60, true);\n $count_users_group = count($usergroup->get_all_users_by_group($id));\n if ($count_users_group == 1) {\n $count_users_group = $count_users_group;\n } else {\n $count_users_group = $count_users_group;\n }\n $picture = $usergroup->get_picture_group(\n $group['id'],\n $group['picture'],\n GROUP_IMAGE_SIZE_ORIGINAL\n );", " $tags = null;\n $group['picture'] = '<img class=\"img-responsive img-circle\" src=\"'.$picture['file'].'\" />';", " $members = Display::returnFontAwesomeIcon('user').'( '.$count_users_group.' )';\n $item_1 = Display::tag('p', $url_open.$name.$url_close);", " $block_groups .= '\n <div class=\"col-md-4\">\n <div class=\"items-user\">\n <div class=\"items-user-avatar\">\n '.$group['picture'].'\n </div>\n <div class=\"user-info\">\n '.$item_1.'", " <p>'.$members.'</p>", " <p>'.$group['description'].'</p>\n <p>'.$tags.'</p>\n <p>'.$url_open.get_lang('SeeMore').$url_close.'</p>\n </div>\n </div>\n </div>';\n }\n $block_groups .= '</div>';\n }\n $block_groups .= '</div>';", " $visibility = [true, true, true, true, true];", " if (!empty($groups)) {\n $block_groups .= Display::return_sortable_grid(\n 'groups',\n null,\n $grid_groups,\n ['hide_navigation' => false, 'per_page' => $itemPerPage],\n $query_vars,\n false,\n $visibility,\n true,\n [],\n $totalGroups\n );\n $block_search .= Display:: panelCollapse(\n get_lang('Groups'),\n $block_groups,\n 'search-groups',\n null,\n 'groups-accordion',\n 'groups-collapse'\n );\n }\n}", "$tpl = new Template($tool_name);\n// Block Social Avatar\nSocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'search');\n$tpl->assign('social_menu_block', $social_menu_block);\n$tpl->assign('social_search', $block_search);\n$tpl->assign('search_form', $searchForm);", "$formModalTpl = new Template();\n$formModalTpl->assign('invitation_form', MessageManager::generate_invitation_form());\n$template = $formModalTpl->get_template('social/form_modals.tpl');\n$formModals = $formModalTpl->fetch($template);", "$tpl->assign('form_modals', $formModals);", "$social_layout = $tpl->get_template('social/search.tpl');\n$tpl->display($social_layout);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [205], "buggy_code_start_loc": [26], "filenames": ["main/social/search.php"], "fixing_code_end_loc": [205], "fixing_code_start_loc": [26], "message": "A Chamilo LMS 1.11.14 reflected XSS vulnerability exists in main/social/search.php=q URI (social network search feature).", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:chamilo:chamilo_lms:*:*:*:*:*:*:*:*", "matchCriteriaId": "F430146D-54FD-40CF-8199-CE337308440A", "versionEndExcluding": "1.11.14", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A Chamilo LMS 1.11.14 reflected XSS vulnerability exists in main/social/search.php=q URI (social network search feature)."}, {"lang": "es", "value": "Se presenta una vulnerabilidad de tipo XSS reflejado en Chamilo LMS versi\u00f3n 1.11.14, en la funci\u00f3n main/social/search.php=q URI (funcionalidad de b\u00fasqueda en redes sociales)"}], "evaluatorComment": null, "id": "CVE-2021-37390", "lastModified": "2021-08-17T15:36:33.400", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-08-10T20:15:08.647", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://gitbook.seguranca-informatica.pt/cve-and-exploits/cves/chamilo-lms-1.11.14-xss-vulnerabilities"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/chamilo/chamilo-lms/commit/3fcc751d5cc7da311532a8756fba5a8778f50ca0"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/chamilo/chamilo-lms/commit/3fcc751d5cc7da311532a8756fba5a8778f50ca0"}, "type": "CWE-79"}
284
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nnamespace um\\core;", "// Exit if accessed directly\nif ( ! defined( 'ABSPATH' ) ) exit;", "if ( ! class_exists( 'um\\core\\Shortcodes' ) ) {", "\n\t/**\n\t * Class Shortcodes\n\t * @package um\\core\n\t */\n\tclass Shortcodes {", "\t\tvar $profile_role = '';", "\t\t/**\n\t\t * Shortcodes constructor.\n\t\t */\n\t\tfunction __construct() {", "\t\t\t$this->message_mode = false;\n\t\t\t$this->custom_message = '';", "\t\t\t$this->loop = array();", "\t\t\tadd_shortcode( 'ultimatemember', array( &$this, 'ultimatemember' ) );", "\t\t\tadd_shortcode( 'ultimatemember_login', array( &$this, 'ultimatemember_login' ) );\n\t\t\tadd_shortcode( 'ultimatemember_register', array( &$this, 'ultimatemember_register' ) );\n\t\t\tadd_shortcode( 'ultimatemember_profile', array( &$this, 'ultimatemember_profile' ) );\n\t\t\tadd_shortcode( 'ultimatemember_directory', array( &$this, 'ultimatemember_directory' ) );", "\t\t\tadd_shortcode( 'um_loggedin', array( &$this, 'um_loggedin' ) );\n\t\t\tadd_shortcode( 'um_loggedout', array( &$this, 'um_loggedout' ) );\n\t\t\tadd_shortcode( 'um_show_content', array( &$this, 'um_shortcode_show_content_for_role' ) );\n\t\t\tadd_shortcode( 'ultimatemember_searchform', array( &$this, 'ultimatemember_searchform' ) );", "\t\t\tadd_filter( 'body_class', array( &$this, 'body_class' ), 0 );", "\t\t\tadd_filter( 'um_shortcode_args_filter', array( &$this, 'display_logout_form' ), 99 );\n\t\t\tadd_filter( 'um_shortcode_args_filter', array( &$this, 'parse_shortcode_args' ), 99 );", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_emoji_base_uri\n\t\t\t * @description Change Emoji base URL\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$url\",\"type\":\"string\",\"desc\":\"Base URL\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_emoji_base_uri', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_emoji_base_uri', 'my_emoji_base_uri', 10, 1 );\n\t\t\t * function my_emoji_base_uri( $url ) {\n\t\t\t * // your code here\n\t\t\t * return $url;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$base_uri = apply_filters( 'um_emoji_base_uri', 'https://s.w.org/images/core/emoji/' );", "\t\t\t$this->emoji[':)'] = $base_uri . '72x72/1f604.png';\n\t\t\t$this->emoji[':smiley:'] = $base_uri . '72x72/1f603.png';\n\t\t\t$this->emoji[':D'] = $base_uri . '72x72/1f600.png';\n\t\t\t$this->emoji[':$'] = $base_uri . '72x72/1f60a.png';\n\t\t\t$this->emoji[':relaxed:'] = $base_uri . '72x72/263a.png';\n\t\t\t$this->emoji[';)'] = $base_uri . '72x72/1f609.png';\n\t\t\t$this->emoji[':heart_eyes:'] = $base_uri . '72x72/1f60d.png';\n\t\t\t$this->emoji[':kissing_heart:'] = $base_uri . '72x72/1f618.png';\n\t\t\t$this->emoji[':kissing_closed_eyes:'] = $base_uri . '72x72/1f61a.png';\n\t\t\t$this->emoji[':kissing:'] = $base_uri . '72x72/1f617.png';\n\t\t\t$this->emoji[':kissing_smiling_eyes:'] = $base_uri . '72x72/1f619.png';\n\t\t\t$this->emoji[';P'] = $base_uri . '72x72/1f61c.png';\n\t\t\t$this->emoji[':P'] = $base_uri . '72x72/1f61b.png';\n\t\t\t$this->emoji[':stuck_out_tongue_closed_eyes:'] = $base_uri . '72x72/1f61d.png';\n\t\t\t$this->emoji[':flushed:'] = $base_uri . '72x72/1f633.png';\n\t\t\t$this->emoji[':grin:'] = $base_uri . '72x72/1f601.png';\n\t\t\t$this->emoji[':pensive:'] = $base_uri . '72x72/1f614.png';\n\t\t\t$this->emoji[':relieved:'] = $base_uri . '72x72/1f60c.png';\n\t\t\t$this->emoji[':unamused'] = $base_uri . '72x72/1f612.png';\n\t\t\t$this->emoji[':('] = $base_uri . '72x72/1f61e.png';\n\t\t\t$this->emoji[':persevere:'] = $base_uri . '72x72/1f623.png';\n\t\t\t$this->emoji[\":'(\"] = $base_uri . '72x72/1f622.png';\n\t\t\t$this->emoji[':joy:'] = $base_uri . '72x72/1f602.png';\n\t\t\t$this->emoji[':sob:'] = $base_uri . '72x72/1f62d.png';\n\t\t\t$this->emoji[':sleepy:'] = $base_uri . '72x72/1f62a.png';\n\t\t\t$this->emoji[':disappointed_relieved:'] = $base_uri . '72x72/1f625.png';\n\t\t\t$this->emoji[':cold_sweat:'] = $base_uri . '72x72/1f630.png';\n\t\t\t$this->emoji[':sweat_smile:'] = $base_uri . '72x72/1f605.png';\n\t\t\t$this->emoji[':sweat:'] = $base_uri . '72x72/1f613.png';\n\t\t\t$this->emoji[':weary:'] = $base_uri . '72x72/1f629.png';\n\t\t\t$this->emoji[':tired_face:'] = $base_uri . '72x72/1f62b.png';\n\t\t\t$this->emoji[':fearful:'] = $base_uri . '72x72/1f628.png';\n\t\t\t$this->emoji[':scream:'] = $base_uri . '72x72/1f631.png';\n\t\t\t$this->emoji[':angry:'] = $base_uri . '72x72/1f620.png';\n\t\t\t$this->emoji[':rage:'] = $base_uri . '72x72/1f621.png';\n\t\t\t$this->emoji[':triumph'] = $base_uri . '72x72/1f624.png';\n\t\t\t$this->emoji[':confounded:'] = $base_uri . '72x72/1f616.png';\n\t\t\t$this->emoji[':laughing:'] = $base_uri . '72x72/1f606.png';\n\t\t\t$this->emoji[':yum:'] = $base_uri . '72x72/1f60b.png';\n\t\t\t$this->emoji[':mask:'] = $base_uri . '72x72/1f637.png';\n\t\t\t$this->emoji[':cool:'] = $base_uri . '72x72/1f60e.png';\n\t\t\t$this->emoji[':sleeping:'] = $base_uri . '72x72/1f634.png';\n\t\t\t$this->emoji[':dizzy_face:'] = $base_uri . '72x72/1f635.png';\n\t\t\t$this->emoji[':astonished:'] = $base_uri . '72x72/1f632.png';\n\t\t\t$this->emoji[':worried:'] = $base_uri . '72x72/1f61f.png';\n\t\t\t$this->emoji[':frowning:'] = $base_uri . '72x72/1f626.png';\n\t\t\t$this->emoji[':anguished:'] = $base_uri . '72x72/1f627.png';\n\t\t\t$this->emoji[':smiling_imp:'] = $base_uri . '72x72/1f608.png';\n\t\t\t$this->emoji[':imp:'] = $base_uri . '72x72/1f47f.png';\n\t\t\t$this->emoji[':open_mouth:'] = $base_uri . '72x72/1f62e.png';\n\t\t\t$this->emoji[':grimacing:'] = $base_uri . '72x72/1f62c.png';\n\t\t\t$this->emoji[':neutral_face:'] = $base_uri . '72x72/1f610.png';\n\t\t\t$this->emoji[':confused:'] = $base_uri . '72x72/1f615.png';\n\t\t\t$this->emoji[':hushed:'] = $base_uri . '72x72/1f62f.png';\n\t\t\t$this->emoji[':no_mouth:'] = $base_uri . '72x72/1f636.png';\n\t\t\t$this->emoji[':innocent:'] = $base_uri . '72x72/1f607.png';\n\t\t\t$this->emoji[':smirk:'] = $base_uri . '72x72/1f60f.png';\n\t\t\t$this->emoji[':expressionless:'] = $base_uri . '72x72/1f611.png';", "\t\t}", "\n\t\t/**\n\t\t * Conditional logout form\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction display_logout_form( $args ) {\n\t\t\tif ( is_user_logged_in() && isset( $args['mode'] ) && $args['mode'] == 'login' ) {", "\t\t\t\tif ( isset( UM()->user()->preview ) && UM()->user()->preview ) {\n\t\t\t\t\treturn $args;\n\t\t\t\t}", "\t\t\t\tif ( get_current_user_id() != um_user( 'ID' ) ) {\n\t\t\t\t\tum_fetch_user( get_current_user_id() );\n\t\t\t\t}", "\t\t\t\t$args['template'] = 'logout';\n\t\t\t}", "\t\t\treturn $args;\n\t\t}", "\n\t\t/**\n\t\t * Filter shortcode args\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction parse_shortcode_args( $args ) {\n\t\t\tif ( $this->message_mode == true ) {\n\t\t\t\tif ( ! empty( $_REQUEST['um_role'] ) ) {\n\t\t\t\t\t$args['template'] = 'message';\n\t\t\t\t\t$roleID = sanitize_key( $_REQUEST['um_role'] );\n\t\t\t\t\t$role = UM()->roles()->role_data( $roleID );", "\t\t\t\t\tif ( ! empty( $role ) && ! empty( $role['status'] ) ) {\n\t\t\t\t\t\t$message_key = $role['status'] . '_message';\n\t\t\t\t\t\t$this->custom_message = ! empty( $role[ $message_key ] ) ? stripslashes( $role[ $message_key ] ) : '';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tforeach ( $args as $k => $v ) {\n\t\t\t\t$args[ $k ] = maybe_unserialize( $args[ $k ] );\n\t\t\t}", "\t\t\treturn $args;\n\t\t}", "\n\t\t/**\n\t\t * Emoji support\n\t\t *\n\t\t * @param $content\n\t\t *\n\t\t * @return mixed|string\n\t\t */\n\t\tfunction emotize( $content ) {\n\t\t\t$content = stripslashes( $content );\n\t\t\tforeach ( $this->emoji as $code => $val ) {\n\t\t\t\t$regex = str_replace(array('(', ')'), array(\"\\\\\" . '(', \"\\\\\" . ')'), $code);\n\t\t\t\t$content = preg_replace('/(' . $regex . ')(\\s|$)/', '<img src=\"' . $val . '\" alt=\"' . $code . '\" title=\"' . $code . '\" class=\"emoji\" />$2', $content);\n\t\t\t}\n\t\t\treturn $content;\n\t\t}", "\n\t\t/**\n\t\t * Remove wpautop filter for post content if it's UM core page\n\t\t */\n\t\tfunction is_um_page() {\n\t\t\tif ( is_ultimatemember() ) {\n\t\t\t\tremove_filter( 'the_content', 'wpautop' );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * Extend body classes\n\t\t *\n\t\t * @param $classes\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction body_class( $classes ) {\n\t\t\t$array = UM()->config()->permalinks;\n\t\t\tif ( ! $array ) {\n\t\t\t\treturn $classes;\n\t\t\t}", "\t\t\tforeach ( $array as $slug => $info ) {\n\t\t\t\tif ( um_is_core_page( $slug ) ) {", "\t\t\t\t\t$classes[] = 'um-page-' . $slug;", "\t\t\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\t\t\t$classes[] = 'um-page-loggedin';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$classes[] = 'um-page-loggedout';\n\t\t\t\t\t}", "\t\t\t\t}\n\t\t\t}", "\t\t\tif ( um_is_core_page( 'user' ) && um_is_user_himself() ) {\n\t\t\t\t$classes[] = 'um-own-profile';\n\t\t\t}", "\t\t\treturn $classes;\n\t\t}", "\n\t\t/**\n\t\t * Retrieve core login form\n\t\t *\n\t\t * @return int\n\t\t */\n\t\tfunction core_login_form() {\n\t\t\t$forms = get_posts(array('post_type' => 'um_form', 'posts_per_page' => 1, 'meta_key' => '_um_core', 'meta_value' => 'login'));\n\t\t\t$form_id = isset( $forms[0]->ID ) ? $forms[0]->ID: 0;", "\t\t\treturn $form_id;\n\t\t}", "\n\t\t/**\n\t\t * Load a compatible template\n\t\t *\n\t\t * @param $tpl\n\t\t */\n\t\tfunction load_template( $tpl ) {\n\t\t\t$loop = ( $this->loop ) ? $this->loop : array();", "\t\t\tif ( isset( $this->set_args ) && is_array( $this->set_args ) ) {\n\t\t\t\t$args = $this->set_args;", "\t\t\t\tunset( $args['file'] );\n\t\t\t\tunset( $args['theme_file'] );\n\t\t\t\tunset( $args['tpl'] );", "\t\t\t\t$args = apply_filters( 'um_template_load_args', $args, $tpl );", "\t\t\t\textract( $args );\n\t\t\t}\n", "\t\t\t// Avoid Directory Traversal vulnerability.\n\t\t\t$tpl = trim( $tpl, \"./\\\\\" );\n", "\t\t\t$file = um_path . \"templates/{$tpl}.php\";\n\t\t\t$theme_file = get_stylesheet_directory() . \"/ultimate-member/templates/{$tpl}.php\";\n\t\t\tif ( file_exists( $theme_file ) ) {\n\t\t\t\t$file = $theme_file;\n\t\t\t}", "\t\t\tif ( file_exists( $file ) ) {", "\t\t\t\tinclude $file;", "\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * Add class based on shortcode\n\t\t *\n\t\t * @param $mode\n\t\t * @param array $args\n\t\t *\n\t\t * @return mixed|string|void\n\t\t */\n\t\tfunction get_class($mode, $args = array()) {", "\t\t\t$classes = 'um-' . $mode;", "\t\t\tif (is_admin()) {\n\t\t\t\t$classes .= ' um-in-admin';\n\t\t\t}", "\t\t\tif (isset(UM()->form()->errors) && UM()->form()->errors) {\n\t\t\t\t$classes .= ' um-err';\n\t\t\t}", "\t\t\tif (UM()->fields()->editing == true) {\n\t\t\t\t$classes .= ' um-editing';\n\t\t\t}", "\t\t\tif (UM()->fields()->viewing == true) {\n\t\t\t\t$classes .= ' um-viewing';\n\t\t\t}", "\t\t\tif (isset($args['template']) && $args['template'] != $args['mode']) {\n\t\t\t\t$classes .= ' um-' . $args['template'];\n\t\t\t}", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_form_official_classes__hook\n\t\t\t * @description Change official form classes\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$classes\",\"type\":\"string\",\"desc\":\"Classes string\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_form_official_classes__hook', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_form_official_classes__hook', 'my_form_official_classes', 10, 1 );\n\t\t\t * function my_form_official_classes( $classes ) {\n\t\t\t * // your code here\n\t\t\t * return $classes;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$classes = apply_filters( 'um_form_official_classes__hook', $classes );\n\t\t\treturn $classes;\n\t\t}", "\n\t\t/**\n\t\t * Logged-in only content\n\t\t *\n\t\t * @param array $args\n\t\t * @param string $content\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction um_loggedin( $args = array(), $content = \"\" ) {\n\t\t\tob_start();", "\t\t\t$args = shortcode_atts(\n\t\t\t\tarray(\n\t\t\t\t\t'lock_text' => __( 'This content has been restricted to logged in users only. Please <a href=\"{login_referrer}\">login</a> to view this content.', 'ultimate-member' ),\n\t\t\t\t\t'show_lock' => 'yes',\n\t\t\t\t),\n\t\t\t\t$args,\n\t\t\t\t'um_loggedin'\n\t\t\t);", "\t\t\tif ( ! is_user_logged_in() ) {\n\t\t\t\tif ( 'no' === $args['show_lock'] ) {\n\t\t\t\t\techo '';\n\t\t\t\t} else {\n\t\t\t\t\t$args['lock_text'] = $this->convert_locker_tags( $args['lock_text'] );\n\t\t\t\t\tUM()->get_template( 'login-to-view.php', '', $args, true );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\techo do_shortcode( $this->convert_locker_tags( wpautop( $content ) ) );\n\t\t\t\t} else {\n\t\t\t\t\techo apply_shortcodes( $this->convert_locker_tags( wpautop( $content ) ) );\n\t\t\t\t}\n\t\t\t}", "\t\t\t$output = ob_get_clean();", "\t\t\treturn htmlspecialchars_decode( $output, ENT_NOQUOTES );\n\t\t}", "\n\t\t/**\n\t\t * Logged-out only content\n\t\t *\n\t\t * @param array $args\n\t\t * @param string $content\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction um_loggedout( $args = array(), $content = '' ) {\n\t\t\tob_start();", "\t\t\t// Hide for logged in users\n\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\techo '';\n\t\t\t} else {\n\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\techo do_shortcode( wpautop( $content ) );\n\t\t\t\t} else {\n\t\t\t\t\techo apply_shortcodes( wpautop( $content ) );\n\t\t\t\t}\n\t\t\t}", "\t\t\t$output = ob_get_clean();\n\t\t\treturn $output;\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_login( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_login = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'login' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_login;\n\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_register( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_register = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'register' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_register;\n\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_profile( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_profile = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'profile' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_profile;", "\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_directory( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_directory = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'directory' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_directory;", "\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * Shortcode\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember( $args = array() ) {\n\t\t\treturn $this->load( $args );\n\t\t}", "\n\t\t/**\n\t\t * Load a module with global function\n\t\t *\n\t\t * @param $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction load( $args ) {\n\t\t\t$defaults = array();\n\t\t\t$args = wp_parse_args( $args, $defaults );", "\t\t\t// when to not continue\n\t\t\t$this->form_id = isset( $args['form_id'] ) ? $args['form_id'] : null;\n\t\t\tif ( ! $this->form_id ) {\n\t\t\t\treturn;\n\t\t\t}", "\t\t\t$this->form_status = get_post_status( $this->form_id );\n\t\t\tif ( $this->form_status != 'publish' ) {\n\t\t\t\treturn;\n\t\t\t}", "\t\t\t// get data into one global array\n\t\t\t$post_data = UM()->query()->post_data( $this->form_id );\n\t\t\t$args = array_merge( $args, $post_data );", "\t\t\tob_start();", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_pre_args_setup\n\t\t\t * @description Change arguments on load shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$post_data\",\"type\":\"string\",\"desc\":\"$_POST data\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_pre_args_setup', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_pre_args_setup', 'my_pre_args_setup', 10, 1 );\n\t\t\t * function my_pre_args_setup( $post_data ) {\n\t\t\t * // your code here\n\t\t\t * return $post_data;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$args = apply_filters( 'um_pre_args_setup', $args );", "\t\t\tif ( ! isset( $args['template'] ) ) {\n\t\t\t\t$args['template'] = '';\n\t\t\t}", "\t\t\tif ( isset( $post_data['template'] ) && $post_data['template'] != $args['template'] ) {\n\t\t\t\t$args['template'] = $post_data['template'];\n\t\t\t}", "\t\t\tif ( ! $this->template_exists( $args['template'] ) ) {\n\t\t\t\t$args['template'] = $post_data['mode'];\n\t\t\t}", "\t\t\tif ( ! isset( $post_data['template'] ) ) {\n\t\t\t\t$post_data['template'] = $post_data['mode'];\n\t\t\t}", "\t\t\tif ( 'directory' == $args['mode'] ) {\n\t\t\t\twp_enqueue_script( 'um_members' );\n\t\t\t\tif ( is_rtl() ) {\n\t\t\t\t\twp_enqueue_style( 'um_members_rtl' );\n\t\t\t\t} else {\n\t\t\t\t\twp_enqueue_style( 'um_members' );\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ( 'directory' != $args['mode'] ) {\n\t\t\t\t$args = array_merge( $post_data, $args );", "\t\t\t\tif ( empty( $args['use_custom_settings'] ) ) {\n\t\t\t\t\t$args = array_merge( $args, $this->get_css_args( $args ) );\n\t\t\t\t} else {\n\t\t\t\t\t$args = array_merge( $this->get_css_args( $args ), $args );\n\t\t\t\t}\n\t\t\t}\n\t\t\t// filter for arguments", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_shortcode_args_filter\n\t\t\t * @description Change arguments on load shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"string\",\"desc\":\"Shortcode arguments\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_shortcode_args_filter', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_shortcode_args_filter', 'my_shortcode_args', 10, 1 );\n\t\t\t * function my_shortcode_args( $args ) {\n\t\t\t * // your code here\n\t\t\t * return $args;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$args = apply_filters( 'um_shortcode_args_filter', $args );", "\t\t\t/**\n\t\t\t * @var string $mode\n\t\t\t */\n\t\t\textract( $args, EXTR_SKIP );", "\t\t\t//not display on admin preview\n\t\t\tif ( empty( $_POST['act_id'] ) || sanitize_key( $_POST['act_id'] ) !== 'um_admin_preview_form' ) {", "\t\t\t\t$enable_loggedin_registration = apply_filters( 'um_registration_for_loggedin_users', false, $args );", "\t\t\t\tif ( 'register' == $mode && is_user_logged_in() && ! $enable_loggedin_registration ) {\n\t\t\t\t\tob_get_clean();\n\t\t\t\t\treturn __( 'You are already registered', 'ultimate-member' );\n\t\t\t\t}\n\t\t\t}", "\t\t\t// for profiles only\n\t\t\tif ( $mode == 'profile' && um_profile_id() ) {", "\t\t\t\t//set requested user if it's not setup from permalinks (for not profile page in edit mode)\n\t\t\t\tif ( ! um_get_requested_user() ) {\n\t\t\t\t\tum_set_requested_user( um_profile_id() );\n\t\t\t\t}", "\t\t\t\tif ( ! empty( $args['use_custom_settings'] ) ) { // Option \"Apply custom settings to this form\"\n\t\t\t\t\tif ( ! empty( $args['role'] ) ) { // Option \"Make this profile form role-specific\"", "\t\t\t\t\t\t// show the first Profile Form with role selected, don't show profile forms below the page with other role-specific setting\n\t\t\t\t\t\tif ( empty( $this->profile_role ) ) {\n\t\t\t\t\t\t\t$current_user_roles = UM()->roles()->get_all_user_roles( um_profile_id() );", "\t\t\t\t\t\t\tif ( empty( $current_user_roles ) ) {\n\t\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t} elseif ( is_array( $args['role'] ) ) {\n\t\t\t\t\t\t\t\tif ( ! count( array_intersect( $args['role'], $current_user_roles ) ) ) {\n\t\t\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif ( ! in_array( $args['role'], $current_user_roles ) ) {\n\t\t\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t$this->profile_role = $args['role'];\n\t\t\t\t\t\t} elseif ( $this->profile_role != $args['role'] ) {\n\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_pre_{$mode}_shortcode\n\t\t\t * @description Action pre-load form shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"array\",\"desc\":\"Form shortcode pre-loading\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_pre_{$mode}_shortcode', 'function_name', 10, 1 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_pre_{$mode}_shortcode', 'my_pre_shortcode', 10, 1 );\n\t\t\t * function my_pre_shortcode( $args ) {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( \"um_pre_{$mode}_shortcode\", $args );\n\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_before_form_is_loaded\n\t\t\t * @description Action pre-load form shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"array\",\"desc\":\"Form shortcode pre-loading\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_before_form_is_loaded', 'function_name', 10, 1 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_before_form_is_loaded', 'my_pre_shortcode', 10, 1 );\n\t\t\t * function my_pre_shortcode( $args ) {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( \"um_before_form_is_loaded\", $args );\n\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_before_{$mode}_form_is_loaded\n\t\t\t * @description Action pre-load form shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"array\",\"desc\":\"Form shortcode pre-loading\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_before_{$mode}_form_is_loaded', 'function_name', 10, 1 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_before_{$mode}_form_is_loaded', 'my_pre_shortcode', 10, 1 );\n\t\t\t * function my_pre_shortcode( $args ) {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( \"um_before_{$mode}_form_is_loaded\", $args );", "\t\t\t$this->template_load( $template, $args );", "\t\t\t$this->dynamic_css( $args );", "\t\t\tif ( um_get_requested_user() || $mode == 'logout' ) {\n\t\t\t\tum_reset_user();\n\t\t\t}", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_after_everything_output\n\t\t\t * @description Action after load shortcode content\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_after_everything_output', 'function_name', 10 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_after_everything_output', 'my_after_everything_output', 10 );\n\t\t\t * function my_after_everything_output() {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( 'um_after_everything_output' );", "\t\t\t$output = ob_get_clean();\n\t\t\treturn $output;\n\t\t}", "\n\t\t/**\n\t\t * Get dynamic CSS args\n\t\t *\n\t\t * @param $args\n\t\t * @return array\n\t\t */\n\t\tfunction get_css_args( $args ) {\n\t\t\t$arr = um_styling_defaults( $args['mode'] );\n\t\t\t$arr = array_merge( $arr, array( 'form_id' => $args['form_id'], 'mode' => $args['mode'] ) );\n\t\t\treturn $arr;\n\t\t}", "\n\t\t/**\n\t\t * Load dynamic css\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction dynamic_css( $args = array() ) {\n\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_disable_dynamic_global_css\n\t\t\t * @description Turn on for disable global dynamic CSS for fix the issue #306\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$disable\",\"type\":\"bool\",\"desc\":\"Disable global CSS\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_disable_dynamic_global_css', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_disable_dynamic_global_css', 'my_disable_dynamic_global_css', 10, 1 );\n\t\t\t * function my_disable_dynamic_global_css( $disable ) {\n\t\t\t * // your code here\n\t\t\t * return $disable;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$disable_css = apply_filters( 'um_disable_dynamic_global_css', false );\n\t\t\tif ( $disable_css )\n\t\t\t\treturn '';", "\t\t\t/**\n\t\t\t * @var $mode\n\t\t\t */\n\t\t\textract( $args );", "\t\t\tinclude_once um_path . 'assets/dynamic_css/dynamic_global.php';", "\t\t\tif ( isset( $mode ) && in_array( $mode, array( 'profile', 'directory' ) ) ) {\n\t\t\t\t$file = um_path . 'assets/dynamic_css/dynamic_' . $mode . '.php';", "\t\t\t\tif ( file_exists( $file ) )\n\t\t\t\t\tinclude_once $file;\n\t\t\t}", "\t\t\treturn '';\n\t\t}", "\n\t\t/**\n\t\t * Loads a template file\n\t\t *\n\t\t * @param $template\n\t\t * @param array $args\n\t\t */\n\t\tfunction template_load( $template, $args = array() ) {\n\t\t\tif ( is_array( $args ) ) {\n\t\t\t\t$this->set_args = $args;\n\t\t\t}\n\t\t\t$this->load_template( $template );\n\t\t}", "\n\t\t/**\n\t\t * Checks if a template file exists\n\t\t *\n\t\t * @param $template\n\t\t *\n\t\t * @return bool\n\t\t */\n\t\tfunction template_exists($template) {", "\t\t\t$file = um_path . 'templates/' . $template . '.php';\n\t\t\t$theme_file = get_stylesheet_directory() . '/ultimate-member/templates/' . $template . '.php';", "\t\t\tif (file_exists($theme_file) || file_exists($file)) {\n\t\t\t\treturn true;\n\t\t\t}", "\t\t\treturn false;\n\t\t}", "\n\t\t/**\n\t\t * Get File Name without path and extension\n\t\t *\n\t\t * @param $file\n\t\t *\n\t\t * @return mixed|string\n\t\t */\n\t\tfunction get_template_name( $file ) {\n\t\t\t$file = basename( $file );\n\t\t\t$file = preg_replace( '/\\\\.[^.\\\\s]{3,4}$/', '', $file );\n\t\t\treturn $file;\n\t\t}", "\n\t\t/**\n\t\t * Get Templates\n\t\t *\n\t\t * @param null $excluded\n\t\t *\n\t\t * @return mixed\n\t\t */\n\t\tfunction get_templates( $excluded = null ) {", "\t\t\tif ( $excluded ) {\n\t\t\t\t$array[ $excluded ] = __( 'Default Template', 'ultimate-member' );\n\t\t\t}", "\t\t\t$paths[] = glob( um_path . 'templates/' . '*.php' );", "\t\t\tif ( file_exists( get_stylesheet_directory() . '/ultimate-member/templates/' ) ) {\n\t\t\t\t$paths[] = glob( get_stylesheet_directory() . '/ultimate-member/templates/' . '*.php' );\n\t\t\t}", "\t\t\tif ( isset( $paths ) && ! empty( $paths ) ) {", "\t\t\t\tforeach ( $paths as $k => $files ) {", "\t\t\t\t\tif ( isset( $files ) && ! empty( $files ) ) {", "\t\t\t\t\t\tforeach ( $files as $file ) {", "\t\t\t\t\t\t\t$clean_filename = $this->get_template_name( $file );", "\t\t\t\t\t\t\tif ( 0 === strpos( $clean_filename, $excluded ) ) {", "\t\t\t\t\t\t\t\t$source = file_get_contents( $file );\n\t\t\t\t\t\t\t\t$tokens = @\\token_get_all( $source );\n\t\t\t\t\t\t\t\t$comment = array(\n\t\t\t\t\t\t\t\t\tT_COMMENT, // All comments since PHP5\n\t\t\t\t\t\t\t\t\tT_DOC_COMMENT, // PHPDoc comments\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tforeach ( $tokens as $token ) {\n\t\t\t\t\t\t\t\t\tif ( in_array( $token[0], $comment ) && strstr( $token[1], '/* Template:' ) && $clean_filename != $excluded ) {\n\t\t\t\t\t\t\t\t\t\t$txt = $token[1];\n\t\t\t\t\t\t\t\t\t\t$txt = str_replace( '/* Template: ', '', $txt );\n\t\t\t\t\t\t\t\t\t\t$txt = str_replace( ' */', '', $txt );\n\t\t\t\t\t\t\t\t\t\t$array[ $clean_filename ] = $txt;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t}", "\t\t\t\t\t\t}", "\t\t\t\t\t}", "\t\t\t\t}", "\t\t\t}", "\t\t\treturn $array;\n\t\t}", "\n\t\t/**\n\t\t * Get Shortcode for given form ID\n\t\t *\n\t\t * @param $post_id\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction get_shortcode( $post_id ) {\n\t\t\t$shortcode = '[ultimatemember form_id=\"' . $post_id . '\"]';\n\t\t\treturn $shortcode;\n\t\t}", "\n\t\t/**\n\t\t * Get Shortcode for given form ID\n\t\t *\n\t\t * @param $post_id\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction get_default_shortcode( $post_id ) {\n\t\t\t$mode = UM()->query()->get_attr( 'mode', $post_id );", "\t\t\tswitch ( $mode ) {\n\t\t\t\tcase 'login':\n\t\t\t\t\t$shortcode = '[ultimatemember_login]';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'profile':\n\t\t\t\t\t$shortcode = '[ultimatemember_profile]';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'register':\n\t\t\t\t\t$shortcode = '[ultimatemember_register]';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'directory':\n\t\t\t\t\t$shortcode = '[ultimatemember_directory]';\n\t\t\t\t\tbreak;\n\t\t\t}", "\t\t\treturn $shortcode;\n\t\t}", "\n\t\t/**\n\t\t * Convert access lock tags\n\t\t *\n\t\t * @param $str\n\t\t *\n\t\t * @return mixed|string\n\t\t */\n\t\tfunction convert_locker_tags( $str ) {\n\t\t\tadd_filter( 'um_template_tags_patterns_hook', array( &$this, 'add_placeholder' ), 10, 1 );\n\t\t\tadd_filter( 'um_template_tags_replaces_hook', array( &$this, 'add_replace_placeholder' ), 10, 1 );\n\t\t\treturn um_convert_tags( $str, array(), false );\n\t\t}", "\n\t\t/**\n\t\t * Convert user tags in a string\n\t\t *\n\t\t * @param $str\n\t\t *\n\t\t * @return mixed\n\t\t */\n\t\tfunction convert_user_tags( $str ) {", "\t\t\t$pattern_array = array(\n\t\t\t\t'{first_name}',\n\t\t\t\t'{last_name}',\n\t\t\t\t'{display_name}',\n\t\t\t\t'{user_avatar_small}',\n\t\t\t\t'{username}',\n\t\t\t\t'{nickname}',\n\t\t\t);", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_allowed_user_tags_patterns\n\t\t\t * @description Extend user placeholders patterns\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$patterns\",\"type\":\"array\",\"desc\":\"Placeholders\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_allowed_user_tags_patterns', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_allowed_user_tags_patterns', 'my_allowed_user_tags', 10, 1 );\n\t\t\t * function my_allowed_user_tags( $patterns ) {\n\t\t\t * // your code here\n\t\t\t * return $patterns;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$pattern_array = apply_filters( 'um_allowed_user_tags_patterns', $pattern_array );", "\t\t\t//$matches = false;\n\t\t\tforeach ( $pattern_array as $pattern ) {", "\t\t\t\tif ( preg_match( $pattern, $str ) ) {", "\t\t\t\t\t$value = '';\n\t\t\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\t\t\t$usermeta = str_replace( '{', '', $pattern );\n\t\t\t\t\t\t$usermeta = str_replace( '}', '', $usermeta );", "\t\t\t\t\t\tif ( $usermeta == 'user_avatar_small' ) {\n\t\t\t\t\t\t\t$value = get_avatar( um_user( 'ID' ), 40 );\n\t\t\t\t\t\t} elseif ( um_user( $usermeta ) ) {\n\t\t\t\t\t\t\t$value = um_user( $usermeta );\n\t\t\t\t\t\t}", "\t\t\t\t\t\tif ( $usermeta == 'username' ) {\n\t\t\t\t\t\t\t$value = um_user( 'user_login' );\n\t\t\t\t\t\t}", "\t\t\t\t\t\tif ( $usermeta == 'nickname' ) {\n\t\t\t\t\t\t\t$value = um_profile( 'nickname' );\n\t\t\t\t\t\t}", "\t\t\t\t\t\t/**\n\t\t\t\t\t\t * UM hook\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * @type filter\n\t\t\t\t\t\t * @title um_profile_tag_hook__{$usermeta}\n\t\t\t\t\t\t * @description Change usermeta field value\n\t\t\t\t\t\t * @input_vars\n\t\t\t\t\t\t * [{\"var\":\"$value\",\"type\":\"array\",\"desc\":\"Meta field value\"},\n\t\t\t\t\t\t * {\"var\":\"$user_id\",\"type\":\"array\",\"desc\":\"User ID\"}]\n\t\t\t\t\t\t * @change_log\n\t\t\t\t\t\t * [\"Since: 2.0\"]\n\t\t\t\t\t\t * @usage\n\t\t\t\t\t\t * <?php add_filter( 'um_profile_tag_hook__{$usermeta}', 'function_name', 10, 2 ); ?>\n\t\t\t\t\t\t * @example\n\t\t\t\t\t\t * <?php\n\t\t\t\t\t\t * add_filter( 'um_profile_tag_hook__{$usermeta}', 'my_profile_tag', 10, 2 );\n\t\t\t\t\t\t * function my_profile_tag( $value, $user_id ) {\n\t\t\t\t\t\t * // your code here\n\t\t\t\t\t\t * return $value;\n\t\t\t\t\t\t * }\n\t\t\t\t\t\t * ?>\n\t\t\t\t\t\t */\n\t\t\t\t\t\t$value = apply_filters( \"um_profile_tag_hook__{$usermeta}\", $value, um_user( 'ID' ) );\n\t\t\t\t\t}", "\t\t\t\t\t$str = preg_replace( '/' . $pattern . '/', $value, $str );\n\t\t\t\t}", "\t\t\t}", "\t\t\treturn $str;\n\t\t}", "\n\t\t/**\n\t\t * Shortcode: Show custom content to specific role\n\t\t *\n\t\t * Show content to specific roles\n\t\t * [um_show_content roles='member'] <!-- insert content here --> [/um_show_content]\n\t\t * You can add multiple target roles, just use ',' e.g. [um_show_content roles='member,candidates,pets']\n\t\t *\n\t\t * Hide content from specific roles\n\t\t * [um_show_content not='contributors'] <!-- insert content here --> [/um_show_content]\n\t\t * You can add multiple target roles, just use ',' e.g. [um_show_content roles='member,candidates,pets']\n\t\t *\n\t\t * @param array $atts\n\t\t * @param string $content\n\t\t * @return string\n\t\t */\n\t\tfunction um_shortcode_show_content_for_role( $atts = array() , $content = '' ) {\n\t\t\tglobal $user_ID;", "\t\t\tif ( ! is_user_logged_in() ) {\n\t\t\t\treturn;\n\t\t\t}", "\t\t\t$a = shortcode_atts( array(\n\t\t\t\t'roles' => '',\n\t\t\t\t'not' => '',\n\t\t\t\t'is_profile' => false,\n\t\t\t), $atts );", "\t\t\tif ( $a['is_profile'] ) {\n\t\t\t\tum_fetch_user( um_profile_id() );\n\t\t\t} else {\n\t\t\t\tum_fetch_user( $user_ID );\n\t\t\t}", "\t\t\t$current_user_roles = um_user( 'roles' );", "\t\t\tif ( ! empty( $a['not'] ) && ! empty( $a['roles'] ) ) {\n\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\treturn do_shortcode( $this->convert_locker_tags( $content ) );\n\t\t\t\t} else {\n\t\t\t\t\treturn apply_shortcodes( $this->convert_locker_tags( $content ) );\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ( ! empty( $a['not'] ) ) {\n\t\t\t\t$not_in_roles = explode( \",\", $a['not'] );", "\t\t\t\tif ( is_array( $not_in_roles ) && ( empty( $current_user_roles ) || count( array_intersect( $current_user_roles, $not_in_roles ) ) <= 0 ) ) {\n\t\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\t\treturn do_shortcode( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn apply_shortcodes( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$roles = explode( \",\", $a['roles'] );", "\t\t\t\tif ( ! empty( $current_user_roles ) && is_array( $roles ) && count( array_intersect( $current_user_roles, $roles ) ) > 0 ) {\n\t\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\t\treturn do_shortcode( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn apply_shortcodes( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\treturn '';\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t * @param string $content\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tpublic function ultimatemember_searchform( $args = array(), $content = \"\" ) {\n\t\t\tif ( ! UM()->options()->get( 'members_page' ) ) {\n\t\t\t\treturn '';\n\t\t\t}", "\t\t\t$member_directory_ids = array();", "\t\t\t$page_id = UM()->config()->permalinks['members'];\n\t\t\tif ( ! empty( $page_id ) ) {\n\t\t\t\t$members_page = get_post( $page_id );\n\t\t\t\tif ( ! empty( $members_page ) && ! is_wp_error( $members_page ) ) {\n\t\t\t\t\tif ( ! empty( $members_page->post_content ) ) {\n\t\t\t\t\t\tpreg_match_all( '/\\[ultimatemember[^\\]]*?form_id\\=[\\'\"]*?(\\d+)[\\'\"]*?/i', $members_page->post_content, $matches );\n\t\t\t\t\t\tif ( ! empty( $matches[1] ) && is_array( $matches[1] ) ) {\n\t\t\t\t\t\t\t$member_directory_ids = array_map( 'absint', $matches[1] );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ( empty( $member_directory_ids ) ) {\n\t\t\t\treturn '';\n\t\t\t}", "\t\t\t//current user priority role\n\t\t\t$priority_user_role = false;\n\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\t$priority_user_role = UM()->roles()->get_priority_user_role( get_current_user_id() );\n\t\t\t}", "\t\t\t$query = array();\n\t\t\tforeach ( $member_directory_ids as $directory_id ) {\n\t\t\t\t$directory_data = UM()->query()->post_data( $directory_id );", "\t\t\t\tif ( isset( $directory_data['roles_can_search'] ) ) {\n\t\t\t\t\t$directory_data['roles_can_search'] = maybe_unserialize( $directory_data['roles_can_search'] );\n\t\t\t\t}", "\t\t\t\t$show_search = empty( $directory_data['roles_can_search'] ) || ( ! empty( $priority_user_role ) && in_array( $priority_user_role, $directory_data['roles_can_search'] ) );\n\t\t\t\tif ( empty( $directory_data['search'] ) || ! $show_search ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\t$hash = UM()->member_directory()->get_directory_hash( $directory_id );", "\t\t\t\t$query[ 'search_' . $hash ] = ! empty( $_GET[ 'search_' . $hash ] ) ? sanitize_text_field( $_GET[ 'search_' . $hash ] ) : '';\n\t\t\t}", "\t\t\tif ( empty( $query ) ) {\n\t\t\t\treturn '';\n\t\t\t}", "\t\t\t$search_value = array_values( $query );", "\t\t\t$template = UM()->get_template( 'searchform.php', '', array( 'query' => $query, 'search_value' => $search_value[0], 'members_page' => um_get_core_page( 'members' ) ) );", "\t\t\treturn $template;\n\t\t}", "\n\t\t/**\n\t\t * UM Placeholders for login referrer\n\t\t *\n\t\t * @param $placeholders\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction add_placeholder( $placeholders ) {\n\t\t\t$placeholders[] = '{login_referrer}';\n\t\t\treturn $placeholders;\n\t\t}", "\n\t\t/**\n\t\t * UM Replace Placeholders for login referrer\n\t\t *\n\t\t * @param $replace_placeholders\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction add_replace_placeholder( $replace_placeholders ) {\n\t\t\t$replace_placeholders[] = um_dynamic_login_page_redirect();\n\t\t\treturn $replace_placeholders;\n\t\t}", "\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [290], "buggy_code_start_loc": [279], "filenames": ["includes/core/class-shortcodes.php"], "fixing_code_end_loc": [292], "fixing_code_start_loc": [278], "message": "A vulnerability, which was classified as critical, has been found in Ultimate Member Plugin up to 2.5.0. This issue affects the function load_template of the file includes/core/class-shortcodes.php of the component Template Handler. The manipulation of the argument tpl leads to pathname traversal. The attack may be initiated remotely. Upgrading to version 2.5.1 is able to address this issue. The name of the patch is e1bc94c1100f02a129721ba4be5fbc44c3d78ec4. It is recommended to upgrade the affected component. The identifier VDB-213545 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ultimatemember:ultimate_member:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "1D0F9909-DAAA-4B41-A39B-946DC1460D50", "versionEndExcluding": "2.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as critical, has been found in Ultimate Member Plugin up to 2.5.0. This issue affects the function load_template of the file includes/core/class-shortcodes.php of the component Template Handler. The manipulation of the argument tpl leads to pathname traversal. The attack may be initiated remotely. Upgrading to version 2.5.1 is able to address this issue. The name of the patch is e1bc94c1100f02a129721ba4be5fbc44c3d78ec4. It is recommended to upgrade the affected component. The identifier VDB-213545 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2022-3966", "lastModified": "2022-11-17T17:18:07.970", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-11-13T08:15:15.607", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ultimatemember/ultimatemember/commit/e1bc94c1100f02a129721ba4be5fbc44c3d78ec4"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/ultimatemember/ultimatemember/releases/tag/2.5.1"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.213545"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-21"}, {"lang": "en", "value": "CWE-22"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ultimatemember/ultimatemember/commit/e1bc94c1100f02a129721ba4be5fbc44c3d78ec4"}, "type": "CWE-21"}
285
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nnamespace um\\core;", "// Exit if accessed directly\nif ( ! defined( 'ABSPATH' ) ) exit;", "if ( ! class_exists( 'um\\core\\Shortcodes' ) ) {", "\n\t/**\n\t * Class Shortcodes\n\t * @package um\\core\n\t */\n\tclass Shortcodes {", "\t\tvar $profile_role = '';", "\t\t/**\n\t\t * Shortcodes constructor.\n\t\t */\n\t\tfunction __construct() {", "\t\t\t$this->message_mode = false;\n\t\t\t$this->custom_message = '';", "\t\t\t$this->loop = array();", "\t\t\tadd_shortcode( 'ultimatemember', array( &$this, 'ultimatemember' ) );", "\t\t\tadd_shortcode( 'ultimatemember_login', array( &$this, 'ultimatemember_login' ) );\n\t\t\tadd_shortcode( 'ultimatemember_register', array( &$this, 'ultimatemember_register' ) );\n\t\t\tadd_shortcode( 'ultimatemember_profile', array( &$this, 'ultimatemember_profile' ) );\n\t\t\tadd_shortcode( 'ultimatemember_directory', array( &$this, 'ultimatemember_directory' ) );", "\t\t\tadd_shortcode( 'um_loggedin', array( &$this, 'um_loggedin' ) );\n\t\t\tadd_shortcode( 'um_loggedout', array( &$this, 'um_loggedout' ) );\n\t\t\tadd_shortcode( 'um_show_content', array( &$this, 'um_shortcode_show_content_for_role' ) );\n\t\t\tadd_shortcode( 'ultimatemember_searchform', array( &$this, 'ultimatemember_searchform' ) );", "\t\t\tadd_filter( 'body_class', array( &$this, 'body_class' ), 0 );", "\t\t\tadd_filter( 'um_shortcode_args_filter', array( &$this, 'display_logout_form' ), 99 );\n\t\t\tadd_filter( 'um_shortcode_args_filter', array( &$this, 'parse_shortcode_args' ), 99 );", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_emoji_base_uri\n\t\t\t * @description Change Emoji base URL\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$url\",\"type\":\"string\",\"desc\":\"Base URL\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_emoji_base_uri', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_emoji_base_uri', 'my_emoji_base_uri', 10, 1 );\n\t\t\t * function my_emoji_base_uri( $url ) {\n\t\t\t * // your code here\n\t\t\t * return $url;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$base_uri = apply_filters( 'um_emoji_base_uri', 'https://s.w.org/images/core/emoji/' );", "\t\t\t$this->emoji[':)'] = $base_uri . '72x72/1f604.png';\n\t\t\t$this->emoji[':smiley:'] = $base_uri . '72x72/1f603.png';\n\t\t\t$this->emoji[':D'] = $base_uri . '72x72/1f600.png';\n\t\t\t$this->emoji[':$'] = $base_uri . '72x72/1f60a.png';\n\t\t\t$this->emoji[':relaxed:'] = $base_uri . '72x72/263a.png';\n\t\t\t$this->emoji[';)'] = $base_uri . '72x72/1f609.png';\n\t\t\t$this->emoji[':heart_eyes:'] = $base_uri . '72x72/1f60d.png';\n\t\t\t$this->emoji[':kissing_heart:'] = $base_uri . '72x72/1f618.png';\n\t\t\t$this->emoji[':kissing_closed_eyes:'] = $base_uri . '72x72/1f61a.png';\n\t\t\t$this->emoji[':kissing:'] = $base_uri . '72x72/1f617.png';\n\t\t\t$this->emoji[':kissing_smiling_eyes:'] = $base_uri . '72x72/1f619.png';\n\t\t\t$this->emoji[';P'] = $base_uri . '72x72/1f61c.png';\n\t\t\t$this->emoji[':P'] = $base_uri . '72x72/1f61b.png';\n\t\t\t$this->emoji[':stuck_out_tongue_closed_eyes:'] = $base_uri . '72x72/1f61d.png';\n\t\t\t$this->emoji[':flushed:'] = $base_uri . '72x72/1f633.png';\n\t\t\t$this->emoji[':grin:'] = $base_uri . '72x72/1f601.png';\n\t\t\t$this->emoji[':pensive:'] = $base_uri . '72x72/1f614.png';\n\t\t\t$this->emoji[':relieved:'] = $base_uri . '72x72/1f60c.png';\n\t\t\t$this->emoji[':unamused'] = $base_uri . '72x72/1f612.png';\n\t\t\t$this->emoji[':('] = $base_uri . '72x72/1f61e.png';\n\t\t\t$this->emoji[':persevere:'] = $base_uri . '72x72/1f623.png';\n\t\t\t$this->emoji[\":'(\"] = $base_uri . '72x72/1f622.png';\n\t\t\t$this->emoji[':joy:'] = $base_uri . '72x72/1f602.png';\n\t\t\t$this->emoji[':sob:'] = $base_uri . '72x72/1f62d.png';\n\t\t\t$this->emoji[':sleepy:'] = $base_uri . '72x72/1f62a.png';\n\t\t\t$this->emoji[':disappointed_relieved:'] = $base_uri . '72x72/1f625.png';\n\t\t\t$this->emoji[':cold_sweat:'] = $base_uri . '72x72/1f630.png';\n\t\t\t$this->emoji[':sweat_smile:'] = $base_uri . '72x72/1f605.png';\n\t\t\t$this->emoji[':sweat:'] = $base_uri . '72x72/1f613.png';\n\t\t\t$this->emoji[':weary:'] = $base_uri . '72x72/1f629.png';\n\t\t\t$this->emoji[':tired_face:'] = $base_uri . '72x72/1f62b.png';\n\t\t\t$this->emoji[':fearful:'] = $base_uri . '72x72/1f628.png';\n\t\t\t$this->emoji[':scream:'] = $base_uri . '72x72/1f631.png';\n\t\t\t$this->emoji[':angry:'] = $base_uri . '72x72/1f620.png';\n\t\t\t$this->emoji[':rage:'] = $base_uri . '72x72/1f621.png';\n\t\t\t$this->emoji[':triumph'] = $base_uri . '72x72/1f624.png';\n\t\t\t$this->emoji[':confounded:'] = $base_uri . '72x72/1f616.png';\n\t\t\t$this->emoji[':laughing:'] = $base_uri . '72x72/1f606.png';\n\t\t\t$this->emoji[':yum:'] = $base_uri . '72x72/1f60b.png';\n\t\t\t$this->emoji[':mask:'] = $base_uri . '72x72/1f637.png';\n\t\t\t$this->emoji[':cool:'] = $base_uri . '72x72/1f60e.png';\n\t\t\t$this->emoji[':sleeping:'] = $base_uri . '72x72/1f634.png';\n\t\t\t$this->emoji[':dizzy_face:'] = $base_uri . '72x72/1f635.png';\n\t\t\t$this->emoji[':astonished:'] = $base_uri . '72x72/1f632.png';\n\t\t\t$this->emoji[':worried:'] = $base_uri . '72x72/1f61f.png';\n\t\t\t$this->emoji[':frowning:'] = $base_uri . '72x72/1f626.png';\n\t\t\t$this->emoji[':anguished:'] = $base_uri . '72x72/1f627.png';\n\t\t\t$this->emoji[':smiling_imp:'] = $base_uri . '72x72/1f608.png';\n\t\t\t$this->emoji[':imp:'] = $base_uri . '72x72/1f47f.png';\n\t\t\t$this->emoji[':open_mouth:'] = $base_uri . '72x72/1f62e.png';\n\t\t\t$this->emoji[':grimacing:'] = $base_uri . '72x72/1f62c.png';\n\t\t\t$this->emoji[':neutral_face:'] = $base_uri . '72x72/1f610.png';\n\t\t\t$this->emoji[':confused:'] = $base_uri . '72x72/1f615.png';\n\t\t\t$this->emoji[':hushed:'] = $base_uri . '72x72/1f62f.png';\n\t\t\t$this->emoji[':no_mouth:'] = $base_uri . '72x72/1f636.png';\n\t\t\t$this->emoji[':innocent:'] = $base_uri . '72x72/1f607.png';\n\t\t\t$this->emoji[':smirk:'] = $base_uri . '72x72/1f60f.png';\n\t\t\t$this->emoji[':expressionless:'] = $base_uri . '72x72/1f611.png';", "\t\t}", "\n\t\t/**\n\t\t * Conditional logout form\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction display_logout_form( $args ) {\n\t\t\tif ( is_user_logged_in() && isset( $args['mode'] ) && $args['mode'] == 'login' ) {", "\t\t\t\tif ( isset( UM()->user()->preview ) && UM()->user()->preview ) {\n\t\t\t\t\treturn $args;\n\t\t\t\t}", "\t\t\t\tif ( get_current_user_id() != um_user( 'ID' ) ) {\n\t\t\t\t\tum_fetch_user( get_current_user_id() );\n\t\t\t\t}", "\t\t\t\t$args['template'] = 'logout';\n\t\t\t}", "\t\t\treturn $args;\n\t\t}", "\n\t\t/**\n\t\t * Filter shortcode args\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction parse_shortcode_args( $args ) {\n\t\t\tif ( $this->message_mode == true ) {\n\t\t\t\tif ( ! empty( $_REQUEST['um_role'] ) ) {\n\t\t\t\t\t$args['template'] = 'message';\n\t\t\t\t\t$roleID = sanitize_key( $_REQUEST['um_role'] );\n\t\t\t\t\t$role = UM()->roles()->role_data( $roleID );", "\t\t\t\t\tif ( ! empty( $role ) && ! empty( $role['status'] ) ) {\n\t\t\t\t\t\t$message_key = $role['status'] . '_message';\n\t\t\t\t\t\t$this->custom_message = ! empty( $role[ $message_key ] ) ? stripslashes( $role[ $message_key ] ) : '';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tforeach ( $args as $k => $v ) {\n\t\t\t\t$args[ $k ] = maybe_unserialize( $args[ $k ] );\n\t\t\t}", "\t\t\treturn $args;\n\t\t}", "\n\t\t/**\n\t\t * Emoji support\n\t\t *\n\t\t * @param $content\n\t\t *\n\t\t * @return mixed|string\n\t\t */\n\t\tfunction emotize( $content ) {\n\t\t\t$content = stripslashes( $content );\n\t\t\tforeach ( $this->emoji as $code => $val ) {\n\t\t\t\t$regex = str_replace(array('(', ')'), array(\"\\\\\" . '(', \"\\\\\" . ')'), $code);\n\t\t\t\t$content = preg_replace('/(' . $regex . ')(\\s|$)/', '<img src=\"' . $val . '\" alt=\"' . $code . '\" title=\"' . $code . '\" class=\"emoji\" />$2', $content);\n\t\t\t}\n\t\t\treturn $content;\n\t\t}", "\n\t\t/**\n\t\t * Remove wpautop filter for post content if it's UM core page\n\t\t */\n\t\tfunction is_um_page() {\n\t\t\tif ( is_ultimatemember() ) {\n\t\t\t\tremove_filter( 'the_content', 'wpautop' );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * Extend body classes\n\t\t *\n\t\t * @param $classes\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction body_class( $classes ) {\n\t\t\t$array = UM()->config()->permalinks;\n\t\t\tif ( ! $array ) {\n\t\t\t\treturn $classes;\n\t\t\t}", "\t\t\tforeach ( $array as $slug => $info ) {\n\t\t\t\tif ( um_is_core_page( $slug ) ) {", "\t\t\t\t\t$classes[] = 'um-page-' . $slug;", "\t\t\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\t\t\t$classes[] = 'um-page-loggedin';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$classes[] = 'um-page-loggedout';\n\t\t\t\t\t}", "\t\t\t\t}\n\t\t\t}", "\t\t\tif ( um_is_core_page( 'user' ) && um_is_user_himself() ) {\n\t\t\t\t$classes[] = 'um-own-profile';\n\t\t\t}", "\t\t\treturn $classes;\n\t\t}", "\n\t\t/**\n\t\t * Retrieve core login form\n\t\t *\n\t\t * @return int\n\t\t */\n\t\tfunction core_login_form() {\n\t\t\t$forms = get_posts(array('post_type' => 'um_form', 'posts_per_page' => 1, 'meta_key' => '_um_core', 'meta_value' => 'login'));\n\t\t\t$form_id = isset( $forms[0]->ID ) ? $forms[0]->ID: 0;", "\t\t\treturn $form_id;\n\t\t}", "\n\t\t/**\n\t\t * Load a compatible template\n\t\t *\n\t\t * @param $tpl\n\t\t */\n\t\tfunction load_template( $tpl ) {\n\t\t\t$loop = ( $this->loop ) ? $this->loop : array();", "\t\t\tif ( isset( $this->set_args ) && is_array( $this->set_args ) ) {\n\t\t\t\t$args = $this->set_args;", "\t\t\t\tunset( $args['file'] );\n\t\t\t\tunset( $args['theme_file'] );\n\t\t\t\tunset( $args['tpl'] );", "\t\t\t\t$args = apply_filters( 'um_template_load_args', $args, $tpl );", "\t\t\t\textract( $args );\n\t\t\t}\n", "", "\t\t\t$file = um_path . \"templates/{$tpl}.php\";\n\t\t\t$theme_file = get_stylesheet_directory() . \"/ultimate-member/templates/{$tpl}.php\";\n\t\t\tif ( file_exists( $theme_file ) ) {\n\t\t\t\t$file = $theme_file;\n\t\t\t}", "\t\t\tif ( file_exists( $file ) ) {", "\t\t\t\t// Avoid Directory Traversal vulnerability by the checking the realpath.\n\t\t\t\t// Templates can be situated only in the get_stylesheet_directory() or plugindir templates.\n\t\t\t\t$real_file = realpath( $file );\n\t\t\t\tif ( 0 === strpos( $real_file, um_path . \"templates\" . DIRECTORY_SEPARATOR ) || 0 === strpos( $real_file, get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'ultimate-member' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR ) ) {\n\t\t\t\t\tinclude $file;\n\t\t\t\t}", "\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * Add class based on shortcode\n\t\t *\n\t\t * @param $mode\n\t\t * @param array $args\n\t\t *\n\t\t * @return mixed|string|void\n\t\t */\n\t\tfunction get_class($mode, $args = array()) {", "\t\t\t$classes = 'um-' . $mode;", "\t\t\tif (is_admin()) {\n\t\t\t\t$classes .= ' um-in-admin';\n\t\t\t}", "\t\t\tif (isset(UM()->form()->errors) && UM()->form()->errors) {\n\t\t\t\t$classes .= ' um-err';\n\t\t\t}", "\t\t\tif (UM()->fields()->editing == true) {\n\t\t\t\t$classes .= ' um-editing';\n\t\t\t}", "\t\t\tif (UM()->fields()->viewing == true) {\n\t\t\t\t$classes .= ' um-viewing';\n\t\t\t}", "\t\t\tif (isset($args['template']) && $args['template'] != $args['mode']) {\n\t\t\t\t$classes .= ' um-' . $args['template'];\n\t\t\t}", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_form_official_classes__hook\n\t\t\t * @description Change official form classes\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$classes\",\"type\":\"string\",\"desc\":\"Classes string\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_form_official_classes__hook', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_form_official_classes__hook', 'my_form_official_classes', 10, 1 );\n\t\t\t * function my_form_official_classes( $classes ) {\n\t\t\t * // your code here\n\t\t\t * return $classes;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$classes = apply_filters( 'um_form_official_classes__hook', $classes );\n\t\t\treturn $classes;\n\t\t}", "\n\t\t/**\n\t\t * Logged-in only content\n\t\t *\n\t\t * @param array $args\n\t\t * @param string $content\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction um_loggedin( $args = array(), $content = \"\" ) {\n\t\t\tob_start();", "\t\t\t$args = shortcode_atts(\n\t\t\t\tarray(\n\t\t\t\t\t'lock_text' => __( 'This content has been restricted to logged in users only. Please <a href=\"{login_referrer}\">login</a> to view this content.', 'ultimate-member' ),\n\t\t\t\t\t'show_lock' => 'yes',\n\t\t\t\t),\n\t\t\t\t$args,\n\t\t\t\t'um_loggedin'\n\t\t\t);", "\t\t\tif ( ! is_user_logged_in() ) {\n\t\t\t\tif ( 'no' === $args['show_lock'] ) {\n\t\t\t\t\techo '';\n\t\t\t\t} else {\n\t\t\t\t\t$args['lock_text'] = $this->convert_locker_tags( $args['lock_text'] );\n\t\t\t\t\tUM()->get_template( 'login-to-view.php', '', $args, true );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\techo do_shortcode( $this->convert_locker_tags( wpautop( $content ) ) );\n\t\t\t\t} else {\n\t\t\t\t\techo apply_shortcodes( $this->convert_locker_tags( wpautop( $content ) ) );\n\t\t\t\t}\n\t\t\t}", "\t\t\t$output = ob_get_clean();", "\t\t\treturn htmlspecialchars_decode( $output, ENT_NOQUOTES );\n\t\t}", "\n\t\t/**\n\t\t * Logged-out only content\n\t\t *\n\t\t * @param array $args\n\t\t * @param string $content\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction um_loggedout( $args = array(), $content = '' ) {\n\t\t\tob_start();", "\t\t\t// Hide for logged in users\n\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\techo '';\n\t\t\t} else {\n\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\techo do_shortcode( wpautop( $content ) );\n\t\t\t\t} else {\n\t\t\t\t\techo apply_shortcodes( wpautop( $content ) );\n\t\t\t\t}\n\t\t\t}", "\t\t\t$output = ob_get_clean();\n\t\t\treturn $output;\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_login( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_login = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'login' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_login;\n\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_register( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_register = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'register' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_register;\n\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_profile( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_profile = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'profile' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_profile;", "\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember_directory( $args = array() ) {\n\t\t\tglobal $wpdb;", "\t\t\t$args = ! empty( $args ) ? $args : array();", "\t\t\t$default_directory = $wpdb->get_var(\n\t\t\t\t\"SELECT pm.post_id \n\t\t\t\tFROM {$wpdb->postmeta} pm \n\t\t\t\tLEFT JOIN {$wpdb->postmeta} pm2 ON( pm.post_id = pm2.post_id AND pm2.meta_key = '_um_is_default' )\n\t\t\t\tWHERE pm.meta_key = '_um_mode' AND \n\t\t\t\t\t pm.meta_value = 'directory' AND \n\t\t\t\t\t pm2.meta_value = '1'\"\n\t\t\t);", "\t\t\t$args['form_id'] = $default_directory;", "\t\t\t$shortcode_attrs = '';\n\t\t\tforeach ( $args as $key => $value ) {\n\t\t\t\t$shortcode_attrs .= \" {$key}=\\\"{$value}\\\"\";\n\t\t\t}", "\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\treturn do_shortcode( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t} else {\n\t\t\t\treturn apply_shortcodes( \"[ultimatemember {$shortcode_attrs} /]\" );\n\t\t\t}\n\t\t}", "\n\t\t/**\n\t\t * Shortcode\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction ultimatemember( $args = array() ) {\n\t\t\treturn $this->load( $args );\n\t\t}", "\n\t\t/**\n\t\t * Load a module with global function\n\t\t *\n\t\t * @param $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction load( $args ) {\n\t\t\t$defaults = array();\n\t\t\t$args = wp_parse_args( $args, $defaults );", "\t\t\t// when to not continue\n\t\t\t$this->form_id = isset( $args['form_id'] ) ? $args['form_id'] : null;\n\t\t\tif ( ! $this->form_id ) {\n\t\t\t\treturn;\n\t\t\t}", "\t\t\t$this->form_status = get_post_status( $this->form_id );\n\t\t\tif ( $this->form_status != 'publish' ) {\n\t\t\t\treturn;\n\t\t\t}", "\t\t\t// get data into one global array\n\t\t\t$post_data = UM()->query()->post_data( $this->form_id );\n\t\t\t$args = array_merge( $args, $post_data );", "\t\t\tob_start();", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_pre_args_setup\n\t\t\t * @description Change arguments on load shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$post_data\",\"type\":\"string\",\"desc\":\"$_POST data\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_pre_args_setup', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_pre_args_setup', 'my_pre_args_setup', 10, 1 );\n\t\t\t * function my_pre_args_setup( $post_data ) {\n\t\t\t * // your code here\n\t\t\t * return $post_data;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$args = apply_filters( 'um_pre_args_setup', $args );", "\t\t\tif ( ! isset( $args['template'] ) ) {\n\t\t\t\t$args['template'] = '';\n\t\t\t}", "\t\t\tif ( isset( $post_data['template'] ) && $post_data['template'] != $args['template'] ) {\n\t\t\t\t$args['template'] = $post_data['template'];\n\t\t\t}", "\t\t\tif ( ! $this->template_exists( $args['template'] ) ) {\n\t\t\t\t$args['template'] = $post_data['mode'];\n\t\t\t}", "\t\t\tif ( ! isset( $post_data['template'] ) ) {\n\t\t\t\t$post_data['template'] = $post_data['mode'];\n\t\t\t}", "\t\t\tif ( 'directory' == $args['mode'] ) {\n\t\t\t\twp_enqueue_script( 'um_members' );\n\t\t\t\tif ( is_rtl() ) {\n\t\t\t\t\twp_enqueue_style( 'um_members_rtl' );\n\t\t\t\t} else {\n\t\t\t\t\twp_enqueue_style( 'um_members' );\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ( 'directory' != $args['mode'] ) {\n\t\t\t\t$args = array_merge( $post_data, $args );", "\t\t\t\tif ( empty( $args['use_custom_settings'] ) ) {\n\t\t\t\t\t$args = array_merge( $args, $this->get_css_args( $args ) );\n\t\t\t\t} else {\n\t\t\t\t\t$args = array_merge( $this->get_css_args( $args ), $args );\n\t\t\t\t}\n\t\t\t}\n\t\t\t// filter for arguments", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_shortcode_args_filter\n\t\t\t * @description Change arguments on load shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"string\",\"desc\":\"Shortcode arguments\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_shortcode_args_filter', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_shortcode_args_filter', 'my_shortcode_args', 10, 1 );\n\t\t\t * function my_shortcode_args( $args ) {\n\t\t\t * // your code here\n\t\t\t * return $args;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$args = apply_filters( 'um_shortcode_args_filter', $args );", "\t\t\t/**\n\t\t\t * @var string $mode\n\t\t\t */\n\t\t\textract( $args, EXTR_SKIP );", "\t\t\t//not display on admin preview\n\t\t\tif ( empty( $_POST['act_id'] ) || sanitize_key( $_POST['act_id'] ) !== 'um_admin_preview_form' ) {", "\t\t\t\t$enable_loggedin_registration = apply_filters( 'um_registration_for_loggedin_users', false, $args );", "\t\t\t\tif ( 'register' == $mode && is_user_logged_in() && ! $enable_loggedin_registration ) {\n\t\t\t\t\tob_get_clean();\n\t\t\t\t\treturn __( 'You are already registered', 'ultimate-member' );\n\t\t\t\t}\n\t\t\t}", "\t\t\t// for profiles only\n\t\t\tif ( $mode == 'profile' && um_profile_id() ) {", "\t\t\t\t//set requested user if it's not setup from permalinks (for not profile page in edit mode)\n\t\t\t\tif ( ! um_get_requested_user() ) {\n\t\t\t\t\tum_set_requested_user( um_profile_id() );\n\t\t\t\t}", "\t\t\t\tif ( ! empty( $args['use_custom_settings'] ) ) { // Option \"Apply custom settings to this form\"\n\t\t\t\t\tif ( ! empty( $args['role'] ) ) { // Option \"Make this profile form role-specific\"", "\t\t\t\t\t\t// show the first Profile Form with role selected, don't show profile forms below the page with other role-specific setting\n\t\t\t\t\t\tif ( empty( $this->profile_role ) ) {\n\t\t\t\t\t\t\t$current_user_roles = UM()->roles()->get_all_user_roles( um_profile_id() );", "\t\t\t\t\t\t\tif ( empty( $current_user_roles ) ) {\n\t\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t} elseif ( is_array( $args['role'] ) ) {\n\t\t\t\t\t\t\t\tif ( ! count( array_intersect( $args['role'], $current_user_roles ) ) ) {\n\t\t\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif ( ! in_array( $args['role'], $current_user_roles ) ) {\n\t\t\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t$this->profile_role = $args['role'];\n\t\t\t\t\t\t} elseif ( $this->profile_role != $args['role'] ) {\n\t\t\t\t\t\t\tob_get_clean();\n\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_pre_{$mode}_shortcode\n\t\t\t * @description Action pre-load form shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"array\",\"desc\":\"Form shortcode pre-loading\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_pre_{$mode}_shortcode', 'function_name', 10, 1 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_pre_{$mode}_shortcode', 'my_pre_shortcode', 10, 1 );\n\t\t\t * function my_pre_shortcode( $args ) {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( \"um_pre_{$mode}_shortcode\", $args );\n\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_before_form_is_loaded\n\t\t\t * @description Action pre-load form shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"array\",\"desc\":\"Form shortcode pre-loading\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_before_form_is_loaded', 'function_name', 10, 1 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_before_form_is_loaded', 'my_pre_shortcode', 10, 1 );\n\t\t\t * function my_pre_shortcode( $args ) {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( \"um_before_form_is_loaded\", $args );\n\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_before_{$mode}_form_is_loaded\n\t\t\t * @description Action pre-load form shortcode\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$args\",\"type\":\"array\",\"desc\":\"Form shortcode pre-loading\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_before_{$mode}_form_is_loaded', 'function_name', 10, 1 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_before_{$mode}_form_is_loaded', 'my_pre_shortcode', 10, 1 );\n\t\t\t * function my_pre_shortcode( $args ) {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( \"um_before_{$mode}_form_is_loaded\", $args );", "\t\t\t$this->template_load( $template, $args );", "\t\t\t$this->dynamic_css( $args );", "\t\t\tif ( um_get_requested_user() || $mode == 'logout' ) {\n\t\t\t\tum_reset_user();\n\t\t\t}", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type action\n\t\t\t * @title um_after_everything_output\n\t\t\t * @description Action after load shortcode content\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage add_action( 'um_after_everything_output', 'function_name', 10 );\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_action( 'um_after_everything_output', 'my_after_everything_output', 10 );\n\t\t\t * function my_after_everything_output() {\n\t\t\t * // your code here\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\tdo_action( 'um_after_everything_output' );", "\t\t\t$output = ob_get_clean();\n\t\t\treturn $output;\n\t\t}", "\n\t\t/**\n\t\t * Get dynamic CSS args\n\t\t *\n\t\t * @param $args\n\t\t * @return array\n\t\t */\n\t\tfunction get_css_args( $args ) {\n\t\t\t$arr = um_styling_defaults( $args['mode'] );\n\t\t\t$arr = array_merge( $arr, array( 'form_id' => $args['form_id'], 'mode' => $args['mode'] ) );\n\t\t\treturn $arr;\n\t\t}", "\n\t\t/**\n\t\t * Load dynamic css\n\t\t *\n\t\t * @param array $args\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction dynamic_css( $args = array() ) {\n\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_disable_dynamic_global_css\n\t\t\t * @description Turn on for disable global dynamic CSS for fix the issue #306\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$disable\",\"type\":\"bool\",\"desc\":\"Disable global CSS\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_disable_dynamic_global_css', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_disable_dynamic_global_css', 'my_disable_dynamic_global_css', 10, 1 );\n\t\t\t * function my_disable_dynamic_global_css( $disable ) {\n\t\t\t * // your code here\n\t\t\t * return $disable;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$disable_css = apply_filters( 'um_disable_dynamic_global_css', false );\n\t\t\tif ( $disable_css )\n\t\t\t\treturn '';", "\t\t\t/**\n\t\t\t * @var $mode\n\t\t\t */\n\t\t\textract( $args );", "\t\t\tinclude_once um_path . 'assets/dynamic_css/dynamic_global.php';", "\t\t\tif ( isset( $mode ) && in_array( $mode, array( 'profile', 'directory' ) ) ) {\n\t\t\t\t$file = um_path . 'assets/dynamic_css/dynamic_' . $mode . '.php';", "\t\t\t\tif ( file_exists( $file ) )\n\t\t\t\t\tinclude_once $file;\n\t\t\t}", "\t\t\treturn '';\n\t\t}", "\n\t\t/**\n\t\t * Loads a template file\n\t\t *\n\t\t * @param $template\n\t\t * @param array $args\n\t\t */\n\t\tfunction template_load( $template, $args = array() ) {\n\t\t\tif ( is_array( $args ) ) {\n\t\t\t\t$this->set_args = $args;\n\t\t\t}\n\t\t\t$this->load_template( $template );\n\t\t}", "\n\t\t/**\n\t\t * Checks if a template file exists\n\t\t *\n\t\t * @param $template\n\t\t *\n\t\t * @return bool\n\t\t */\n\t\tfunction template_exists($template) {", "\t\t\t$file = um_path . 'templates/' . $template . '.php';\n\t\t\t$theme_file = get_stylesheet_directory() . '/ultimate-member/templates/' . $template . '.php';", "\t\t\tif (file_exists($theme_file) || file_exists($file)) {\n\t\t\t\treturn true;\n\t\t\t}", "\t\t\treturn false;\n\t\t}", "\n\t\t/**\n\t\t * Get File Name without path and extension\n\t\t *\n\t\t * @param $file\n\t\t *\n\t\t * @return mixed|string\n\t\t */\n\t\tfunction get_template_name( $file ) {\n\t\t\t$file = basename( $file );\n\t\t\t$file = preg_replace( '/\\\\.[^.\\\\s]{3,4}$/', '', $file );\n\t\t\treturn $file;\n\t\t}", "\n\t\t/**\n\t\t * Get Templates\n\t\t *\n\t\t * @param null $excluded\n\t\t *\n\t\t * @return mixed\n\t\t */\n\t\tfunction get_templates( $excluded = null ) {", "\t\t\tif ( $excluded ) {\n\t\t\t\t$array[ $excluded ] = __( 'Default Template', 'ultimate-member' );\n\t\t\t}", "\t\t\t$paths[] = glob( um_path . 'templates/' . '*.php' );", "\t\t\tif ( file_exists( get_stylesheet_directory() . '/ultimate-member/templates/' ) ) {\n\t\t\t\t$paths[] = glob( get_stylesheet_directory() . '/ultimate-member/templates/' . '*.php' );\n\t\t\t}", "\t\t\tif ( isset( $paths ) && ! empty( $paths ) ) {", "\t\t\t\tforeach ( $paths as $k => $files ) {", "\t\t\t\t\tif ( isset( $files ) && ! empty( $files ) ) {", "\t\t\t\t\t\tforeach ( $files as $file ) {", "\t\t\t\t\t\t\t$clean_filename = $this->get_template_name( $file );", "\t\t\t\t\t\t\tif ( 0 === strpos( $clean_filename, $excluded ) ) {", "\t\t\t\t\t\t\t\t$source = file_get_contents( $file );\n\t\t\t\t\t\t\t\t$tokens = @\\token_get_all( $source );\n\t\t\t\t\t\t\t\t$comment = array(\n\t\t\t\t\t\t\t\t\tT_COMMENT, // All comments since PHP5\n\t\t\t\t\t\t\t\t\tT_DOC_COMMENT, // PHPDoc comments\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tforeach ( $tokens as $token ) {\n\t\t\t\t\t\t\t\t\tif ( in_array( $token[0], $comment ) && strstr( $token[1], '/* Template:' ) && $clean_filename != $excluded ) {\n\t\t\t\t\t\t\t\t\t\t$txt = $token[1];\n\t\t\t\t\t\t\t\t\t\t$txt = str_replace( '/* Template: ', '', $txt );\n\t\t\t\t\t\t\t\t\t\t$txt = str_replace( ' */', '', $txt );\n\t\t\t\t\t\t\t\t\t\t$array[ $clean_filename ] = $txt;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t}", "\t\t\t\t\t\t}", "\t\t\t\t\t}", "\t\t\t\t}", "\t\t\t}", "\t\t\treturn $array;\n\t\t}", "\n\t\t/**\n\t\t * Get Shortcode for given form ID\n\t\t *\n\t\t * @param $post_id\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction get_shortcode( $post_id ) {\n\t\t\t$shortcode = '[ultimatemember form_id=\"' . $post_id . '\"]';\n\t\t\treturn $shortcode;\n\t\t}", "\n\t\t/**\n\t\t * Get Shortcode for given form ID\n\t\t *\n\t\t * @param $post_id\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tfunction get_default_shortcode( $post_id ) {\n\t\t\t$mode = UM()->query()->get_attr( 'mode', $post_id );", "\t\t\tswitch ( $mode ) {\n\t\t\t\tcase 'login':\n\t\t\t\t\t$shortcode = '[ultimatemember_login]';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'profile':\n\t\t\t\t\t$shortcode = '[ultimatemember_profile]';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'register':\n\t\t\t\t\t$shortcode = '[ultimatemember_register]';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'directory':\n\t\t\t\t\t$shortcode = '[ultimatemember_directory]';\n\t\t\t\t\tbreak;\n\t\t\t}", "\t\t\treturn $shortcode;\n\t\t}", "\n\t\t/**\n\t\t * Convert access lock tags\n\t\t *\n\t\t * @param $str\n\t\t *\n\t\t * @return mixed|string\n\t\t */\n\t\tfunction convert_locker_tags( $str ) {\n\t\t\tadd_filter( 'um_template_tags_patterns_hook', array( &$this, 'add_placeholder' ), 10, 1 );\n\t\t\tadd_filter( 'um_template_tags_replaces_hook', array( &$this, 'add_replace_placeholder' ), 10, 1 );\n\t\t\treturn um_convert_tags( $str, array(), false );\n\t\t}", "\n\t\t/**\n\t\t * Convert user tags in a string\n\t\t *\n\t\t * @param $str\n\t\t *\n\t\t * @return mixed\n\t\t */\n\t\tfunction convert_user_tags( $str ) {", "\t\t\t$pattern_array = array(\n\t\t\t\t'{first_name}',\n\t\t\t\t'{last_name}',\n\t\t\t\t'{display_name}',\n\t\t\t\t'{user_avatar_small}',\n\t\t\t\t'{username}',\n\t\t\t\t'{nickname}',\n\t\t\t);", "\t\t\t/**\n\t\t\t * UM hook\n\t\t\t *\n\t\t\t * @type filter\n\t\t\t * @title um_allowed_user_tags_patterns\n\t\t\t * @description Extend user placeholders patterns\n\t\t\t * @input_vars\n\t\t\t * [{\"var\":\"$patterns\",\"type\":\"array\",\"desc\":\"Placeholders\"}]\n\t\t\t * @change_log\n\t\t\t * [\"Since: 2.0\"]\n\t\t\t * @usage\n\t\t\t * <?php add_filter( 'um_allowed_user_tags_patterns', 'function_name', 10, 1 ); ?>\n\t\t\t * @example\n\t\t\t * <?php\n\t\t\t * add_filter( 'um_allowed_user_tags_patterns', 'my_allowed_user_tags', 10, 1 );\n\t\t\t * function my_allowed_user_tags( $patterns ) {\n\t\t\t * // your code here\n\t\t\t * return $patterns;\n\t\t\t * }\n\t\t\t * ?>\n\t\t\t */\n\t\t\t$pattern_array = apply_filters( 'um_allowed_user_tags_patterns', $pattern_array );", "\t\t\t//$matches = false;\n\t\t\tforeach ( $pattern_array as $pattern ) {", "\t\t\t\tif ( preg_match( $pattern, $str ) ) {", "\t\t\t\t\t$value = '';\n\t\t\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\t\t\t$usermeta = str_replace( '{', '', $pattern );\n\t\t\t\t\t\t$usermeta = str_replace( '}', '', $usermeta );", "\t\t\t\t\t\tif ( $usermeta == 'user_avatar_small' ) {\n\t\t\t\t\t\t\t$value = get_avatar( um_user( 'ID' ), 40 );\n\t\t\t\t\t\t} elseif ( um_user( $usermeta ) ) {\n\t\t\t\t\t\t\t$value = um_user( $usermeta );\n\t\t\t\t\t\t}", "\t\t\t\t\t\tif ( $usermeta == 'username' ) {\n\t\t\t\t\t\t\t$value = um_user( 'user_login' );\n\t\t\t\t\t\t}", "\t\t\t\t\t\tif ( $usermeta == 'nickname' ) {\n\t\t\t\t\t\t\t$value = um_profile( 'nickname' );\n\t\t\t\t\t\t}", "\t\t\t\t\t\t/**\n\t\t\t\t\t\t * UM hook\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * @type filter\n\t\t\t\t\t\t * @title um_profile_tag_hook__{$usermeta}\n\t\t\t\t\t\t * @description Change usermeta field value\n\t\t\t\t\t\t * @input_vars\n\t\t\t\t\t\t * [{\"var\":\"$value\",\"type\":\"array\",\"desc\":\"Meta field value\"},\n\t\t\t\t\t\t * {\"var\":\"$user_id\",\"type\":\"array\",\"desc\":\"User ID\"}]\n\t\t\t\t\t\t * @change_log\n\t\t\t\t\t\t * [\"Since: 2.0\"]\n\t\t\t\t\t\t * @usage\n\t\t\t\t\t\t * <?php add_filter( 'um_profile_tag_hook__{$usermeta}', 'function_name', 10, 2 ); ?>\n\t\t\t\t\t\t * @example\n\t\t\t\t\t\t * <?php\n\t\t\t\t\t\t * add_filter( 'um_profile_tag_hook__{$usermeta}', 'my_profile_tag', 10, 2 );\n\t\t\t\t\t\t * function my_profile_tag( $value, $user_id ) {\n\t\t\t\t\t\t * // your code here\n\t\t\t\t\t\t * return $value;\n\t\t\t\t\t\t * }\n\t\t\t\t\t\t * ?>\n\t\t\t\t\t\t */\n\t\t\t\t\t\t$value = apply_filters( \"um_profile_tag_hook__{$usermeta}\", $value, um_user( 'ID' ) );\n\t\t\t\t\t}", "\t\t\t\t\t$str = preg_replace( '/' . $pattern . '/', $value, $str );\n\t\t\t\t}", "\t\t\t}", "\t\t\treturn $str;\n\t\t}", "\n\t\t/**\n\t\t * Shortcode: Show custom content to specific role\n\t\t *\n\t\t * Show content to specific roles\n\t\t * [um_show_content roles='member'] <!-- insert content here --> [/um_show_content]\n\t\t * You can add multiple target roles, just use ',' e.g. [um_show_content roles='member,candidates,pets']\n\t\t *\n\t\t * Hide content from specific roles\n\t\t * [um_show_content not='contributors'] <!-- insert content here --> [/um_show_content]\n\t\t * You can add multiple target roles, just use ',' e.g. [um_show_content roles='member,candidates,pets']\n\t\t *\n\t\t * @param array $atts\n\t\t * @param string $content\n\t\t * @return string\n\t\t */\n\t\tfunction um_shortcode_show_content_for_role( $atts = array() , $content = '' ) {\n\t\t\tglobal $user_ID;", "\t\t\tif ( ! is_user_logged_in() ) {\n\t\t\t\treturn;\n\t\t\t}", "\t\t\t$a = shortcode_atts( array(\n\t\t\t\t'roles' => '',\n\t\t\t\t'not' => '',\n\t\t\t\t'is_profile' => false,\n\t\t\t), $atts );", "\t\t\tif ( $a['is_profile'] ) {\n\t\t\t\tum_fetch_user( um_profile_id() );\n\t\t\t} else {\n\t\t\t\tum_fetch_user( $user_ID );\n\t\t\t}", "\t\t\t$current_user_roles = um_user( 'roles' );", "\t\t\tif ( ! empty( $a['not'] ) && ! empty( $a['roles'] ) ) {\n\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\treturn do_shortcode( $this->convert_locker_tags( $content ) );\n\t\t\t\t} else {\n\t\t\t\t\treturn apply_shortcodes( $this->convert_locker_tags( $content ) );\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ( ! empty( $a['not'] ) ) {\n\t\t\t\t$not_in_roles = explode( \",\", $a['not'] );", "\t\t\t\tif ( is_array( $not_in_roles ) && ( empty( $current_user_roles ) || count( array_intersect( $current_user_roles, $not_in_roles ) ) <= 0 ) ) {\n\t\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\t\treturn do_shortcode( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn apply_shortcodes( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$roles = explode( \",\", $a['roles'] );", "\t\t\t\tif ( ! empty( $current_user_roles ) && is_array( $roles ) && count( array_intersect( $current_user_roles, $roles ) ) > 0 ) {\n\t\t\t\t\tif ( version_compare( get_bloginfo('version'),'5.4', '<' ) ) {\n\t\t\t\t\t\treturn do_shortcode( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn apply_shortcodes( $this->convert_locker_tags( $content ) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\treturn '';\n\t\t}", "\n\t\t/**\n\t\t * @param array $args\n\t\t * @param string $content\n\t\t *\n\t\t * @return string\n\t\t */\n\t\tpublic function ultimatemember_searchform( $args = array(), $content = \"\" ) {\n\t\t\tif ( ! UM()->options()->get( 'members_page' ) ) {\n\t\t\t\treturn '';\n\t\t\t}", "\t\t\t$member_directory_ids = array();", "\t\t\t$page_id = UM()->config()->permalinks['members'];\n\t\t\tif ( ! empty( $page_id ) ) {\n\t\t\t\t$members_page = get_post( $page_id );\n\t\t\t\tif ( ! empty( $members_page ) && ! is_wp_error( $members_page ) ) {\n\t\t\t\t\tif ( ! empty( $members_page->post_content ) ) {\n\t\t\t\t\t\tpreg_match_all( '/\\[ultimatemember[^\\]]*?form_id\\=[\\'\"]*?(\\d+)[\\'\"]*?/i', $members_page->post_content, $matches );\n\t\t\t\t\t\tif ( ! empty( $matches[1] ) && is_array( $matches[1] ) ) {\n\t\t\t\t\t\t\t$member_directory_ids = array_map( 'absint', $matches[1] );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ( empty( $member_directory_ids ) ) {\n\t\t\t\treturn '';\n\t\t\t}", "\t\t\t//current user priority role\n\t\t\t$priority_user_role = false;\n\t\t\tif ( is_user_logged_in() ) {\n\t\t\t\t$priority_user_role = UM()->roles()->get_priority_user_role( get_current_user_id() );\n\t\t\t}", "\t\t\t$query = array();\n\t\t\tforeach ( $member_directory_ids as $directory_id ) {\n\t\t\t\t$directory_data = UM()->query()->post_data( $directory_id );", "\t\t\t\tif ( isset( $directory_data['roles_can_search'] ) ) {\n\t\t\t\t\t$directory_data['roles_can_search'] = maybe_unserialize( $directory_data['roles_can_search'] );\n\t\t\t\t}", "\t\t\t\t$show_search = empty( $directory_data['roles_can_search'] ) || ( ! empty( $priority_user_role ) && in_array( $priority_user_role, $directory_data['roles_can_search'] ) );\n\t\t\t\tif ( empty( $directory_data['search'] ) || ! $show_search ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\t$hash = UM()->member_directory()->get_directory_hash( $directory_id );", "\t\t\t\t$query[ 'search_' . $hash ] = ! empty( $_GET[ 'search_' . $hash ] ) ? sanitize_text_field( $_GET[ 'search_' . $hash ] ) : '';\n\t\t\t}", "\t\t\tif ( empty( $query ) ) {\n\t\t\t\treturn '';\n\t\t\t}", "\t\t\t$search_value = array_values( $query );", "\t\t\t$template = UM()->get_template( 'searchform.php', '', array( 'query' => $query, 'search_value' => $search_value[0], 'members_page' => um_get_core_page( 'members' ) ) );", "\t\t\treturn $template;\n\t\t}", "\n\t\t/**\n\t\t * UM Placeholders for login referrer\n\t\t *\n\t\t * @param $placeholders\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction add_placeholder( $placeholders ) {\n\t\t\t$placeholders[] = '{login_referrer}';\n\t\t\treturn $placeholders;\n\t\t}", "\n\t\t/**\n\t\t * UM Replace Placeholders for login referrer\n\t\t *\n\t\t * @param $replace_placeholders\n\t\t *\n\t\t * @return array\n\t\t */\n\t\tfunction add_replace_placeholder( $replace_placeholders ) {\n\t\t\t$replace_placeholders[] = um_dynamic_login_page_redirect();\n\t\t\treturn $replace_placeholders;\n\t\t}", "\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [290], "buggy_code_start_loc": [279], "filenames": ["includes/core/class-shortcodes.php"], "fixing_code_end_loc": [292], "fixing_code_start_loc": [278], "message": "A vulnerability, which was classified as critical, has been found in Ultimate Member Plugin up to 2.5.0. This issue affects the function load_template of the file includes/core/class-shortcodes.php of the component Template Handler. The manipulation of the argument tpl leads to pathname traversal. The attack may be initiated remotely. Upgrading to version 2.5.1 is able to address this issue. The name of the patch is e1bc94c1100f02a129721ba4be5fbc44c3d78ec4. It is recommended to upgrade the affected component. The identifier VDB-213545 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ultimatemember:ultimate_member:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "1D0F9909-DAAA-4B41-A39B-946DC1460D50", "versionEndExcluding": "2.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as critical, has been found in Ultimate Member Plugin up to 2.5.0. This issue affects the function load_template of the file includes/core/class-shortcodes.php of the component Template Handler. The manipulation of the argument tpl leads to pathname traversal. The attack may be initiated remotely. Upgrading to version 2.5.1 is able to address this issue. The name of the patch is e1bc94c1100f02a129721ba4be5fbc44c3d78ec4. It is recommended to upgrade the affected component. The identifier VDB-213545 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2022-3966", "lastModified": "2022-11-17T17:18:07.970", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-11-13T08:15:15.607", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ultimatemember/ultimatemember/commit/e1bc94c1100f02a129721ba4be5fbc44c3d78ec4"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/ultimatemember/ultimatemember/releases/tag/2.5.1"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.213545"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-21"}, {"lang": "en", "value": "CWE-22"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/ultimatemember/ultimatemember/commit/e1bc94c1100f02a129721ba4be5fbc44c3d78ec4"}, "type": "CWE-21"}
285
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nnamespace Api\\Model;\nuse Api\\Model\\BaseModel;\nuse AsyncAws\\S3\\S3Client;", "/**\n * \n * @author star7th \n */\nclass AttachmentModel extends BaseModel {", "\tProtected $autoCheckFields = false; //一定要关闭字段缓存,不然会报找不到表的错误", "\t//获取某个用户的当前已使用附件流量\n\tpublic function getUserFlow($uid){\n\t\t$month = Date(\"Y-m\") ;\n\t\t$file_flow = D(\"FileFlow\")->where(\" uid = '%s' and date_month = '$month' \" , array($uid))->find() ;\n\t\tif($file_flow){\n\t\t\treturn intval($file_flow['used']) ;\n\t\t}else{\n\t\t\tD(\"FileFlow\")->add(array(\n\t\t\t\t\"uid\" => $uid ,\n\t\t\t\t\"used\" => 0 ,\n\t\t\t\t\"date_month\" => $month ,", "\t\t\t));\n\t\t\treturn 0 ;\n\t\t}\n\t}", "\t//记录某个用户流量\n\tpublic function recordUserFlow($uid , $file_size){\n\t\t$month = Date(\"Y-m\") ;\n\t\t$used = $this->getUserFlow($uid) ;\n\t\treturn D(\"FileFlow\")->where(\" uid = '%s' and date_month = '$month' \" , array($uid))->save(array(\n\t\t\t\"used\" => $used + intval($file_size) \n\t\t));\n\t}", "\tpublic function deleteFile($file_id){\n\t\t$file_id = intval($file_id) ;\n\t\t$file = D(\"UploadFile\")->where(\"file_id = '$file_id' \")->find();\n\t\t$real_url = $file['real_url'] ;\n\t\t$array = explode(\"/Public/Uploads/\", $real_url) ;\n\t\t$file_path = \"../Public/Uploads/\".$array[1] ;\n\t\tif (file_exists($file_path)) {\n\t\t\t@unlink($file_path);\n\t\t}\n\t\t$this->deleteOss($real_url);\n\t\tD(\"UploadFile\")->where(\" file_id = '$file_id' \")->delete();\n\t\tD(\"FilePage\")->where(\" file_id = '$file_id' \")->delete();\n\t\treturn true ;", "\t}", "\t//上传文件,返回url\n\tpublic function upload($_files , $file_key , $uid , $item_id = 0 , $page_id = 0 ){\n\t\t$uploadFile = $_files[$file_key] ;", "\t\tif( !$this->isAllowedFilename($_files[$file_key]['name']) ){\n\t\t\treturn false;\n\t\t}", "\t\t$oss_open = D(\"Options\")->get(\"oss_open\" ) ;\n\t\tif ($oss_open) {\n\t\t\t\t$url = $this->uploadOss($uploadFile);\n\t\t\t\tif ($url) {\n\t\t\t\t\t\t$sign = md5($url.time().rand()) ;\n\t\t\t\t\t\t$insert = array(\n\t\t\t\t\t\t\"sign\" => $sign,\n\t\t\t\t\t\t\"uid\" => $uid,\n\t\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\t\"display_name\" => $uploadFile['name'],\n\t\t\t\t\t\t\"file_type\" => $uploadFile['type'],\n\t\t\t\t\t\t\"file_size\" => $uploadFile['size'],\n\t\t\t\t\t\t\"real_url\" => $url,\n\t\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\t$file_id = D(\"UploadFile\")->add($insert);\n\t\t\t\t\t\t$insert = array(\n\t\t\t\t\t\t\t\"file_id\" => $file_id,\n\t\t\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t$ret = D(\"FilePage\")->add($insert);\n\t\t\t\t\t\t$url = server_url(\"api/attachment/visitFile\",array(\"sign\" => $sign)); \n\t\t\t\t\t return $url ;\n\t\t\t\t}\n\t\t}else{\n\t\t\t$upload = new \\Think\\Upload();// 实例化上传类\n\t\t\t$upload->maxSize = 1003145728 ;// 设置附件上传大小\n\t\t\t$upload->rootPath = './../Public/Uploads/';// 设置附件上传目录\n\t\t\t$upload->savePath = '';// 设置附件上传子目录\n\t\t\t$info = $upload->uploadOne($uploadFile) ;\n\t\t\tif(!$info) {// 上传错误提示错误信息\n\t\t\t\tvar_dump($upload->getError());\n\t\t\t\treturn;\n\t\t\t}else{// 上传成功 获取上传文件信息\n\t\t\t\t$url = site_url().'/Public/Uploads/'.$info['savepath'].$info['savename'] ;\n\t\t\t\t$sign = md5($url.time().rand()) ;\n\t\t\t\t$insert = array(\n\t\t\t\t\t\"sign\" => $sign,\n\t\t\t\t\t\"uid\" => $uid,\n\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\"display_name\" => $uploadFile['name'],\n\t\t\t\t\t\"file_type\" => $uploadFile['type'],\n\t\t\t\t\t\"file_size\" => $uploadFile['size'],\n\t\t\t\t\t\"real_url\" => $url,\n\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t);\n\t\t\t\t\t$file_id = D(\"UploadFile\")->add($insert);\n\t\t\t\t\t$insert = array(\n\t\t\t\t\t\t\"file_id\" => $file_id,\n\t\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t\t);\n\t\t\t\t\t$ret = D(\"FilePage\")->add($insert);\n\t\t\t\t$url = server_url(\"api/attachment/visitFile\",array(\"sign\" => $sign));\n\t\t\t\treturn $url ;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", " \t//上传到oss。参数$uploadFile是文件上传流,如$_FILES['file'] .也可以自己拼凑\n\tpublic function uploadOss($uploadFile){\n\t\t$oss_setting_json = D(\"Options\")->get(\"oss_setting\") ;\n\t\t$oss_setting = json_decode($oss_setting_json,1);", "\t\tif ($oss_setting && $oss_setting['oss_type'] && ( $oss_setting['oss_type'] == 's3_storage' || $oss_setting['oss_type'] == 'aliyun') ) {", "\t\t\treturn $this->uploadS3($uploadFile , $oss_setting);", "\t\t}", "\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qiniu') {", "\t\t\t$oss_setting['endpoint'] = $this->getQiuniuEndpointByKey($oss_setting['key'] , $oss_setting['bucket']);\n\t\t\treturn $this->uploadS3($uploadFile , $oss_setting); ", "\t\t}\n\t\t// 腾讯云\n\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qcloud') {\n\t\t\t// 腾讯云,一开始让用户填写region而没填写endpoint,所以要自己拼接\n\t\t\t$oss_setting['endpoint'] = \"https://cos.{$oss_setting['region']}.myqcloud.com\";\n\t\t\t// 腾讯云的SecretId相当于s3的key, secretKey相当于s3的secret\n\t\t\t$oss_setting['key'] = $oss_setting['secretId'] ;\n\t\t\t$oss_setting['secret'] = $oss_setting['secretKey'] ;\n\t\t\treturn $this->uploadS3($uploadFile , $oss_setting); \n\t\t}", "\n\t\treturn false ;\n\t}", "\t// 通过s3协议上传\n\t// 注意传进来的oss_setting数组需要先转换成合法格式\n\tpublic function uploadS3($uploadFile , $oss_setting){", "\t\t$ext = strrchr($uploadFile['name'], '.'); //获取扩展名\n\t\t$oss_path = \"showdoc_\".get_rand_str().$ext;", "\t\t// 如果不包含协议头,自己给它补充\n\t\tif(!strstr($oss_setting['endpoint'] , '://')){\n\t\t\t$oss_setting['endpoint'] = 'https://'.$oss_setting['endpoint'] ;\n\t\t}", "\t\t$s3 = new S3Client([\n\t\t\t'accessKeyId' => $oss_setting['key'],\n\t\t\t'accessKeySecret' => $oss_setting['secret'] ,\n\t\t\t'endpoint' => $oss_setting['endpoint'] ,\n\t\t\t'sendChunkedBody' => false\n\t\t]);\n\t\n\t\t// Send a PutObject request and get the result object.\n\t\t$resObj = $s3->putObject([\n\t\t\t'Bucket' => $oss_setting['bucket'],\n\t\t\t'Key' => $oss_path,\n\t\t\t'Body' => fopen($uploadFile['tmp_name'], 'rb')\n\t\t]);", "\t\t// 不抛出异常,默认就是成功的", "\t\tif ($oss_setting['domain']) {\n\t\t\treturn $oss_setting['protocol'] . '://'.$oss_setting['domain'].\"/\".$oss_path ;\n\t\t}else{\n\t\t\t$tmp_array = parse_url($oss_setting['endpoint']);\n\t\t\t$endpoint_host = $tmp_array['host'] ;\n\t\t\treturn 'https://'.$oss_setting['bucket'].'.'.$endpoint_host.'/'.$oss_path;\n\t\t}\n\t}", " \t//从oss中删除\n\tpublic function deleteOss($file_url){\n\t\t$oss_setting_json = D(\"Options\")->get(\"oss_setting\") ;\n\t\t$oss_setting = json_decode($oss_setting_json,1);\n\t\tif ($oss_setting && $oss_setting['oss_type'] && ( $oss_setting['oss_type'] == 's3_storage' || $oss_setting['oss_type'] == 'aliyun') ) {\n\t\t\treturn $this->deleteS3($file_url , $oss_setting);\n\t\t}", "\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qiniu') {\n\t\t\t$oss_setting['endpoint'] = $this->getQiuniuEndpointByKey($oss_setting['key'] , $oss_setting['bucket']);\n\t\t\treturn $this->deleteS3($file_url , $oss_setting); \n\t\t}\n\t\t//var_dump($config);\n\t\t// 腾讯云\n\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qcloud') {", "\t\t\t// 腾讯云,一开始让用户填写region而没填写endpoint,所以要自己拼接\n\t\t\t$oss_setting['endpoint'] = \"https://cos.{$oss_setting['region']}.myqcloud.com\";\n\t\t\t// 腾讯云的SecretId相当于s3的key, secretKey相当于s3的secret\n\t\t\t$oss_setting['key'] = $oss_setting['secretId'] ;\n\t\t\t$oss_setting['secret'] = $oss_setting['secretKey'] ;\n\t\t\treturn $this->deleteS3($file_url , $oss_setting); ", "\t\t}", "\n\t\treturn false ;\n\t}", "\t// 通过s3协议删除\n\t// 注意传进来的oss_setting数组需要先转换成合法格式\n\tpublic function deleteS3($file_url , $oss_setting){", "\t\t$array = parse_url($file_url) ;\n\t\t$file = $array['path'] ; // 得到的是url中的路径,例如/path_.txt\n\t\t$file = substr($file, 1); // 要把路径前的/去掉,才是得到文件名path_.txt\n\t\t// 如果不包含协议头,自己给它补充\n\t\tif(!strstr($oss_setting['endpoint'] , '://')){\n\t\t\t$oss_setting['endpoint'] = 'https://'.$oss_setting['endpoint'] ;\n\t\t}", "\t\t$s3 = new S3Client([\n\t\t\t'accessKeyId' => $oss_setting['key'],\n\t\t\t'accessKeySecret' => $oss_setting['secret'] ,\n\t\t\t'endpoint' => $oss_setting['endpoint'] ,\n\t\t]);\n\t\n\t\t// Send a PutObject request and get the result object.\n\t\t$resObj = $s3->deleteObject([\n\t\t\t'Bucket' => $oss_setting['bucket'],\n\t\t\t'Key' => $file,\n\t\t]);", "\t\t// 不抛出异常,默认就是成功的", "\n\t}", "\t// 由于历史原因,当初没有让用户填写七牛云的region。而且即使填写了,也不能直接获取到七牛云s3兼容协议上传的endpoint\n\t// 所以,需要自己调接口查询然后拼凑。七牛这个坑货。\n\tpublic function getQiuniuEndpointByKey($key,$bucket){", "\t\t$query_url = \"https://api.qiniu.com/v2/query?ak={$key}&bucket={$bucket}\";\n\t\t$res = http_post($query_url,array());", "\t\t$array = json_decode($res,true) ;\n\t\t// var_dump($array);exit();\n\t\tif($array && $array['region'] ){\n\t\t\tswitch ($array['region']) {\n\t\t\t\tcase 'z0':\n\t\t\t\t\treturn 'https://s3-cn-east-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'z1':\n\t\t\t\t\treturn 'https://s3-cn-north-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'z2':\n\t\t\t\t\treturn 'https://s3-cn-south-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'na0':\n\t\t\t\t\treturn 'https://s3-us-north-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'as0':\n\t\t\t\t\treturn 'https://s3-ap-southeast-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn false;\n\t\t\t\t\tbreak;\n\t\t\t}", "\t\t}", "\t}", "\t// 判断文件名是否包含危险的扩展名\n\t// 准备弃用。因为一个个ban太麻烦了。准备改用白名单机制\n\tpublic function isDangerFilename($filename){", "\t\t$isDangerStr = function ($filename , $keyword){\n\t\t\tif(strstr(strip_tags(strtolower( $filename )), $keyword) ){\n\t\t\t\treturn true ;\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t\tif (\n\t\t\t $isDangerStr($filename , \".php\")\n\t\t\t|| $isDangerStr($filename , \".svg\")\n\t\t\t|| $isDangerStr($filename , \".htm\")\n\t\t\t|| $isDangerStr($filename , \".shtm\")\n\t\t\t|| $isDangerStr($filename , \"%\")\n\t\t\t|| $isDangerStr($filename , \".xml\")\n\t\t\t|| $isDangerStr($filename , \".xxhtml\")\n\t\t\t|| $isDangerStr($filename , \".asp\")\t\t\t\n\t\t\t|| $isDangerStr($filename , \".xsl\")\n\t\t\t|| $isDangerStr($filename , \".aspx\")\n\t\t\t|| $isDangerStr($filename , \".xsd\")\n\t\t\t|| $isDangerStr($filename , \".asa\")\n\t\t\t|| $isDangerStr($filename , \".cshtml\")\n\t\t\t|| $isDangerStr($filename , \".axd\")\n\t\t\t|| $isDangerStr($filename , \"htm\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\n\t\treturn false;\n\t}", "\t// 判断上传的文件扩展名是否处于白名单内\n\tpublic function isAllowedFilename($filename){\n\t\t$allow_array = array(\n\t\t\t'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',\n\t\t\t'.mp3','.wav','.m4a','.ogg','.webma','.mp4','.flv',\n\t\t\t'.mov','.webmv','.m3u8a','.flac','.mkv',\n\t\t\t'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso','.bz2','.epub',\n\t\t\t'.pdf','.ofd','.swf','.epub','.xps',\n\t\t\t'.doc','.docx','.odt','.rtf','.docm','.dotm','.dot','.dotx','.wps','.wpt',", "\t\t\t'.ppt','.pptx','.xls','.xlsx','.txt','.md','.psd','.csv',", "\t\t\t'.cer','.ppt','.pub','.properties','.json','.css',\n\t\t\t) ;", "\t\t$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名(转为小写后)\n\t\tif(in_array( $ext , $allow_array ) ){\n\t\t\treturn true ;\n\t\t}\n\t\treturn false;\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [333], "buggy_code_start_loc": [332], "filenames": ["server/Application/Api/Model/AttachmentModel.class.php"], "fixing_code_end_loc": [333], "fixing_code_start_loc": [332], "message": "Stored XSS via File Upload in GitHub repository star7th/showdoc prior to v.2.10.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:showdoc:showdoc:*:*:*:*:*:*:*:*", "matchCriteriaId": "EB841EBE-162B-4399-B2A5-B1EE3350CD36", "versionEndExcluding": null, "versionEndIncluding": "2.10.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Stored XSS via File Upload in GitHub repository star7th/showdoc prior to v.2.10.4."}, {"lang": "es", "value": "Una vulnerabilidad de tipo XSS almacenado por medio de una carga de archivos en el repositorio de GitHub star7th/showdoc versiones anteriores a 2.10.4"}], "evaluatorComment": null, "id": "CVE-2022-0956", "lastModified": "2022-03-22T18:46:16.657", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-03-15T13:15:07.743", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/star7th/showdoc/commit/56e450c3adf75c707500d7231a78c9fc894c7f13"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/5b0e3f02-309f-4b59-8020-d7ac0f1999f2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/star7th/showdoc/commit/56e450c3adf75c707500d7231a78c9fc894c7f13"}, "type": "CWE-79"}
286
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nnamespace Api\\Model;\nuse Api\\Model\\BaseModel;\nuse AsyncAws\\S3\\S3Client;", "/**\n * \n * @author star7th \n */\nclass AttachmentModel extends BaseModel {", "\tProtected $autoCheckFields = false; //一定要关闭字段缓存,不然会报找不到表的错误", "\t//获取某个用户的当前已使用附件流量\n\tpublic function getUserFlow($uid){\n\t\t$month = Date(\"Y-m\") ;\n\t\t$file_flow = D(\"FileFlow\")->where(\" uid = '%s' and date_month = '$month' \" , array($uid))->find() ;\n\t\tif($file_flow){\n\t\t\treturn intval($file_flow['used']) ;\n\t\t}else{\n\t\t\tD(\"FileFlow\")->add(array(\n\t\t\t\t\"uid\" => $uid ,\n\t\t\t\t\"used\" => 0 ,\n\t\t\t\t\"date_month\" => $month ,", "\t\t\t));\n\t\t\treturn 0 ;\n\t\t}\n\t}", "\t//记录某个用户流量\n\tpublic function recordUserFlow($uid , $file_size){\n\t\t$month = Date(\"Y-m\") ;\n\t\t$used = $this->getUserFlow($uid) ;\n\t\treturn D(\"FileFlow\")->where(\" uid = '%s' and date_month = '$month' \" , array($uid))->save(array(\n\t\t\t\"used\" => $used + intval($file_size) \n\t\t));\n\t}", "\tpublic function deleteFile($file_id){\n\t\t$file_id = intval($file_id) ;\n\t\t$file = D(\"UploadFile\")->where(\"file_id = '$file_id' \")->find();\n\t\t$real_url = $file['real_url'] ;\n\t\t$array = explode(\"/Public/Uploads/\", $real_url) ;\n\t\t$file_path = \"../Public/Uploads/\".$array[1] ;\n\t\tif (file_exists($file_path)) {\n\t\t\t@unlink($file_path);\n\t\t}\n\t\t$this->deleteOss($real_url);\n\t\tD(\"UploadFile\")->where(\" file_id = '$file_id' \")->delete();\n\t\tD(\"FilePage\")->where(\" file_id = '$file_id' \")->delete();\n\t\treturn true ;", "\t}", "\t//上传文件,返回url\n\tpublic function upload($_files , $file_key , $uid , $item_id = 0 , $page_id = 0 ){\n\t\t$uploadFile = $_files[$file_key] ;", "\t\tif( !$this->isAllowedFilename($_files[$file_key]['name']) ){\n\t\t\treturn false;\n\t\t}", "\t\t$oss_open = D(\"Options\")->get(\"oss_open\" ) ;\n\t\tif ($oss_open) {\n\t\t\t\t$url = $this->uploadOss($uploadFile);\n\t\t\t\tif ($url) {\n\t\t\t\t\t\t$sign = md5($url.time().rand()) ;\n\t\t\t\t\t\t$insert = array(\n\t\t\t\t\t\t\"sign\" => $sign,\n\t\t\t\t\t\t\"uid\" => $uid,\n\t\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\t\"display_name\" => $uploadFile['name'],\n\t\t\t\t\t\t\"file_type\" => $uploadFile['type'],\n\t\t\t\t\t\t\"file_size\" => $uploadFile['size'],\n\t\t\t\t\t\t\"real_url\" => $url,\n\t\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\t$file_id = D(\"UploadFile\")->add($insert);\n\t\t\t\t\t\t$insert = array(\n\t\t\t\t\t\t\t\"file_id\" => $file_id,\n\t\t\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t$ret = D(\"FilePage\")->add($insert);\n\t\t\t\t\t\t$url = server_url(\"api/attachment/visitFile\",array(\"sign\" => $sign)); \n\t\t\t\t\t return $url ;\n\t\t\t\t}\n\t\t}else{\n\t\t\t$upload = new \\Think\\Upload();// 实例化上传类\n\t\t\t$upload->maxSize = 1003145728 ;// 设置附件上传大小\n\t\t\t$upload->rootPath = './../Public/Uploads/';// 设置附件上传目录\n\t\t\t$upload->savePath = '';// 设置附件上传子目录\n\t\t\t$info = $upload->uploadOne($uploadFile) ;\n\t\t\tif(!$info) {// 上传错误提示错误信息\n\t\t\t\tvar_dump($upload->getError());\n\t\t\t\treturn;\n\t\t\t}else{// 上传成功 获取上传文件信息\n\t\t\t\t$url = site_url().'/Public/Uploads/'.$info['savepath'].$info['savename'] ;\n\t\t\t\t$sign = md5($url.time().rand()) ;\n\t\t\t\t$insert = array(\n\t\t\t\t\t\"sign\" => $sign,\n\t\t\t\t\t\"uid\" => $uid,\n\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\"display_name\" => $uploadFile['name'],\n\t\t\t\t\t\"file_type\" => $uploadFile['type'],\n\t\t\t\t\t\"file_size\" => $uploadFile['size'],\n\t\t\t\t\t\"real_url\" => $url,\n\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t);\n\t\t\t\t\t$file_id = D(\"UploadFile\")->add($insert);\n\t\t\t\t\t$insert = array(\n\t\t\t\t\t\t\"file_id\" => $file_id,\n\t\t\t\t\t\t\"item_id\" => $item_id,\n\t\t\t\t\t\t\"page_id\" => $page_id,\n\t\t\t\t\t\t\"addtime\" => time(),\n\t\t\t\t\t\t);\n\t\t\t\t\t$ret = D(\"FilePage\")->add($insert);\n\t\t\t\t$url = server_url(\"api/attachment/visitFile\",array(\"sign\" => $sign));\n\t\t\t\treturn $url ;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", " \t//上传到oss。参数$uploadFile是文件上传流,如$_FILES['file'] .也可以自己拼凑\n\tpublic function uploadOss($uploadFile){\n\t\t$oss_setting_json = D(\"Options\")->get(\"oss_setting\") ;\n\t\t$oss_setting = json_decode($oss_setting_json,1);", "\t\tif ($oss_setting && $oss_setting['oss_type'] && ( $oss_setting['oss_type'] == 's3_storage' || $oss_setting['oss_type'] == 'aliyun') ) {", "\t\t\treturn $this->uploadS3($uploadFile , $oss_setting);", "\t\t}", "\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qiniu') {", "\t\t\t$oss_setting['endpoint'] = $this->getQiuniuEndpointByKey($oss_setting['key'] , $oss_setting['bucket']);\n\t\t\treturn $this->uploadS3($uploadFile , $oss_setting); ", "\t\t}\n\t\t// 腾讯云\n\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qcloud') {\n\t\t\t// 腾讯云,一开始让用户填写region而没填写endpoint,所以要自己拼接\n\t\t\t$oss_setting['endpoint'] = \"https://cos.{$oss_setting['region']}.myqcloud.com\";\n\t\t\t// 腾讯云的SecretId相当于s3的key, secretKey相当于s3的secret\n\t\t\t$oss_setting['key'] = $oss_setting['secretId'] ;\n\t\t\t$oss_setting['secret'] = $oss_setting['secretKey'] ;\n\t\t\treturn $this->uploadS3($uploadFile , $oss_setting); \n\t\t}", "\n\t\treturn false ;\n\t}", "\t// 通过s3协议上传\n\t// 注意传进来的oss_setting数组需要先转换成合法格式\n\tpublic function uploadS3($uploadFile , $oss_setting){", "\t\t$ext = strrchr($uploadFile['name'], '.'); //获取扩展名\n\t\t$oss_path = \"showdoc_\".get_rand_str().$ext;", "\t\t// 如果不包含协议头,自己给它补充\n\t\tif(!strstr($oss_setting['endpoint'] , '://')){\n\t\t\t$oss_setting['endpoint'] = 'https://'.$oss_setting['endpoint'] ;\n\t\t}", "\t\t$s3 = new S3Client([\n\t\t\t'accessKeyId' => $oss_setting['key'],\n\t\t\t'accessKeySecret' => $oss_setting['secret'] ,\n\t\t\t'endpoint' => $oss_setting['endpoint'] ,\n\t\t\t'sendChunkedBody' => false\n\t\t]);\n\t\n\t\t// Send a PutObject request and get the result object.\n\t\t$resObj = $s3->putObject([\n\t\t\t'Bucket' => $oss_setting['bucket'],\n\t\t\t'Key' => $oss_path,\n\t\t\t'Body' => fopen($uploadFile['tmp_name'], 'rb')\n\t\t]);", "\t\t// 不抛出异常,默认就是成功的", "\t\tif ($oss_setting['domain']) {\n\t\t\treturn $oss_setting['protocol'] . '://'.$oss_setting['domain'].\"/\".$oss_path ;\n\t\t}else{\n\t\t\t$tmp_array = parse_url($oss_setting['endpoint']);\n\t\t\t$endpoint_host = $tmp_array['host'] ;\n\t\t\treturn 'https://'.$oss_setting['bucket'].'.'.$endpoint_host.'/'.$oss_path;\n\t\t}\n\t}", " \t//从oss中删除\n\tpublic function deleteOss($file_url){\n\t\t$oss_setting_json = D(\"Options\")->get(\"oss_setting\") ;\n\t\t$oss_setting = json_decode($oss_setting_json,1);\n\t\tif ($oss_setting && $oss_setting['oss_type'] && ( $oss_setting['oss_type'] == 's3_storage' || $oss_setting['oss_type'] == 'aliyun') ) {\n\t\t\treturn $this->deleteS3($file_url , $oss_setting);\n\t\t}", "\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qiniu') {\n\t\t\t$oss_setting['endpoint'] = $this->getQiuniuEndpointByKey($oss_setting['key'] , $oss_setting['bucket']);\n\t\t\treturn $this->deleteS3($file_url , $oss_setting); \n\t\t}\n\t\t//var_dump($config);\n\t\t// 腾讯云\n\t\tif ($oss_setting && $oss_setting['oss_type'] && $oss_setting['oss_type'] == 'qcloud') {", "\t\t\t// 腾讯云,一开始让用户填写region而没填写endpoint,所以要自己拼接\n\t\t\t$oss_setting['endpoint'] = \"https://cos.{$oss_setting['region']}.myqcloud.com\";\n\t\t\t// 腾讯云的SecretId相当于s3的key, secretKey相当于s3的secret\n\t\t\t$oss_setting['key'] = $oss_setting['secretId'] ;\n\t\t\t$oss_setting['secret'] = $oss_setting['secretKey'] ;\n\t\t\treturn $this->deleteS3($file_url , $oss_setting); ", "\t\t}", "\n\t\treturn false ;\n\t}", "\t// 通过s3协议删除\n\t// 注意传进来的oss_setting数组需要先转换成合法格式\n\tpublic function deleteS3($file_url , $oss_setting){", "\t\t$array = parse_url($file_url) ;\n\t\t$file = $array['path'] ; // 得到的是url中的路径,例如/path_.txt\n\t\t$file = substr($file, 1); // 要把路径前的/去掉,才是得到文件名path_.txt\n\t\t// 如果不包含协议头,自己给它补充\n\t\tif(!strstr($oss_setting['endpoint'] , '://')){\n\t\t\t$oss_setting['endpoint'] = 'https://'.$oss_setting['endpoint'] ;\n\t\t}", "\t\t$s3 = new S3Client([\n\t\t\t'accessKeyId' => $oss_setting['key'],\n\t\t\t'accessKeySecret' => $oss_setting['secret'] ,\n\t\t\t'endpoint' => $oss_setting['endpoint'] ,\n\t\t]);\n\t\n\t\t// Send a PutObject request and get the result object.\n\t\t$resObj = $s3->deleteObject([\n\t\t\t'Bucket' => $oss_setting['bucket'],\n\t\t\t'Key' => $file,\n\t\t]);", "\t\t// 不抛出异常,默认就是成功的", "\n\t}", "\t// 由于历史原因,当初没有让用户填写七牛云的region。而且即使填写了,也不能直接获取到七牛云s3兼容协议上传的endpoint\n\t// 所以,需要自己调接口查询然后拼凑。七牛这个坑货。\n\tpublic function getQiuniuEndpointByKey($key,$bucket){", "\t\t$query_url = \"https://api.qiniu.com/v2/query?ak={$key}&bucket={$bucket}\";\n\t\t$res = http_post($query_url,array());", "\t\t$array = json_decode($res,true) ;\n\t\t// var_dump($array);exit();\n\t\tif($array && $array['region'] ){\n\t\t\tswitch ($array['region']) {\n\t\t\t\tcase 'z0':\n\t\t\t\t\treturn 'https://s3-cn-east-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'z1':\n\t\t\t\t\treturn 'https://s3-cn-north-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'z2':\n\t\t\t\t\treturn 'https://s3-cn-south-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'na0':\n\t\t\t\t\treturn 'https://s3-us-north-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'as0':\n\t\t\t\t\treturn 'https://s3-ap-southeast-1.qiniucs.com';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn false;\n\t\t\t\t\tbreak;\n\t\t\t}", "\t\t}", "\t}", "\t// 判断文件名是否包含危险的扩展名\n\t// 准备弃用。因为一个个ban太麻烦了。准备改用白名单机制\n\tpublic function isDangerFilename($filename){", "\t\t$isDangerStr = function ($filename , $keyword){\n\t\t\tif(strstr(strip_tags(strtolower( $filename )), $keyword) ){\n\t\t\t\treturn true ;\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t\tif (\n\t\t\t $isDangerStr($filename , \".php\")\n\t\t\t|| $isDangerStr($filename , \".svg\")\n\t\t\t|| $isDangerStr($filename , \".htm\")\n\t\t\t|| $isDangerStr($filename , \".shtm\")\n\t\t\t|| $isDangerStr($filename , \"%\")\n\t\t\t|| $isDangerStr($filename , \".xml\")\n\t\t\t|| $isDangerStr($filename , \".xxhtml\")\n\t\t\t|| $isDangerStr($filename , \".asp\")\t\t\t\n\t\t\t|| $isDangerStr($filename , \".xsl\")\n\t\t\t|| $isDangerStr($filename , \".aspx\")\n\t\t\t|| $isDangerStr($filename , \".xsd\")\n\t\t\t|| $isDangerStr($filename , \".asa\")\n\t\t\t|| $isDangerStr($filename , \".cshtml\")\n\t\t\t|| $isDangerStr($filename , \".axd\")\n\t\t\t|| $isDangerStr($filename , \"htm\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\n\t\treturn false;\n\t}", "\t// 判断上传的文件扩展名是否处于白名单内\n\tpublic function isAllowedFilename($filename){\n\t\t$allow_array = array(\n\t\t\t'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',\n\t\t\t'.mp3','.wav','.m4a','.ogg','.webma','.mp4','.flv',\n\t\t\t'.mov','.webmv','.m3u8a','.flac','.mkv',\n\t\t\t'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso','.bz2','.epub',\n\t\t\t'.pdf','.ofd','.swf','.epub','.xps',\n\t\t\t'.doc','.docx','.odt','.rtf','.docm','.dotm','.dot','.dotx','.wps','.wpt',", "\t\t\t'.ppt','.pptx','.xls','.xlsx','.txt','.psd','.csv',", "\t\t\t'.cer','.ppt','.pub','.properties','.json','.css',\n\t\t\t) ;", "\t\t$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名(转为小写后)\n\t\tif(in_array( $ext , $allow_array ) ){\n\t\t\treturn true ;\n\t\t}\n\t\treturn false;\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [333], "buggy_code_start_loc": [332], "filenames": ["server/Application/Api/Model/AttachmentModel.class.php"], "fixing_code_end_loc": [333], "fixing_code_start_loc": [332], "message": "Stored XSS via File Upload in GitHub repository star7th/showdoc prior to v.2.10.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:showdoc:showdoc:*:*:*:*:*:*:*:*", "matchCriteriaId": "EB841EBE-162B-4399-B2A5-B1EE3350CD36", "versionEndExcluding": null, "versionEndIncluding": "2.10.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Stored XSS via File Upload in GitHub repository star7th/showdoc prior to v.2.10.4."}, {"lang": "es", "value": "Una vulnerabilidad de tipo XSS almacenado por medio de una carga de archivos en el repositorio de GitHub star7th/showdoc versiones anteriores a 2.10.4"}], "evaluatorComment": null, "id": "CVE-2022-0956", "lastModified": "2022-03-22T18:46:16.657", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 5.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-03-15T13:15:07.743", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/star7th/showdoc/commit/56e450c3adf75c707500d7231a78c9fc894c7f13"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Third Party Advisory"], "url": "https://huntr.dev/bounties/5b0e3f02-309f-4b59-8020-d7ac0f1999f2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/star7th/showdoc/commit/56e450c3adf75c707500d7231a78c9fc894c7f13"}, "type": "CWE-79"}
286
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/*\ninit.php - bootloader to initialize variables\n * If the config.php file is not found then an error\n * will be displayed asking the visitor to set up the\n * config.php file.\n *\n * Will also search for config.php in the OpenDocMan parent\n * directory to allow the OpendocMan directory to remain\n * untouched.", "Copyright (C) 2011 Stephen Lawrence Jr.", "This program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.", "This program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.", "You should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n */", "/*\n * Connect to Database\n */\n$GLOBALS['connection'] = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die (\"Unable to connect: \" . mysql_error());\n$db = mysql_select_db(DB_NAME, $GLOBALS['connection']);", "$dsn = \"mysql:host=\" . DB_HOST . \";dbname=\" . DB_NAME . \";charset=utf8\";\ntry {\n $pdo = new PDO($dsn, DB_USER, DB_PASS);\n} catch (PDOException $e) {\n print \"Error!: \" . $e->getMessage() . \"<br/>\";\n die();\n}", "$GLOBALS['pdo'] = $pdo;", "ob_start();\ninclude('includes/FirePHPCore/fb.php');", "/*\n/*\n * Load the Settings class\n */\nrequire_once ( 'Settings_class.php');\n$settings = new Settings();\n$settings->load();", "/*\n * Common functions\n */\nrequire_once( 'functions.php' );", "/*\n * Load the allowed file types list\n */\nrequire_once ( 'FileTypes_class.php' );\n$filetypes = new FileTypes_class();\n$filetypes->load();", "// Set the revision directory. (relative to $dataDir)\n$CONFIG['revisionDir'] = $GLOBALS['CONFIG']['dataDir'] . 'revisionDir/';", "// Set the revision directory. (relative to $dataDir)\n$CONFIG['archiveDir'] = $GLOBALS['CONFIG']['dataDir'] . 'archiveDir/';", "$_GET = sanitizeme($_GET);\n$_REQUEST = sanitizeme($_REQUEST);\n$_POST = sanitizeme($_POST);\n$_SERVER = sanitizeme($_SERVER);", "" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [77], "buggy_code_start_loc": [77], "filenames": ["odm-init.php"], "fixing_code_end_loc": [79], "fixing_code_start_loc": [78], "message": "Cross-site scripting (XSS) vulnerability in odm-init.php in OpenDocMan before 1.2.7.3 allows remote authenticated users to inject arbitrary web script or HTML via the file name of an uploaded file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:opendocman:opendocman:*:*:*:*:*:*:*:*", "matchCriteriaId": "A08B1B90-D9D2-491F-A8B4-F57935E62F87", "versionEndExcluding": null, "versionEndIncluding": "1.2.7.2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.2:-:*:*:*:*:*:*", "matchCriteriaId": "C4D3F02F-3FE2-4D7A-97A5-7CFB53BFEBC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.2:a:*:*:*:*:*:*", "matchCriteriaId": "EC21AE07-0BE2-470A-9A9D-9B0A0E1BB50F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.2:b:*:*:*:*:*:*", "matchCriteriaId": "5A4674E7-CDAE-46E0-BB50-89982B13EA3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.3:-:*:*:*:*:*:*", "matchCriteriaId": "AEC5FABB-8752-4CFD-BED7-29DD2CE51B80", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.3:a:*:*:*:*:*:*", "matchCriteriaId": "FE2D011C-A93E-46D0-93CE-3670B92C84A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.5:*:*:*:*:*:*:*", "matchCriteriaId": "C4EA4AA2-95AD-4BD2-83E5-C4AE32317216", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.6:*:*:*:*:*:*:*", "matchCriteriaId": "F5DAD56F-53B1-4D49-9A58-CC60AE2CF5CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.7:-:*:*:*:*:*:*", "matchCriteriaId": "E7691977-FF85-4A33-8F38-2F35E975B1AB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.7:beta:*:*:*:*:*:*", "matchCriteriaId": "6356D416-603D-4CC2-B788-F66AA5C183EA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.8:*:*:*:*:*:*:*", "matchCriteriaId": "3E47E7FB-D37A-4194-A57C-C40E2F3B5743", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "FBA22C31-F0BB-47FF-95B5-6C00FCEBF763", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.7.1:*:*:*:*:*:*:*", "matchCriteriaId": "4E930F06-8FDB-414A-ACAC-0B3273B290A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in odm-init.php in OpenDocMan before 1.2.7.3 allows remote authenticated users to inject arbitrary web script or HTML via the file name of an uploaded file."}, {"lang": "es", "value": "Vulnerabilidad de XSS en odm-init.php en OpenDocMan anterior a 1.2.7.3 permite a usuarios remotos autenticados inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del nombre de fichero de un fichero subido."}], "evaluatorComment": null, "id": "CVE-2014-4853", "lastModified": "2014-07-11T00:10:59.870", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-07-10T16:55:06.203", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://packetstormsecurity.com/files/127330/OpenDocMan-1.2.7.2-Cross-Site-Scripting.html"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "http://www.opendocman.com/opendocman-v1-2-7-3-release-notes"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/opendocman/opendocman/commit/d202ef3def8674be61a3e4ccbe28beba4953b7ce"}, {"source": "cve@mitre.org", "tags": null, "url": "https://github.com/opendocman/opendocman/issues/163"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/opendocman/opendocman/commit/d202ef3def8674be61a3e4ccbe28beba4953b7ce"}, "type": "CWE-79"}
287
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/*\ninit.php - bootloader to initialize variables\n * If the config.php file is not found then an error\n * will be displayed asking the visitor to set up the\n * config.php file.\n *\n * Will also search for config.php in the OpenDocMan parent\n * directory to allow the OpendocMan directory to remain\n * untouched.", "Copyright (C) 2011 Stephen Lawrence Jr.", "This program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.", "This program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.", "You should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n */", "/*\n * Connect to Database\n */\n$GLOBALS['connection'] = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die (\"Unable to connect: \" . mysql_error());\n$db = mysql_select_db(DB_NAME, $GLOBALS['connection']);", "$dsn = \"mysql:host=\" . DB_HOST . \";dbname=\" . DB_NAME . \";charset=utf8\";\ntry {\n $pdo = new PDO($dsn, DB_USER, DB_PASS);\n} catch (PDOException $e) {\n print \"Error!: \" . $e->getMessage() . \"<br/>\";\n die();\n}", "$GLOBALS['pdo'] = $pdo;", "ob_start();\ninclude('includes/FirePHPCore/fb.php');", "/*\n/*\n * Load the Settings class\n */\nrequire_once ( 'Settings_class.php');\n$settings = new Settings();\n$settings->load();", "/*\n * Common functions\n */\nrequire_once( 'functions.php' );", "/*\n * Load the allowed file types list\n */\nrequire_once ( 'FileTypes_class.php' );\n$filetypes = new FileTypes_class();\n$filetypes->load();", "// Set the revision directory. (relative to $dataDir)\n$CONFIG['revisionDir'] = $GLOBALS['CONFIG']['dataDir'] . 'revisionDir/';", "// Set the revision directory. (relative to $dataDir)\n$CONFIG['archiveDir'] = $GLOBALS['CONFIG']['dataDir'] . 'archiveDir/';", "$_GET = sanitizeme($_GET);\n$_REQUEST = sanitizeme($_REQUEST);\n$_POST = sanitizeme($_POST);\n$_SERVER = sanitizeme($_SERVER);", "$_FILES = sanitizeme($_FILES);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [77], "buggy_code_start_loc": [77], "filenames": ["odm-init.php"], "fixing_code_end_loc": [79], "fixing_code_start_loc": [78], "message": "Cross-site scripting (XSS) vulnerability in odm-init.php in OpenDocMan before 1.2.7.3 allows remote authenticated users to inject arbitrary web script or HTML via the file name of an uploaded file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:opendocman:opendocman:*:*:*:*:*:*:*:*", "matchCriteriaId": "A08B1B90-D9D2-491F-A8B4-F57935E62F87", "versionEndExcluding": null, "versionEndIncluding": "1.2.7.2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.2:-:*:*:*:*:*:*", "matchCriteriaId": "C4D3F02F-3FE2-4D7A-97A5-7CFB53BFEBC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.2:a:*:*:*:*:*:*", "matchCriteriaId": "EC21AE07-0BE2-470A-9A9D-9B0A0E1BB50F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.2:b:*:*:*:*:*:*", "matchCriteriaId": "5A4674E7-CDAE-46E0-BB50-89982B13EA3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.3:-:*:*:*:*:*:*", "matchCriteriaId": "AEC5FABB-8752-4CFD-BED7-29DD2CE51B80", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.3:a:*:*:*:*:*:*", "matchCriteriaId": "FE2D011C-A93E-46D0-93CE-3670B92C84A6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.5:*:*:*:*:*:*:*", "matchCriteriaId": "C4EA4AA2-95AD-4BD2-83E5-C4AE32317216", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.6:*:*:*:*:*:*:*", "matchCriteriaId": "F5DAD56F-53B1-4D49-9A58-CC60AE2CF5CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.7:-:*:*:*:*:*:*", "matchCriteriaId": "E7691977-FF85-4A33-8F38-2F35E975B1AB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.7:beta:*:*:*:*:*:*", "matchCriteriaId": "6356D416-603D-4CC2-B788-F66AA5C183EA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.6.8:*:*:*:*:*:*:*", "matchCriteriaId": "3E47E7FB-D37A-4194-A57C-C40E2F3B5743", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "FBA22C31-F0BB-47FF-95B5-6C00FCEBF763", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:opendocman:opendocman:1.2.7.1:*:*:*:*:*:*:*", "matchCriteriaId": "4E930F06-8FDB-414A-ACAC-0B3273B290A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in odm-init.php in OpenDocMan before 1.2.7.3 allows remote authenticated users to inject arbitrary web script or HTML via the file name of an uploaded file."}, {"lang": "es", "value": "Vulnerabilidad de XSS en odm-init.php en OpenDocMan anterior a 1.2.7.3 permite a usuarios remotos autenticados inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del nombre de fichero de un fichero subido."}], "evaluatorComment": null, "id": "CVE-2014-4853", "lastModified": "2014-07-11T00:10:59.870", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-07-10T16:55:06.203", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://packetstormsecurity.com/files/127330/OpenDocMan-1.2.7.2-Cross-Site-Scripting.html"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "http://www.opendocman.com/opendocman-v1-2-7-3-release-notes"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/opendocman/opendocman/commit/d202ef3def8674be61a3e4ccbe28beba4953b7ce"}, {"source": "cve@mitre.org", "tags": null, "url": "https://github.com/opendocman/opendocman/issues/163"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/opendocman/opendocman/commit/d202ef3def8674be61a3e4ccbe28beba4953b7ce"}, "type": "CWE-79"}
287
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "include ('../inc/includes.php');\nheader(\"Content-Type: text/html; charset=UTF-8\");\nHtml::header_nocache();", "Session::checkLoginUser();", "// Read parameters\n$context = $_POST['context'] ?? '';\n$itemtype = $_POST[\"itemtype\"] ?? '';", "// Check for required params\nif (empty($itemtype)) {\n http_response_code(400);\n Toolbox::logWarning(\"Bad request: itemtype cannot be empty\");\n die;\n}", "// Check if itemtype is valid in the given context\nif ($context == \"impact\") {\n $isValidItemtype = Impact::isEnabled($itemtype);\n} else {\n $isValidItemtype = CommonITILObject::isPossibleToAssignType($itemtype);\n}", "// Make a select box\nif ($isValidItemtype) {\n $table = getTableForItemType($itemtype);", " $rand = mt_rand();\n if (isset($_POST[\"rand\"])) {\n $rand = $_POST[\"rand\"];\n }", " // Message for post-only\n if (!isset($_POST[\"admin\"]) || ($_POST[\"admin\"] == 0)) {\n echo \"<br>\".__('Enter the first letters (user, item name, serial or asset number)');\n }\n echo \"<br>\";\n $field_id = Html::cleanId(\"dropdown_\".$_POST['myname'].$rand);\n $p = [\n 'itemtype' => $itemtype,\n 'entity_restrict' => $_POST['entity_restrict'],\n 'table' => $table,\n 'multiple' => $_POST[\"multiple\"],\n 'myname' => $_POST[\"myname\"],\n 'rand' => $_POST[\"rand\"],", " '_idor_token' => Session::getNewIDORToken($itemtype),", " ];", " if (isset($_POST[\"used\"]) && !empty($_POST[\"used\"])) {\n if (isset($_POST[\"used\"][$itemtype])) {\n $p[\"used\"] = $_POST[\"used\"][$itemtype];\n }\n }", " // Add context if defined\n if (!empty($context)) {\n $p[\"context\"] = $context;\n }", " echo Html::jsAjaxDropdown($_POST['myname'], $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownFindNum.php\",\n $p);", " // Auto update summary of active or just solved tickets\n $params = ['items_id' => '__VALUE__',\n 'itemtype' => $_POST['itemtype']];\n Ajax::updateItemOnSelectEvent($field_id, \"item_ticket_selection_information$rand\",\n $CFG_GLPI[\"root_doc\"].\"/ajax/ticketiteminformation.php\",\n $params);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "include ('../inc/includes.php');\nheader(\"Content-Type: text/html; charset=UTF-8\");\nHtml::header_nocache();", "Session::checkLoginUser();", "// Read parameters\n$context = $_POST['context'] ?? '';\n$itemtype = $_POST[\"itemtype\"] ?? '';", "// Check for required params\nif (empty($itemtype)) {\n http_response_code(400);\n Toolbox::logWarning(\"Bad request: itemtype cannot be empty\");\n die;\n}", "// Check if itemtype is valid in the given context\nif ($context == \"impact\") {\n $isValidItemtype = Impact::isEnabled($itemtype);\n} else {\n $isValidItemtype = CommonITILObject::isPossibleToAssignType($itemtype);\n}", "// Make a select box\nif ($isValidItemtype) {\n $table = getTableForItemType($itemtype);", " $rand = mt_rand();\n if (isset($_POST[\"rand\"])) {\n $rand = $_POST[\"rand\"];\n }", " // Message for post-only\n if (!isset($_POST[\"admin\"]) || ($_POST[\"admin\"] == 0)) {\n echo \"<br>\".__('Enter the first letters (user, item name, serial or asset number)');\n }\n echo \"<br>\";\n $field_id = Html::cleanId(\"dropdown_\".$_POST['myname'].$rand);\n $p = [\n 'itemtype' => $itemtype,\n 'entity_restrict' => $_POST['entity_restrict'],\n 'table' => $table,\n 'multiple' => $_POST[\"multiple\"],\n 'myname' => $_POST[\"myname\"],\n 'rand' => $_POST[\"rand\"],", " '_idor_token' => Session::getNewIDORToken($itemtype, [\n 'entity_restrict' => $_POST['entity_restrict'],\n ]),", " ];", " if (isset($_POST[\"used\"]) && !empty($_POST[\"used\"])) {\n if (isset($_POST[\"used\"][$itemtype])) {\n $p[\"used\"] = $_POST[\"used\"][$itemtype];\n }\n }", " // Add context if defined\n if (!empty($context)) {\n $p[\"context\"] = $context;\n }", " echo Html::jsAjaxDropdown($_POST['myname'], $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownFindNum.php\",\n $p);", " // Auto update summary of active or just solved tickets\n $params = ['items_id' => '__VALUE__',\n 'itemtype' => $_POST['itemtype']];\n Ajax::updateItemOnSelectEvent($field_id, \"item_ticket_selection_information$rand\",\n $CFG_GLPI[\"root_doc\"].\"/ajax/ticketiteminformation.php\",\n $params);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access this file directly\");\n}", "/**\n * Computer_Item Class\n *\n * Relation between Computer and Items (monitor, printer, phone, peripheral only)\n**/\nclass Computer_Item extends CommonDBRelation{", " // From CommonDBRelation\n static public $itemtype_1 = 'Computer';\n static public $items_id_1 = 'computers_id';", " static public $itemtype_2 = 'itemtype';\n static public $items_id_2 = 'items_id';\n static public $checkItem_2_Rights = self::HAVE_VIEW_RIGHT_ON_ITEM;", "\n function getForbiddenStandardMassiveAction() {", " $forbidden = parent::getForbiddenStandardMassiveAction();\n $forbidden[] = 'update';\n return $forbidden;\n }", "\n /**\n * Count connection for a Computer and an itemtype\n *\n * @since 0.84\n *\n * @param $comp Computer object\n * @param $item CommonDBTM object\n *\n * @return integer: count\n **/\n static function countForAll(Computer $comp, CommonDBTM $item) {", " return countElementsInTable('glpi_computers_items',\n ['computers_id' => $comp->getField('id'),\n 'itemtype' => $item->getType(),\n 'items_id' => $item->getField('id')]);\n }", "\n function prepareInputForAdd($input) {\n global $CFG_GLPI;", " $item = static::getItemFromArray(static::$itemtype_2, static::$items_id_2, $input);\n if (!($item instanceof CommonDBTM)\n || (($item->getField('is_global') == 0)\n && ($this->countForItem($item) > 0))) {\n return false;\n }", " $comp = static::getItemFromArray(static::$itemtype_1, static::$items_id_1, $input);\n if (!($comp instanceof Computer)\n || (self::countForAll($comp, $item) >0)) {\n // no duplicates\n return false;\n }", " if (!$item->getField('is_global')) {\n // Autoupdate some fields - should be in post_addItem (here to avoid more DB access)\n $updates = [];", " if ($CFG_GLPI[\"is_location_autoupdate\"]\n && ($comp->fields['locations_id'] != $item->getField('locations_id'))) {", " $updates['locations_id'] = addslashes($comp->fields['locations_id']);\n Session::addMessageAfterRedirect(\n __('Location updated. The connected items have been moved in the same location.'),\n true);\n }\n if (($CFG_GLPI[\"is_user_autoupdate\"]\n && ($comp->fields['users_id'] != $item->getField('users_id')))\n || ($CFG_GLPI[\"is_group_autoupdate\"]\n && ($comp->fields['groups_id'] != $item->getField('groups_id')))) {", " if ($CFG_GLPI[\"is_user_autoupdate\"]) {\n $updates['users_id'] = $comp->fields['users_id'];\n }\n if ($CFG_GLPI[\"is_group_autoupdate\"]) {\n $updates['groups_id'] = $comp->fields['groups_id'];\n }\n Session::addMessageAfterRedirect(\n __('User or group updated. The connected items have been moved in the same values.'),\n true);\n }", " if ($CFG_GLPI[\"is_contact_autoupdate\"]\n && (($comp->fields['contact'] != $item->getField('contact'))\n || ($comp->fields['contact_num'] != $item->getField('contact_num')))) {", " $updates['contact'] = addslashes($comp->fields['contact']);\n $updates['contact_num'] = addslashes($comp->fields['contact_num']);\n Session::addMessageAfterRedirect(\n __('Alternate username updated. The connected items have been updated using this alternate username.'),\n true);\n }", " if (($CFG_GLPI[\"state_autoupdate_mode\"] < 0)\n && ($comp->fields['states_id'] != $item->getField('states_id'))) {", " $updates['states_id'] = $comp->fields['states_id'];\n Session::addMessageAfterRedirect(\n __('Status updated. The connected items have been updated using this status.'),\n true);\n }", " if (($CFG_GLPI[\"state_autoupdate_mode\"] > 0)\n && ($item->getField('states_id') != $CFG_GLPI[\"state_autoupdate_mode\"])) {", " $updates['states_id'] = $CFG_GLPI[\"state_autoupdate_mode\"];\n }", " if (count($updates)) {\n $updates['id'] = $input['items_id'];\n $history = true;\n if (isset($input['_no_history']) && $input['_no_history']) {\n $history = false;\n }\n $item->update($updates, $history);\n }\n }\n return parent::prepareInputForAdd($input);\n }", "\n function cleanDBonPurge() {\n global $CFG_GLPI;", " if (!isset($this->input['_no_auto_action'])) {\n //Get the computer name\n $computer = new Computer();\n $computer->getFromDB($this->fields['computers_id']);", " //Get device fields\n if ($device = getItemForItemtype($this->fields['itemtype'])) {\n if ($device->getFromDB($this->fields['items_id'])) {", " if (!$device->getField('is_global')) {\n $updates = [];\n if ($CFG_GLPI[\"is_location_autoclean\"] && $device->isField('locations_id')) {\n $updates['locations_id'] = 0;\n }\n if ($CFG_GLPI[\"is_user_autoclean\"] && $device->isField('users_id')) {\n $updates['users_id'] = 0;\n }\n if ($CFG_GLPI[\"is_group_autoclean\"] && $device->isField('groups_id')) {\n $updates['groups_id'] = 0;\n }\n if ($CFG_GLPI[\"is_contact_autoclean\"] && $device->isField('contact')) {\n $updates['contact'] = \"\";\n }\n if ($CFG_GLPI[\"is_contact_autoclean\"] && $device->isField('contact_num')) {\n $updates['contact_num'] = \"\";\n }\n if (($CFG_GLPI[\"state_autoclean_mode\"] < 0)\n && $device->isField('states_id')) {\n $updates['states_id'] = 0;\n }", " if (($CFG_GLPI[\"state_autoclean_mode\"] > 0)\n && $device->isField('states_id')\n && ($device->getField('states_id') != $CFG_GLPI[\"state_autoclean_mode\"])) {", " $updates['states_id'] = $CFG_GLPI[\"state_autoclean_mode\"];\n }", " if (count($updates)) {\n $updates['id'] = $this->fields['items_id'];\n $device->update($updates);\n }\n }\n }\n }\n }\n }", "\n static function getMassiveActionsForItemtype(array &$actions, $itemtype, $is_deleted = 0,\n CommonDBTM $checkitem = null) {", " $action_prefix = __CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR;\n $specificities = self::getRelationMassiveActionsSpecificities();", " if (in_array($itemtype, $specificities['itemtypes'])) {\n $actions[$action_prefix.'add'] = \"<i class='ma-icon fas fa-plug'></i>\".\n _x('button', 'Connect');\n $actions[$action_prefix.'remove'] = _x('button', 'Disconnect');\n }\n parent::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem);\n }", "\n static function getRelationMassiveActionsSpecificities() {", " $specificities = parent::getRelationMassiveActionsSpecificities();", " $specificities['itemtypes'] = ['Monitor', 'Peripheral', 'Phone', 'Printer'];", " $specificities['select_items_options_2']['entity_restrict'] = $_SESSION['glpiactive_entity'];\n $specificities['select_items_options_2']['onlyglobal'] = true;", " $specificities['only_remove_all_at_once'] = true;", " // Set the labels for add_item and remove_item\n $specificities['button_labels']['add'] = _sx('button', 'Connect');\n $specificities['button_labels']['remove'] = _sx('button', 'Disconnect');", " return $specificities;\n }", "\n /**\n * Disconnect an item to its computer\n *\n * @param $item CommonDBTM object: the Monitor/Phone/Peripheral/Printer\n *\n * @return boolean : action succeeded\n */\n function disconnectForItem(CommonDBTM $item) {\n global $DB;", " if ($item->getField('id')) {\n $iterator = $DB->request([\n 'SELECT' => ['id'],\n 'FROM' => $this->getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $item->getID()\n ]\n ]);", " if (count($iterator) > 0) {\n $ok = true;\n while ($data = $iterator->next()) {\n if ($this->can($data[\"id\"], UPDATE)) {\n $ok &= $this->delete($data);\n }\n }\n return $ok;\n }\n }\n return false;\n }", "\n /**\n *\n * Print the form for computers or templates connections to printers, screens or peripherals\n *\n * @param Computer $comp Computer object\n * @param boolean $withtemplate Template or basic item (default 0)\n *\n * @return void\n **/\n static function showForComputer(Computer $comp, $withtemplate = 0) {\n global $CFG_GLPI;", " $ID = $comp->fields['id'];\n $canedit = $comp->canEdit($ID);\n $rand = mt_rand();", " $datas = [];\n $used = [];\n foreach ($CFG_GLPI[\"directconnect_types\"] as $itemtype) {\n $item = new $itemtype();\n if ($item->canView()) {\n $iterator = self::getTypeItems($ID, $itemtype);", " while ($data = $iterator->next()) {\n $data['assoc_itemtype'] = $itemtype;\n $datas[] = $data;\n $used[$itemtype][] = $data['id'];\n }\n }\n }\n $number = count($datas);", " if ($canedit\n && !(!empty($withtemplate) && ($withtemplate == 2))) {\n echo \"<div class='firstbloc'>\";\n echo \"<form name='computeritem_form$rand' id='computeritem_form$rand' method='post'\n action='\".Toolbox::getItemTypeFormURL(__CLASS__).\"'>\";", " echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr class='tab_bg_2'><th colspan='2'>\".__('Connect an item').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n if (!empty($withtemplate)) {\n echo \"<input type='hidden' name='_no_history' value='1'>\";\n }\n self::dropdownAllConnect('Computer', \"items_id\", $comp->fields[\"entities_id\"],\n $withtemplate, $used);\n echo \"</td><td class='center' width='20%'>\";\n echo \"<input type='submit' name='add' value=\\\"\"._sx('button', 'Connect').\"\\\" class='submit'>\";\n echo \"<input type='hidden' name='computers_id' value='\".$comp->fields['id'].\"'>\";\n echo \"</td></tr>\";\n echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }", " if ($number) {\n echo \"<div class='spaced'>\";\n if ($canedit) {\n Html::openMassiveActionsForm('mass'.__CLASS__.$rand);\n $massiveactionparams\n = ['num_displayed'\n => min($_SESSION['glpilist_limit'], $number),\n 'specific_actions'\n => ['purge' => _x('button', 'Disconnect')],\n 'container'\n => 'mass'.__CLASS__.$rand];\n Html::showMassiveActions($massiveactionparams);\n }\n echo \"<table class='tab_cadre_fixehov'>\";\n $header_begin = \"<tr>\";\n $header_top = '';\n $header_bottom = '';\n $header_end = '';", " if ($canedit) {\n $header_top .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_top .= \"</th>\";\n $header_bottom .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_bottom .= \"</th>\";\n }", " $header_end .= \"<th>\"._n('Type', 'Types', 1).\"</th>\";\n $header_end .= \"<th>\".__('Name').\"</th>\";\n if (Plugin::haveImport()) {\n $header_end .= \"<th>\".__('Automatic inventory').\"</th>\";\n }\n $header_end .= \"<th>\".Entity::getTypeName(1).\"</th>\";\n $header_end .= \"<th>\".__('Serial number').\"</th>\";\n $header_end .= \"<th>\".__('Inventory number').\"</th>\";\n $header_end .= \"</tr>\";\n echo $header_begin.$header_top.$header_end;", " foreach ($datas as $data) {\n $linkname = $data[\"name\"];\n $itemtype = $data['assoc_itemtype'];\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($data[\"name\"])) {\n $linkname = sprintf(__('%1$s (%2$s)'), $linkname, $data[\"id\"]);\n }\n $link = $itemtype::getFormURLWithID($data[\"id\"]);\n $name = \"<a href=\\\"\".$link.\"\\\">\".$linkname.\"</a>\";", " echo \"<tr class='tab_bg_1'>\";", " if ($canedit) {\n echo \"<td width='10'>\";\n Html::showMassiveActionCheckBox(__CLASS__, $data[\"linkid\"]);\n echo \"</td>\";\n }\n echo \"<td>\".$data['assoc_itemtype']::getTypeName(1).\"</td>\";\n echo \"<td \".\n ((isset($data['is_deleted']) && $data['is_deleted'])?\"class='tab_bg_2_2'\":\"\").\n \">\".$name.\"</td>\";\n if (Plugin::haveImport()) {\n $dynamic_field = static::getTable() . '_is_dynamic';\n echo \"<td>\".Dropdown::getYesNo($data[$dynamic_field]).\"</td>\";\n }\n echo \"<td>\".Dropdown::getDropdownName(\"glpi_entities\",\n $data['entities_id']);\n echo \"</td>\";\n echo \"<td>\".\n (isset($data[\"serial\"])? \"\".$data[\"serial\"].\"\" :\"-\").\"</td>\";\n echo \"<td>\".\n (isset($data[\"otherserial\"])? \"\".$data[\"otherserial\"].\"\" :\"-\").\"</td>\";\n echo \"</tr>\";\n }\n echo $header_begin.$header_bottom.$header_end;", " echo \"</table>\";\n if ($canedit && $number) {\n $massiveactionparams['ontop'] = false;\n Html::showMassiveActions($massiveactionparams);\n Html::closeForm();\n }\n echo \"</div>\";\n }\n }", "\n /**\n * Prints a direct connection to a computer\n *\n * @param $item CommonDBTM object: the Monitor/Phone/Peripheral/Printer\n * @param $withtemplate integer withtemplate param (default 0)\n *\n * @return void\n **/\n static function showForItem(CommonDBTM $item, $withtemplate = 0) {\n // Prints a direct connection to a computer\n global $DB;", " $comp = new Computer();\n $ID = $item->getField('id');", " if (!$item->can($ID, READ)) {\n return;\n }\n $canedit = $item->canEdit($ID);\n $rand = mt_rand();", " // Is global connection ?\n $global = $item->getField('is_global');", " $used = [];\n $compids = [];\n $dynamic = [];\n $result = $DB->request(\n [\n 'SELECT' => ['id', 'computers_id', 'is_dynamic'],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $ID,\n 'is_deleted' => 0,\n ]\n ]\n );\n foreach ($result as $data) {\n $compids[$data['id']] = $data['computers_id'];\n $dynamic[$data['id']] = $data['is_dynamic'];\n $used['Computer'][] = $data['computers_id'];\n }\n $number = count($compids);\n if ($canedit\n && ($global || !$number)\n && !(!empty($withtemplate) && ($withtemplate == 2))) {\n echo \"<div class='firstbloc'>\";\n echo \"<form name='computeritem_form$rand' id='computeritem_form$rand' method='post'\n action='\".Toolbox::getItemTypeFormURL(__CLASS__).\"'>\";", " echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr class='tab_bg_2'><th colspan='2'>\".__('Connect a computer').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td class='right'>\";\n echo \"<input type='hidden' name='items_id' value='$ID'>\";\n echo \"<input type='hidden' name='itemtype' value='\".$item->getType().\"'>\";\n if ($item->isRecursive()) {\n self::dropdownConnect('Computer', $item->getType(), \"computers_id\",\n getSonsOf(\"glpi_entities\", $item->getEntityID()), 0, $used);\n } else {\n self::dropdownConnect('Computer', $item->getType(), \"computers_id\",\n $item->getEntityID(), 0, $used);\n }\n echo \"</td><td class='center'>\";\n echo \"<input type='submit' name='add' value=\\\"\"._sx('button', 'Connect').\"\\\" class='submit'>\";\n echo \"</td></tr>\";\n echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }", " echo \"<div class='spaced'>\";\n if ($canedit && $number) {\n Html::openMassiveActionsForm('mass'.__CLASS__.$rand);\n $massiveactionparams\n = ['num_displayed'\n => min($_SESSION['glpilist_limit'], $number),\n 'specific_actions'\n => ['purge' => _x('button', 'Disconnect')],\n 'container'\n => 'mass'.__CLASS__.$rand];\n Html::showMassiveActions($massiveactionparams);\n }\n echo \"<table class='tab_cadre_fixehov'>\";", " if ($number > 0) {\n $header_begin = \"<tr>\";\n $header_top = '';\n $header_bottom = '';\n $header_end = '';", " if ($canedit) {\n $header_top .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_top .= \"</th>\";\n $header_bottom .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_bottom .= \"</th>\";\n }", " $header_end .= \"<th>\".__('Name').\"</th>\";\n if (Plugin::haveImport()) {\n $header_end .= \"<th>\".__('Automatic inventory').\"</th>\";\n }\n $header_end .= \"<th>\".Entity::getTypeName(1).\"</th>\";\n $header_end .= \"<th>\".__('Serial number').\"</th>\";\n $header_end .= \"<th>\".__('Inventory number').\"</th>\";\n $header_end .= \"</tr>\";\n echo $header_begin.$header_top.$header_end;", " foreach ($compids as $key => $compid) {\n $comp->getFromDB($compid);", " echo \"<tr class='tab_bg_1'>\";", " if ($canedit) {\n echo \"<td width='10'>\";\n Html::showMassiveActionCheckBox(__CLASS__, $key);\n echo \"</td>\";\n }\n echo \"<td \".\n ($comp->getField('is_deleted')?\"class='tab_bg_2_2'\":\"\").\n \">\".$comp->getLink().\"</td>\";\n if (Plugin::haveImport()) {\n echo \"<td>\".Dropdown::getYesNo($dynamic[$key]).\"</td>\";\n }\n echo \"<td class='center'>\".Dropdown::getDropdownName(\"glpi_entities\",\n $comp->getField('entities_id'));\n echo \"</td>\";\n echo \"<td class='center'>\".$comp->getField('serial').\"</td>\";\n echo \"<td class='center'>\".$comp->getField('otherserial').\"</td>\";\n echo \"</tr>\";\n }\n echo $header_begin.$header_bottom.$header_end;\n } else {\n echo \"<tr><td class='tab_bg_1 b'><i>\".__('Not connected').\"</i>\";\n echo \"</td></tr>\";\n }", " echo \"</table>\";\n if ($canedit && $number) {\n $massiveactionparams['ontop'] = false;\n Html::showMassiveActions($massiveactionparams);\n Html::closeForm();\n }\n echo \"</div>\";\n }", "\n /**\n * Unglobalize an item : duplicate item and connections\n *\n * @param $item CommonDBTM object to unglobalize\n **/\n static function unglobalizeItem(CommonDBTM $item) {\n global $DB;", " // Update item to unit management :\n if ($item->getField('is_global')) {\n $input = ['id' => $item->fields['id'],\n 'is_global' => 0];\n $item->update($input);", " // Get connect_wire for this connection\n $iterator = $DB->request([\n 'SELECT' => ['id'],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'items_id' => $item->getID(),\n 'itemtype' => $item->getType()\n ]\n ]);", " $first = true;\n while ($data = $iterator->next()) {\n if ($first) {\n $first = false;\n unset($input['id']);\n $conn = new self();\n } else {\n $temp = clone $item;\n unset($temp->fields['id']);\n if ($newID=$temp->add($temp->fields)) {\n $conn->update(['id' => $data['id'],\n 'items_id' => $newID]);\n }\n }\n }\n }\n }", "\n /**\n * Make a select box for connections\n *\n * @since 0.84\n *\n * @param string $fromtype from where the connection is\n * @param string $myname select name\n * @param integer|integer[] $entity_restrict Restrict to a defined entity (default = -1)\n * @param boolean $onlyglobal display only global devices (used for templates) (default 0)\n * @param integer[] $used Already used items ID: not to display in dropdown\n *\n * @return integer Random generated number used for select box ID (select box HTML is printed)\n */\n static function dropdownAllConnect($fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;", " $rand = mt_rand();", " $options = [];\n $options['checkright'] = true;\n $options['name'] = 'itemtype';", " $rand = Dropdown::showItemType($CFG_GLPI['directconnect_types'], $options);\n if ($rand) {\n $params = ['itemtype' => '__VALUE__',\n 'fromtype' => $fromtype,\n 'value' => 0,\n 'myname' => $myname,\n 'onlyglobal' => $onlyglobal,\n 'entity_restrict' => $entity_restrict,\n 'used' => $used];", " if ($onlyglobal) {\n $params['condition'] = ['is_global' => 1];\n }\n Ajax::updateItemOnSelectEvent(\"dropdown_itemtype$rand\", \"show_$myname$rand\",\n $CFG_GLPI[\"root_doc\"].\"/ajax/dropdownConnect.php\", $params);", " echo \"<br><div id='show_$myname$rand'>&nbsp;</div>\\n\";\n }\n return $rand;", " }", "\n /**\n * Make a select box for connections\n *\n * @param string $itemtype type to connect\n * @param string $fromtype from where the connection is\n * @param string $myname select name\n * @param integer|integer[] $entity_restrict Restrict to a defined entity (default = -1)\n * @param boolean $onlyglobal display only global devices (used for templates) (default 0)\n * @param integer[] $used Already used items ID: not to display in dropdown\n *\n * @return integer Random generated number used for select box ID (select box HTML is printed)\n */\n static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;", " $rand = mt_rand();", " $field_id = Html::cleanId(\"dropdown_\".$myname.$rand);\n $param = [\n 'entity_restrict' => $entity_restrict,\n 'fromtype' => $fromtype,\n 'itemtype' => $itemtype,\n 'onlyglobal' => $onlyglobal,\n 'used' => $used,", " '_idor_token' => Session::getNewIDORToken($itemtype),", " ];", " echo Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownConnect.php\",\n $param);", " return $rand;\n }", "\n function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {", " // can exists for Template\n if ($item->can($item->getField('id'), READ)) {\n $nb = 0;\n switch ($item->getType()) {\n case 'Phone' :\n case 'Printer' :\n case 'Peripheral' :\n case 'Monitor' :\n if (Computer::canView()) {\n if ($_SESSION['glpishow_count_on_tabs']) {\n $nb = self::countForItem($item);\n }\n return self::createTabEntry(_n('Connection', 'Connections', Session::getPluralNumber()),\n $nb);\n }\n break;", " case 'Computer' :\n if (Phone::canView()\n || Printer::canView()\n || Peripheral::canView()\n || Monitor::canView()) {\n if ($_SESSION['glpishow_count_on_tabs']) {\n $nb = self::countForMainItem($item);\n }\n return self::createTabEntry(_n('Connection', 'Connections', Session::getPluralNumber()),\n $nb);\n }\n break;\n }\n }\n return '';\n }", "\n static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {", " switch ($item->getType()) {\n case 'Phone' :\n case 'Printer' :\n case 'Peripheral' :\n case 'Monitor' :\n self::showForItem($item, $withtemplate);\n return true;", " case 'Computer' :\n self::showForComputer($item, $withtemplate);\n return true;\n }\n }", "\n /**\n * Duplicate connected items to computer from an item template to its clone\n *\n * @deprecated 9.5\n * @since 0.84\n *\n * @param integer $oldid ID of the item to clone\n * @param integer $newid ID of the item cloned\n **/\n static function cloneComputer($oldid, $newid) {\n global $DB;", " Toolbox::deprecated('Use clone');\n $iterator = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => ['computers_id' => $oldid]\n ]);", " while ($data = $iterator->next()) {\n $conn = new Computer_Item();\n $conn->add(['computers_id' => $newid,\n 'itemtype' => $data[\"itemtype\"],\n 'items_id' => $data[\"items_id\"]]);\n }\n }", "\n /**\n * Duplicate connected items to item from an item template to its clone\n *\n * @deprecated 9.5\n * @since 0.83.3\n *\n * @param string $itemtype type of the item to clone\n * @param integer $oldid ID of the item to clone\n * @param integer $newid ID of the item cloned\n **/\n static function cloneItem($itemtype, $oldid, $newid) {\n global $DB;", " Toolbox::deprecated('Use clone');\n $iterator = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $itemtype,\n 'items_id' => $oldid\n ]\n ]);", " while ($data = $iterator->next()) {\n $conn = new self();\n $conn->add(['computers_id' => $data[\"computers_id\"],\n 'itemtype' => $data[\"itemtype\"],\n 'items_id' => $newid]);\n }\n }", "\n /**\n * @since 9.1.7\n *\n * @param CommonDBTM $item item linked to the computer to check\n * @param integer[] $entities entities to check\n *\n * @return boolean\n **/\n static function canUnrecursSpecif(CommonDBTM $item, $entities) {\n global $DB;", " // RELATION : computers -> items\n $iterator = $DB->request([\n 'SELECT' => [\n 'itemtype',\n new \\QueryExpression('GROUP_CONCAT(DISTINCT '.$DB->quoteName('items_id').') AS ids'),\n 'computers_id'\n ],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $item->fields['id']\n ],\n 'GROUP' => 'itemtype'\n ]);", " while ($data = $iterator->next()) {\n if (countElementsInTable(\"glpi_computers\",\n ['id' => $data[\"computers_id\"],\n 'NOT' => ['entities_id' => $entities]]) > 0) {\n return false;\n }\n }\n return true;\n }", "\n protected static function getListForItemParams(CommonDBTM $item, $noent = false) {\n $params = parent::getListForItemParams($item, $noent);\n $params['WHERE'][self::getTable() . '.is_deleted'] = 0;\n return $params;\n }", " /**\n * Get SELECT param for getTypeItemsQueryParams\n *\n * @param CommonDBTM $item\n *\n * @return array\n */\n public static function getTypeItemsQueryParams_Select(CommonDBTM $item): array {\n $table = static::getTable();\n $select = parent::getTypeItemsQueryParams_Select($item);\n $select[] = \"$table.is_dynamic AS {$table}_is_dynamic\";", " return $select;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access this file directly\");\n}", "/**\n * Computer_Item Class\n *\n * Relation between Computer and Items (monitor, printer, phone, peripheral only)\n**/\nclass Computer_Item extends CommonDBRelation{", " // From CommonDBRelation\n static public $itemtype_1 = 'Computer';\n static public $items_id_1 = 'computers_id';", " static public $itemtype_2 = 'itemtype';\n static public $items_id_2 = 'items_id';\n static public $checkItem_2_Rights = self::HAVE_VIEW_RIGHT_ON_ITEM;", "\n function getForbiddenStandardMassiveAction() {", " $forbidden = parent::getForbiddenStandardMassiveAction();\n $forbidden[] = 'update';\n return $forbidden;\n }", "\n /**\n * Count connection for a Computer and an itemtype\n *\n * @since 0.84\n *\n * @param $comp Computer object\n * @param $item CommonDBTM object\n *\n * @return integer: count\n **/\n static function countForAll(Computer $comp, CommonDBTM $item) {", " return countElementsInTable('glpi_computers_items',\n ['computers_id' => $comp->getField('id'),\n 'itemtype' => $item->getType(),\n 'items_id' => $item->getField('id')]);\n }", "\n function prepareInputForAdd($input) {\n global $CFG_GLPI;", " $item = static::getItemFromArray(static::$itemtype_2, static::$items_id_2, $input);\n if (!($item instanceof CommonDBTM)\n || (($item->getField('is_global') == 0)\n && ($this->countForItem($item) > 0))) {\n return false;\n }", " $comp = static::getItemFromArray(static::$itemtype_1, static::$items_id_1, $input);\n if (!($comp instanceof Computer)\n || (self::countForAll($comp, $item) >0)) {\n // no duplicates\n return false;\n }", " if (!$item->getField('is_global')) {\n // Autoupdate some fields - should be in post_addItem (here to avoid more DB access)\n $updates = [];", " if ($CFG_GLPI[\"is_location_autoupdate\"]\n && ($comp->fields['locations_id'] != $item->getField('locations_id'))) {", " $updates['locations_id'] = addslashes($comp->fields['locations_id']);\n Session::addMessageAfterRedirect(\n __('Location updated. The connected items have been moved in the same location.'),\n true);\n }\n if (($CFG_GLPI[\"is_user_autoupdate\"]\n && ($comp->fields['users_id'] != $item->getField('users_id')))\n || ($CFG_GLPI[\"is_group_autoupdate\"]\n && ($comp->fields['groups_id'] != $item->getField('groups_id')))) {", " if ($CFG_GLPI[\"is_user_autoupdate\"]) {\n $updates['users_id'] = $comp->fields['users_id'];\n }\n if ($CFG_GLPI[\"is_group_autoupdate\"]) {\n $updates['groups_id'] = $comp->fields['groups_id'];\n }\n Session::addMessageAfterRedirect(\n __('User or group updated. The connected items have been moved in the same values.'),\n true);\n }", " if ($CFG_GLPI[\"is_contact_autoupdate\"]\n && (($comp->fields['contact'] != $item->getField('contact'))\n || ($comp->fields['contact_num'] != $item->getField('contact_num')))) {", " $updates['contact'] = addslashes($comp->fields['contact']);\n $updates['contact_num'] = addslashes($comp->fields['contact_num']);\n Session::addMessageAfterRedirect(\n __('Alternate username updated. The connected items have been updated using this alternate username.'),\n true);\n }", " if (($CFG_GLPI[\"state_autoupdate_mode\"] < 0)\n && ($comp->fields['states_id'] != $item->getField('states_id'))) {", " $updates['states_id'] = $comp->fields['states_id'];\n Session::addMessageAfterRedirect(\n __('Status updated. The connected items have been updated using this status.'),\n true);\n }", " if (($CFG_GLPI[\"state_autoupdate_mode\"] > 0)\n && ($item->getField('states_id') != $CFG_GLPI[\"state_autoupdate_mode\"])) {", " $updates['states_id'] = $CFG_GLPI[\"state_autoupdate_mode\"];\n }", " if (count($updates)) {\n $updates['id'] = $input['items_id'];\n $history = true;\n if (isset($input['_no_history']) && $input['_no_history']) {\n $history = false;\n }\n $item->update($updates, $history);\n }\n }\n return parent::prepareInputForAdd($input);\n }", "\n function cleanDBonPurge() {\n global $CFG_GLPI;", " if (!isset($this->input['_no_auto_action'])) {\n //Get the computer name\n $computer = new Computer();\n $computer->getFromDB($this->fields['computers_id']);", " //Get device fields\n if ($device = getItemForItemtype($this->fields['itemtype'])) {\n if ($device->getFromDB($this->fields['items_id'])) {", " if (!$device->getField('is_global')) {\n $updates = [];\n if ($CFG_GLPI[\"is_location_autoclean\"] && $device->isField('locations_id')) {\n $updates['locations_id'] = 0;\n }\n if ($CFG_GLPI[\"is_user_autoclean\"] && $device->isField('users_id')) {\n $updates['users_id'] = 0;\n }\n if ($CFG_GLPI[\"is_group_autoclean\"] && $device->isField('groups_id')) {\n $updates['groups_id'] = 0;\n }\n if ($CFG_GLPI[\"is_contact_autoclean\"] && $device->isField('contact')) {\n $updates['contact'] = \"\";\n }\n if ($CFG_GLPI[\"is_contact_autoclean\"] && $device->isField('contact_num')) {\n $updates['contact_num'] = \"\";\n }\n if (($CFG_GLPI[\"state_autoclean_mode\"] < 0)\n && $device->isField('states_id')) {\n $updates['states_id'] = 0;\n }", " if (($CFG_GLPI[\"state_autoclean_mode\"] > 0)\n && $device->isField('states_id')\n && ($device->getField('states_id') != $CFG_GLPI[\"state_autoclean_mode\"])) {", " $updates['states_id'] = $CFG_GLPI[\"state_autoclean_mode\"];\n }", " if (count($updates)) {\n $updates['id'] = $this->fields['items_id'];\n $device->update($updates);\n }\n }\n }\n }\n }\n }", "\n static function getMassiveActionsForItemtype(array &$actions, $itemtype, $is_deleted = 0,\n CommonDBTM $checkitem = null) {", " $action_prefix = __CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR;\n $specificities = self::getRelationMassiveActionsSpecificities();", " if (in_array($itemtype, $specificities['itemtypes'])) {\n $actions[$action_prefix.'add'] = \"<i class='ma-icon fas fa-plug'></i>\".\n _x('button', 'Connect');\n $actions[$action_prefix.'remove'] = _x('button', 'Disconnect');\n }\n parent::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem);\n }", "\n static function getRelationMassiveActionsSpecificities() {", " $specificities = parent::getRelationMassiveActionsSpecificities();", " $specificities['itemtypes'] = ['Monitor', 'Peripheral', 'Phone', 'Printer'];", " $specificities['select_items_options_2']['entity_restrict'] = $_SESSION['glpiactive_entity'];\n $specificities['select_items_options_2']['onlyglobal'] = true;", " $specificities['only_remove_all_at_once'] = true;", " // Set the labels for add_item and remove_item\n $specificities['button_labels']['add'] = _sx('button', 'Connect');\n $specificities['button_labels']['remove'] = _sx('button', 'Disconnect');", " return $specificities;\n }", "\n /**\n * Disconnect an item to its computer\n *\n * @param $item CommonDBTM object: the Monitor/Phone/Peripheral/Printer\n *\n * @return boolean : action succeeded\n */\n function disconnectForItem(CommonDBTM $item) {\n global $DB;", " if ($item->getField('id')) {\n $iterator = $DB->request([\n 'SELECT' => ['id'],\n 'FROM' => $this->getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $item->getID()\n ]\n ]);", " if (count($iterator) > 0) {\n $ok = true;\n while ($data = $iterator->next()) {\n if ($this->can($data[\"id\"], UPDATE)) {\n $ok &= $this->delete($data);\n }\n }\n return $ok;\n }\n }\n return false;\n }", "\n /**\n *\n * Print the form for computers or templates connections to printers, screens or peripherals\n *\n * @param Computer $comp Computer object\n * @param boolean $withtemplate Template or basic item (default 0)\n *\n * @return void\n **/\n static function showForComputer(Computer $comp, $withtemplate = 0) {\n global $CFG_GLPI;", " $ID = $comp->fields['id'];\n $canedit = $comp->canEdit($ID);\n $rand = mt_rand();", " $datas = [];\n $used = [];\n foreach ($CFG_GLPI[\"directconnect_types\"] as $itemtype) {\n $item = new $itemtype();\n if ($item->canView()) {\n $iterator = self::getTypeItems($ID, $itemtype);", " while ($data = $iterator->next()) {\n $data['assoc_itemtype'] = $itemtype;\n $datas[] = $data;\n $used[$itemtype][] = $data['id'];\n }\n }\n }\n $number = count($datas);", " if ($canedit\n && !(!empty($withtemplate) && ($withtemplate == 2))) {\n echo \"<div class='firstbloc'>\";\n echo \"<form name='computeritem_form$rand' id='computeritem_form$rand' method='post'\n action='\".Toolbox::getItemTypeFormURL(__CLASS__).\"'>\";", " echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr class='tab_bg_2'><th colspan='2'>\".__('Connect an item').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n if (!empty($withtemplate)) {\n echo \"<input type='hidden' name='_no_history' value='1'>\";\n }\n self::dropdownAllConnect('Computer', \"items_id\", $comp->fields[\"entities_id\"],\n $withtemplate, $used);\n echo \"</td><td class='center' width='20%'>\";\n echo \"<input type='submit' name='add' value=\\\"\"._sx('button', 'Connect').\"\\\" class='submit'>\";\n echo \"<input type='hidden' name='computers_id' value='\".$comp->fields['id'].\"'>\";\n echo \"</td></tr>\";\n echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }", " if ($number) {\n echo \"<div class='spaced'>\";\n if ($canedit) {\n Html::openMassiveActionsForm('mass'.__CLASS__.$rand);\n $massiveactionparams\n = ['num_displayed'\n => min($_SESSION['glpilist_limit'], $number),\n 'specific_actions'\n => ['purge' => _x('button', 'Disconnect')],\n 'container'\n => 'mass'.__CLASS__.$rand];\n Html::showMassiveActions($massiveactionparams);\n }\n echo \"<table class='tab_cadre_fixehov'>\";\n $header_begin = \"<tr>\";\n $header_top = '';\n $header_bottom = '';\n $header_end = '';", " if ($canedit) {\n $header_top .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_top .= \"</th>\";\n $header_bottom .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_bottom .= \"</th>\";\n }", " $header_end .= \"<th>\"._n('Type', 'Types', 1).\"</th>\";\n $header_end .= \"<th>\".__('Name').\"</th>\";\n if (Plugin::haveImport()) {\n $header_end .= \"<th>\".__('Automatic inventory').\"</th>\";\n }\n $header_end .= \"<th>\".Entity::getTypeName(1).\"</th>\";\n $header_end .= \"<th>\".__('Serial number').\"</th>\";\n $header_end .= \"<th>\".__('Inventory number').\"</th>\";\n $header_end .= \"</tr>\";\n echo $header_begin.$header_top.$header_end;", " foreach ($datas as $data) {\n $linkname = $data[\"name\"];\n $itemtype = $data['assoc_itemtype'];\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($data[\"name\"])) {\n $linkname = sprintf(__('%1$s (%2$s)'), $linkname, $data[\"id\"]);\n }\n $link = $itemtype::getFormURLWithID($data[\"id\"]);\n $name = \"<a href=\\\"\".$link.\"\\\">\".$linkname.\"</a>\";", " echo \"<tr class='tab_bg_1'>\";", " if ($canedit) {\n echo \"<td width='10'>\";\n Html::showMassiveActionCheckBox(__CLASS__, $data[\"linkid\"]);\n echo \"</td>\";\n }\n echo \"<td>\".$data['assoc_itemtype']::getTypeName(1).\"</td>\";\n echo \"<td \".\n ((isset($data['is_deleted']) && $data['is_deleted'])?\"class='tab_bg_2_2'\":\"\").\n \">\".$name.\"</td>\";\n if (Plugin::haveImport()) {\n $dynamic_field = static::getTable() . '_is_dynamic';\n echo \"<td>\".Dropdown::getYesNo($data[$dynamic_field]).\"</td>\";\n }\n echo \"<td>\".Dropdown::getDropdownName(\"glpi_entities\",\n $data['entities_id']);\n echo \"</td>\";\n echo \"<td>\".\n (isset($data[\"serial\"])? \"\".$data[\"serial\"].\"\" :\"-\").\"</td>\";\n echo \"<td>\".\n (isset($data[\"otherserial\"])? \"\".$data[\"otherserial\"].\"\" :\"-\").\"</td>\";\n echo \"</tr>\";\n }\n echo $header_begin.$header_bottom.$header_end;", " echo \"</table>\";\n if ($canedit && $number) {\n $massiveactionparams['ontop'] = false;\n Html::showMassiveActions($massiveactionparams);\n Html::closeForm();\n }\n echo \"</div>\";\n }\n }", "\n /**\n * Prints a direct connection to a computer\n *\n * @param $item CommonDBTM object: the Monitor/Phone/Peripheral/Printer\n * @param $withtemplate integer withtemplate param (default 0)\n *\n * @return void\n **/\n static function showForItem(CommonDBTM $item, $withtemplate = 0) {\n // Prints a direct connection to a computer\n global $DB;", " $comp = new Computer();\n $ID = $item->getField('id');", " if (!$item->can($ID, READ)) {\n return;\n }\n $canedit = $item->canEdit($ID);\n $rand = mt_rand();", " // Is global connection ?\n $global = $item->getField('is_global');", " $used = [];\n $compids = [];\n $dynamic = [];\n $result = $DB->request(\n [\n 'SELECT' => ['id', 'computers_id', 'is_dynamic'],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $ID,\n 'is_deleted' => 0,\n ]\n ]\n );\n foreach ($result as $data) {\n $compids[$data['id']] = $data['computers_id'];\n $dynamic[$data['id']] = $data['is_dynamic'];\n $used['Computer'][] = $data['computers_id'];\n }\n $number = count($compids);\n if ($canedit\n && ($global || !$number)\n && !(!empty($withtemplate) && ($withtemplate == 2))) {\n echo \"<div class='firstbloc'>\";\n echo \"<form name='computeritem_form$rand' id='computeritem_form$rand' method='post'\n action='\".Toolbox::getItemTypeFormURL(__CLASS__).\"'>\";", " echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr class='tab_bg_2'><th colspan='2'>\".__('Connect a computer').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td class='right'>\";\n echo \"<input type='hidden' name='items_id' value='$ID'>\";\n echo \"<input type='hidden' name='itemtype' value='\".$item->getType().\"'>\";\n if ($item->isRecursive()) {\n self::dropdownConnect('Computer', $item->getType(), \"computers_id\",\n getSonsOf(\"glpi_entities\", $item->getEntityID()), 0, $used);\n } else {\n self::dropdownConnect('Computer', $item->getType(), \"computers_id\",\n $item->getEntityID(), 0, $used);\n }\n echo \"</td><td class='center'>\";\n echo \"<input type='submit' name='add' value=\\\"\"._sx('button', 'Connect').\"\\\" class='submit'>\";\n echo \"</td></tr>\";\n echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }", " echo \"<div class='spaced'>\";\n if ($canedit && $number) {\n Html::openMassiveActionsForm('mass'.__CLASS__.$rand);\n $massiveactionparams\n = ['num_displayed'\n => min($_SESSION['glpilist_limit'], $number),\n 'specific_actions'\n => ['purge' => _x('button', 'Disconnect')],\n 'container'\n => 'mass'.__CLASS__.$rand];\n Html::showMassiveActions($massiveactionparams);\n }\n echo \"<table class='tab_cadre_fixehov'>\";", " if ($number > 0) {\n $header_begin = \"<tr>\";\n $header_top = '';\n $header_bottom = '';\n $header_end = '';", " if ($canedit) {\n $header_top .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_top .= \"</th>\";\n $header_bottom .= \"<th width='10'>\".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);\n $header_bottom .= \"</th>\";\n }", " $header_end .= \"<th>\".__('Name').\"</th>\";\n if (Plugin::haveImport()) {\n $header_end .= \"<th>\".__('Automatic inventory').\"</th>\";\n }\n $header_end .= \"<th>\".Entity::getTypeName(1).\"</th>\";\n $header_end .= \"<th>\".__('Serial number').\"</th>\";\n $header_end .= \"<th>\".__('Inventory number').\"</th>\";\n $header_end .= \"</tr>\";\n echo $header_begin.$header_top.$header_end;", " foreach ($compids as $key => $compid) {\n $comp->getFromDB($compid);", " echo \"<tr class='tab_bg_1'>\";", " if ($canedit) {\n echo \"<td width='10'>\";\n Html::showMassiveActionCheckBox(__CLASS__, $key);\n echo \"</td>\";\n }\n echo \"<td \".\n ($comp->getField('is_deleted')?\"class='tab_bg_2_2'\":\"\").\n \">\".$comp->getLink().\"</td>\";\n if (Plugin::haveImport()) {\n echo \"<td>\".Dropdown::getYesNo($dynamic[$key]).\"</td>\";\n }\n echo \"<td class='center'>\".Dropdown::getDropdownName(\"glpi_entities\",\n $comp->getField('entities_id'));\n echo \"</td>\";\n echo \"<td class='center'>\".$comp->getField('serial').\"</td>\";\n echo \"<td class='center'>\".$comp->getField('otherserial').\"</td>\";\n echo \"</tr>\";\n }\n echo $header_begin.$header_bottom.$header_end;\n } else {\n echo \"<tr><td class='tab_bg_1 b'><i>\".__('Not connected').\"</i>\";\n echo \"</td></tr>\";\n }", " echo \"</table>\";\n if ($canedit && $number) {\n $massiveactionparams['ontop'] = false;\n Html::showMassiveActions($massiveactionparams);\n Html::closeForm();\n }\n echo \"</div>\";\n }", "\n /**\n * Unglobalize an item : duplicate item and connections\n *\n * @param $item CommonDBTM object to unglobalize\n **/\n static function unglobalizeItem(CommonDBTM $item) {\n global $DB;", " // Update item to unit management :\n if ($item->getField('is_global')) {\n $input = ['id' => $item->fields['id'],\n 'is_global' => 0];\n $item->update($input);", " // Get connect_wire for this connection\n $iterator = $DB->request([\n 'SELECT' => ['id'],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'items_id' => $item->getID(),\n 'itemtype' => $item->getType()\n ]\n ]);", " $first = true;\n while ($data = $iterator->next()) {\n if ($first) {\n $first = false;\n unset($input['id']);\n $conn = new self();\n } else {\n $temp = clone $item;\n unset($temp->fields['id']);\n if ($newID=$temp->add($temp->fields)) {\n $conn->update(['id' => $data['id'],\n 'items_id' => $newID]);\n }\n }\n }\n }\n }", "\n /**\n * Make a select box for connections\n *\n * @since 0.84\n *\n * @param string $fromtype from where the connection is\n * @param string $myname select name\n * @param integer|integer[] $entity_restrict Restrict to a defined entity (default = -1)\n * @param boolean $onlyglobal display only global devices (used for templates) (default 0)\n * @param integer[] $used Already used items ID: not to display in dropdown\n *\n * @return integer Random generated number used for select box ID (select box HTML is printed)\n */\n static function dropdownAllConnect($fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;", " $rand = mt_rand();", " $options = [];\n $options['checkright'] = true;\n $options['name'] = 'itemtype';", " $rand = Dropdown::showItemType($CFG_GLPI['directconnect_types'], $options);\n if ($rand) {\n $params = ['itemtype' => '__VALUE__',\n 'fromtype' => $fromtype,\n 'value' => 0,\n 'myname' => $myname,\n 'onlyglobal' => $onlyglobal,\n 'entity_restrict' => $entity_restrict,\n 'used' => $used];", " if ($onlyglobal) {\n $params['condition'] = ['is_global' => 1];\n }\n Ajax::updateItemOnSelectEvent(\"dropdown_itemtype$rand\", \"show_$myname$rand\",\n $CFG_GLPI[\"root_doc\"].\"/ajax/dropdownConnect.php\", $params);", " echo \"<br><div id='show_$myname$rand'>&nbsp;</div>\\n\";\n }\n return $rand;", " }", "\n /**\n * Make a select box for connections\n *\n * @param string $itemtype type to connect\n * @param string $fromtype from where the connection is\n * @param string $myname select name\n * @param integer|integer[] $entity_restrict Restrict to a defined entity (default = -1)\n * @param boolean $onlyglobal display only global devices (used for templates) (default 0)\n * @param integer[] $used Already used items ID: not to display in dropdown\n *\n * @return integer Random generated number used for select box ID (select box HTML is printed)\n */\n static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;", " $rand = mt_rand();", " $field_id = Html::cleanId(\"dropdown_\".$myname.$rand);\n $param = [\n 'entity_restrict' => $entity_restrict,\n 'fromtype' => $fromtype,\n 'itemtype' => $itemtype,\n 'onlyglobal' => $onlyglobal,\n 'used' => $used,", " '_idor_token' => Session::getNewIDORToken($itemtype, [\n 'entity_restrict' => $entity_restrict,\n ]),", " ];", " echo Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownConnect.php\",\n $param);", " return $rand;\n }", "\n function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {", " // can exists for Template\n if ($item->can($item->getField('id'), READ)) {\n $nb = 0;\n switch ($item->getType()) {\n case 'Phone' :\n case 'Printer' :\n case 'Peripheral' :\n case 'Monitor' :\n if (Computer::canView()) {\n if ($_SESSION['glpishow_count_on_tabs']) {\n $nb = self::countForItem($item);\n }\n return self::createTabEntry(_n('Connection', 'Connections', Session::getPluralNumber()),\n $nb);\n }\n break;", " case 'Computer' :\n if (Phone::canView()\n || Printer::canView()\n || Peripheral::canView()\n || Monitor::canView()) {\n if ($_SESSION['glpishow_count_on_tabs']) {\n $nb = self::countForMainItem($item);\n }\n return self::createTabEntry(_n('Connection', 'Connections', Session::getPluralNumber()),\n $nb);\n }\n break;\n }\n }\n return '';\n }", "\n static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {", " switch ($item->getType()) {\n case 'Phone' :\n case 'Printer' :\n case 'Peripheral' :\n case 'Monitor' :\n self::showForItem($item, $withtemplate);\n return true;", " case 'Computer' :\n self::showForComputer($item, $withtemplate);\n return true;\n }\n }", "\n /**\n * Duplicate connected items to computer from an item template to its clone\n *\n * @deprecated 9.5\n * @since 0.84\n *\n * @param integer $oldid ID of the item to clone\n * @param integer $newid ID of the item cloned\n **/\n static function cloneComputer($oldid, $newid) {\n global $DB;", " Toolbox::deprecated('Use clone');\n $iterator = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => ['computers_id' => $oldid]\n ]);", " while ($data = $iterator->next()) {\n $conn = new Computer_Item();\n $conn->add(['computers_id' => $newid,\n 'itemtype' => $data[\"itemtype\"],\n 'items_id' => $data[\"items_id\"]]);\n }\n }", "\n /**\n * Duplicate connected items to item from an item template to its clone\n *\n * @deprecated 9.5\n * @since 0.83.3\n *\n * @param string $itemtype type of the item to clone\n * @param integer $oldid ID of the item to clone\n * @param integer $newid ID of the item cloned\n **/\n static function cloneItem($itemtype, $oldid, $newid) {\n global $DB;", " Toolbox::deprecated('Use clone');\n $iterator = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $itemtype,\n 'items_id' => $oldid\n ]\n ]);", " while ($data = $iterator->next()) {\n $conn = new self();\n $conn->add(['computers_id' => $data[\"computers_id\"],\n 'itemtype' => $data[\"itemtype\"],\n 'items_id' => $newid]);\n }\n }", "\n /**\n * @since 9.1.7\n *\n * @param CommonDBTM $item item linked to the computer to check\n * @param integer[] $entities entities to check\n *\n * @return boolean\n **/\n static function canUnrecursSpecif(CommonDBTM $item, $entities) {\n global $DB;", " // RELATION : computers -> items\n $iterator = $DB->request([\n 'SELECT' => [\n 'itemtype',\n new \\QueryExpression('GROUP_CONCAT(DISTINCT '.$DB->quoteName('items_id').') AS ids'),\n 'computers_id'\n ],\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'itemtype' => $item->getType(),\n 'items_id' => $item->fields['id']\n ],\n 'GROUP' => 'itemtype'\n ]);", " while ($data = $iterator->next()) {\n if (countElementsInTable(\"glpi_computers\",\n ['id' => $data[\"computers_id\"],\n 'NOT' => ['entities_id' => $entities]]) > 0) {\n return false;\n }\n }\n return true;\n }", "\n protected static function getListForItemParams(CommonDBTM $item, $noent = false) {\n $params = parent::getListForItemParams($item, $noent);\n $params['WHERE'][self::getTable() . '.is_deleted'] = 0;\n return $params;\n }", " /**\n * Get SELECT param for getTypeItemsQueryParams\n *\n * @param CommonDBTM $item\n *\n * @return array\n */\n public static function getTypeItemsQueryParams_Select(CommonDBTM $item): array {\n $table = static::getTable();\n $select = parent::getTypeItemsQueryParams_Select($item);\n $select[] = \"$table.is_dynamic AS {$table}_is_dynamic\";", " return $select;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access this file directly\");\n}", "class Dropdown {", " //Empty value displayed in a dropdown\n const EMPTY_VALUE = '-----';", " /**\n * Print out an HTML \"<select>\" for a dropdown with preselected value\n *\n * @param string $itemtype itemtype used for create dropdown\n * @param array $options array of possible options:\n * - name : string / name of the select (default is depending itemtype)\n * - value : integer / preselected value (default -1)\n * - comments : boolean / is the comments displayed near the dropdown (default true)\n * - toadd : array / array of specific values to add at the begining\n * - entity : integer or array / restrict to a defined entity or array of entities\n * (default -1 : no restriction)\n * - entity_sons : boolean / if entity restrict specified auto select its sons\n * only available if entity is a single value not an array\n * (default false)\n * - toupdate : array / Update a specific item on select change on dropdown\n * (need value_fieldname, to_update,\n * url (see Ajax::updateItemOnSelectEvent for information)\n * and may have moreparams)\n * - used : array / Already used items ID: not to display in dropdown\n * (default empty)\n * - on_change : string / value to transmit to \"onChange\"\n * - rand : integer / already computed rand value\n * - condition : array / aditional SQL condition to limit display\n * - displaywith : array / array of field to display with request\n * - emptylabel : Empty choice's label (default self::EMPTY_VALUE)\n * - display_emptychoice : Display emptychoice ? (default true)\n * - display : boolean / display or get string (default true)\n * - width : specific width needed (default auto adaptive)\n * - permit_select_parent : boolean / for tree dropdown permit to see parent items\n * not available by default (default false)\n * - specific_tags : array of HTML5 tags to add the the field\n * - url : url of the ajax php code which should return the json data to show in\n * the dropdown\n *\n * @return boolean : false if error and random id if OK\n *\n * @since 9.5.0 Usage of string in condition option is removed\n **/\n static function show($itemtype, $options = []) {\n global $CFG_GLPI;", " if ($itemtype && !($item = getItemForItemtype($itemtype))) {\n return false;\n }", " $table = $item->getTable();", " $params['name'] = $item->getForeignKeyField();\n $params['value'] = (($itemtype == 'Entity') ? $_SESSION['glpiactive_entity'] : '');\n $params['comments'] = true;\n $params['entity'] = -1;\n $params['entity_sons'] = false;\n $params['toupdate'] = '';\n $params['width'] = '';\n $params['used'] = [];\n $params['toadd'] = [];\n $params['on_change'] = '';\n $params['condition'] = [];\n $params['rand'] = mt_rand();\n $params['displaywith'] = [];\n //Parameters about choice 0\n //Empty choice's label\n $params['emptylabel'] = self::EMPTY_VALUE;\n //Display emptychoice ?\n $params['display_emptychoice'] = ($itemtype != 'Entity');\n $params['placeholder'] = '';\n $params['display'] = true;\n $params['permit_select_parent'] = false;\n $params['addicon'] = true;\n $params['specific_tags'] = [];\n $params['url'] = $CFG_GLPI['root_doc'].\"/ajax/getDropdownValue.php\";", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }\n $output = '';\n $name = $params['emptylabel'];\n $comment = \"\";", " // Check default value for dropdown : need to be a numeric (or null)\n if ($params['value'] !== null\n && ((strlen($params['value']) == 0) || !is_numeric($params['value']) && $params['value'] != 'mygroups')) {\n $params['value'] = 0;\n }", " if (isset($params['toadd'][$params['value']])) {\n $name = $params['toadd'][$params['value']];\n } else if (($params['value'] > 0)\n || (($itemtype == \"Entity\")\n && ($params['value'] >= 0))) {\n $tmpname = self::getDropdownName($table, $params['value'], 1);", " if ($tmpname[\"name\"] != \"&nbsp;\") {\n $name = $tmpname[\"name\"];\n $comment = $tmpname[\"comment\"];\n }\n }", " // Manage entity_sons\n if (!($params['entity'] < 0)\n && $params['entity_sons']) {\n if (is_array($params['entity'])) {\n // translation not needed - only for debug\n $output .= \"entity_sons options is not available with entity option as array\";\n } else {\n $params['entity'] = getSonsOf('glpi_entities', $params['entity']);\n }\n }", " $field_id = Html::cleanId(\"dropdown_\".$params['name'].$params['rand']);", " // Manage condition\n if (!empty($params['condition'])) {\n // Put condition in session and replace it by its key\n // This is made to prevent passing to many parameters when calling the ajax script\n $params['condition'] = static::addNewCondition($params['condition']);\n }", " if (!$item instanceof CommonTreeDropdown) {\n $name = Toolbox::unclean_cross_side_scripting_deep($name);\n }\n $p = ['value' => $params['value'],\n 'valuename' => $name,\n 'width' => $params['width'],\n 'itemtype' => $itemtype,\n 'display_emptychoice' => $params['display_emptychoice'],\n 'placeholder' => $params['placeholder'],\n 'displaywith' => $params['displaywith'],\n 'emptylabel' => $params['emptylabel'],\n 'condition' => $params['condition'],\n 'used' => $params['used'],\n 'toadd' => $params['toadd'],", " 'entity_restrict' => (is_array($params['entity']) ? json_encode(array_values($params['entity'])) : $params['entity']),", " 'on_change' => $params['on_change'],\n 'permit_select_parent' => $params['permit_select_parent'],\n 'specific_tags' => $params['specific_tags'],", " '_idor_token' => Session::getNewIDORToken($itemtype),", " ];", " $output = \"<span class='no-wrap'>\";\n $output.= Html::jsAjaxDropdown($params['name'], $field_id,\n $params['url'],\n $p);\n // Display comment\n if ($params['comments']) {\n $comment_id = Html::cleanId(\"comment_\".$params['name'].$params['rand']);\n $link_id = Html::cleanId(\"comment_link_\".$params['name'].$params['rand']);\n $kblink_id = Html::cleanId(\"kb_link_\".$params['name'].$params['rand']);\n $options_tooltip = ['contentid' => $comment_id,\n 'linkid' => $link_id,\n 'display' => false];", " if ($item->canView()) {\n if ($params['value']\n && $item->getFromDB($params['value'])\n && $item->canViewItem()) {\n $options_tooltip['link'] = $item->getLinkURL();\n } else {\n $options_tooltip['link'] = $item->getSearchURL();\n }\n }", " if (empty($comment)) {\n $comment = Toolbox::ucfirst(\n sprintf(\n __('Show %1$s'),\n $item::getTypeName(Session::getPluralNumber())\n )\n );\n }\n $output .= \"&nbsp;\".Html::showToolTip($comment, $options_tooltip);", " if (($item instanceof CommonDropdown)\n && $item->canCreate()\n && !isset($_REQUEST['_in_modal'])\n && $params['addicon']) {", " $output .= \"<span class='fa fa-plus-circle pointer' title=\\\"\".__s('Add').\"\\\"\n onClick=\\\"\".Html::jsGetElementbyID('add_'.$field_id).\".dialog('open');\\\"\n ><span class='sr-only'>\" . __s('Add') . \"</span></span>\";\n $output .= Ajax::createIframeModalWindow('add_'.$field_id,\n $item->getFormURL(),\n ['display' => false]);\n }", " // Display specific Links\n if ($itemtype == \"Supplier\") {\n if ($item->getFromDB($params['value'])) {\n $output .= $item->getLinks();\n }\n }", " if ($itemtype == 'Location') {\n $output .= \"<span class='fa fa-globe-americas pointer' title='\".__s('Display on map').\"' onclick='showMapForLocation(this)' data-fid='$field_id'></span>\";\n }", " $paramscomment = [\n 'value' => '__VALUE__',\n 'itemtype' => $itemtype,\n '_idor_token' => Session::getNewIDORToken($itemtype)\n ];\n if ($item->isField('knowbaseitemcategories_id')\n && Session::haveRight('knowbase', READ)) {", " if (method_exists($item, 'getLinks')) {\n $output .= \"<span id='$kblink_id'>\";\n $output .= '&nbsp;'.$item->getLinks();\n $output .= \"</span>\";\n $paramscomment['withlink'] = $kblink_id;\n $output .= Ajax::updateItemOnSelectEvent($field_id, $kblink_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/kblink.php\",\n $paramscomment, false);\n }\n }", " if ($item->canView()) {\n $paramscomment['withlink'] = $link_id;\n }", " $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/comments.php\",\n $paramscomment, false);\n }\n $output .= Ajax::commonDropdownUpdateItem($params, false);\n $output .= \"</span>\";\n if ($params['display']) {\n echo $output;\n return $params['rand'];\n }\n return $output;\n }", "\n /**\n * Add new condition\n *\n * @todo should not use session to pass query parameters...\n *\n * @param array $condition Condition to add\n *\n * @return string\n */\n static function addNewCondition(array $condition) {\n $sha1 = sha1(serialize($condition));\n $_SESSION['glpicondition'][$sha1] = $condition;\n return $sha1;\n }", " /**\n * Get the value of a dropdown\n *\n * Returns the value of the dropdown from $table with ID $id.\n *\n * @param string $table the dropdown table from witch we want values on the select\n * @param integer $id id of the element to get\n * @param boolean $withcomment give array with name and comment (default 0)\n * @param boolean $translate (true by default)\n * @param boolean $tooltip (true by default) returns a tooltip, else returns only 'comment'\n *\n * @return string the value of the dropdown or &nbsp; if not exists\n **/\n static function getDropdownName($table, $id, $withcomment = 0, $translate = true, $tooltip = true) {\n global $DB;", " $dft_retval = \"&nbsp;\";", " $item = getItemForItemtype(getItemTypeForTable($table));", " if (!is_object($item)) {\n return $dft_retval;\n }", " if ($item instanceof CommonTreeDropdown) {\n return getTreeValueCompleteName($table, $id, $withcomment, $translate, $tooltip);\n }", " $name = \"\";\n $comment = \"\";", " if ($id) {\n $SELECTNAME = new \\QueryExpression(\"'' AS \". $DB->quoteName('transname'));\n $SELECTCOMMENT = new \\QueryExpression(\"'' AS \" . $DB->quoteName('transcomment'));\n $JOIN = [];\n $JOINS = [];\n if ($translate) {\n if (Session::haveTranslations(getItemTypeForTable($table), 'name')) {\n $SELECTNAME = 'namet.value AS transname';\n $JOINS['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => getItemTypeForTable($table),\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => 'name'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations(getItemTypeForTable($table), 'comment')) {\n $SELECTCOMMENT = 'namec.value AS transcomment';\n $JOINS['glpi_dropdowntranslations AS namec'] = [\n 'ON' => [\n 'namec' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namec.itemtype' => getItemTypeForTable($table),\n 'namec.language' => $_SESSION['glpilanguage'],\n 'namec.field' => 'comment'\n ]\n ]\n ]\n ];\n }", " if (count($JOINS)) {\n $JOIN = ['LEFT JOIN' => $JOINS];\n }\n }", " $criteria = [\n 'SELECT' => [\n \"$table.*\",\n $SELECTNAME,\n $SELECTCOMMENT\n ],\n 'FROM' => $table,\n 'WHERE' => [\"$table.id\" => $id]\n ] + $JOIN;\n $iterator = $DB->request($criteria);", " /// TODO review comment management...\n /// TODO getDropdownName need to return only name\n /// When needed to use comment use class instead : getComments function\n /// GetName of class already give Name !!\n /// TODO CommonDBTM : review getComments to be recursive and add informations from class hierarchy\n /// getUserName have the same system : clean it too\n /// Need to study the problem\n if (count($iterator)) {\n $data = $iterator->next();\n if ($translate && !empty($data['transname'])) {\n $name = $data['transname'];\n } else {\n $name = $data[$item->getNameField()];\n }\n if (isset($data[\"comment\"])) {\n if ($translate && !empty($data['transcomment'])) {\n $comment = $data['transcomment'];\n } else {\n $comment = $data[\"comment\"];\n }\n }", " switch ($table) {\n case \"glpi_computers\" :\n if (empty($name)) {\n $name = \"($id)\";\n }\n break;", " case \"glpi_contacts\" :\n //TRANS: %1$s is the name, %2$s is the firstname\n $name = sprintf(__('%1$s %2$s'), $name, $data[\"firstname\"]);\n if ($tooltip) {\n if (!empty($data[\"phone\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".Phone::getTypeName(1),\n \"</span>\".$data['phone']);\n }\n if (!empty($data[\"phone2\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('Phone 2'),\n \"</span>\".$data['phone2']);\n }\n if (!empty($data[\"mobile\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('Mobile phone'),\n \"</span>\".$data['mobile']);\n }\n if (!empty($data[\"fax\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".__('Fax'),\n \"</span>\".$data['fax']);\n }\n if (!empty($data[\"email\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\"._n('Email', 'Emails', 1),\n \"</span>\".$data['email']);\n }\n }\n break;", " case \"glpi_suppliers\" :\n if ($tooltip) {\n if (!empty($data[\"phonenumber\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".Phone::getTypeName(1),\n \"</span>\".$data['phonenumber']);\n }\n if (!empty($data[\"fax\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".__('Fax'),\n \"</span>\".$data['fax']);\n }\n if (!empty($data[\"email\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\"._n('Email', 'Emails', 1),\n \"</span>\".$data['email']);\n }\n }\n break;", " case \"glpi_netpoints\" :\n $name = sprintf(__('%1$s (%2$s)'), $name,\n self::getDropdownName(\"glpi_locations\",\n $data[\"locations_id\"], false, $translate));\n break;", " case \"glpi_budgets\" :\n if ($tooltip) {\n if (!empty($data['locations_id'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".Location::getTypeName(1).\"</span>\",\n self::getDropdownName(\"glpi_locations\",\n $data[\"locations_id\"],\n false, $translate));", " }\n if (!empty($data['budgettypes_id'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\"._n('Type', 'Types', 1).\"</span>\",\n self::getDropdownName(\"glpi_budgettypes\",\n $data[\"budgettypes_id\"], false, $translate));", " }\n if (!empty($data['begin_date'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('Start date').\"</span>\",\n Html::convDateTime($data[\"begin_date\"]));", " }\n if (!empty($data['end_date'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('End date').\"</span>\",\n Html::convDateTime($data[\"end_date\"]));\n }\n }\n }\n }\n }", " if (empty($name)) {\n $name = $dft_retval;\n }", " if ($withcomment) {\n return [\n 'name' => $name,\n 'comment' => $comment\n ];\n }", " return $name;\n }", "\n /**\n * Get values of a dropdown for a list of item\n *\n * @param string $table the dropdown table from witch we want values on the select\n * @param integer[] $ids array containing the ids to get\n *\n * @return array containing the value of the dropdown or &nbsp; if not exists\n **/\n static function getDropdownArrayNames($table, $ids) {\n global $DB;", " $tabs = [];", " if (count($ids)) {\n $itemtype = getItemTypeForTable($table);\n if ($item = getItemForItemtype($itemtype)) {\n $field = 'name';\n if ($item instanceof CommonTreeDropdown) {\n $field = 'completename';\n }", " $iterator = $DB->request([\n 'SELECT' => ['id', $field],\n 'FROM' => $table,\n 'WHERE' => ['id' => $ids]\n ]);", " while ($data = $iterator->next()) {\n $tabs[$data['id']] = $data[$field];\n }\n }\n }\n return $tabs;\n }", "\n /**\n * Make a select box for device type\n *\n * @param string $name name of the select box\n * @param string[] $types array of types to display\n * @param array $options Parameters which could be used in options array :\n * - value : integer / preselected value (default '')\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - emptylabel : Empty choice's label (default self::EMPTY_VALUE)\n * - display : boolean if false get string\n * - width : specific width needed (default not set)\n * - emptylabel : empty label if empty displayed (default self::EMPTY_VALUE)\n * - display_emptychoice : display empty choice (default false)\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showItemTypes($name, $types = [], $options = []) {\n $params['value'] = '';\n $params['used'] = [];\n $params['emptylabel'] = self::EMPTY_VALUE;\n $params['display'] = true;\n $params['width'] = '80%';\n $params['display_emptychoice'] = true;\n $params['rand'] = mt_rand();", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " $values = [];\n if (count($types)) {\n foreach ($types as $type) {\n if ($item = getItemForItemtype($type)) {\n $values[$type] = $item->getTypeName(1);\n }\n }\n }\n asort($values);\n return self::showFromArray($name, $values,\n $params);\n }", "\n /**\n * Make a select box for device type\n *\n * @param string $name name of the select box\n * @param string $itemtype_ref itemtype reference where to search in itemtype field\n * @param array $options array of possible options:\n * - may be value (default value) / field (used field to search itemtype)\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function dropdownUsedItemTypes($name, $itemtype_ref, $options = []) {\n global $DB;", " $p['value'] = 0;\n $p['field'] = 'itemtype';", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " $iterator = $DB->request([\n 'SELECT' => $p['field'],\n 'DISTINCT' => true,\n 'FROM' => getTableForItemType($itemtype_ref)\n ]);", " $tabs = [];\n while ($data = $iterator->next()) {\n $tabs[$data[$p['field']]] = $data[$p['field']];\n }\n return self::showItemTypes($name, $tabs, ['value' => $p['value']]);\n }", "\n /**\n * Make a select box for icons\n *\n * @param string $myname the name of the HTML select\n * @param mixed $value the preselected value we want\n * @param string $store_path path where icons are stored\n * @param boolean $display display of get string ? (true by default)\n *\n *\n * @return void|string\n * void if param display=true\n * string if param display=false (HTML code)\n **/\n static function dropdownIcons($myname, $value, $store_path, $display = true) {", " $output = '';\n if (is_dir($store_path)) {\n if ($dh = opendir($store_path)) {\n $files = [];", " while (($file = readdir($dh)) !== false) {\n $files[] = $file;\n }", " closedir($dh);\n sort($files);", " foreach ($files as $file) {\n if (preg_match(\"/\\.png$/i\", $file)) {\n $values[$file] = $file;\n }\n }\n Dropdown::showFromArray($myname, $values,\n ['value' => $value,\n 'display_emptychoice' => true]);", " } else {\n //TRANS: %s is the store path\n printf(__('Error reading directory %s'), $store_path);\n }", " } else {\n //TRANS: %s is the store path\n printf(__('Error: %s is not a directory'), $store_path);\n }\n if ($display) {\n echo $output;\n } else {\n return $output;\n }\n }", "\n /**\n * Dropdown for GMT selection\n *\n * @param string $name select name\n * @param mixed $value default value (default '')\n **/\n static function showGMT($name, $value = '') {", " $elements = [-12, -11, -10, -9, -8, -7, -6, -5, -4, -3.5, -3, -2, -1, 0,\n '+1', '+2', '+3', '+3.5', '+4', '+4.5', '+5', '+5.5', '+6', '+6.5', '+7',\n '+8', '+9', '+9.5', '+10', '+11', '+12', '+13'];", " $values = [];\n foreach ($elements as $element) {\n if ($element != 0) {\n $values[$element*HOUR_TIMESTAMP] = sprintf(__('%1$s %2$s'), __('GMT'),\n sprintf(_n('%s hour', '%s hours', $element),\n $element));\n } else {\n $display_value = __('GMT');\n $values[$element*HOUR_TIMESTAMP] = __('GMT');\n }\n }\n Dropdown::showFromArray($name, $values, ['value' => $value]);\n }", "\n /**\n * Make a select box for a boolean choice (Yes/No) or display a checkbox. Add a\n * 'use_checkbox' = true to the $params array to display a checkbox instead a select box\n *\n * @param string $name select name\n * @param mixed $value preselected value. (default 0)\n * @param integer $restrict_to allows to display only yes or no in the dropdown (default -1)\n * @param array $params Array of optional options (passed to showFromArray)\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showYesNo($name, $value = 0, $restrict_to = -1, $params = []) {", " if (!array_key_exists ('use_checkbox', $params)) {\n // TODO: switch to true when Html::showCheckbox() is validated\n $params['use_checkbox'] = false;\n }\n if ($params['use_checkbox']) {", " if (!empty($params['rand'])) {\n $rand = $params['rand'];\n } else {\n $rand = mt_rand();\n }", " $options = ['name' => $name,\n 'id' => Html::cleanId(\"dropdown_\".$name.$rand)];", " switch ($restrict_to) {\n case 0 :\n $options['checked'] = false;\n $options['readonly'] = true;\n break;", " case 1 :\n $options['checked'] = true;\n $options['readonly'] = true;\n break;", " default :\n $options['checked'] = ($value ? 1 : 0);\n $options['readonly'] = false;\n break;\n }", " $output = Html::getCheckbox($options);\n if (!isset($params['display']) || $params['display'] == 'true') {\n echo $output;\n return $rand;\n } else {\n return $output;\n }\n }", " if ($restrict_to != 0) {\n $options[0] = __('No');\n }", " if ($restrict_to != 1) {\n $options[1] = __('Yes');\n }", " $params['value'] = $value;\n $params['width'] = \"65px\";\n return self::showFromArray($name, $options, $params);\n }", "\n /**\n * Get Yes No string\n *\n * @param mixed $value Yes No value\n *\n * @return string\n **/\n static function getYesNo($value) {", " if ($value) {\n return __('Yes');\n }\n return __('No');\n }", "\n /**\n * Get the Device list name the user is allowed to edit\n *\n * @return array (group of dropdown) of array (itemtype => localized name)\n **/\n static function getDeviceItemTypes() {\n static $optgroup = null;", " if (!Session::haveRight('device', READ)) {\n return [];\n }", " if (is_null($optgroup)) {\n $devices = [];\n foreach (CommonDevice::getDeviceTypes() as $device_type) {\n $devices[$device_type] = $device_type::getTypeName(Session::getPluralNumber());\n }\n asort($devices);\n $optgroup = [_n('Component', 'Components', Session::getPluralNumber()) => $devices];\n }\n return $optgroup;\n }", "\n /**\n * Get the dropdown list name the user is allowed to edit\n *\n * @return array (group of dropdown) of array (itemtype => localized name)\n **/\n static function getStandardDropdownItemTypes() {\n static $optgroup = null;", " if (is_null($optgroup)) {\n $optgroup = [\n __('Common') => [\n 'Location' => null,\n 'State' => null,\n 'Manufacturer' => null,\n 'Blacklist' => null,\n 'BlacklistedMailContent' => null\n ],", " __('Assistance') => [\n 'ITILCategory' => null,\n 'TaskCategory' => null,\n 'TaskTemplate' => null,\n 'SolutionType' => null,\n 'SolutionTemplate' => null,\n 'RequestType' => null,\n 'ITILFollowupTemplate' => null,\n 'ProjectState' => null,\n 'ProjectType' => null,\n 'ProjectTaskType' => null,\n 'ProjectTaskTemplate' => null,\n 'PlanningExternalEventTemplate' => null,\n 'PlanningEventCategory' => null,\n ],", " _n('Type', 'Types', Session::getPluralNumber()) => [\n 'ComputerType' => null,\n 'NetworkEquipmentType' => null,\n 'PrinterType' => null,\n 'MonitorType' => null,\n 'PeripheralType' => null,\n 'PhoneType' => null,\n 'SoftwareLicenseType' => null,\n 'CartridgeItemType' => null,\n 'ConsumableItemType' => null,\n 'ContractType' => null,\n 'ContactType' => null,\n 'DeviceGenericType' => null,\n 'DeviceSensorType' => null,\n 'DeviceMemoryType' => null,\n 'SupplierType' => null,\n 'InterfaceType' => null,\n 'DeviceCaseType' => null,\n 'PhonePowerSupply' => null,\n 'Filesystem' => null,\n 'CertificateType' => null,\n 'BudgetType' => null,\n 'DeviceSimcardType' => null,\n 'LineType' => null,\n 'RackType' => null,\n 'PDUType' => null,\n 'PassiveDCEquipmentType' => null,\n 'ClusterType' => null,\n ],", " _n('Model', 'Models', 1) => [\n 'ComputerModel' => null,\n 'NetworkEquipmentModel' => null,\n 'PrinterModel' => null,\n 'MonitorModel' => null,\n 'PeripheralModel' => null,\n 'PhoneModel' => null,", " // Devices models :\n 'DeviceCaseModel' => null,\n 'DeviceControlModel' => null,\n 'DeviceDriveModel' => null,\n 'DeviceGenericModel' => null,\n 'DeviceGraphicCardModel' => null,\n 'DeviceHardDriveModel' => null,\n 'DeviceMemoryModel' => null,\n 'DeviceMotherBoardModel' => null,\n 'DeviceNetworkCardModel' => null,\n 'DevicePciModel' => null,\n 'DevicePowerSupplyModel' => null,\n 'DeviceProcessorModel' => null,\n 'DeviceSoundCardModel' => null,\n 'DeviceSensorModel' => null,\n 'RackModel' => null,\n 'EnclosureModel' => null,\n 'PDUModel' => null,\n 'PassiveDCEquipmentModel' => null,\n ],", " _n('Virtual machine', 'Virtual machines', Session::getPluralNumber()) => [\n 'VirtualMachineType' => null,\n 'VirtualMachineSystem' => null,\n 'VirtualMachineState' => null\n ],", " __('Management') => [\n 'DocumentCategory' => null,\n 'DocumentType' => null,\n 'BusinessCriticity' => null\n ],", " __('Tools') => [\n 'KnowbaseItemCategory' => null\n ],", " _n('Calendar', 'Calendars', 1) => [\n 'Calendar' => null,\n 'Holiday' => null\n ],", " OperatingSystem::getTypeName(Session::getPluralNumber()) => [\n 'OperatingSystem' => null,\n 'OperatingSystemVersion' => null,\n 'OperatingSystemServicePack' => null,\n 'OperatingSystemArchitecture' => null,\n 'OperatingSystemEdition' => null,\n 'OperatingSystemKernel' => null,\n 'OperatingSystemKernelVersion' => null,\n 'AutoUpdateSystem' => null\n ],", " __('Networking') => [\n 'NetworkInterface' => null,\n 'Netpoint' => null,\n 'Network' => null,\n 'Vlan' => null,\n 'LineOperator' => null,\n 'DomainType' => null,\n 'DomainRelation' => null,\n 'DomainRecordType' => null\n ],", " __('Internet') => [\n 'IPNetwork' => null,\n 'FQDN' => null,\n 'WifiNetwork' => null,\n 'NetworkName' => null\n ],", " _n('Software', 'Software', 1) => [\n 'SoftwareCategory' => null\n ],", " User::getTypeName(1) => [\n 'UserTitle' => null,\n 'UserCategory' => null\n ],", " __('Authorizations assignment rules') => [\n 'RuleRightParameter' => null\n ],", " __('Fields unicity') => [\n 'Fieldblacklist' => null\n ],", " __('External authentications') => [\n 'SsoVariable' => null\n ],\n __('Power management') => [\n 'Plug' => null\n ],\n __('Appliances') => [\n 'ApplianceType' => null,\n 'ApplianceEnvironment' => null\n ]", " ]; //end $opt", " $plugdrop = Plugin::getDropdowns();", " if (count($plugdrop)) {\n $optgroup = array_merge($optgroup, $plugdrop);\n }", " foreach ($optgroup as $label => &$dp) {\n foreach ($dp as $key => &$val) {\n if ($tmp = getItemForItemtype($key)) {\n if (!$tmp->canView()) {\n unset($optgroup[$label][$key]);\n } else if ($val === null) {\n $val = $key::getTypeName(Session::getPluralNumber());\n }\n } else {\n unset($optgroup[$label][$key]);\n }\n }", " if (count($optgroup[$label]) == 0) {\n unset($optgroup[$label]);\n }\n }\n }\n return $optgroup;\n }", "\n /**\n * Display a menu to select a itemtype which open the search form\n *\n * @param $title string title to display\n * @param $optgroup array (group of dropdown) of array (itemtype => localized name)\n * @param $value string URL of selected current value (default '')\n **/\n static function showItemTypeMenu($title, $optgroup, $value = '') {", " echo \"<table class='tab_cadre' width='50%'>\";\n echo \"<tr class='tab_bg_1'><td class='b'>&nbsp;\".$title.\"&nbsp; \";\n $selected = '';", " foreach ($optgroup as $label => $dp) {\n foreach ($dp as $key => $val) {\n $search = $key::getSearchURL();", " if (basename($search) == basename($value)) {\n $selected = $search;\n }\n $values[$label][$search] = $val;\n }\n }\n Dropdown::showFromArray('dpmenu', $values,\n ['on_change'\n => \"var _value = this.options[this.selectedIndex].value; if (_value != 0) {window.location.href=_value;}\",\n 'value' => $selected,\n 'display_emptychoice' => true]);", " echo \"</td></tr>\";\n echo \"</table><br>\";\n }", "\n /**\n * Display a list to select a itemtype with link to search form\n *\n * @param $optgroup array (group of dropdown) of array (itemtype => localized name)\n */\n static function showItemTypeList($optgroup) {", " echo \"<div id='list_nav'>\";\n $nb = 0;\n foreach ($optgroup as $label => $dp) {\n $nb += count($dp);\n }\n $step = ($nb > 15 ? ($nb/3) : $nb);\n echo \"<table class='tab_glpi'><tr class='top'><td width='33%' class='center'>\";\n echo \"<table class='tab_cadre'>\";\n $i = 1;", " foreach ($optgroup as $label => $dp) {\n echo \"<tr><th>$label</th></tr>\\n\";", " foreach ($dp as $key => $val) {\n $class=\"class='tab_bg_4'\";\n if (($itemtype = getItemForItemtype($key))\n && $itemtype->isEntityAssign()) {\n $class=\"class='tab_bg_2'\";\n }\n echo \"<tr $class><td><a href='\".$key::getSearchURL().\"'>\";\n echo \"$val</a></td></tr>\\n\";\n $i++;\n }", " if (($i >= $step) && ($i < $nb)) {\n echo \"</table></td><td width='25'>&nbsp;</td><td><table class='tab_cadre'>\";\n $step += $step;\n }\n }\n echo \"</table></td></tr></table></div>\";\n }", "\n /**\n * Dropdown available languages\n *\n * @param string $myname select name\n * @param array $options array of additionnal options:\n * - display_emptychoice : allow selection of no language\n * - emptylabel : specific string to empty label if display_emptychoice is true\n **/\n static function showLanguages($myname, $options = []) {\n $values = [];\n if (isset($options['display_emptychoice']) && ($options['display_emptychoice'])) {\n if (isset($options['emptylabel'])) {\n $values[''] = $options['emptylabel'];\n } else {\n $values[''] = self::EMPTY_VALUE;\n }\n unset($options['display_emptychoice']);\n }", " $values = array_merge($values, self::getLanguages());\n return self::showFromArray($myname, $values, $options);\n }", " /**\n * Get available languages\n *\n * @since 9.5.0\n *\n * @return array\n */\n public static function getLanguages() {\n global $CFG_GLPI;", " $languages = [];\n foreach ($CFG_GLPI[\"languages\"] as $key => $val) {\n if (isset($val[1]) && is_file(GLPI_ROOT .\"/locales/\".$val[1])) {\n $languages[$key] = $val[0];\n }\n }", " return $languages;\n }", "\n /**\n * @since 0.84\n *\n * @param $value\n **/\n static function getLanguageName($value) {\n global $CFG_GLPI;", " if (isset($CFG_GLPI[\"languages\"][$value][0])) {\n return $CFG_GLPI[\"languages\"][$value][0];\n }\n return $value;\n }", "\n /**\n * Print a select with hours\n *\n * Print a select named $name with hours options and selected value $value\n *\n *@param $name string HTML select name\n *@param $options array of options :\n * - value default value (default '')\n * - limit_planning limit planning to the configuration range (default false)\n * - display boolean if false get string\n * - width specific width needed (default auto adaptive)\n * - step step time (defaut config GLPI)\n *\n * @since 0.85 update prototype\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showHours($name, $options = []) {\n global $CFG_GLPI;", " $p['value'] = '';\n $p['limit_planning'] = false;\n $p['display'] = true;\n $p['width'] = '';\n $p['step'] = $CFG_GLPI[\"time_step\"];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " $begin = 0;\n $end = 24;\n // Check if the $step is Ok for the $value field\n $split = explode(\":\", $p['value']);", " // Valid value XX:YY ou XX:YY:ZZ\n if ((count($split) == 2) || (count($split) == 3)) {\n $min = $split[1];", " // Problem\n if (($min%$p['step']) != 0) {\n // set minimum step\n $p['step'] = 5;\n }\n }", " if ($p['limit_planning']) {\n $plan_begin = explode(\":\", $CFG_GLPI[\"planning_begin\"]);\n $plan_end = explode(\":\", $CFG_GLPI[\"planning_end\"]);\n $begin = (int) $plan_begin[0];\n $end = (int) $plan_end[0];\n }", " $values = [];\n $selected = '';", " for ($i=$begin; $i<$end; $i++) {\n if ($i < 10) {\n $tmp = \"0\".$i;\n } else {\n $tmp = $i;\n }", " for ($j=0; $j<60; $j+=$p['step']) {\n if ($j < 10) {\n $val = $tmp.\":0$j\";\n } else {\n $val = $tmp.\":$j\";\n }\n $values[$val] = $val;\n if (($p['value'] == $val.\":00\") || ($p['value'] == $val)) {\n $selected = $val;\n }\n }\n }\n // Last item\n $val = $end.\":00\";\n $values[$val] = $val;\n if (($p['value'] == $val.\":00\") || ($p['value'] == $val)) {\n $selected = $val;\n }\n $p['value'] = $selected;\n return Dropdown::showFromArray($name, $values, $p);\n }", "\n /**\n * show a dropdown to selec a type\n *\n * @since 0.83\n *\n * @param array|string $types Types used (default \"state_types\") (default '')\n * @param array $options Array of optional options\n * name, value, rand, emptylabel, display_emptychoice, on_change, plural, checkright\n * - toupdate : array / Update a specific item on select change on dropdown\n * (need value_fieldname, to_update,\n * url (see Ajax::updateItemOnSelectEvent for information)\n * and may have moreparams)\n *\n * @return integer rand for select id\n **/\n static function showItemType($types = '', $options = []) {\n global $CFG_GLPI;", " $params['name'] = 'itemtype';\n $params['value'] = '';\n $params['rand'] = mt_rand();\n $params['on_change'] = '';\n $params['plural'] = false;\n //Parameters about choice 0\n //Empty choice's label\n $params['emptylabel'] = self::EMPTY_VALUE;\n //Display emptychoice ?\n $params['display_emptychoice'] = true;\n $params['checkright'] = false;\n $params['toupdate'] = '';\n $params['display'] = true;", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " if (!is_array($types)) {\n $types = $CFG_GLPI[\"state_types\"];\n }\n $options = [];", " foreach ($types as $type) {\n if ($item = getItemForItemtype($type)) {\n if ($params['checkright'] && !$item->canView()) {\n continue;\n }\n $options[$type] = $item->getTypeName($params['plural'] ? 2 : 1);\n }\n }\n asort($options);", " if (count($options)) {\n return Dropdown::showFromArray($params['name'], $options, [\n 'value' => $params['value'],\n 'on_change' => $params['on_change'],\n 'toupdate' => $params['toupdate'],\n 'display_emptychoice' => $params['display_emptychoice'],\n 'emptylabel' => $params['emptylabel'],\n 'display' => $params['display'],\n 'rand' => $params['rand'],\n ]);\n }\n return 0;\n }", "\n /**\n * Make a select box for all items\n *\n * @since 0.85\n *\n * @param $options array:\n * - itemtype_name : the name of the field containing the itemtype (default 'itemtype')\n * - items_id_name : the name of the field containing the id of the selected item\n * (default 'items_id')\n * - itemtypes : all possible types to search for (default: $CFG_GLPI[\"state_types\"])\n * - default_itemtype : the default itemtype to select (don't define if you don't\n * need a default) (defaut 0)\n * - entity_restrict : restrict entity in searching items (default -1)\n * - onlyglobal : don't match item that don't have `is_global` == 1 (false by default)\n * - checkright : check to see if we can \"view\" the itemtype (false by default)\n * - showItemSpecificity : given an item, the AJAX file to open if there is special\n * treatment. For instance, select a Item_Device* for CommonDevice\n * - emptylabel : Empty choice's label (default self::EMPTY_VALUE)\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - display : true : display directly, false return the html\n *\n * @return integer randomized value used to generate HTML IDs\n **/\n static function showSelectItemFromItemtypes(array $options = []) {\n global $CFG_GLPI;", " $params = [];\n $params['itemtype_name'] = 'itemtype';\n $params['items_id_name'] = 'items_id';\n $params['itemtypes'] = '';\n $params['default_itemtype'] = 0;\n $params['entity_restrict'] = -1;\n $params['onlyglobal'] = false;\n $params['checkright'] = false;\n $params['showItemSpecificity'] = '';\n $params['emptylabel'] = self::EMPTY_VALUE;\n $params['used'] = [];\n $params['display'] = true;\n $params['rand'] = mt_rand();", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " $select = self::showItemType($params['itemtypes'], [\n 'checkright' => $params['checkright'],\n 'name' => $params['itemtype_name'],\n 'emptylabel' => $params['emptylabel'],\n 'display' => $params['display'],\n 'rand' => $params['rand'],\n ]);", " $p_ajax = [\n 'idtable' => '__VALUE__',\n 'name' => $params['items_id_name'],\n 'entity_restrict' => $params['entity_restrict'],\n 'showItemSpecificity' => $params['showItemSpecificity'],\n 'rand' => $params['rand']\n ];", " // manage condition\n if ($params['onlyglobal']) {\n $p_ajax['condition'] = static::addNewCondition(['is_global' => 1]);\n }\n if ($params['used']) {\n $p_ajax['used'] = $params['used'];\n }", " $field_id = Html::cleanId(\"dropdown_\".$params['itemtype_name'].$params['rand']);\n $show_id = Html::cleanId(\"show_\".$params['items_id_name'].$params['rand']);", " $ajax = Ajax::updateItemOnSelectEvent(\n $field_id,\n $show_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/dropdownAllItems.php\",\n $p_ajax,\n $params['display']\n );", " $out = \"\";\n if (!$params['display']) {\n $out.= $select.$ajax;\n }", " $out.= \"<br><span id='$show_id'>&nbsp;</span>\\n\";", " // We check $options as the caller will set $options['default_itemtype'] only if it needs a\n // default itemtype and the default value can be '' thus empty won't be valid !\n if (array_key_exists ('default_itemtype', $options)) {\n $out.= \"<script type='text/javascript' >\\n\";\n $out.= \"$(function() {\";\n $out.= Html::jsSetDropdownValue($field_id, $params['default_itemtype']);\n $out.= \"});</script>\\n\";", " $p_ajax[\"idtable\"] = $params['default_itemtype'];\n $ajax2 = Ajax::updateItem(\n $show_id,\n $CFG_GLPI[\"root_doc\"]. \"/ajax/dropdownAllItems.php\",\n $p_ajax,\n \"\",\n $params['display']\n );", " if (!$params['display']) {\n $out.= $ajax2;\n }\n }", " if ($params['display']) {\n echo $out;\n return $params['rand'];\n }", " return $out;\n }", "\n /**\n * Dropdown numbers\n *\n * @since 0.84\n *\n * @param string $myname select name\n * @param array $options array of additionnal options :\n * - value default value (default 0)\n * - rand random value\n * - min min value (default 0)\n * - max max value (default 100)\n * - step step used (default 1)\n * - toadd array of values to add at the beginning\n * - unit string unit to used\n * - display boolean if false get string\n * - width specific width needed (default 80%)\n * - on_change string / value to transmit to \"onChange\"\n * - used array / Already used items ID: not to display in dropdown (default empty)\n **/\n static function showNumber($myname, $options = []) {\n global $CFG_GLPI;", " $p = [\n 'value' => 0,\n 'rand' => mt_rand(),\n 'min' => 0,\n 'max' => 100,\n 'step' => 1,\n 'toadd' => [],\n 'unit' => '',\n 'display' => true,\n 'width' => '',\n 'on_change' => '',\n 'used' => [],\n 'specific_tags' => [],\n ];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }\n if (($p['value'] < $p['min']) && !isset($p['toadd'][$p['value']])) {\n $min = $p['min'];", " while (isset($p['used'][$min])) {\n ++$min;\n }\n $p['value'] = $min;\n }", " $field_id = Html::cleanId(\"dropdown_\".$myname.$p['rand']);\n if (!isset($p['toadd'][$p['value']])) {\n $valuename = self::getValueWithUnit($p['value'], $p['unit']);\n } else {\n $valuename = $p['toadd'][$p['value']];\n }\n $param = ['value' => $p['value'],\n 'valuename' => $valuename,\n 'width' => $p['width'],\n 'on_change' => $p['on_change'],\n 'used' => $p['used'],\n 'unit' => $p['unit'],\n 'min' => $p['min'],\n 'max' => $p['max'],\n 'step' => $p['step'],\n 'toadd' => $p['toadd'],\n 'specific_tags' => $p['specific_tags']];", " $out = Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownNumber.php\",\n $param);", " if ($p['display']) {\n echo $out;\n return $p['rand'];\n }\n return $out;\n }", "\n /**\n * Get value with unit / Automatic management of standar unit (year, month, %, ...)\n *\n * @since 0.84\n *\n * @param $value integer number of item\n * @param $unit string of unit (maybe year, month, day, hour, % for standard management)\n **/\n static function getValueWithUnit($value, $unit) {", " if (strlen($unit) == 0) {\n return $value;\n }", " switch ($unit) {\n case 'year' :\n //TRANS: %d is a number of years\n return sprintf(_n('%d year', '%d years', $value), $value);", " case 'month' :\n //TRANS: %d is a number of months\n return sprintf(_n('%d month', '%d months', $value), $value);", " case 'day' :\n //TRANS: %d is a number of days\n return sprintf(_n('%d day', '%d days', $value), $value);", " case 'hour' :\n //TRANS: %d is a number of hours\n return sprintf(_n('%d hour', '%d hours', $value), $value);", " case 'minute' :\n //TRANS: %d is a number of minutes\n return sprintf(_n('%d minute', '%d minutes', $value), $value);", " case 'second' :\n //TRANS: %d is a number of seconds\n return sprintf(_n('%d second', '%d seconds', $value), $value);", " case 'millisecond' :\n //TRANS: %d is a number of milliseconds\n return sprintf(_n('%d millisecond', '%d milliseconds', $value), $value);", " case 'auto':\n $value = str_replace([' ', '&nbsp;'], ['', ''], $value); // unformat value\n return Toolbox::getSize($value*1024*1024);", " case '%' :\n return sprintf(__('%d%%'), $value);", " default :\n return sprintf(__('%1$s %2$s'), $value, $unit);\n }\n }", "\n /**\n * Dropdown integers\n *\n * @since 0.83\n *\n * @param string $myname select name\n * @param array $options array of options\n * - value : default value\n * - min : min value : default 0\n * - max : max value : default DAY_TIMESTAMP\n * - value : default value\n * - addfirstminutes : add first minutes before first step (default false)\n * - toadd : array of values to add\n * - inhours : only show timestamp in hours not in days\n * - display : boolean / display or return string\n * - width : string / display width of the item\n **/\n static function showTimeStamp($myname, $options = []) {\n global $CFG_GLPI;", " $params['value'] = 0;\n $params['rand'] = mt_rand();\n $params['min'] = 0;\n $params['max'] = DAY_TIMESTAMP;\n $params['step'] = $CFG_GLPI[\"time_step\"]*MINUTE_TIMESTAMP;\n $params['emptylabel'] = self::EMPTY_VALUE;\n $params['addfirstminutes'] = false;\n $params['toadd'] = [];\n $params['inhours'] = false;\n $params['display'] = true;\n $params['display_emptychoice'] = true;\n $params['width'] = '80%';", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " // Manage min :\n $params['min'] = floor($params['min']/$params['step'])*$params['step'];", " if ($params['min'] == 0) {\n $params['min'] = $params['step'];\n }", " $params['max'] = max($params['value'], $params['max']);", " // Floor with MINUTE_TIMESTAMP for rounded purpose\n if (empty($params['value'])) {\n $params['value'] = 0;\n }\n if (($params['value'] < max($params['min'], 10*MINUTE_TIMESTAMP))\n && $params['addfirstminutes']) {\n $params['value'] = floor(($params['value'])/MINUTE_TIMESTAMP)*MINUTE_TIMESTAMP;\n } else if (!in_array($params['value'], $params['toadd'])) {\n // Round to a valid step except if value is already valid (defined in values to add)\n $params['value'] = floor(($params['value'])/$params['step'])*$params['step'];\n }", " $values = [];", " if ($params['value']) {\n $values[$params['value']] = '';\n }", " if ($params['addfirstminutes']) {\n $max = max($params['min'], 10*MINUTE_TIMESTAMP);\n for ($i=MINUTE_TIMESTAMP; $i < $max; $i+=MINUTE_TIMESTAMP) {\n $values[$i] = '';\n }\n }", " for ($i = $params['min']; $i <= $params['max']; $i+=$params['step']) {\n $values[$i] = '';\n }", " if (count($params['toadd'])) {\n foreach ($params['toadd'] as $key) {\n $values[$key] = '';\n }\n ksort($values);\n }", " foreach ($values as $i => $val) {\n if (empty($val)) {\n if ($params['inhours']) {\n $day = 0;\n $hour = floor($i/HOUR_TIMESTAMP);\n } else {\n $day = floor($i/DAY_TIMESTAMP);\n $hour = floor(($i%DAY_TIMESTAMP)/HOUR_TIMESTAMP);\n }\n $minute = floor(($i%HOUR_TIMESTAMP)/MINUTE_TIMESTAMP);\n if ($minute === '0') {\n $minute = '00';\n }\n $values[$i] = '';\n if ($day > 0) {\n if (($hour > 0) || ($minute > 0)) {\n if ($minute < 10) {\n $minute = '0'.$minute;\n }", " //TRANS: %1$d is the number of days, %2$d the number of hours,\n // %3$s the number of minutes : display 1 day 3h15\n $values[$i] = sprintf(_n('%1$d day %2$dh%3$s', '%1$d days %2$dh%3$s', $day),\n $day, $hour, $minute);\n } else {\n $values[$i] = sprintf(_n('%d day', '%d days', $day), $day);\n }", " } else if ($hour > 0 || $minute > 0) {\n if ($minute < 10) {\n $minute = '0'.$minute;\n }", " //TRANS: %1$d the number of hours, %2$s the number of minutes : display 3h15\n $values[$i] = sprintf(__('%1$dh%2$s'), $hour, $minute);\n }\n }\n }\n return Dropdown::showFromArray($myname, $values,\n ['value' => $params['value'],\n 'display' => $params['display'],\n 'width' => $params['width'],\n 'display_emptychoice' => $params['display_emptychoice'],\n 'rand' => $params['rand'],\n 'emptylabel' => $params['emptylabel']]);\n }", "\n /**\n * Toggle view in LDAP user import/synchro between no restriction and date restriction\n *\n * @param $enabled (default 0)\n **/\n static function showAdvanceDateRestrictionSwitch($enabled = 0) {\n global $CFG_GLPI;", " $rand = mt_rand();\n $url = $CFG_GLPI[\"root_doc\"].\"/ajax/ldapdaterestriction.php\";\n echo \"<script type='text/javascript' >\\n\";\n echo \"function activateRestriction() {\\n\";\n $params = ['enabled'=> 1];\n Ajax::updateItemJsCode('date_restriction', $url, $params);\n echo \"};\";", " echo \"function deactivateRestriction() {\\n\";\n $params = ['enabled' => 0];\n Ajax::updateItemJsCode('date_restriction', $url, $params);\n echo \"};\";\n echo \"</script>\";", " echo \"</table>\";\n echo \"<span id='date_restriction'>\";\n $_POST['enabled'] = $enabled;\n include (GLPI_ROOT.\"/ajax/ldapdaterestriction.php\");\n echo \"</span>\\n\";\n return $rand;\n }", "\n /**\n * Dropdown of values in an array\n *\n * @param string $name select name\n * @param array $elements array of elements to display\n * @param array $options array of possible options:\n * - value : integer / preselected value (default 0)\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - readonly : boolean / used as a readonly item (default false)\n * - on_change : string / value to transmit to \"onChange\"\n * - multiple : boolean / can select several values (default false)\n * - size : integer / number of rows for the select (default = 1)\n * - display : boolean / display or return string\n * - other : boolean or string if not false, then we can use an \"other\" value\n * if it is a string, then the default value will be this string\n * - rand : specific rand if needed (default is generated one)\n * - width : specific width needed (default not set)\n * - emptylabel : empty label if empty displayed (default self::EMPTY_VALUE)\n * - display_emptychoice : display empty choice, cannot be used when \"multiple\" option set to true (default false)\n * - class : class attributes to add\n * - tooltip : string / message to add as tooltip on the dropdown (default '')\n * - option_tooltips : array / message to add as tooltip on the dropdown options. Use the same keys as for the $elements parameter, but none is mandotary. Missing keys will just be ignored and no tooltip will be added. To add a tooltip on an option group, is the '__optgroup_label' key inside the array describing option tooltips : 'optgroupname1' => array('__optgroup_label' => 'tooltip for option group') (default empty)\n * - noselect2 : if true, don't use select2 lib\n *\n * Permit to use optgroup defining items in arrays\n * array('optgroupname' => array('key1' => 'val1',\n * 'key2' => 'val2'),\n * 'optgroupname2' => array('key3' => 'val3',\n * 'key4' => 'val4'))\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showFromArray($name, array $elements, $options = []) {", " $param['value'] = '';\n $param['values'] = [''];\n $param['class'] = '';\n $param['tooltip'] = '';\n $param['option_tooltips'] = [];\n $param['used'] = [];\n $param['readonly'] = false;\n $param['on_change'] = '';\n $param['width'] = '';\n $param['multiple'] = false;\n $param['size'] = 1;\n $param['display'] = true;\n $param['other'] = false;\n $param['rand'] = mt_rand();\n $param['emptylabel'] = self::EMPTY_VALUE;\n $param['display_emptychoice'] = false;\n $param['disabled'] = false;\n $param['noselect2'] = false;", " if (is_array($options) && count($options)) {\n if (isset($options['value']) && strlen($options['value'])) {\n $options['values'] = [$options['value']];\n unset($options['value']);\n }\n foreach ($options as $key => $val) {\n $param[$key] = $val;\n }\n }", " if ($param['other'] !== false) {\n $other_select_option = $name . '_other_value';\n $param['on_change'] .= \"displayOtherSelectOptions(this, \\\"$other_select_option\\\");\";", " // If $param['other'] is a string, then we must highlight \"other\" option\n if (is_string($param['other'])) {\n if (!$param[\"multiple\"]) {\n $param['values'] = [$other_select_option];\n } else {\n $param['values'][] = $other_select_option;\n }\n }\n }", " $param['option_tooltips'] = Html::entities_deep($param['option_tooltips']);", " if ($param[\"display_emptychoice\"] && !$param[\"multiple\"]) {\n $elements = [ 0 => $param['emptylabel'] ] + $elements;\n }", " if ($param[\"multiple\"]) {\n $field_name = $name.\"[]\";\n } else {\n $field_name = $name;\n }", " $output = '';\n // readonly mode\n $field_id = Html::cleanId(\"dropdown_\".$name.$param['rand']);\n if ($param['readonly']) {\n $to_display = [];\n foreach ($param['values'] as $value) {\n $output .= \"<input type='hidden' name='$field_name' value='$value'>\";\n if (isset($elements[$value])) {\n $to_display[] = $elements[$value];\n }\n }\n $output .= implode('<br>', $to_display);\n } else {", " $output .= \"<select name='$field_name' id='$field_id'\";", " if ($param['tooltip']) {\n $output .= ' title=\"'.Html::entities_deep($param['tooltip']).'\"';\n }", " if ($param['class']) {\n $output .= ' class=\"'.Html::entities_deep($param['class']).'\"';\n }", " if (!empty($param[\"on_change\"])) {\n $output .= \" onChange='\".$param[\"on_change\"].\"'\";\n }", " if ((is_int($param[\"size\"])) && ($param[\"size\"] > 0)) {\n $output .= \" size='\".$param[\"size\"].\"'\";\n }", " if ($param[\"multiple\"]) {\n $output .= \" multiple\";\n }", " if ($param[\"disabled\"]) {\n $output .= \" disabled='disabled'\";\n }", " $output .= '>';\n $max_option_size = 0;\n foreach ($elements as $key => $val) {\n // optgroup management\n if (is_array($val)) {\n $opt_goup = Html::entities_deep($key);\n if ($max_option_size < strlen($opt_goup)) {\n $max_option_size = strlen($opt_goup);\n }", " $output .= \"<optgroup label=\\\"$opt_goup\\\"\";\n $optgroup_tooltips = false;\n if (isset($param['option_tooltips'][$key])) {\n if (is_array($param['option_tooltips'][$key])) {\n if (isset($param['option_tooltips'][$key]['__optgroup_label'])) {\n $output .= ' title=\"'.$param['option_tooltips'][$key]['__optgroup_label'].'\"';\n }\n $optgroup_tooltips = $param['option_tooltips'][$key];\n } else {\n $output .= ' title=\"'.$param['option_tooltips'][$key].'\"';\n }\n }\n $output .= \">\";", " foreach ($val as $key2 => $val2) {\n if (!isset($param['used'][$key2])) {\n $output .= \"<option value='\".$key2.\"'\";\n // Do not use in_array : trouble with 0 and empty value\n foreach ($param['values'] as $value) {\n if (strcmp($key2, $value) === 0) {\n $output .= \" selected\";\n break;\n }\n }\n if ($optgroup_tooltips && isset($optgroup_tooltips[$key2])) {\n $output .= ' title=\"'.$optgroup_tooltips[$key2].'\"';\n }\n $output .= \">\" . $val2 . \"</option>\";\n if ($max_option_size < strlen($val2)) {\n $max_option_size = strlen($val2);\n }\n }\n }\n $output .= \"</optgroup>\";\n } else {\n if (!isset($param['used'][$key])) {\n $output .= \"<option value='\".Html::entities_deep($key).\"'\";\n // Do not use in_array : trouble with 0 and empty value\n foreach ($param['values'] as $value) {\n if (strcmp($key, $value)===0) {\n $output .= \" selected\";\n break;\n }\n }\n if (isset($param['option_tooltips'][$key])) {\n $output .= ' title=\"'.$param['option_tooltips'][$key].'\"';\n }\n $output .= \">\" .$val . \"</option>\";\n if ($max_option_size < strlen($val)) {\n $max_option_size = strlen($val);\n }\n }\n }\n }", " if ($param['other'] !== false) {\n $output .= \"<option value='$other_select_option'\";\n if (is_string($param['other'])) {\n $output .= \" selected\";\n }\n $output .= \">\".__('Other...').\"</option>\";\n }", " $output .= \"</select>\";\n if ($param['other'] !== false) {\n $output .= \"<input name='$other_select_option' id='$other_select_option' type='text'\";\n if (is_string($param['other'])) {\n $output .= \" value=\\\"\" . $param['other'] . \"\\\"\";\n } else {\n $output .= \" style=\\\"display: none\\\"\";\n }\n $output .= \">\";\n }\n }", " if (!$param['noselect2']) {\n // Width set on select\n $output .= Html::jsAdaptDropdown($field_id, ['width' => $param[\"width\"]]);\n }", " if ($param[\"multiple\"]) {\n // Hack for All / None because select2 does not provide it\n $select = __('All');\n $deselect = __('None');\n $output .= \"<div class='invisible' id='selectallbuttons_$field_id'>\";\n $output .= \"<div class='select2-actionable-menu'>\";\n $output .= \"<a class='vsubmit' \".\n \"onclick=\\\"selectAll('$field_id');$('#$field_id').select2('close');\\\">$select\".\n \"</a> \";\n $output .= \"<a class='vsubmit floatright' onclick=\\\"deselectAll('$field_id');\\\">$deselect\".\n \"</a>\";\n $output .= \"</div></div>\";", " $js = \"\n var multichecksappend$field_id = false;\n $('#$field_id').on('select2:open', function(e) {\n if (!multichecksappend$field_id) {\n $('#select2-$field_id-results').parent().append($('#selectallbuttons_$field_id').html());\n multichecksappend$field_id = true;\n }\n });\";\n $output .= Html::scriptBlock($js);\n }\n $output .= Ajax::commonDropdownUpdateItem($param, false);", " if ($param['display']) {\n echo $output;\n return $param['rand'];\n }\n return $output;\n }", "\n /**\n * Dropdown for global item management\n *\n * @param integer $ID item ID\n * @param array attrs array which contains the extra paramters\n *\n * Parameters can be :\n * - target target for actions\n * - withtemplate template or basic computer\n * - value value of global state\n * - management_restrict global management restrict mode\n **/\n static function showGlobalSwitch($ID, $attrs = []) {\n $params['management_restrict'] = 0;\n $params['value'] = 0;\n $params['name'] = 'is_global';\n $params['target'] = '';", " foreach ($attrs as $key => $value) {\n if ($value != '') {\n $params[$key] = $value;\n }\n }", " if ($params['value']\n && empty($params['withtemplate'])) {\n echo __('Global management');", " if ($params['management_restrict'] == 2) {\n echo \"&nbsp;\";\n Html::showSimpleForm($params['target'], 'unglobalize', __('Use unitary management'),\n ['id' => $ID], '', '',\n [__('Do you really want to use unitary management for this item?'),\n __('Duplicate the element as many times as there are connections')]);\n echo \"&nbsp;\";", " echo \"<span class='fa fa-info pointer'\".\n \" title=\\\"\".__s('Duplicate the element as many times as there are connections').\n \"\\\"><span class='sr-only'>\". __s('Duplicate the element as many times as there are connections') . \"</span></span>\";\n }", " } else {\n if ($params['management_restrict'] == 2) {\n $rand = mt_rand();\n $values = [MANAGEMENT_UNITARY => __('Unit management'),\n MANAGEMENT_GLOBAL => __('Global management')];\n Dropdown::showFromArray($params['name'], $values, ['value' => $params['value']]);\n } else {\n // Templates edition\n if (!empty($params['withtemplate'])) {\n echo \"<input type='hidden' name='is_global' value='\".\n $params['management_restrict'].\"'>\";\n echo (!$params['management_restrict']?__('Unit management') :__('Global management'));\n } else {\n echo (!$params['value']?__('Unit management'):__('Global management'));\n }\n }\n }\n }", "\n /**\n * Import a dropdown - check if already exists\n *\n * @param string $itemtype name of the class\n * @param array $input of value to import\n *\n * @return boolean|integer ID of the new item or false on error\n **/\n static function import($itemtype, $input) {", " if (!($item = getItemForItemtype($itemtype))) {\n return false;\n }\n return $item->import($input);\n }", "\n /**\n * Import a value in a dropdown table.\n *\n * This import a new dropdown if it doesn't exist - Play dictionnary if needed\n *\n * @param string $itemtype name of the class\n * @param string $value Value of the new dropdown.\n * @param integer $entities_id entity in case of specific dropdown\n * @param array $external_params\n * @param string $comment\n * @param boolean $add if true, add it if not found. if false, just check if exists\n *\n * @return integer : dropdown id.\n **/\n static function importExternal($itemtype, $value, $entities_id = -1, $external_params = [],\n $comment = '', $add = true) {", " if (!($item = getItemForItemtype($itemtype))) {\n return false;\n }\n return $item->importExternal($value, $entities_id, $external_params, $comment, $add);\n }", " /**\n * Get the label associated with a management type\n *\n * @param integer value the type of management (default 0)\n *\n * @return string the label corresponding to it, or \"\"\n **/\n static function getGlobalSwitch($value = 0) {", " switch ($value) {\n case 0 :\n return __('Unit management');", " case 1 :\n return __('Global management');", " default :\n return \"\";\n }\n }", "\n /**\n * show dropdown for output format\n *\n * @since 0.83\n **/\n static function showOutputFormat() {\n $values[Search::PDF_OUTPUT_LANDSCAPE] = __('Current page in landscape PDF');\n $values[Search::PDF_OUTPUT_PORTRAIT] = __('Current page in portrait PDF');\n $values[Search::SYLK_OUTPUT] = __('Current page in SLK');\n $values[Search::CSV_OUTPUT] = __('Current page in CSV');\n $values['-'.Search::PDF_OUTPUT_LANDSCAPE] = __('All pages in landscape PDF');\n $values['-'.Search::PDF_OUTPUT_PORTRAIT] = __('All pages in portrait PDF');\n $values['-'.Search::SYLK_OUTPUT] = __('All pages in SLK');\n $values['-'.Search::CSV_OUTPUT] = __('All pages in CSV');", " Dropdown::showFromArray('display_type', $values);\n echo \"<button type='submit' name='export' class='unstyled pointer' \".\n \" title=\\\"\" . _sx('button', 'Export') . \"\\\">\" .\n \"<i class='far fa-save'></i><span class='sr-only'>\"._sx('button', 'Export').\"<span>\";\n }", "\n /**\n * show dropdown to select list limit\n *\n * @since 0.83\n *\n * @param string $onchange Optional, for ajax (default '')\n **/\n static function showListLimit($onchange = '', $display = true) {\n global $CFG_GLPI;", " if (isset($_SESSION['glpilist_limit'])) {\n $list_limit = $_SESSION['glpilist_limit'];\n } else {\n $list_limit = $CFG_GLPI['list_limit'];\n }", " $values = [];", " for ($i=5; $i<20; $i+=5) {\n $values[$i] = $i;\n }\n for ($i=20; $i<50; $i+=10) {\n $values[$i] = $i;\n }\n for ($i=50; $i<250; $i+=50) {\n $values[$i] = $i;\n }\n for ($i=250; $i<1000; $i+=250) {\n $values[$i] = $i;\n }\n for ($i=1000; $i<5000; $i+=1000) {\n $values[$i] = $i;\n }\n for ($i=5000; $i<=10000; $i+=5000) {\n $values[$i] = $i;\n }\n $values[9999999] = 9999999;\n // Propose max input vars -10\n $max = Toolbox::get_max_input_vars();\n if ($max > 10) {\n $values[$max-10] = $max-10;\n }\n ksort($values);\n return self::showFromArray('glpilist_limit', $values,\n ['on_change' => $onchange,\n 'value' => $list_limit,\n 'display' => $display]);\n }", " /**\n * Get dropdown value\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownValue($post, $json = true) {\n global $DB, $CFG_GLPI;\n", "", " if (isset($post[\"entity_restrict\"])\n && !is_array($post[\"entity_restrict\"])\n && (substr($post[\"entity_restrict\"], 0, 1) === '[')\n && (substr($post[\"entity_restrict\"], -1) === ']')) {\n $decoded = Toolbox::jsonDecode($post['entity_restrict']);\n $entities = [];\n if (is_array($decoded)) {\n foreach ($decoded as $value) {\n $entities[] = (int)$value;\n }\n }\n $post[\"entity_restrict\"] = $entities;\n }\n if (isset($post['entity_restrict']) && 'default' === $post['entity_restrict']) {\n $post['entity_restrict'] = $_SESSION['glpiactiveentities'];", " }", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post)) {\n return;", " }", " // Security\n if (!($item = getItemForItemtype($post['itemtype']))) {\n return;\n }", " $table = $item->getTable();\n $datas = [];", " $displaywith = false;\n if (isset($post['displaywith'])) {\n if (is_array($post['displaywith']) && count($post['displaywith'])) {\n $table = getTableForItemType($post['itemtype']);\n foreach ($post['displaywith'] as $key => $value) {\n if (!$DB->fieldExists($table, $value)) {\n unset($post['displaywith'][$key]);\n }\n }\n if (count($post['displaywith'])) {\n $displaywith = true;\n }\n }\n }", " if (!isset($post['permit_select_parent'])) {\n $post['permit_select_parent'] = false;\n }", " if (isset($post['condition']) && !empty($post['condition']) && !is_array($post['condition'])) {\n // Retreive conditions from SESSION using its key\n $key = $post['condition'];\n if (isset($_SESSION['glpicondition']) && isset($_SESSION['glpicondition'][$key])) {\n $post['condition'] = $_SESSION['glpicondition'][$key];\n } else {\n $post['condition'] = [];\n }\n }", " if (!isset($post['emptylabel']) || ($post['emptylabel'] == '')) {\n $post['emptylabel'] = Dropdown::EMPTY_VALUE;\n }", " $where = [];", " if ($item->maybeDeleted()) {\n $where[\"$table.is_deleted\"] = 0;\n }\n if ($item->maybeTemplate()) {\n $where[\"$table.is_template\"] = 0;\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " if (isset($post['used'])) {\n $used = $post['used'];", " if (count($used)) {\n $where['NOT'] = [\"$table.id\" => $used];\n }\n }", " if (isset($post['toadd'])) {\n $toadd = $post['toadd'];\n } else {\n $toadd = [];\n }", " if (isset($post['condition']) && ($post['condition'] != '')) {\n $where = array_merge($where, $post['condition']);\n }", " $one_item = -1;\n if (isset($post['_one_id'])) {\n $one_item = $post['_one_id'];\n }", " // Count real items returned\n $count = 0;", " if ($item instanceof CommonTreeDropdown) {\n if ($one_item >= 0) {\n $where[\"$table.id\"] = $one_item;\n } else {\n if (!empty($post['searchText'])) {\n $search = Search::makeTextSearchValue($post['searchText']);", " $swhere = [\n \"$table.completename\" => ['LIKE', $search],\n ];\n if (Session::haveTranslations($post['itemtype'], 'completename')) {\n $swhere[\"namet.value\"] = ['LIKE', $search];\n }", " if ($_SESSION['glpiis_ids_visible']\n && is_numeric($post['searchText']) && (int)$post['searchText'] == $post['searchText']) {\n $swhere[$table . '.' . $item->getIndexName()] = ['LIKE', \"%{$post['searchText']}%\"];\n }", " // search also in displaywith columns\n if ($displaywith && count($post['displaywith'])) {\n foreach ($post['displaywith'] as $with) {\n $swhere[\"$table.$with\"] = ['LIKE', $search];\n }\n }", " $where[] = ['OR' => $swhere];\n }\n }", " $multi = false;", " // Manage multiple Entities dropdowns\n $order = [\"$table.completename\"];", " // No multi if get one item\n if ($item->isEntityAssign()) {\n $recur = $item->maybeRecursive();", " // Entities are not really recursive : do not display parents\n if ($post['itemtype'] == 'Entity') {\n $recur = false;\n }", " if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria(\n $table,\n '',\n $post[\"entity_restrict\"],\n $recur\n );", " if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }\n } else {\n // If private item do not use entity\n if (!$item->maybePrivate()) {\n $where = $where + getEntitiesRestrictCriteria($table, '', '', $recur);", " if (count($_SESSION['glpiactiveentities']) > 1) {\n $multi = true;\n }\n } else {\n $multi = false;\n }\n }", " // Force recursive items to multi entity view\n if ($recur) {\n $multi = true;\n }", " // no multi view for entitites\n if ($post['itemtype'] == \"Entity\") {\n $multi = false;\n }", " if ($multi) {\n array_unshift($order, \"$table.entities_id\");\n }\n }", " $addselect = [];\n $ljoin = [];\n if (Session::haveTranslations($post['itemtype'], 'completename')) {\n $addselect[] = \"namet.value AS transcompletename\";\n $ljoin['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => $post['itemtype'],\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => 'completename'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'name')) {\n $addselect[] = \"namet2.value AS transname\";\n $ljoin['glpi_dropdowntranslations AS namet2'] = [\n 'ON' => [\n 'namet2' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet2.itemtype' => $post['itemtype'],\n 'namet2.language' => $_SESSION['glpilanguage'],\n 'namet2.field' => 'name'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'comment')) {\n $addselect[] = \"commentt.value AS transcomment\";\n $ljoin['glpi_dropdowntranslations AS commentt'] = [\n 'ON' => [\n 'commentt' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'commentt.itemtype' => $post['itemtype'],\n 'commentt.language' => $_SESSION['glpilanguage'],\n 'commentt.field' => 'comment'\n ]\n ]\n ]\n ];\n }", " if ($start > 0 && $multi) {\n //we want to load last entry of previous page\n //(and therefore one more result) to check if\n //entity name must be displayed again\n --$start;\n ++$limit;\n }", " $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'FROM' => $table,\n 'WHERE' => $where,\n 'ORDER' => $order,\n 'START' => $start,\n 'LIMIT' => $limit\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n $iterator = $DB->request($criteria);", " // Empty search text : display first\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if ($post['display_emptychoice']) {\n $datas[] = [\n 'id' => 0,\n 'text' => $post['emptylabel']\n ];\n }\n }", " if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $datas[] = [\n 'id' => $key,\n 'text' => stripslashes($val)\n ];\n }\n }\n }\n $last_level_displayed = [];\n $datastoadd = [];", " // Ignore first item for all pages except first page\n $firstitem = (($post['page'] > 1));\n if (count($iterator)) {\n $prev = -1;\n $firstitem_entity = -1;", " while ($data = $iterator->next()) {\n $ID = $data['id'];\n $level = $data['level'];", " if (isset($data['transname']) && !empty($data['transname'])) {\n $outputval = $data['transname'];\n } else {\n $outputval = $data['name'];\n }", " if ($multi\n && ($data[\"entities_id\"] != $prev)) {\n // Do not do it for first item for next page load\n if (!$firstitem) {\n if ($prev >= 0) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n }\n }\n $prev = $data[\"entities_id\"];\n if ($firstitem) {\n $firstitem_entity = $prev;\n }\n // Reset last level displayed :\n $datastoadd = [];\n }", " if ($_SESSION['glpiuse_flat_dropdowntree']) {\n if (isset($data['transcompletename']) && !empty($data['transcompletename'])) {\n $outputval = $data['transcompletename'];\n } else {\n $outputval = $data['completename'];\n }\n $level = 0;\n } else { // Need to check if parent is the good one\n // Do not do if only get one item\n if (($level > 1)) {\n // Last parent is not the good one need to display arbo\n if (!isset($last_level_displayed[$level-1])\n || ($last_level_displayed[$level-1] != $data[$item->getForeignKeyField()])) {", " $work_level = $level-1;\n $work_parentID = $data[$item->getForeignKeyField()];\n $parent_datas = [];\n do {\n // Get parent\n if ($item->getFromDB($work_parentID)) {\n // Do not do for first item for next page load\n if (!$firstitem) {\n $title = $item->fields['completename'];", " $selection_text = $title;", " if (isset($item->fields[\"comment\"])) {\n $addcomment\n = DropdownTranslation::getTranslatedValue($ID, $post['itemtype'],\n 'comment',\n $_SESSION['glpilanguage'],\n $item->fields['comment']);\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n $output2 = DropdownTranslation::getTranslatedValue($item->fields['id'],\n $post['itemtype'],\n 'name',\n $_SESSION['glpilanguage'],\n $item->fields['name']);", " $temp = ['id' => $work_parentID,\n 'text' => $output2,\n 'level' => (int)$work_level,\n 'disabled' => true];\n if ($post['permit_select_parent']) {\n $temp['title'] = $title;\n $temp['selection_text'] = $selection_text;\n unset($temp['disabled']);\n }\n array_unshift($parent_datas, $temp);\n }\n $last_level_displayed[$work_level] = $item->fields['id'];\n $work_level--;\n $work_parentID = $item->fields[$item->getForeignKeyField()];", " } else { // Error getting item : stop\n $work_level = -1;\n }", " } while (($work_level >= 1)\n && (!isset($last_level_displayed[$work_level])\n || ($last_level_displayed[$work_level] != $work_parentID)));\n // Add parents\n foreach ($parent_datas as $val) {\n $datastoadd[] = $val;\n }\n }\n }\n $last_level_displayed[$level] = $data['id'];\n }", " // Do not do for first item for next page load\n if (!$firstitem) {\n if ($_SESSION[\"glpiis_ids_visible\"]\n || (Toolbox::strlen($outputval) == 0)) {\n $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);\n }", " if (isset($data['transcompletename']) && !empty($data['transcompletename'])) {\n $title = $data['transcompletename'];\n } else {\n $title = $data['completename'];\n }", " $selection_text = $title;", " if (isset($data[\"comment\"])) {\n if (isset($data['transcomment']) && !empty($data['transcomment'])) {\n $addcomment = $data['transcomment'];\n } else {\n $addcomment = $data['comment'];\n }\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n $datastoadd[] = [\n 'id' => $ID,\n 'text' => $outputval,\n 'level' => (int)$level,\n 'title' => $title,\n 'selection_text' => $selection_text\n ];\n $count++;\n }\n $firstitem = false;\n }\n }", " if ($multi) {\n if (count($datastoadd)) {\n // On paging mode do not add entity information each time\n if ($prev == $firstitem_entity) {\n $datas = array_merge($datas, $datastoadd);\n } else {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n }\n } else {\n if (count($datastoadd)) {\n $datas = array_merge($datas, $datastoadd);\n }\n }\n } else { // Not a dropdowntree\n $multi = false;\n // No multi if get one item\n if ($item->isEntityAssign()) {\n $multi = $item->maybeRecursive();", " if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria(\n $table,\n \"entities_id\",\n $post[\"entity_restrict\"],\n $multi\n );", " if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }", " } else {\n // Do not use entity if may be private\n if (!$item->maybePrivate()) {\n $where = $where + getEntitiesRestrictCriteria($table, '', '', $multi);", " if (count($_SESSION['glpiactiveentities'])>1) {\n $multi = true;\n }\n } else {\n $multi = false;\n }\n }\n }", " $field = \"name\";\n if ($item instanceof CommonDevice) {\n $field = \"designation\";\n } else if ($item instanceof Item_Devices) {\n $field = \"itemtype\";\n }", " if (!empty($post['searchText'])) {\n $search = Search::makeTextSearchValue($post['searchText']);\n $orwhere = [\"$table.$field\" => ['LIKE', $search]];", " if ($_SESSION['glpiis_ids_visible']\n && is_numeric($post['searchText']) && (int)$post['searchText'] == $post['searchText']) {\n $orwhere[$table . '.' . $item->getIndexName()] = ['LIKE', \"%{$post['searchText']}%\"];\n }", " if ($item instanceof CommonDCModelDropdown) {\n $orwhere[$table . '.product_number'] = ['LIKE', $search];\n }", " if (Session::haveTranslations($post['itemtype'], $field)) {\n $orwhere['namet.value'] = ['LIKE', $search];\n }\n if ($post['itemtype'] == \"SoftwareLicense\") {\n $orwhere['glpi_softwares.name'] = ['LIKE', $search];\n }", " // search also in displaywith columns\n if ($displaywith && count($post['displaywith'])) {\n foreach ($post['displaywith'] as $with) {\n $orwhere[\"$table.$with\"] = ['LIKE', $search];\n }\n }", " $where[] = ['OR' => $orwhere];\n }\n $addselect = [];\n $ljoin = [];\n if (Session::haveTranslations($post['itemtype'], $field)) {\n $addselect[] = \"namet.value AS transname\";\n $ljoin['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => $post['itemtype'],\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => $field\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'comment')) {\n $addselect[] = \"commentt.value AS transcomment\";\n $ljoin['glpi_dropdowntranslations AS commentt'] = [\n 'ON' => [\n 'commentt' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'commentt.itemtype' => $post['itemtype'],\n 'commentt.language' => $_SESSION['glpilanguage'],\n 'commentt.field' => 'comment'\n ]\n ]\n ]\n ];\n }", " $criteria = [];\n switch ($post['itemtype']) {\n case \"Contact\" :\n $criteria = [\n 'SELECT' => [\n \"$table.entities_id\",\n new \\QueryExpression(\n \"CONCAT(IFNULL(\" . $DB->quoteName('name') . \",''),' ',IFNULL(\" .\n $DB->quoteName('firstname') . \",'')) AS \" . $DB->quoteName($field)\n ),\n \"$table.comment\",\n \"$table.id\"\n ],\n 'FROM' => $table\n ];\n break;", " case \"SoftwareLicense\" :\n $criteria = [\n 'SELECT' => [\n \"$table.*\",\n new \\QueryExpression(\"CONCAT(glpi_softwares.name,' - ',glpi_softwarelicenses.name) AS $field\")\n ],\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_softwares' => [\n 'ON' => [\n 'glpi_softwarelicenses' => 'softwares_id',\n 'glpi_softwares' => 'id'\n ]\n ]\n ]\n ];\n break;", " case \"Profile\" :\n $criteria = [\n 'SELECT' => \"$table.*\",\n 'DISTINCT' => true,\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_profilerights' => [\n 'ON' => [\n 'glpi_profilerights' => 'profiles_id',\n $table => 'id'\n ]\n ]\n ]\n ];\n break;", " case KnowbaseItem::getType():\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'DISTINCT' => true,\n 'FROM' => $table\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }", " $visibility = KnowbaseItem::getVisibilityCriteria();\n if (count($visibility['LEFT JOIN'])) {\n $criteria['LEFT JOIN'] = array_merge(\n (isset($criteria['LEFT JOIN']) ? $criteria['LEFT JOIN'] : []),\n $visibility['LEFT JOIN']\n );\n //Do not use where??\n /*if (isset($visibility['WHERE'])) {\n $where = $visibility['WHERE'];\n }*/\n }\n break;", " case Project::getType():\n $visibility = Project::getVisibilityCriteria();\n if (count($visibility['LEFT JOIN'])) {\n $ljoin = array_merge($ljoin, $visibility['LEFT JOIN']);\n if (isset($visibility['WHERE'])) {\n $where[] = $visibility['WHERE'];\n }\n }\n //no break to reach default case.", " default :\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'FROM' => $table\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n }", " $criteria = array_merge(\n $criteria, [\n 'WHERE' => $where,\n 'START' => $start,\n 'LIMIT' => $limit\n ]\n );", " if ($multi) {\n $criteria['ORDERBY'] = [\"$table.entities_id\", \"$table.$field\"];\n } else {\n $criteria['ORDERBY'] = [\"$table.$field\"];\n }", " $iterator = $DB->request($criteria);", " // Display first if no search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if (!isset($post['display_emptychoice']) || $post['display_emptychoice']) {\n $datas[] = [\n 'id' => 0,\n 'text' => $post[\"emptylabel\"]\n ];\n }\n }\n if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $datas[] = [\n 'id' => $key,\n 'text' => stripslashes($val)\n ];\n }\n }\n }", " $datastoadd = [];", " if (count($iterator)) {\n $prev = -1;", " while ($data = $iterator->next()) {\n if ($multi\n && ($data[\"entities_id\"] != $prev)) {\n if ($prev >= 0) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n }\n $prev = $data[\"entities_id\"];\n $datastoadd = [];\n }", " if (isset($data['transname']) && !empty($data['transname'])) {\n $outputval = $data['transname'];\n } else if ($field == 'itemtype' && class_exists($data['itemtype'])) {\n $tmpitem = new $data[$field]();\n if ($tmpitem->getFromDB($data['items_id'])) {\n $outputval = sprintf(__('%1$s - %2$s'), $tmpitem->getTypeName(), $tmpitem->getName());\n } else {\n $outputval = $tmpitem->getTypeName();\n }\n } else if ($item instanceof CommonDCModelDropdown) {\n $outputval =sprintf(__('%1$s - %2$s'), $data[$field], $data['product_number']);\n } else {\n $outputval = $data[$field];\n }", " $ID = $data['id'];\n $addcomment = \"\";\n $title = $outputval;\n if (isset($data[\"comment\"])) {\n if (isset($data['transcomment']) && !empty($data['transcomment'])) {\n $addcomment .= $data['transcomment'];\n } else {\n $addcomment .= $data[\"comment\"];\n }", " $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n if ($_SESSION[\"glpiis_ids_visible\"]\n || (strlen($outputval) == 0)) {\n //TRANS: %1$s is the name, %2$s the ID\n $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);\n }\n if ($displaywith) {\n foreach ($post['displaywith'] as $key) {\n if (isset($data[$key])) {\n $withoutput = $data[$key];\n if (isForeignKeyField($key)) {\n $withoutput = Dropdown::getDropdownName(getTableNameForForeignKeyField($key),\n $data[$key]);\n }\n if ((strlen($withoutput) > 0) && ($withoutput != '&nbsp;')) {\n $outputval = sprintf(__('%1$s - %2$s'), $outputval, $withoutput);\n }\n }\n }\n }\n $datastoadd[] = [\n 'id' => $ID,\n 'text' => $outputval,\n 'title' => $title\n ];\n $count++;\n }\n if ($multi) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n } else {\n if (count($datastoadd)) {\n $datas = array_merge($datas, $datastoadd);\n }\n }\n }\n }", " $ret['results'] = Toolbox::unclean_cross_side_scripting_deep($datas);\n $ret['count'] = $count;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown connect\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownConnect($post, $json = true) {\n global $DB, $CFG_GLPI;", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post)) {\n return;\n }", " if (!isset($post['fromtype']) || !($fromitem = getItemForItemtype($post['fromtype']))) {\n return;\n }", " $fromitem->checkGlobal(UPDATE);\n $used = [];\n if (isset( $post[\"used\"])) {\n $used = $post[\"used\"];", " if (isset($used[$post['itemtype']])) {\n $used = $used[$post['itemtype']];\n } else {\n $used = [];\n }\n }", " // Make a select box\n $table = getTableForItemType($post[\"itemtype\"]);\n if (!$item = getItemForItemtype($post['itemtype'])) {\n return;\n }", " $where = [];", " if ($item->maybeDeleted()) {\n $where[\"$table.is_deleted\"] = 0;\n }\n if ($item->maybeTemplate()) {\n $where[\"$table.is_template\"] = 0;\n }", " if (isset($post['searchText']) && (strlen($post['searchText']) > 0)) {\n $search = Search::makeTextSearchValue($post['searchText']);\n $where['OR'] = [\n \"$table.name\" => ['LIKE', $search],\n \"$table.otherserial\" => ['LIKE', $search],\n \"$table.serial\" => ['LIKE', $search]\n ];\n }", " $multi = $item->maybeRecursive();", " if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria($table, '', $post[\"entity_restrict\"], $multi);\n if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }", " } else {\n $where = $where + getEntitiesRestrictCriteria($table, '', $_SESSION['glpiactiveentities'], $multi);\n if (count($_SESSION['glpiactiveentities']) > 1) {\n $multi = true;\n }\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " if (!isset($post['onlyglobal'])) {\n $post['onlyglobal'] = false;\n }", " if ($post[\"onlyglobal\"]\n && ($post[\"itemtype\"] != 'Computer')) {\n $where[\"$table.is_global\"] = 1;\n } else {\n $where_used = [];\n if (!empty($used)) {\n $where_used[] = ['NOT' => [\"$table.id\" => $used]];\n }", " if ($post[\"itemtype\"] == 'Computer') {\n $where = $where + $where_used;\n } else {\n $where[] = [\n 'OR' => [\n [\n 'glpi_computers_items.id' => null\n ] + $where_used,\n \"$table.is_global\" => 1\n ]\n ];\n }\n }", " $criteria = [\n 'SELECT' => [\n \"$table.id\",\n \"$table.name AS name\",\n \"$table.serial AS serial\",\n \"$table.otherserial AS otherserial\",\n \"$table.entities_id AS entities_id\"\n ],\n 'DISTINCT' => true,\n 'FROM' => $table,\n 'WHERE' => $where,\n 'ORDERBY' => ['entities_id', 'name ASC'],\n 'LIMIT' => $limit,\n 'START' => $start\n ];", " if (($post[\"itemtype\"] != 'Computer') && !$post[\"onlyglobal\"]) {\n $criteria['LEFT JOIN'] = [\n 'glpi_computers_items' => [\n 'ON' => [\n $table => 'id',\n 'glpi_computers_items' => 'items_id', [\n 'AND' => [\n 'glpi_computers_items.itemtype' => $post['itemtype']\n ]\n ]\n ]\n ]\n ];\n }", " $iterator = $DB->request($criteria);", " $results = [];\n // Display first if no search\n if (empty($post['searchText'])) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n }\n if (count($iterator)) {\n $prev = -1;\n $datatoadd = [];", " while ($data = $iterator->next()) {\n if ($multi && ($data[\"entities_id\"] != $prev)) {\n if (count($datatoadd)) {\n $results[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datatoadd\n ];\n }\n $prev = $data[\"entities_id\"];\n // Reset last level displayed :\n $datatoadd = [];\n }\n $output = $data['name'];\n $ID = $data['id'];", " if ($_SESSION[\"glpiis_ids_visible\"]\n || empty($output)) {\n $output = sprintf(__('%1$s (%2$s)'), $output, $ID);\n }\n if (!empty($data['serial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data[\"serial\"]);\n }\n if (!empty($data['otherserial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data[\"otherserial\"]);\n }\n $datatoadd[] = [\n 'id' => $ID,\n 'text' => $output\n ];\n }", " if ($multi) {\n if (count($datatoadd)) {\n $results[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datatoadd\n ];\n }\n } else {\n if (count($datatoadd)) {\n $results = array_merge($results, $datatoadd);\n }\n }\n }", " $ret['results'] = $results;\n return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown find num\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownFindNum($post, $json = true) {\n global $DB, $CFG_GLPI;", " // Security\n if (!$DB->tableExists($post['table'])) {\n return;\n }", " $itemtypeisplugin = isPluginItemType($post['itemtype']);", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post)) {\n return;\n }", " if (!$item = getItemForItemtype($post['itemtype'])) {\n return;\n }", " $where = [];\n if (isset($post['used']) && !empty($post['used'])) {\n $where['NOT'] = ['id' => $post['used']];\n }", " if ($item->maybeDeleted()) {\n $where['is_deleted'] = 0;\n }", " if ($item->maybeTemplate()) {\n $where['is_template'] = 0;\n }", " if (isset($_POST['searchText']) && (strlen($post['searchText']) > 0)) {\n $search = ['LIKE', Search::makeTextSearchValue($post['searchText'])];\n $orwhere =[\n 'name' => $search,\n 'id' => $post['searchText']\n ];", " if ($DB->fieldExists($post['table'], \"contact\")) {\n $orwhere['contact'] = $search;\n }\n if ($DB->fieldExists($post['table'], \"serial\")) {\n $orwhere['serial'] = $search;\n }\n if ($DB->fieldExists($post['table'], \"otherserial\")) {\n $orwhere['otherserial'] = $search;\n }\n $where[] = ['OR' => $orwhere];\n }", " // If software or plugins : filter to display only the objects that are allowed to be visible in Helpdesk\n $filterHelpdesk = in_array($post['itemtype'], $CFG_GLPI[\"helpdesk_visible_types\"]);", " if (isset($post['context'])\n && $post['context'] == \"impact\"\n && Impact::isEnabled($post['itemtype'])\n ) {\n $filterHelpdesk = false;\n }", " if ($filterHelpdesk) {\n $where['is_helpdesk_visible'] = 1;\n }", " if ($item->isEntityAssign()) {\n if (isset($post[\"entity_restrict\"]) && ($post[\"entity_restrict\"] >= 0)) {\n $entity = $post[\"entity_restrict\"];\n } else {\n $entity = '';\n }", " // allow opening ticket on recursive object (printer, software, ...)\n $recursive = $item->maybeRecursive();\n $where = $where + getEntitiesRestrictCriteria($post['table'], '', $entity, $recursive);\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " $iterator = $DB->request([\n 'FROM' => $post['table'],\n 'WHERE' => $where,\n 'ORDER' => $item->getNameField(),\n 'LIMIT' => $limit,\n 'START' => $start\n ]);", " $results = [];", " // Display first if no search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n }\n $count = 0;\n if (count($iterator)) {\n while ($data = $iterator->next()) {\n $output = $data[$item->getNameField()];", " if (isset($data['contact']) && !empty($data['contact'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data['contact']);\n }\n if (isset($data['serial']) && !empty($data['serial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);\n }\n if (isset($data['otherserial']) && !empty($data['otherserial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);\n }", " if (empty($output)\n || $_SESSION['glpiis_ids_visible']) {\n $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);\n }", " $results[] = [\n 'id' => $data['id'],\n 'text' => $output\n ];\n $count++;\n }\n }", " $ret['count'] = $count;\n $ret['results'] = $results;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown netpoint\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownNetpoint($post, $json = true) {\n global $DB, $CFG_GLPI;", " // Make a select box with preselected values\n $results = [];\n $location_restrict = false;", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " $criteria = [\n 'SELECT' => [\n 'glpi_netpoints.comment AS comment',\n 'glpi_netpoints.id',\n 'glpi_netpoints.name AS netpname',\n 'glpi_locations.completename AS loc'\n ],\n 'FROM' => 'glpi_netpoints',\n 'LEFT JOIN' => [\n 'glpi_locations' => [\n 'ON' => [\n 'glpi_netpoints' => 'locations_id',\n 'glpi_locations' => 'id'\n ]\n ]\n ],\n 'WHERE' => [],\n 'ORDERBY' => [\n 'glpi_locations.completename',\n 'glpi_netpoints.name'\n ],\n 'START' => $start,\n 'LIMIT' => $limit\n ];", " if (!(isset($post[\"devtype\"])\n && ($post[\"devtype\"] != 'NetworkEquipment')\n && isset($post[\"locations_id\"])\n && ($post[\"locations_id\"] > 0))) {", " if (isset($post[\"entity_restrict\"]) && ($post[\"entity_restrict\"] >= 0)) {\n $criteria['WHERE']['glpi_netpoints.entities_id'] = $post['entity_restrict'];\n } else {\n $criteria['WHERE'] = $criteria['WHERE'] + getEntitiesRestrictCriteria('glpi_locations');\n }\n }", " if (isset($post['searchText']) && strlen($post['searchText']) > 0) {\n $criteria['WHERE']['OR'] = [\n 'glpi_netpoints.name' => ['LIKE', Search::makeTextSearchValue($post['searchText'])],\n 'glpi_locations.completename' => ['LIKE', Search::makeTextSearchValue($post['searchText'])]\n ];\n }", " if (isset($post[\"devtype\"]) && !empty($post[\"devtype\"])) {\n $criteria['LEFT JOIN']['glpi_networkportethernets'] = [\n 'ON' => [\n 'glpi_networkportethernets' => 'netpoints_id',\n 'glpi_netpoints' => 'id'\n ]\n ];", " $extra_and = [];\n if ($post[\"devtype\"] == 'NetworkEquipment') {\n $extra_and['glpi_networkports.itemtype'] = 'NetworkEquipment';\n } else {\n $extra_and['NOT'] = ['glpi_networkports.itemtype' => 'NetworkEquipment'];\n if (isset($post[\"locations_id\"]) && ($post[\"locations_id\"] >= 0)) {\n $location_restrict = true;\n $criteria['WHERE']['glpi_netpoints.locations_id'] = $post['locations_id'];\n }\n }", " $criteria['LEFT JOIN']['glpi_networkports'] = [\n 'ON' => [\n 'glpi_networkportethernets' => 'id',\n 'glpi_networkports' => 'id', [\n 'AND' => [\n 'glpi_networkports.instantiation_type' => 'NetworkPortEthernet',\n ] + $extra_and\n ]\n ]\n ];\n $criteria['WHERE']['glpi_networkportethernets.netpoints_id'] = null;\n } else if (isset($post[\"locations_id\"]) && ($post[\"locations_id\"] >= 0)) {\n $location_restrict = true;\n $criteria['WHERE']['glpi_netpoints.locations_id'] = $post['locations_id'];\n }", " $iterator = $DB->request($criteria);", " // Display first if no search\n if (empty($post['searchText'])) {\n if ($post['page'] == 1) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n }\n }", " $count = 0;\n if (count($iterator)) {\n while ($data = $iterator->next()) {\n $output = $data['netpname'];\n $loc = $data['loc'];\n $ID = $data['id'];\n $title = $output;\n if (isset($data[\"comment\"])) {\n //TRANS: %1$s is the location, %2$s is the comment\n $title = sprintf(__('%1$s - %2$s'), $title, $loc);\n $title = sprintf(__('%1$s - %2$s'), $title, $data[\"comment\"]);\n }\n if (!$location_restrict) {\n $output = sprintf(__('%1$s (%2$s)'), $output, $loc);\n }", " $results[] = [\n 'id' => $ID,\n 'text' => $output,\n 'title' => $title\n ];\n $count++;\n }\n }", " $ret['count'] = $count;\n $ret['results'] = $results;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown number\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownNumber($post, $json = true) {\n global $CFG_GLPI;", " $used = [];", " if (isset($post['used'])) {\n $used = $post['used'];\n }", " if (!isset($post['value'])) {\n $post['value'] = 0;\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " if (isset($post['toadd'])) {\n $toadd = $post['toadd'];\n } else {\n $toadd = [];\n }", " $data = [];\n // Count real items returned\n $count = 0;", " if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $data[] = ['id' => $key,\n 'text' => (string)stripslashes($val)];\n }\n }\n }", " $values = [];", " if (!isset($post['min'])) {\n $post['min'] = 1;\n }", " if (!isset($post['step'])) {\n $post['step'] = 1;\n }", " if (!isset($post['max'])) {\n //limit max entries to avoid loop issues\n $post['max'] = $CFG_GLPI['dropdown_max'] * $post['step'];\n }", " for ($i=$post['min']; $i<=$post['max']; $i+=$post['step']) {\n if (!empty($post['searchText']) && strstr($i, $post['searchText']) || empty($post['searchText'])) {\n if (!in_array($i, $used)) {\n $values[\"$i\"] = $i;\n }\n }\n }", " if (count($values)) {\n $start = ($post['page']-1)*$post['page_limit'];\n $tosend = array_splice($values, $start, $post['page_limit']);\n foreach ($tosend as $i) {\n $txt = $i;\n if (isset($post['unit'])) {\n $txt = Dropdown::getValueWithUnit($i, $post['unit']);\n }\n $data[] = ['id' => $i,\n 'text' => (string)$txt];\n $count++;\n }", " } else {\n if (!isset($toadd[-1])) {\n $value = -1;\n if (isset($post['min']) && $value < $post['min']) {\n $value = $post['min'];\n } else if (isset($post['max']) && $value > $post['max']) {\n $value = $post['max'];\n }", " if (isset($post['unit'])) {\n $txt = Dropdown::getValueWithUnit($value, $post['unit']);\n }\n $data[] = [\n 'id' => $value,\n 'text' => (string)stripslashes($txt)\n ];\n $count++;\n }\n }", " $ret['results'] = $data;\n $ret['count'] = $count;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown users\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownUsers($post, $json = true) {\n global $CFG_GLPI;", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post + ['itemtype' => 'User', 'right' => ($post['right'] ?? \"\")])) {\n return;\n }", " if (!isset($post['right'])) {\n $post['right'] = \"all\";\n }", " // Default view : Nobody\n if (!isset($post['all'])) {\n $post['all'] = 0;\n }", " $used = [];", " if (isset($post['used'])) {\n $used = $post['used'];\n }", " if (!isset($post['value'])) {\n $post['value'] = 0;\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $entity_restrict = -1;\n if (isset($post['entity_restrict'])) {\n $entity_restrict = Toolbox::jsonDecode($post['entity_restrict']);\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $searchText = (isset($post['searchText']) ? $post['searchText'] : null);\n $inactive_deleted = isset($post['inactive_deleted']) ? $post['inactive_deleted'] : 0;\n $result = User::getSqlSearchResult(\n false,\n $post['right'],\n $entity_restrict,\n $post['value'],\n $used,\n $searchText,\n $start,\n (int)$post['page_limit'],\n $inactive_deleted\n );", " $users = [];", " // Count real items returned\n $count = 0;\n if (count($result)) {\n while ($data = $result->next()) {\n $users[$data[\"id\"]] = formatUserName($data[\"id\"], $data[\"name\"], $data[\"realname\"],\n $data[\"firstname\"]);\n $logins[$data[\"id\"]] = $data[\"name\"];\n }\n }", " $results = [];", " // Display first if empty search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if ($post['all'] == 0) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n } else if ($post['all'] == 1) {\n $results[] = [\n 'id' => 0,\n 'text' => __('All')\n ];\n }\n }", " if (count($users)) {\n foreach ($users as $ID => $output) {\n $title = sprintf(__('%1$s - %2$s'), $output, $logins[$ID]);", " $results[] = [\n 'id' => $ID,\n 'text' => $output,\n 'title' => $title\n ];\n $count++;\n }\n }", " $ret['results'] = $results;\n $ret['count'] = $count;", " return ($json === true) ? json_encode($ret) : $ret;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access this file directly\");\n}", "class Dropdown {", " //Empty value displayed in a dropdown\n const EMPTY_VALUE = '-----';", " /**\n * Print out an HTML \"<select>\" for a dropdown with preselected value\n *\n * @param string $itemtype itemtype used for create dropdown\n * @param array $options array of possible options:\n * - name : string / name of the select (default is depending itemtype)\n * - value : integer / preselected value (default -1)\n * - comments : boolean / is the comments displayed near the dropdown (default true)\n * - toadd : array / array of specific values to add at the begining\n * - entity : integer or array / restrict to a defined entity or array of entities\n * (default -1 : no restriction)\n * - entity_sons : boolean / if entity restrict specified auto select its sons\n * only available if entity is a single value not an array\n * (default false)\n * - toupdate : array / Update a specific item on select change on dropdown\n * (need value_fieldname, to_update,\n * url (see Ajax::updateItemOnSelectEvent for information)\n * and may have moreparams)\n * - used : array / Already used items ID: not to display in dropdown\n * (default empty)\n * - on_change : string / value to transmit to \"onChange\"\n * - rand : integer / already computed rand value\n * - condition : array / aditional SQL condition to limit display\n * - displaywith : array / array of field to display with request\n * - emptylabel : Empty choice's label (default self::EMPTY_VALUE)\n * - display_emptychoice : Display emptychoice ? (default true)\n * - display : boolean / display or get string (default true)\n * - width : specific width needed (default auto adaptive)\n * - permit_select_parent : boolean / for tree dropdown permit to see parent items\n * not available by default (default false)\n * - specific_tags : array of HTML5 tags to add the the field\n * - url : url of the ajax php code which should return the json data to show in\n * the dropdown\n *\n * @return boolean : false if error and random id if OK\n *\n * @since 9.5.0 Usage of string in condition option is removed\n **/\n static function show($itemtype, $options = []) {\n global $CFG_GLPI;", " if ($itemtype && !($item = getItemForItemtype($itemtype))) {\n return false;\n }", " $table = $item->getTable();", " $params['name'] = $item->getForeignKeyField();\n $params['value'] = (($itemtype == 'Entity') ? $_SESSION['glpiactive_entity'] : '');\n $params['comments'] = true;\n $params['entity'] = -1;\n $params['entity_sons'] = false;\n $params['toupdate'] = '';\n $params['width'] = '';\n $params['used'] = [];\n $params['toadd'] = [];\n $params['on_change'] = '';\n $params['condition'] = [];\n $params['rand'] = mt_rand();\n $params['displaywith'] = [];\n //Parameters about choice 0\n //Empty choice's label\n $params['emptylabel'] = self::EMPTY_VALUE;\n //Display emptychoice ?\n $params['display_emptychoice'] = ($itemtype != 'Entity');\n $params['placeholder'] = '';\n $params['display'] = true;\n $params['permit_select_parent'] = false;\n $params['addicon'] = true;\n $params['specific_tags'] = [];\n $params['url'] = $CFG_GLPI['root_doc'].\"/ajax/getDropdownValue.php\";", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }\n $output = '';\n $name = $params['emptylabel'];\n $comment = \"\";", " // Check default value for dropdown : need to be a numeric (or null)\n if ($params['value'] !== null\n && ((strlen($params['value']) == 0) || !is_numeric($params['value']) && $params['value'] != 'mygroups')) {\n $params['value'] = 0;\n }", " if (isset($params['toadd'][$params['value']])) {\n $name = $params['toadd'][$params['value']];\n } else if (($params['value'] > 0)\n || (($itemtype == \"Entity\")\n && ($params['value'] >= 0))) {\n $tmpname = self::getDropdownName($table, $params['value'], 1);", " if ($tmpname[\"name\"] != \"&nbsp;\") {\n $name = $tmpname[\"name\"];\n $comment = $tmpname[\"comment\"];\n }\n }", " // Manage entity_sons\n if (!($params['entity'] < 0)\n && $params['entity_sons']) {\n if (is_array($params['entity'])) {\n // translation not needed - only for debug\n $output .= \"entity_sons options is not available with entity option as array\";\n } else {\n $params['entity'] = getSonsOf('glpi_entities', $params['entity']);\n }\n }", " $field_id = Html::cleanId(\"dropdown_\".$params['name'].$params['rand']);", " // Manage condition\n if (!empty($params['condition'])) {\n // Put condition in session and replace it by its key\n // This is made to prevent passing to many parameters when calling the ajax script\n $params['condition'] = static::addNewCondition($params['condition']);\n }", " if (!$item instanceof CommonTreeDropdown) {\n $name = Toolbox::unclean_cross_side_scripting_deep($name);\n }\n $p = ['value' => $params['value'],\n 'valuename' => $name,\n 'width' => $params['width'],\n 'itemtype' => $itemtype,\n 'display_emptychoice' => $params['display_emptychoice'],\n 'placeholder' => $params['placeholder'],\n 'displaywith' => $params['displaywith'],\n 'emptylabel' => $params['emptylabel'],\n 'condition' => $params['condition'],\n 'used' => $params['used'],\n 'toadd' => $params['toadd'],", " 'entity_restrict' => ($entity_restrict = (is_array($params['entity']) ? json_encode(array_values($params['entity'])) : $params['entity'])),", " 'on_change' => $params['on_change'],\n 'permit_select_parent' => $params['permit_select_parent'],\n 'specific_tags' => $params['specific_tags'],", " '_idor_token' => Session::getNewIDORToken($itemtype, [\n 'entity_restrict' => $entity_restrict,\n ]),", " ];", " $output = \"<span class='no-wrap'>\";\n $output.= Html::jsAjaxDropdown($params['name'], $field_id,\n $params['url'],\n $p);\n // Display comment\n if ($params['comments']) {\n $comment_id = Html::cleanId(\"comment_\".$params['name'].$params['rand']);\n $link_id = Html::cleanId(\"comment_link_\".$params['name'].$params['rand']);\n $kblink_id = Html::cleanId(\"kb_link_\".$params['name'].$params['rand']);\n $options_tooltip = ['contentid' => $comment_id,\n 'linkid' => $link_id,\n 'display' => false];", " if ($item->canView()) {\n if ($params['value']\n && $item->getFromDB($params['value'])\n && $item->canViewItem()) {\n $options_tooltip['link'] = $item->getLinkURL();\n } else {\n $options_tooltip['link'] = $item->getSearchURL();\n }\n }", " if (empty($comment)) {\n $comment = Toolbox::ucfirst(\n sprintf(\n __('Show %1$s'),\n $item::getTypeName(Session::getPluralNumber())\n )\n );\n }\n $output .= \"&nbsp;\".Html::showToolTip($comment, $options_tooltip);", " if (($item instanceof CommonDropdown)\n && $item->canCreate()\n && !isset($_REQUEST['_in_modal'])\n && $params['addicon']) {", " $output .= \"<span class='fa fa-plus-circle pointer' title=\\\"\".__s('Add').\"\\\"\n onClick=\\\"\".Html::jsGetElementbyID('add_'.$field_id).\".dialog('open');\\\"\n ><span class='sr-only'>\" . __s('Add') . \"</span></span>\";\n $output .= Ajax::createIframeModalWindow('add_'.$field_id,\n $item->getFormURL(),\n ['display' => false]);\n }", " // Display specific Links\n if ($itemtype == \"Supplier\") {\n if ($item->getFromDB($params['value'])) {\n $output .= $item->getLinks();\n }\n }", " if ($itemtype == 'Location') {\n $output .= \"<span class='fa fa-globe-americas pointer' title='\".__s('Display on map').\"' onclick='showMapForLocation(this)' data-fid='$field_id'></span>\";\n }", " $paramscomment = [\n 'value' => '__VALUE__',\n 'itemtype' => $itemtype,\n '_idor_token' => Session::getNewIDORToken($itemtype)\n ];\n if ($item->isField('knowbaseitemcategories_id')\n && Session::haveRight('knowbase', READ)) {", " if (method_exists($item, 'getLinks')) {\n $output .= \"<span id='$kblink_id'>\";\n $output .= '&nbsp;'.$item->getLinks();\n $output .= \"</span>\";\n $paramscomment['withlink'] = $kblink_id;\n $output .= Ajax::updateItemOnSelectEvent($field_id, $kblink_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/kblink.php\",\n $paramscomment, false);\n }\n }", " if ($item->canView()) {\n $paramscomment['withlink'] = $link_id;\n }", " $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/comments.php\",\n $paramscomment, false);\n }\n $output .= Ajax::commonDropdownUpdateItem($params, false);\n $output .= \"</span>\";\n if ($params['display']) {\n echo $output;\n return $params['rand'];\n }\n return $output;\n }", "\n /**\n * Add new condition\n *\n * @todo should not use session to pass query parameters...\n *\n * @param array $condition Condition to add\n *\n * @return string\n */\n static function addNewCondition(array $condition) {\n $sha1 = sha1(serialize($condition));\n $_SESSION['glpicondition'][$sha1] = $condition;\n return $sha1;\n }", " /**\n * Get the value of a dropdown\n *\n * Returns the value of the dropdown from $table with ID $id.\n *\n * @param string $table the dropdown table from witch we want values on the select\n * @param integer $id id of the element to get\n * @param boolean $withcomment give array with name and comment (default 0)\n * @param boolean $translate (true by default)\n * @param boolean $tooltip (true by default) returns a tooltip, else returns only 'comment'\n *\n * @return string the value of the dropdown or &nbsp; if not exists\n **/\n static function getDropdownName($table, $id, $withcomment = 0, $translate = true, $tooltip = true) {\n global $DB;", " $dft_retval = \"&nbsp;\";", " $item = getItemForItemtype(getItemTypeForTable($table));", " if (!is_object($item)) {\n return $dft_retval;\n }", " if ($item instanceof CommonTreeDropdown) {\n return getTreeValueCompleteName($table, $id, $withcomment, $translate, $tooltip);\n }", " $name = \"\";\n $comment = \"\";", " if ($id) {\n $SELECTNAME = new \\QueryExpression(\"'' AS \". $DB->quoteName('transname'));\n $SELECTCOMMENT = new \\QueryExpression(\"'' AS \" . $DB->quoteName('transcomment'));\n $JOIN = [];\n $JOINS = [];\n if ($translate) {\n if (Session::haveTranslations(getItemTypeForTable($table), 'name')) {\n $SELECTNAME = 'namet.value AS transname';\n $JOINS['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => getItemTypeForTable($table),\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => 'name'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations(getItemTypeForTable($table), 'comment')) {\n $SELECTCOMMENT = 'namec.value AS transcomment';\n $JOINS['glpi_dropdowntranslations AS namec'] = [\n 'ON' => [\n 'namec' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namec.itemtype' => getItemTypeForTable($table),\n 'namec.language' => $_SESSION['glpilanguage'],\n 'namec.field' => 'comment'\n ]\n ]\n ]\n ];\n }", " if (count($JOINS)) {\n $JOIN = ['LEFT JOIN' => $JOINS];\n }\n }", " $criteria = [\n 'SELECT' => [\n \"$table.*\",\n $SELECTNAME,\n $SELECTCOMMENT\n ],\n 'FROM' => $table,\n 'WHERE' => [\"$table.id\" => $id]\n ] + $JOIN;\n $iterator = $DB->request($criteria);", " /// TODO review comment management...\n /// TODO getDropdownName need to return only name\n /// When needed to use comment use class instead : getComments function\n /// GetName of class already give Name !!\n /// TODO CommonDBTM : review getComments to be recursive and add informations from class hierarchy\n /// getUserName have the same system : clean it too\n /// Need to study the problem\n if (count($iterator)) {\n $data = $iterator->next();\n if ($translate && !empty($data['transname'])) {\n $name = $data['transname'];\n } else {\n $name = $data[$item->getNameField()];\n }\n if (isset($data[\"comment\"])) {\n if ($translate && !empty($data['transcomment'])) {\n $comment = $data['transcomment'];\n } else {\n $comment = $data[\"comment\"];\n }\n }", " switch ($table) {\n case \"glpi_computers\" :\n if (empty($name)) {\n $name = \"($id)\";\n }\n break;", " case \"glpi_contacts\" :\n //TRANS: %1$s is the name, %2$s is the firstname\n $name = sprintf(__('%1$s %2$s'), $name, $data[\"firstname\"]);\n if ($tooltip) {\n if (!empty($data[\"phone\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".Phone::getTypeName(1),\n \"</span>\".$data['phone']);\n }\n if (!empty($data[\"phone2\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('Phone 2'),\n \"</span>\".$data['phone2']);\n }\n if (!empty($data[\"mobile\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('Mobile phone'),\n \"</span>\".$data['mobile']);\n }\n if (!empty($data[\"fax\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".__('Fax'),\n \"</span>\".$data['fax']);\n }\n if (!empty($data[\"email\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\"._n('Email', 'Emails', 1),\n \"</span>\".$data['email']);\n }\n }\n break;", " case \"glpi_suppliers\" :\n if ($tooltip) {\n if (!empty($data[\"phonenumber\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".Phone::getTypeName(1),\n \"</span>\".$data['phonenumber']);\n }\n if (!empty($data[\"fax\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\".__('Fax'),\n \"</span>\".$data['fax']);\n }\n if (!empty($data[\"email\"])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\"._n('Email', 'Emails', 1),\n \"</span>\".$data['email']);\n }\n }\n break;", " case \"glpi_netpoints\" :\n $name = sprintf(__('%1$s (%2$s)'), $name,\n self::getDropdownName(\"glpi_locations\",\n $data[\"locations_id\"], false, $translate));\n break;", " case \"glpi_budgets\" :\n if ($tooltip) {\n if (!empty($data['locations_id'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".Location::getTypeName(1).\"</span>\",\n self::getDropdownName(\"glpi_locations\",\n $data[\"locations_id\"],\n false, $translate));", " }\n if (!empty($data['budgettypes_id'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'), \"<span class='b'>\"._n('Type', 'Types', 1).\"</span>\",\n self::getDropdownName(\"glpi_budgettypes\",\n $data[\"budgettypes_id\"], false, $translate));", " }\n if (!empty($data['begin_date'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('Start date').\"</span>\",\n Html::convDateTime($data[\"begin_date\"]));", " }\n if (!empty($data['end_date'])) {\n $comment .= \"<br>\".sprintf(__('%1$s: %2$s'),\n \"<span class='b'>\".__('End date').\"</span>\",\n Html::convDateTime($data[\"end_date\"]));\n }\n }\n }\n }\n }", " if (empty($name)) {\n $name = $dft_retval;\n }", " if ($withcomment) {\n return [\n 'name' => $name,\n 'comment' => $comment\n ];\n }", " return $name;\n }", "\n /**\n * Get values of a dropdown for a list of item\n *\n * @param string $table the dropdown table from witch we want values on the select\n * @param integer[] $ids array containing the ids to get\n *\n * @return array containing the value of the dropdown or &nbsp; if not exists\n **/\n static function getDropdownArrayNames($table, $ids) {\n global $DB;", " $tabs = [];", " if (count($ids)) {\n $itemtype = getItemTypeForTable($table);\n if ($item = getItemForItemtype($itemtype)) {\n $field = 'name';\n if ($item instanceof CommonTreeDropdown) {\n $field = 'completename';\n }", " $iterator = $DB->request([\n 'SELECT' => ['id', $field],\n 'FROM' => $table,\n 'WHERE' => ['id' => $ids]\n ]);", " while ($data = $iterator->next()) {\n $tabs[$data['id']] = $data[$field];\n }\n }\n }\n return $tabs;\n }", "\n /**\n * Make a select box for device type\n *\n * @param string $name name of the select box\n * @param string[] $types array of types to display\n * @param array $options Parameters which could be used in options array :\n * - value : integer / preselected value (default '')\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - emptylabel : Empty choice's label (default self::EMPTY_VALUE)\n * - display : boolean if false get string\n * - width : specific width needed (default not set)\n * - emptylabel : empty label if empty displayed (default self::EMPTY_VALUE)\n * - display_emptychoice : display empty choice (default false)\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showItemTypes($name, $types = [], $options = []) {\n $params['value'] = '';\n $params['used'] = [];\n $params['emptylabel'] = self::EMPTY_VALUE;\n $params['display'] = true;\n $params['width'] = '80%';\n $params['display_emptychoice'] = true;\n $params['rand'] = mt_rand();", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " $values = [];\n if (count($types)) {\n foreach ($types as $type) {\n if ($item = getItemForItemtype($type)) {\n $values[$type] = $item->getTypeName(1);\n }\n }\n }\n asort($values);\n return self::showFromArray($name, $values,\n $params);\n }", "\n /**\n * Make a select box for device type\n *\n * @param string $name name of the select box\n * @param string $itemtype_ref itemtype reference where to search in itemtype field\n * @param array $options array of possible options:\n * - may be value (default value) / field (used field to search itemtype)\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function dropdownUsedItemTypes($name, $itemtype_ref, $options = []) {\n global $DB;", " $p['value'] = 0;\n $p['field'] = 'itemtype';", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " $iterator = $DB->request([\n 'SELECT' => $p['field'],\n 'DISTINCT' => true,\n 'FROM' => getTableForItemType($itemtype_ref)\n ]);", " $tabs = [];\n while ($data = $iterator->next()) {\n $tabs[$data[$p['field']]] = $data[$p['field']];\n }\n return self::showItemTypes($name, $tabs, ['value' => $p['value']]);\n }", "\n /**\n * Make a select box for icons\n *\n * @param string $myname the name of the HTML select\n * @param mixed $value the preselected value we want\n * @param string $store_path path where icons are stored\n * @param boolean $display display of get string ? (true by default)\n *\n *\n * @return void|string\n * void if param display=true\n * string if param display=false (HTML code)\n **/\n static function dropdownIcons($myname, $value, $store_path, $display = true) {", " $output = '';\n if (is_dir($store_path)) {\n if ($dh = opendir($store_path)) {\n $files = [];", " while (($file = readdir($dh)) !== false) {\n $files[] = $file;\n }", " closedir($dh);\n sort($files);", " foreach ($files as $file) {\n if (preg_match(\"/\\.png$/i\", $file)) {\n $values[$file] = $file;\n }\n }\n Dropdown::showFromArray($myname, $values,\n ['value' => $value,\n 'display_emptychoice' => true]);", " } else {\n //TRANS: %s is the store path\n printf(__('Error reading directory %s'), $store_path);\n }", " } else {\n //TRANS: %s is the store path\n printf(__('Error: %s is not a directory'), $store_path);\n }\n if ($display) {\n echo $output;\n } else {\n return $output;\n }\n }", "\n /**\n * Dropdown for GMT selection\n *\n * @param string $name select name\n * @param mixed $value default value (default '')\n **/\n static function showGMT($name, $value = '') {", " $elements = [-12, -11, -10, -9, -8, -7, -6, -5, -4, -3.5, -3, -2, -1, 0,\n '+1', '+2', '+3', '+3.5', '+4', '+4.5', '+5', '+5.5', '+6', '+6.5', '+7',\n '+8', '+9', '+9.5', '+10', '+11', '+12', '+13'];", " $values = [];\n foreach ($elements as $element) {\n if ($element != 0) {\n $values[$element*HOUR_TIMESTAMP] = sprintf(__('%1$s %2$s'), __('GMT'),\n sprintf(_n('%s hour', '%s hours', $element),\n $element));\n } else {\n $display_value = __('GMT');\n $values[$element*HOUR_TIMESTAMP] = __('GMT');\n }\n }\n Dropdown::showFromArray($name, $values, ['value' => $value]);\n }", "\n /**\n * Make a select box for a boolean choice (Yes/No) or display a checkbox. Add a\n * 'use_checkbox' = true to the $params array to display a checkbox instead a select box\n *\n * @param string $name select name\n * @param mixed $value preselected value. (default 0)\n * @param integer $restrict_to allows to display only yes or no in the dropdown (default -1)\n * @param array $params Array of optional options (passed to showFromArray)\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showYesNo($name, $value = 0, $restrict_to = -1, $params = []) {", " if (!array_key_exists ('use_checkbox', $params)) {\n // TODO: switch to true when Html::showCheckbox() is validated\n $params['use_checkbox'] = false;\n }\n if ($params['use_checkbox']) {", " if (!empty($params['rand'])) {\n $rand = $params['rand'];\n } else {\n $rand = mt_rand();\n }", " $options = ['name' => $name,\n 'id' => Html::cleanId(\"dropdown_\".$name.$rand)];", " switch ($restrict_to) {\n case 0 :\n $options['checked'] = false;\n $options['readonly'] = true;\n break;", " case 1 :\n $options['checked'] = true;\n $options['readonly'] = true;\n break;", " default :\n $options['checked'] = ($value ? 1 : 0);\n $options['readonly'] = false;\n break;\n }", " $output = Html::getCheckbox($options);\n if (!isset($params['display']) || $params['display'] == 'true') {\n echo $output;\n return $rand;\n } else {\n return $output;\n }\n }", " if ($restrict_to != 0) {\n $options[0] = __('No');\n }", " if ($restrict_to != 1) {\n $options[1] = __('Yes');\n }", " $params['value'] = $value;\n $params['width'] = \"65px\";\n return self::showFromArray($name, $options, $params);\n }", "\n /**\n * Get Yes No string\n *\n * @param mixed $value Yes No value\n *\n * @return string\n **/\n static function getYesNo($value) {", " if ($value) {\n return __('Yes');\n }\n return __('No');\n }", "\n /**\n * Get the Device list name the user is allowed to edit\n *\n * @return array (group of dropdown) of array (itemtype => localized name)\n **/\n static function getDeviceItemTypes() {\n static $optgroup = null;", " if (!Session::haveRight('device', READ)) {\n return [];\n }", " if (is_null($optgroup)) {\n $devices = [];\n foreach (CommonDevice::getDeviceTypes() as $device_type) {\n $devices[$device_type] = $device_type::getTypeName(Session::getPluralNumber());\n }\n asort($devices);\n $optgroup = [_n('Component', 'Components', Session::getPluralNumber()) => $devices];\n }\n return $optgroup;\n }", "\n /**\n * Get the dropdown list name the user is allowed to edit\n *\n * @return array (group of dropdown) of array (itemtype => localized name)\n **/\n static function getStandardDropdownItemTypes() {\n static $optgroup = null;", " if (is_null($optgroup)) {\n $optgroup = [\n __('Common') => [\n 'Location' => null,\n 'State' => null,\n 'Manufacturer' => null,\n 'Blacklist' => null,\n 'BlacklistedMailContent' => null\n ],", " __('Assistance') => [\n 'ITILCategory' => null,\n 'TaskCategory' => null,\n 'TaskTemplate' => null,\n 'SolutionType' => null,\n 'SolutionTemplate' => null,\n 'RequestType' => null,\n 'ITILFollowupTemplate' => null,\n 'ProjectState' => null,\n 'ProjectType' => null,\n 'ProjectTaskType' => null,\n 'ProjectTaskTemplate' => null,\n 'PlanningExternalEventTemplate' => null,\n 'PlanningEventCategory' => null,\n ],", " _n('Type', 'Types', Session::getPluralNumber()) => [\n 'ComputerType' => null,\n 'NetworkEquipmentType' => null,\n 'PrinterType' => null,\n 'MonitorType' => null,\n 'PeripheralType' => null,\n 'PhoneType' => null,\n 'SoftwareLicenseType' => null,\n 'CartridgeItemType' => null,\n 'ConsumableItemType' => null,\n 'ContractType' => null,\n 'ContactType' => null,\n 'DeviceGenericType' => null,\n 'DeviceSensorType' => null,\n 'DeviceMemoryType' => null,\n 'SupplierType' => null,\n 'InterfaceType' => null,\n 'DeviceCaseType' => null,\n 'PhonePowerSupply' => null,\n 'Filesystem' => null,\n 'CertificateType' => null,\n 'BudgetType' => null,\n 'DeviceSimcardType' => null,\n 'LineType' => null,\n 'RackType' => null,\n 'PDUType' => null,\n 'PassiveDCEquipmentType' => null,\n 'ClusterType' => null,\n ],", " _n('Model', 'Models', 1) => [\n 'ComputerModel' => null,\n 'NetworkEquipmentModel' => null,\n 'PrinterModel' => null,\n 'MonitorModel' => null,\n 'PeripheralModel' => null,\n 'PhoneModel' => null,", " // Devices models :\n 'DeviceCaseModel' => null,\n 'DeviceControlModel' => null,\n 'DeviceDriveModel' => null,\n 'DeviceGenericModel' => null,\n 'DeviceGraphicCardModel' => null,\n 'DeviceHardDriveModel' => null,\n 'DeviceMemoryModel' => null,\n 'DeviceMotherBoardModel' => null,\n 'DeviceNetworkCardModel' => null,\n 'DevicePciModel' => null,\n 'DevicePowerSupplyModel' => null,\n 'DeviceProcessorModel' => null,\n 'DeviceSoundCardModel' => null,\n 'DeviceSensorModel' => null,\n 'RackModel' => null,\n 'EnclosureModel' => null,\n 'PDUModel' => null,\n 'PassiveDCEquipmentModel' => null,\n ],", " _n('Virtual machine', 'Virtual machines', Session::getPluralNumber()) => [\n 'VirtualMachineType' => null,\n 'VirtualMachineSystem' => null,\n 'VirtualMachineState' => null\n ],", " __('Management') => [\n 'DocumentCategory' => null,\n 'DocumentType' => null,\n 'BusinessCriticity' => null\n ],", " __('Tools') => [\n 'KnowbaseItemCategory' => null\n ],", " _n('Calendar', 'Calendars', 1) => [\n 'Calendar' => null,\n 'Holiday' => null\n ],", " OperatingSystem::getTypeName(Session::getPluralNumber()) => [\n 'OperatingSystem' => null,\n 'OperatingSystemVersion' => null,\n 'OperatingSystemServicePack' => null,\n 'OperatingSystemArchitecture' => null,\n 'OperatingSystemEdition' => null,\n 'OperatingSystemKernel' => null,\n 'OperatingSystemKernelVersion' => null,\n 'AutoUpdateSystem' => null\n ],", " __('Networking') => [\n 'NetworkInterface' => null,\n 'Netpoint' => null,\n 'Network' => null,\n 'Vlan' => null,\n 'LineOperator' => null,\n 'DomainType' => null,\n 'DomainRelation' => null,\n 'DomainRecordType' => null\n ],", " __('Internet') => [\n 'IPNetwork' => null,\n 'FQDN' => null,\n 'WifiNetwork' => null,\n 'NetworkName' => null\n ],", " _n('Software', 'Software', 1) => [\n 'SoftwareCategory' => null\n ],", " User::getTypeName(1) => [\n 'UserTitle' => null,\n 'UserCategory' => null\n ],", " __('Authorizations assignment rules') => [\n 'RuleRightParameter' => null\n ],", " __('Fields unicity') => [\n 'Fieldblacklist' => null\n ],", " __('External authentications') => [\n 'SsoVariable' => null\n ],\n __('Power management') => [\n 'Plug' => null\n ],\n __('Appliances') => [\n 'ApplianceType' => null,\n 'ApplianceEnvironment' => null\n ]", " ]; //end $opt", " $plugdrop = Plugin::getDropdowns();", " if (count($plugdrop)) {\n $optgroup = array_merge($optgroup, $plugdrop);\n }", " foreach ($optgroup as $label => &$dp) {\n foreach ($dp as $key => &$val) {\n if ($tmp = getItemForItemtype($key)) {\n if (!$tmp->canView()) {\n unset($optgroup[$label][$key]);\n } else if ($val === null) {\n $val = $key::getTypeName(Session::getPluralNumber());\n }\n } else {\n unset($optgroup[$label][$key]);\n }\n }", " if (count($optgroup[$label]) == 0) {\n unset($optgroup[$label]);\n }\n }\n }\n return $optgroup;\n }", "\n /**\n * Display a menu to select a itemtype which open the search form\n *\n * @param $title string title to display\n * @param $optgroup array (group of dropdown) of array (itemtype => localized name)\n * @param $value string URL of selected current value (default '')\n **/\n static function showItemTypeMenu($title, $optgroup, $value = '') {", " echo \"<table class='tab_cadre' width='50%'>\";\n echo \"<tr class='tab_bg_1'><td class='b'>&nbsp;\".$title.\"&nbsp; \";\n $selected = '';", " foreach ($optgroup as $label => $dp) {\n foreach ($dp as $key => $val) {\n $search = $key::getSearchURL();", " if (basename($search) == basename($value)) {\n $selected = $search;\n }\n $values[$label][$search] = $val;\n }\n }\n Dropdown::showFromArray('dpmenu', $values,\n ['on_change'\n => \"var _value = this.options[this.selectedIndex].value; if (_value != 0) {window.location.href=_value;}\",\n 'value' => $selected,\n 'display_emptychoice' => true]);", " echo \"</td></tr>\";\n echo \"</table><br>\";\n }", "\n /**\n * Display a list to select a itemtype with link to search form\n *\n * @param $optgroup array (group of dropdown) of array (itemtype => localized name)\n */\n static function showItemTypeList($optgroup) {", " echo \"<div id='list_nav'>\";\n $nb = 0;\n foreach ($optgroup as $label => $dp) {\n $nb += count($dp);\n }\n $step = ($nb > 15 ? ($nb/3) : $nb);\n echo \"<table class='tab_glpi'><tr class='top'><td width='33%' class='center'>\";\n echo \"<table class='tab_cadre'>\";\n $i = 1;", " foreach ($optgroup as $label => $dp) {\n echo \"<tr><th>$label</th></tr>\\n\";", " foreach ($dp as $key => $val) {\n $class=\"class='tab_bg_4'\";\n if (($itemtype = getItemForItemtype($key))\n && $itemtype->isEntityAssign()) {\n $class=\"class='tab_bg_2'\";\n }\n echo \"<tr $class><td><a href='\".$key::getSearchURL().\"'>\";\n echo \"$val</a></td></tr>\\n\";\n $i++;\n }", " if (($i >= $step) && ($i < $nb)) {\n echo \"</table></td><td width='25'>&nbsp;</td><td><table class='tab_cadre'>\";\n $step += $step;\n }\n }\n echo \"</table></td></tr></table></div>\";\n }", "\n /**\n * Dropdown available languages\n *\n * @param string $myname select name\n * @param array $options array of additionnal options:\n * - display_emptychoice : allow selection of no language\n * - emptylabel : specific string to empty label if display_emptychoice is true\n **/\n static function showLanguages($myname, $options = []) {\n $values = [];\n if (isset($options['display_emptychoice']) && ($options['display_emptychoice'])) {\n if (isset($options['emptylabel'])) {\n $values[''] = $options['emptylabel'];\n } else {\n $values[''] = self::EMPTY_VALUE;\n }\n unset($options['display_emptychoice']);\n }", " $values = array_merge($values, self::getLanguages());\n return self::showFromArray($myname, $values, $options);\n }", " /**\n * Get available languages\n *\n * @since 9.5.0\n *\n * @return array\n */\n public static function getLanguages() {\n global $CFG_GLPI;", " $languages = [];\n foreach ($CFG_GLPI[\"languages\"] as $key => $val) {\n if (isset($val[1]) && is_file(GLPI_ROOT .\"/locales/\".$val[1])) {\n $languages[$key] = $val[0];\n }\n }", " return $languages;\n }", "\n /**\n * @since 0.84\n *\n * @param $value\n **/\n static function getLanguageName($value) {\n global $CFG_GLPI;", " if (isset($CFG_GLPI[\"languages\"][$value][0])) {\n return $CFG_GLPI[\"languages\"][$value][0];\n }\n return $value;\n }", "\n /**\n * Print a select with hours\n *\n * Print a select named $name with hours options and selected value $value\n *\n *@param $name string HTML select name\n *@param $options array of options :\n * - value default value (default '')\n * - limit_planning limit planning to the configuration range (default false)\n * - display boolean if false get string\n * - width specific width needed (default auto adaptive)\n * - step step time (defaut config GLPI)\n *\n * @since 0.85 update prototype\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showHours($name, $options = []) {\n global $CFG_GLPI;", " $p['value'] = '';\n $p['limit_planning'] = false;\n $p['display'] = true;\n $p['width'] = '';\n $p['step'] = $CFG_GLPI[\"time_step\"];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " $begin = 0;\n $end = 24;\n // Check if the $step is Ok for the $value field\n $split = explode(\":\", $p['value']);", " // Valid value XX:YY ou XX:YY:ZZ\n if ((count($split) == 2) || (count($split) == 3)) {\n $min = $split[1];", " // Problem\n if (($min%$p['step']) != 0) {\n // set minimum step\n $p['step'] = 5;\n }\n }", " if ($p['limit_planning']) {\n $plan_begin = explode(\":\", $CFG_GLPI[\"planning_begin\"]);\n $plan_end = explode(\":\", $CFG_GLPI[\"planning_end\"]);\n $begin = (int) $plan_begin[0];\n $end = (int) $plan_end[0];\n }", " $values = [];\n $selected = '';", " for ($i=$begin; $i<$end; $i++) {\n if ($i < 10) {\n $tmp = \"0\".$i;\n } else {\n $tmp = $i;\n }", " for ($j=0; $j<60; $j+=$p['step']) {\n if ($j < 10) {\n $val = $tmp.\":0$j\";\n } else {\n $val = $tmp.\":$j\";\n }\n $values[$val] = $val;\n if (($p['value'] == $val.\":00\") || ($p['value'] == $val)) {\n $selected = $val;\n }\n }\n }\n // Last item\n $val = $end.\":00\";\n $values[$val] = $val;\n if (($p['value'] == $val.\":00\") || ($p['value'] == $val)) {\n $selected = $val;\n }\n $p['value'] = $selected;\n return Dropdown::showFromArray($name, $values, $p);\n }", "\n /**\n * show a dropdown to selec a type\n *\n * @since 0.83\n *\n * @param array|string $types Types used (default \"state_types\") (default '')\n * @param array $options Array of optional options\n * name, value, rand, emptylabel, display_emptychoice, on_change, plural, checkright\n * - toupdate : array / Update a specific item on select change on dropdown\n * (need value_fieldname, to_update,\n * url (see Ajax::updateItemOnSelectEvent for information)\n * and may have moreparams)\n *\n * @return integer rand for select id\n **/\n static function showItemType($types = '', $options = []) {\n global $CFG_GLPI;", " $params['name'] = 'itemtype';\n $params['value'] = '';\n $params['rand'] = mt_rand();\n $params['on_change'] = '';\n $params['plural'] = false;\n //Parameters about choice 0\n //Empty choice's label\n $params['emptylabel'] = self::EMPTY_VALUE;\n //Display emptychoice ?\n $params['display_emptychoice'] = true;\n $params['checkright'] = false;\n $params['toupdate'] = '';\n $params['display'] = true;", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " if (!is_array($types)) {\n $types = $CFG_GLPI[\"state_types\"];\n }\n $options = [];", " foreach ($types as $type) {\n if ($item = getItemForItemtype($type)) {\n if ($params['checkright'] && !$item->canView()) {\n continue;\n }\n $options[$type] = $item->getTypeName($params['plural'] ? 2 : 1);\n }\n }\n asort($options);", " if (count($options)) {\n return Dropdown::showFromArray($params['name'], $options, [\n 'value' => $params['value'],\n 'on_change' => $params['on_change'],\n 'toupdate' => $params['toupdate'],\n 'display_emptychoice' => $params['display_emptychoice'],\n 'emptylabel' => $params['emptylabel'],\n 'display' => $params['display'],\n 'rand' => $params['rand'],\n ]);\n }\n return 0;\n }", "\n /**\n * Make a select box for all items\n *\n * @since 0.85\n *\n * @param $options array:\n * - itemtype_name : the name of the field containing the itemtype (default 'itemtype')\n * - items_id_name : the name of the field containing the id of the selected item\n * (default 'items_id')\n * - itemtypes : all possible types to search for (default: $CFG_GLPI[\"state_types\"])\n * - default_itemtype : the default itemtype to select (don't define if you don't\n * need a default) (defaut 0)\n * - entity_restrict : restrict entity in searching items (default -1)\n * - onlyglobal : don't match item that don't have `is_global` == 1 (false by default)\n * - checkright : check to see if we can \"view\" the itemtype (false by default)\n * - showItemSpecificity : given an item, the AJAX file to open if there is special\n * treatment. For instance, select a Item_Device* for CommonDevice\n * - emptylabel : Empty choice's label (default self::EMPTY_VALUE)\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - display : true : display directly, false return the html\n *\n * @return integer randomized value used to generate HTML IDs\n **/\n static function showSelectItemFromItemtypes(array $options = []) {\n global $CFG_GLPI;", " $params = [];\n $params['itemtype_name'] = 'itemtype';\n $params['items_id_name'] = 'items_id';\n $params['itemtypes'] = '';\n $params['default_itemtype'] = 0;\n $params['entity_restrict'] = -1;\n $params['onlyglobal'] = false;\n $params['checkright'] = false;\n $params['showItemSpecificity'] = '';\n $params['emptylabel'] = self::EMPTY_VALUE;\n $params['used'] = [];\n $params['display'] = true;\n $params['rand'] = mt_rand();", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " $select = self::showItemType($params['itemtypes'], [\n 'checkright' => $params['checkright'],\n 'name' => $params['itemtype_name'],\n 'emptylabel' => $params['emptylabel'],\n 'display' => $params['display'],\n 'rand' => $params['rand'],\n ]);", " $p_ajax = [\n 'idtable' => '__VALUE__',\n 'name' => $params['items_id_name'],\n 'entity_restrict' => $params['entity_restrict'],\n 'showItemSpecificity' => $params['showItemSpecificity'],\n 'rand' => $params['rand']\n ];", " // manage condition\n if ($params['onlyglobal']) {\n $p_ajax['condition'] = static::addNewCondition(['is_global' => 1]);\n }\n if ($params['used']) {\n $p_ajax['used'] = $params['used'];\n }", " $field_id = Html::cleanId(\"dropdown_\".$params['itemtype_name'].$params['rand']);\n $show_id = Html::cleanId(\"show_\".$params['items_id_name'].$params['rand']);", " $ajax = Ajax::updateItemOnSelectEvent(\n $field_id,\n $show_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/dropdownAllItems.php\",\n $p_ajax,\n $params['display']\n );", " $out = \"\";\n if (!$params['display']) {\n $out.= $select.$ajax;\n }", " $out.= \"<br><span id='$show_id'>&nbsp;</span>\\n\";", " // We check $options as the caller will set $options['default_itemtype'] only if it needs a\n // default itemtype and the default value can be '' thus empty won't be valid !\n if (array_key_exists ('default_itemtype', $options)) {\n $out.= \"<script type='text/javascript' >\\n\";\n $out.= \"$(function() {\";\n $out.= Html::jsSetDropdownValue($field_id, $params['default_itemtype']);\n $out.= \"});</script>\\n\";", " $p_ajax[\"idtable\"] = $params['default_itemtype'];\n $ajax2 = Ajax::updateItem(\n $show_id,\n $CFG_GLPI[\"root_doc\"]. \"/ajax/dropdownAllItems.php\",\n $p_ajax,\n \"\",\n $params['display']\n );", " if (!$params['display']) {\n $out.= $ajax2;\n }\n }", " if ($params['display']) {\n echo $out;\n return $params['rand'];\n }", " return $out;\n }", "\n /**\n * Dropdown numbers\n *\n * @since 0.84\n *\n * @param string $myname select name\n * @param array $options array of additionnal options :\n * - value default value (default 0)\n * - rand random value\n * - min min value (default 0)\n * - max max value (default 100)\n * - step step used (default 1)\n * - toadd array of values to add at the beginning\n * - unit string unit to used\n * - display boolean if false get string\n * - width specific width needed (default 80%)\n * - on_change string / value to transmit to \"onChange\"\n * - used array / Already used items ID: not to display in dropdown (default empty)\n **/\n static function showNumber($myname, $options = []) {\n global $CFG_GLPI;", " $p = [\n 'value' => 0,\n 'rand' => mt_rand(),\n 'min' => 0,\n 'max' => 100,\n 'step' => 1,\n 'toadd' => [],\n 'unit' => '',\n 'display' => true,\n 'width' => '',\n 'on_change' => '',\n 'used' => [],\n 'specific_tags' => [],\n ];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }\n if (($p['value'] < $p['min']) && !isset($p['toadd'][$p['value']])) {\n $min = $p['min'];", " while (isset($p['used'][$min])) {\n ++$min;\n }\n $p['value'] = $min;\n }", " $field_id = Html::cleanId(\"dropdown_\".$myname.$p['rand']);\n if (!isset($p['toadd'][$p['value']])) {\n $valuename = self::getValueWithUnit($p['value'], $p['unit']);\n } else {\n $valuename = $p['toadd'][$p['value']];\n }\n $param = ['value' => $p['value'],\n 'valuename' => $valuename,\n 'width' => $p['width'],\n 'on_change' => $p['on_change'],\n 'used' => $p['used'],\n 'unit' => $p['unit'],\n 'min' => $p['min'],\n 'max' => $p['max'],\n 'step' => $p['step'],\n 'toadd' => $p['toadd'],\n 'specific_tags' => $p['specific_tags']];", " $out = Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownNumber.php\",\n $param);", " if ($p['display']) {\n echo $out;\n return $p['rand'];\n }\n return $out;\n }", "\n /**\n * Get value with unit / Automatic management of standar unit (year, month, %, ...)\n *\n * @since 0.84\n *\n * @param $value integer number of item\n * @param $unit string of unit (maybe year, month, day, hour, % for standard management)\n **/\n static function getValueWithUnit($value, $unit) {", " if (strlen($unit) == 0) {\n return $value;\n }", " switch ($unit) {\n case 'year' :\n //TRANS: %d is a number of years\n return sprintf(_n('%d year', '%d years', $value), $value);", " case 'month' :\n //TRANS: %d is a number of months\n return sprintf(_n('%d month', '%d months', $value), $value);", " case 'day' :\n //TRANS: %d is a number of days\n return sprintf(_n('%d day', '%d days', $value), $value);", " case 'hour' :\n //TRANS: %d is a number of hours\n return sprintf(_n('%d hour', '%d hours', $value), $value);", " case 'minute' :\n //TRANS: %d is a number of minutes\n return sprintf(_n('%d minute', '%d minutes', $value), $value);", " case 'second' :\n //TRANS: %d is a number of seconds\n return sprintf(_n('%d second', '%d seconds', $value), $value);", " case 'millisecond' :\n //TRANS: %d is a number of milliseconds\n return sprintf(_n('%d millisecond', '%d milliseconds', $value), $value);", " case 'auto':\n $value = str_replace([' ', '&nbsp;'], ['', ''], $value); // unformat value\n return Toolbox::getSize($value*1024*1024);", " case '%' :\n return sprintf(__('%d%%'), $value);", " default :\n return sprintf(__('%1$s %2$s'), $value, $unit);\n }\n }", "\n /**\n * Dropdown integers\n *\n * @since 0.83\n *\n * @param string $myname select name\n * @param array $options array of options\n * - value : default value\n * - min : min value : default 0\n * - max : max value : default DAY_TIMESTAMP\n * - value : default value\n * - addfirstminutes : add first minutes before first step (default false)\n * - toadd : array of values to add\n * - inhours : only show timestamp in hours not in days\n * - display : boolean / display or return string\n * - width : string / display width of the item\n **/\n static function showTimeStamp($myname, $options = []) {\n global $CFG_GLPI;", " $params['value'] = 0;\n $params['rand'] = mt_rand();\n $params['min'] = 0;\n $params['max'] = DAY_TIMESTAMP;\n $params['step'] = $CFG_GLPI[\"time_step\"]*MINUTE_TIMESTAMP;\n $params['emptylabel'] = self::EMPTY_VALUE;\n $params['addfirstminutes'] = false;\n $params['toadd'] = [];\n $params['inhours'] = false;\n $params['display'] = true;\n $params['display_emptychoice'] = true;\n $params['width'] = '80%';", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $params[$key] = $val;\n }\n }", " // Manage min :\n $params['min'] = floor($params['min']/$params['step'])*$params['step'];", " if ($params['min'] == 0) {\n $params['min'] = $params['step'];\n }", " $params['max'] = max($params['value'], $params['max']);", " // Floor with MINUTE_TIMESTAMP for rounded purpose\n if (empty($params['value'])) {\n $params['value'] = 0;\n }\n if (($params['value'] < max($params['min'], 10*MINUTE_TIMESTAMP))\n && $params['addfirstminutes']) {\n $params['value'] = floor(($params['value'])/MINUTE_TIMESTAMP)*MINUTE_TIMESTAMP;\n } else if (!in_array($params['value'], $params['toadd'])) {\n // Round to a valid step except if value is already valid (defined in values to add)\n $params['value'] = floor(($params['value'])/$params['step'])*$params['step'];\n }", " $values = [];", " if ($params['value']) {\n $values[$params['value']] = '';\n }", " if ($params['addfirstminutes']) {\n $max = max($params['min'], 10*MINUTE_TIMESTAMP);\n for ($i=MINUTE_TIMESTAMP; $i < $max; $i+=MINUTE_TIMESTAMP) {\n $values[$i] = '';\n }\n }", " for ($i = $params['min']; $i <= $params['max']; $i+=$params['step']) {\n $values[$i] = '';\n }", " if (count($params['toadd'])) {\n foreach ($params['toadd'] as $key) {\n $values[$key] = '';\n }\n ksort($values);\n }", " foreach ($values as $i => $val) {\n if (empty($val)) {\n if ($params['inhours']) {\n $day = 0;\n $hour = floor($i/HOUR_TIMESTAMP);\n } else {\n $day = floor($i/DAY_TIMESTAMP);\n $hour = floor(($i%DAY_TIMESTAMP)/HOUR_TIMESTAMP);\n }\n $minute = floor(($i%HOUR_TIMESTAMP)/MINUTE_TIMESTAMP);\n if ($minute === '0') {\n $minute = '00';\n }\n $values[$i] = '';\n if ($day > 0) {\n if (($hour > 0) || ($minute > 0)) {\n if ($minute < 10) {\n $minute = '0'.$minute;\n }", " //TRANS: %1$d is the number of days, %2$d the number of hours,\n // %3$s the number of minutes : display 1 day 3h15\n $values[$i] = sprintf(_n('%1$d day %2$dh%3$s', '%1$d days %2$dh%3$s', $day),\n $day, $hour, $minute);\n } else {\n $values[$i] = sprintf(_n('%d day', '%d days', $day), $day);\n }", " } else if ($hour > 0 || $minute > 0) {\n if ($minute < 10) {\n $minute = '0'.$minute;\n }", " //TRANS: %1$d the number of hours, %2$s the number of minutes : display 3h15\n $values[$i] = sprintf(__('%1$dh%2$s'), $hour, $minute);\n }\n }\n }\n return Dropdown::showFromArray($myname, $values,\n ['value' => $params['value'],\n 'display' => $params['display'],\n 'width' => $params['width'],\n 'display_emptychoice' => $params['display_emptychoice'],\n 'rand' => $params['rand'],\n 'emptylabel' => $params['emptylabel']]);\n }", "\n /**\n * Toggle view in LDAP user import/synchro between no restriction and date restriction\n *\n * @param $enabled (default 0)\n **/\n static function showAdvanceDateRestrictionSwitch($enabled = 0) {\n global $CFG_GLPI;", " $rand = mt_rand();\n $url = $CFG_GLPI[\"root_doc\"].\"/ajax/ldapdaterestriction.php\";\n echo \"<script type='text/javascript' >\\n\";\n echo \"function activateRestriction() {\\n\";\n $params = ['enabled'=> 1];\n Ajax::updateItemJsCode('date_restriction', $url, $params);\n echo \"};\";", " echo \"function deactivateRestriction() {\\n\";\n $params = ['enabled' => 0];\n Ajax::updateItemJsCode('date_restriction', $url, $params);\n echo \"};\";\n echo \"</script>\";", " echo \"</table>\";\n echo \"<span id='date_restriction'>\";\n $_POST['enabled'] = $enabled;\n include (GLPI_ROOT.\"/ajax/ldapdaterestriction.php\");\n echo \"</span>\\n\";\n return $rand;\n }", "\n /**\n * Dropdown of values in an array\n *\n * @param string $name select name\n * @param array $elements array of elements to display\n * @param array $options array of possible options:\n * - value : integer / preselected value (default 0)\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - readonly : boolean / used as a readonly item (default false)\n * - on_change : string / value to transmit to \"onChange\"\n * - multiple : boolean / can select several values (default false)\n * - size : integer / number of rows for the select (default = 1)\n * - display : boolean / display or return string\n * - other : boolean or string if not false, then we can use an \"other\" value\n * if it is a string, then the default value will be this string\n * - rand : specific rand if needed (default is generated one)\n * - width : specific width needed (default not set)\n * - emptylabel : empty label if empty displayed (default self::EMPTY_VALUE)\n * - display_emptychoice : display empty choice, cannot be used when \"multiple\" option set to true (default false)\n * - class : class attributes to add\n * - tooltip : string / message to add as tooltip on the dropdown (default '')\n * - option_tooltips : array / message to add as tooltip on the dropdown options. Use the same keys as for the $elements parameter, but none is mandotary. Missing keys will just be ignored and no tooltip will be added. To add a tooltip on an option group, is the '__optgroup_label' key inside the array describing option tooltips : 'optgroupname1' => array('__optgroup_label' => 'tooltip for option group') (default empty)\n * - noselect2 : if true, don't use select2 lib\n *\n * Permit to use optgroup defining items in arrays\n * array('optgroupname' => array('key1' => 'val1',\n * 'key2' => 'val2'),\n * 'optgroupname2' => array('key3' => 'val3',\n * 'key4' => 'val4'))\n *\n * @return integer|string\n * integer if option display=true (random part of elements id)\n * string if option display=false (HTML code)\n **/\n static function showFromArray($name, array $elements, $options = []) {", " $param['value'] = '';\n $param['values'] = [''];\n $param['class'] = '';\n $param['tooltip'] = '';\n $param['option_tooltips'] = [];\n $param['used'] = [];\n $param['readonly'] = false;\n $param['on_change'] = '';\n $param['width'] = '';\n $param['multiple'] = false;\n $param['size'] = 1;\n $param['display'] = true;\n $param['other'] = false;\n $param['rand'] = mt_rand();\n $param['emptylabel'] = self::EMPTY_VALUE;\n $param['display_emptychoice'] = false;\n $param['disabled'] = false;\n $param['noselect2'] = false;", " if (is_array($options) && count($options)) {\n if (isset($options['value']) && strlen($options['value'])) {\n $options['values'] = [$options['value']];\n unset($options['value']);\n }\n foreach ($options as $key => $val) {\n $param[$key] = $val;\n }\n }", " if ($param['other'] !== false) {\n $other_select_option = $name . '_other_value';\n $param['on_change'] .= \"displayOtherSelectOptions(this, \\\"$other_select_option\\\");\";", " // If $param['other'] is a string, then we must highlight \"other\" option\n if (is_string($param['other'])) {\n if (!$param[\"multiple\"]) {\n $param['values'] = [$other_select_option];\n } else {\n $param['values'][] = $other_select_option;\n }\n }\n }", " $param['option_tooltips'] = Html::entities_deep($param['option_tooltips']);", " if ($param[\"display_emptychoice\"] && !$param[\"multiple\"]) {\n $elements = [ 0 => $param['emptylabel'] ] + $elements;\n }", " if ($param[\"multiple\"]) {\n $field_name = $name.\"[]\";\n } else {\n $field_name = $name;\n }", " $output = '';\n // readonly mode\n $field_id = Html::cleanId(\"dropdown_\".$name.$param['rand']);\n if ($param['readonly']) {\n $to_display = [];\n foreach ($param['values'] as $value) {\n $output .= \"<input type='hidden' name='$field_name' value='$value'>\";\n if (isset($elements[$value])) {\n $to_display[] = $elements[$value];\n }\n }\n $output .= implode('<br>', $to_display);\n } else {", " $output .= \"<select name='$field_name' id='$field_id'\";", " if ($param['tooltip']) {\n $output .= ' title=\"'.Html::entities_deep($param['tooltip']).'\"';\n }", " if ($param['class']) {\n $output .= ' class=\"'.Html::entities_deep($param['class']).'\"';\n }", " if (!empty($param[\"on_change\"])) {\n $output .= \" onChange='\".$param[\"on_change\"].\"'\";\n }", " if ((is_int($param[\"size\"])) && ($param[\"size\"] > 0)) {\n $output .= \" size='\".$param[\"size\"].\"'\";\n }", " if ($param[\"multiple\"]) {\n $output .= \" multiple\";\n }", " if ($param[\"disabled\"]) {\n $output .= \" disabled='disabled'\";\n }", " $output .= '>';\n $max_option_size = 0;\n foreach ($elements as $key => $val) {\n // optgroup management\n if (is_array($val)) {\n $opt_goup = Html::entities_deep($key);\n if ($max_option_size < strlen($opt_goup)) {\n $max_option_size = strlen($opt_goup);\n }", " $output .= \"<optgroup label=\\\"$opt_goup\\\"\";\n $optgroup_tooltips = false;\n if (isset($param['option_tooltips'][$key])) {\n if (is_array($param['option_tooltips'][$key])) {\n if (isset($param['option_tooltips'][$key]['__optgroup_label'])) {\n $output .= ' title=\"'.$param['option_tooltips'][$key]['__optgroup_label'].'\"';\n }\n $optgroup_tooltips = $param['option_tooltips'][$key];\n } else {\n $output .= ' title=\"'.$param['option_tooltips'][$key].'\"';\n }\n }\n $output .= \">\";", " foreach ($val as $key2 => $val2) {\n if (!isset($param['used'][$key2])) {\n $output .= \"<option value='\".$key2.\"'\";\n // Do not use in_array : trouble with 0 and empty value\n foreach ($param['values'] as $value) {\n if (strcmp($key2, $value) === 0) {\n $output .= \" selected\";\n break;\n }\n }\n if ($optgroup_tooltips && isset($optgroup_tooltips[$key2])) {\n $output .= ' title=\"'.$optgroup_tooltips[$key2].'\"';\n }\n $output .= \">\" . $val2 . \"</option>\";\n if ($max_option_size < strlen($val2)) {\n $max_option_size = strlen($val2);\n }\n }\n }\n $output .= \"</optgroup>\";\n } else {\n if (!isset($param['used'][$key])) {\n $output .= \"<option value='\".Html::entities_deep($key).\"'\";\n // Do not use in_array : trouble with 0 and empty value\n foreach ($param['values'] as $value) {\n if (strcmp($key, $value)===0) {\n $output .= \" selected\";\n break;\n }\n }\n if (isset($param['option_tooltips'][$key])) {\n $output .= ' title=\"'.$param['option_tooltips'][$key].'\"';\n }\n $output .= \">\" .$val . \"</option>\";\n if ($max_option_size < strlen($val)) {\n $max_option_size = strlen($val);\n }\n }\n }\n }", " if ($param['other'] !== false) {\n $output .= \"<option value='$other_select_option'\";\n if (is_string($param['other'])) {\n $output .= \" selected\";\n }\n $output .= \">\".__('Other...').\"</option>\";\n }", " $output .= \"</select>\";\n if ($param['other'] !== false) {\n $output .= \"<input name='$other_select_option' id='$other_select_option' type='text'\";\n if (is_string($param['other'])) {\n $output .= \" value=\\\"\" . $param['other'] . \"\\\"\";\n } else {\n $output .= \" style=\\\"display: none\\\"\";\n }\n $output .= \">\";\n }\n }", " if (!$param['noselect2']) {\n // Width set on select\n $output .= Html::jsAdaptDropdown($field_id, ['width' => $param[\"width\"]]);\n }", " if ($param[\"multiple\"]) {\n // Hack for All / None because select2 does not provide it\n $select = __('All');\n $deselect = __('None');\n $output .= \"<div class='invisible' id='selectallbuttons_$field_id'>\";\n $output .= \"<div class='select2-actionable-menu'>\";\n $output .= \"<a class='vsubmit' \".\n \"onclick=\\\"selectAll('$field_id');$('#$field_id').select2('close');\\\">$select\".\n \"</a> \";\n $output .= \"<a class='vsubmit floatright' onclick=\\\"deselectAll('$field_id');\\\">$deselect\".\n \"</a>\";\n $output .= \"</div></div>\";", " $js = \"\n var multichecksappend$field_id = false;\n $('#$field_id').on('select2:open', function(e) {\n if (!multichecksappend$field_id) {\n $('#select2-$field_id-results').parent().append($('#selectallbuttons_$field_id').html());\n multichecksappend$field_id = true;\n }\n });\";\n $output .= Html::scriptBlock($js);\n }\n $output .= Ajax::commonDropdownUpdateItem($param, false);", " if ($param['display']) {\n echo $output;\n return $param['rand'];\n }\n return $output;\n }", "\n /**\n * Dropdown for global item management\n *\n * @param integer $ID item ID\n * @param array attrs array which contains the extra paramters\n *\n * Parameters can be :\n * - target target for actions\n * - withtemplate template or basic computer\n * - value value of global state\n * - management_restrict global management restrict mode\n **/\n static function showGlobalSwitch($ID, $attrs = []) {\n $params['management_restrict'] = 0;\n $params['value'] = 0;\n $params['name'] = 'is_global';\n $params['target'] = '';", " foreach ($attrs as $key => $value) {\n if ($value != '') {\n $params[$key] = $value;\n }\n }", " if ($params['value']\n && empty($params['withtemplate'])) {\n echo __('Global management');", " if ($params['management_restrict'] == 2) {\n echo \"&nbsp;\";\n Html::showSimpleForm($params['target'], 'unglobalize', __('Use unitary management'),\n ['id' => $ID], '', '',\n [__('Do you really want to use unitary management for this item?'),\n __('Duplicate the element as many times as there are connections')]);\n echo \"&nbsp;\";", " echo \"<span class='fa fa-info pointer'\".\n \" title=\\\"\".__s('Duplicate the element as many times as there are connections').\n \"\\\"><span class='sr-only'>\". __s('Duplicate the element as many times as there are connections') . \"</span></span>\";\n }", " } else {\n if ($params['management_restrict'] == 2) {\n $rand = mt_rand();\n $values = [MANAGEMENT_UNITARY => __('Unit management'),\n MANAGEMENT_GLOBAL => __('Global management')];\n Dropdown::showFromArray($params['name'], $values, ['value' => $params['value']]);\n } else {\n // Templates edition\n if (!empty($params['withtemplate'])) {\n echo \"<input type='hidden' name='is_global' value='\".\n $params['management_restrict'].\"'>\";\n echo (!$params['management_restrict']?__('Unit management') :__('Global management'));\n } else {\n echo (!$params['value']?__('Unit management'):__('Global management'));\n }\n }\n }\n }", "\n /**\n * Import a dropdown - check if already exists\n *\n * @param string $itemtype name of the class\n * @param array $input of value to import\n *\n * @return boolean|integer ID of the new item or false on error\n **/\n static function import($itemtype, $input) {", " if (!($item = getItemForItemtype($itemtype))) {\n return false;\n }\n return $item->import($input);\n }", "\n /**\n * Import a value in a dropdown table.\n *\n * This import a new dropdown if it doesn't exist - Play dictionnary if needed\n *\n * @param string $itemtype name of the class\n * @param string $value Value of the new dropdown.\n * @param integer $entities_id entity in case of specific dropdown\n * @param array $external_params\n * @param string $comment\n * @param boolean $add if true, add it if not found. if false, just check if exists\n *\n * @return integer : dropdown id.\n **/\n static function importExternal($itemtype, $value, $entities_id = -1, $external_params = [],\n $comment = '', $add = true) {", " if (!($item = getItemForItemtype($itemtype))) {\n return false;\n }\n return $item->importExternal($value, $entities_id, $external_params, $comment, $add);\n }", " /**\n * Get the label associated with a management type\n *\n * @param integer value the type of management (default 0)\n *\n * @return string the label corresponding to it, or \"\"\n **/\n static function getGlobalSwitch($value = 0) {", " switch ($value) {\n case 0 :\n return __('Unit management');", " case 1 :\n return __('Global management');", " default :\n return \"\";\n }\n }", "\n /**\n * show dropdown for output format\n *\n * @since 0.83\n **/\n static function showOutputFormat() {\n $values[Search::PDF_OUTPUT_LANDSCAPE] = __('Current page in landscape PDF');\n $values[Search::PDF_OUTPUT_PORTRAIT] = __('Current page in portrait PDF');\n $values[Search::SYLK_OUTPUT] = __('Current page in SLK');\n $values[Search::CSV_OUTPUT] = __('Current page in CSV');\n $values['-'.Search::PDF_OUTPUT_LANDSCAPE] = __('All pages in landscape PDF');\n $values['-'.Search::PDF_OUTPUT_PORTRAIT] = __('All pages in portrait PDF');\n $values['-'.Search::SYLK_OUTPUT] = __('All pages in SLK');\n $values['-'.Search::CSV_OUTPUT] = __('All pages in CSV');", " Dropdown::showFromArray('display_type', $values);\n echo \"<button type='submit' name='export' class='unstyled pointer' \".\n \" title=\\\"\" . _sx('button', 'Export') . \"\\\">\" .\n \"<i class='far fa-save'></i><span class='sr-only'>\"._sx('button', 'Export').\"<span>\";\n }", "\n /**\n * show dropdown to select list limit\n *\n * @since 0.83\n *\n * @param string $onchange Optional, for ajax (default '')\n **/\n static function showListLimit($onchange = '', $display = true) {\n global $CFG_GLPI;", " if (isset($_SESSION['glpilist_limit'])) {\n $list_limit = $_SESSION['glpilist_limit'];\n } else {\n $list_limit = $CFG_GLPI['list_limit'];\n }", " $values = [];", " for ($i=5; $i<20; $i+=5) {\n $values[$i] = $i;\n }\n for ($i=20; $i<50; $i+=10) {\n $values[$i] = $i;\n }\n for ($i=50; $i<250; $i+=50) {\n $values[$i] = $i;\n }\n for ($i=250; $i<1000; $i+=250) {\n $values[$i] = $i;\n }\n for ($i=1000; $i<5000; $i+=1000) {\n $values[$i] = $i;\n }\n for ($i=5000; $i<=10000; $i+=5000) {\n $values[$i] = $i;\n }\n $values[9999999] = 9999999;\n // Propose max input vars -10\n $max = Toolbox::get_max_input_vars();\n if ($max > 10) {\n $values[$max-10] = $max-10;\n }\n ksort($values);\n return self::showFromArray('glpilist_limit', $values,\n ['on_change' => $onchange,\n 'value' => $list_limit,\n 'display' => $display]);\n }", " /**\n * Get dropdown value\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownValue($post, $json = true) {\n global $DB, $CFG_GLPI;\n", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post)) {\n return;\n }\n", " if (isset($post[\"entity_restrict\"])\n && !is_array($post[\"entity_restrict\"])\n && (substr($post[\"entity_restrict\"], 0, 1) === '[')\n && (substr($post[\"entity_restrict\"], -1) === ']')) {\n $decoded = Toolbox::jsonDecode($post['entity_restrict']);\n $entities = [];\n if (is_array($decoded)) {\n foreach ($decoded as $value) {\n $entities[] = (int)$value;\n }\n }\n $post[\"entity_restrict\"] = $entities;\n }\n if (isset($post['entity_restrict']) && 'default' === $post['entity_restrict']) {\n $post['entity_restrict'] = $_SESSION['glpiactiveentities'];", "", " }", " // Security\n if (!($item = getItemForItemtype($post['itemtype']))) {\n return;\n }", " $table = $item->getTable();\n $datas = [];", " $displaywith = false;\n if (isset($post['displaywith'])) {\n if (is_array($post['displaywith']) && count($post['displaywith'])) {\n $table = getTableForItemType($post['itemtype']);\n foreach ($post['displaywith'] as $key => $value) {\n if (!$DB->fieldExists($table, $value)) {\n unset($post['displaywith'][$key]);\n }\n }\n if (count($post['displaywith'])) {\n $displaywith = true;\n }\n }\n }", " if (!isset($post['permit_select_parent'])) {\n $post['permit_select_parent'] = false;\n }", " if (isset($post['condition']) && !empty($post['condition']) && !is_array($post['condition'])) {\n // Retreive conditions from SESSION using its key\n $key = $post['condition'];\n if (isset($_SESSION['glpicondition']) && isset($_SESSION['glpicondition'][$key])) {\n $post['condition'] = $_SESSION['glpicondition'][$key];\n } else {\n $post['condition'] = [];\n }\n }", " if (!isset($post['emptylabel']) || ($post['emptylabel'] == '')) {\n $post['emptylabel'] = Dropdown::EMPTY_VALUE;\n }", " $where = [];", " if ($item->maybeDeleted()) {\n $where[\"$table.is_deleted\"] = 0;\n }\n if ($item->maybeTemplate()) {\n $where[\"$table.is_template\"] = 0;\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " if (isset($post['used'])) {\n $used = $post['used'];", " if (count($used)) {\n $where['NOT'] = [\"$table.id\" => $used];\n }\n }", " if (isset($post['toadd'])) {\n $toadd = $post['toadd'];\n } else {\n $toadd = [];\n }", " if (isset($post['condition']) && ($post['condition'] != '')) {\n $where = array_merge($where, $post['condition']);\n }", " $one_item = -1;\n if (isset($post['_one_id'])) {\n $one_item = $post['_one_id'];\n }", " // Count real items returned\n $count = 0;", " if ($item instanceof CommonTreeDropdown) {\n if ($one_item >= 0) {\n $where[\"$table.id\"] = $one_item;\n } else {\n if (!empty($post['searchText'])) {\n $search = Search::makeTextSearchValue($post['searchText']);", " $swhere = [\n \"$table.completename\" => ['LIKE', $search],\n ];\n if (Session::haveTranslations($post['itemtype'], 'completename')) {\n $swhere[\"namet.value\"] = ['LIKE', $search];\n }", " if ($_SESSION['glpiis_ids_visible']\n && is_numeric($post['searchText']) && (int)$post['searchText'] == $post['searchText']) {\n $swhere[$table . '.' . $item->getIndexName()] = ['LIKE', \"%{$post['searchText']}%\"];\n }", " // search also in displaywith columns\n if ($displaywith && count($post['displaywith'])) {\n foreach ($post['displaywith'] as $with) {\n $swhere[\"$table.$with\"] = ['LIKE', $search];\n }\n }", " $where[] = ['OR' => $swhere];\n }\n }", " $multi = false;", " // Manage multiple Entities dropdowns\n $order = [\"$table.completename\"];", " // No multi if get one item\n if ($item->isEntityAssign()) {\n $recur = $item->maybeRecursive();", " // Entities are not really recursive : do not display parents\n if ($post['itemtype'] == 'Entity') {\n $recur = false;\n }", " if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria(\n $table,\n '',\n $post[\"entity_restrict\"],\n $recur\n );", " if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }\n } else {\n // If private item do not use entity\n if (!$item->maybePrivate()) {\n $where = $where + getEntitiesRestrictCriteria($table, '', '', $recur);", " if (count($_SESSION['glpiactiveentities']) > 1) {\n $multi = true;\n }\n } else {\n $multi = false;\n }\n }", " // Force recursive items to multi entity view\n if ($recur) {\n $multi = true;\n }", " // no multi view for entitites\n if ($post['itemtype'] == \"Entity\") {\n $multi = false;\n }", " if ($multi) {\n array_unshift($order, \"$table.entities_id\");\n }\n }", " $addselect = [];\n $ljoin = [];\n if (Session::haveTranslations($post['itemtype'], 'completename')) {\n $addselect[] = \"namet.value AS transcompletename\";\n $ljoin['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => $post['itemtype'],\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => 'completename'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'name')) {\n $addselect[] = \"namet2.value AS transname\";\n $ljoin['glpi_dropdowntranslations AS namet2'] = [\n 'ON' => [\n 'namet2' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet2.itemtype' => $post['itemtype'],\n 'namet2.language' => $_SESSION['glpilanguage'],\n 'namet2.field' => 'name'\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'comment')) {\n $addselect[] = \"commentt.value AS transcomment\";\n $ljoin['glpi_dropdowntranslations AS commentt'] = [\n 'ON' => [\n 'commentt' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'commentt.itemtype' => $post['itemtype'],\n 'commentt.language' => $_SESSION['glpilanguage'],\n 'commentt.field' => 'comment'\n ]\n ]\n ]\n ];\n }", " if ($start > 0 && $multi) {\n //we want to load last entry of previous page\n //(and therefore one more result) to check if\n //entity name must be displayed again\n --$start;\n ++$limit;\n }", " $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'FROM' => $table,\n 'WHERE' => $where,\n 'ORDER' => $order,\n 'START' => $start,\n 'LIMIT' => $limit\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n $iterator = $DB->request($criteria);", " // Empty search text : display first\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if ($post['display_emptychoice']) {\n $datas[] = [\n 'id' => 0,\n 'text' => $post['emptylabel']\n ];\n }\n }", " if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $datas[] = [\n 'id' => $key,\n 'text' => stripslashes($val)\n ];\n }\n }\n }\n $last_level_displayed = [];\n $datastoadd = [];", " // Ignore first item for all pages except first page\n $firstitem = (($post['page'] > 1));\n if (count($iterator)) {\n $prev = -1;\n $firstitem_entity = -1;", " while ($data = $iterator->next()) {\n $ID = $data['id'];\n $level = $data['level'];", " if (isset($data['transname']) && !empty($data['transname'])) {\n $outputval = $data['transname'];\n } else {\n $outputval = $data['name'];\n }", " if ($multi\n && ($data[\"entities_id\"] != $prev)) {\n // Do not do it for first item for next page load\n if (!$firstitem) {\n if ($prev >= 0) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n }\n }\n $prev = $data[\"entities_id\"];\n if ($firstitem) {\n $firstitem_entity = $prev;\n }\n // Reset last level displayed :\n $datastoadd = [];\n }", " if ($_SESSION['glpiuse_flat_dropdowntree']) {\n if (isset($data['transcompletename']) && !empty($data['transcompletename'])) {\n $outputval = $data['transcompletename'];\n } else {\n $outputval = $data['completename'];\n }\n $level = 0;\n } else { // Need to check if parent is the good one\n // Do not do if only get one item\n if (($level > 1)) {\n // Last parent is not the good one need to display arbo\n if (!isset($last_level_displayed[$level-1])\n || ($last_level_displayed[$level-1] != $data[$item->getForeignKeyField()])) {", " $work_level = $level-1;\n $work_parentID = $data[$item->getForeignKeyField()];\n $parent_datas = [];\n do {\n // Get parent\n if ($item->getFromDB($work_parentID)) {\n // Do not do for first item for next page load\n if (!$firstitem) {\n $title = $item->fields['completename'];", " $selection_text = $title;", " if (isset($item->fields[\"comment\"])) {\n $addcomment\n = DropdownTranslation::getTranslatedValue($ID, $post['itemtype'],\n 'comment',\n $_SESSION['glpilanguage'],\n $item->fields['comment']);\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n $output2 = DropdownTranslation::getTranslatedValue($item->fields['id'],\n $post['itemtype'],\n 'name',\n $_SESSION['glpilanguage'],\n $item->fields['name']);", " $temp = ['id' => $work_parentID,\n 'text' => $output2,\n 'level' => (int)$work_level,\n 'disabled' => true];\n if ($post['permit_select_parent']) {\n $temp['title'] = $title;\n $temp['selection_text'] = $selection_text;\n unset($temp['disabled']);\n }\n array_unshift($parent_datas, $temp);\n }\n $last_level_displayed[$work_level] = $item->fields['id'];\n $work_level--;\n $work_parentID = $item->fields[$item->getForeignKeyField()];", " } else { // Error getting item : stop\n $work_level = -1;\n }", " } while (($work_level >= 1)\n && (!isset($last_level_displayed[$work_level])\n || ($last_level_displayed[$work_level] != $work_parentID)));\n // Add parents\n foreach ($parent_datas as $val) {\n $datastoadd[] = $val;\n }\n }\n }\n $last_level_displayed[$level] = $data['id'];\n }", " // Do not do for first item for next page load\n if (!$firstitem) {\n if ($_SESSION[\"glpiis_ids_visible\"]\n || (Toolbox::strlen($outputval) == 0)) {\n $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);\n }", " if (isset($data['transcompletename']) && !empty($data['transcompletename'])) {\n $title = $data['transcompletename'];\n } else {\n $title = $data['completename'];\n }", " $selection_text = $title;", " if (isset($data[\"comment\"])) {\n if (isset($data['transcomment']) && !empty($data['transcomment'])) {\n $addcomment = $data['transcomment'];\n } else {\n $addcomment = $data['comment'];\n }\n $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n $datastoadd[] = [\n 'id' => $ID,\n 'text' => $outputval,\n 'level' => (int)$level,\n 'title' => $title,\n 'selection_text' => $selection_text\n ];\n $count++;\n }\n $firstitem = false;\n }\n }", " if ($multi) {\n if (count($datastoadd)) {\n // On paging mode do not add entity information each time\n if ($prev == $firstitem_entity) {\n $datas = array_merge($datas, $datastoadd);\n } else {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n }\n } else {\n if (count($datastoadd)) {\n $datas = array_merge($datas, $datastoadd);\n }\n }\n } else { // Not a dropdowntree\n $multi = false;\n // No multi if get one item\n if ($item->isEntityAssign()) {\n $multi = $item->maybeRecursive();", " if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria(\n $table,\n \"entities_id\",\n $post[\"entity_restrict\"],\n $multi\n );", " if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }", " } else {\n // Do not use entity if may be private\n if (!$item->maybePrivate()) {\n $where = $where + getEntitiesRestrictCriteria($table, '', '', $multi);", " if (count($_SESSION['glpiactiveentities'])>1) {\n $multi = true;\n }\n } else {\n $multi = false;\n }\n }\n }", " $field = \"name\";\n if ($item instanceof CommonDevice) {\n $field = \"designation\";\n } else if ($item instanceof Item_Devices) {\n $field = \"itemtype\";\n }", " if (!empty($post['searchText'])) {\n $search = Search::makeTextSearchValue($post['searchText']);\n $orwhere = [\"$table.$field\" => ['LIKE', $search]];", " if ($_SESSION['glpiis_ids_visible']\n && is_numeric($post['searchText']) && (int)$post['searchText'] == $post['searchText']) {\n $orwhere[$table . '.' . $item->getIndexName()] = ['LIKE', \"%{$post['searchText']}%\"];\n }", " if ($item instanceof CommonDCModelDropdown) {\n $orwhere[$table . '.product_number'] = ['LIKE', $search];\n }", " if (Session::haveTranslations($post['itemtype'], $field)) {\n $orwhere['namet.value'] = ['LIKE', $search];\n }\n if ($post['itemtype'] == \"SoftwareLicense\") {\n $orwhere['glpi_softwares.name'] = ['LIKE', $search];\n }", " // search also in displaywith columns\n if ($displaywith && count($post['displaywith'])) {\n foreach ($post['displaywith'] as $with) {\n $orwhere[\"$table.$with\"] = ['LIKE', $search];\n }\n }", " $where[] = ['OR' => $orwhere];\n }\n $addselect = [];\n $ljoin = [];\n if (Session::haveTranslations($post['itemtype'], $field)) {\n $addselect[] = \"namet.value AS transname\";\n $ljoin['glpi_dropdowntranslations AS namet'] = [\n 'ON' => [\n 'namet' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'namet.itemtype' => $post['itemtype'],\n 'namet.language' => $_SESSION['glpilanguage'],\n 'namet.field' => $field\n ]\n ]\n ]\n ];\n }\n if (Session::haveTranslations($post['itemtype'], 'comment')) {\n $addselect[] = \"commentt.value AS transcomment\";\n $ljoin['glpi_dropdowntranslations AS commentt'] = [\n 'ON' => [\n 'commentt' => 'items_id',\n $table => 'id', [\n 'AND' => [\n 'commentt.itemtype' => $post['itemtype'],\n 'commentt.language' => $_SESSION['glpilanguage'],\n 'commentt.field' => 'comment'\n ]\n ]\n ]\n ];\n }", " $criteria = [];\n switch ($post['itemtype']) {\n case \"Contact\" :\n $criteria = [\n 'SELECT' => [\n \"$table.entities_id\",\n new \\QueryExpression(\n \"CONCAT(IFNULL(\" . $DB->quoteName('name') . \",''),' ',IFNULL(\" .\n $DB->quoteName('firstname') . \",'')) AS \" . $DB->quoteName($field)\n ),\n \"$table.comment\",\n \"$table.id\"\n ],\n 'FROM' => $table\n ];\n break;", " case \"SoftwareLicense\" :\n $criteria = [\n 'SELECT' => [\n \"$table.*\",\n new \\QueryExpression(\"CONCAT(glpi_softwares.name,' - ',glpi_softwarelicenses.name) AS $field\")\n ],\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_softwares' => [\n 'ON' => [\n 'glpi_softwarelicenses' => 'softwares_id',\n 'glpi_softwares' => 'id'\n ]\n ]\n ]\n ];\n break;", " case \"Profile\" :\n $criteria = [\n 'SELECT' => \"$table.*\",\n 'DISTINCT' => true,\n 'FROM' => $table,\n 'LEFT JOIN' => [\n 'glpi_profilerights' => [\n 'ON' => [\n 'glpi_profilerights' => 'profiles_id',\n $table => 'id'\n ]\n ]\n ]\n ];\n break;", " case KnowbaseItem::getType():\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'DISTINCT' => true,\n 'FROM' => $table\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }", " $visibility = KnowbaseItem::getVisibilityCriteria();\n if (count($visibility['LEFT JOIN'])) {\n $criteria['LEFT JOIN'] = array_merge(\n (isset($criteria['LEFT JOIN']) ? $criteria['LEFT JOIN'] : []),\n $visibility['LEFT JOIN']\n );\n //Do not use where??\n /*if (isset($visibility['WHERE'])) {\n $where = $visibility['WHERE'];\n }*/\n }\n break;", " case Project::getType():\n $visibility = Project::getVisibilityCriteria();\n if (count($visibility['LEFT JOIN'])) {\n $ljoin = array_merge($ljoin, $visibility['LEFT JOIN']);\n if (isset($visibility['WHERE'])) {\n $where[] = $visibility['WHERE'];\n }\n }\n //no break to reach default case.", " default :\n $criteria = [\n 'SELECT' => array_merge([\"$table.*\"], $addselect),\n 'FROM' => $table\n ];\n if (count($ljoin)) {\n $criteria['LEFT JOIN'] = $ljoin;\n }\n }", " $criteria = array_merge(\n $criteria, [\n 'WHERE' => $where,\n 'START' => $start,\n 'LIMIT' => $limit\n ]\n );", " if ($multi) {\n $criteria['ORDERBY'] = [\"$table.entities_id\", \"$table.$field\"];\n } else {\n $criteria['ORDERBY'] = [\"$table.$field\"];\n }", " $iterator = $DB->request($criteria);", " // Display first if no search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if (!isset($post['display_emptychoice']) || $post['display_emptychoice']) {\n $datas[] = [\n 'id' => 0,\n 'text' => $post[\"emptylabel\"]\n ];\n }\n }\n if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $datas[] = [\n 'id' => $key,\n 'text' => stripslashes($val)\n ];\n }\n }\n }", " $datastoadd = [];", " if (count($iterator)) {\n $prev = -1;", " while ($data = $iterator->next()) {\n if ($multi\n && ($data[\"entities_id\"] != $prev)) {\n if ($prev >= 0) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n }\n $prev = $data[\"entities_id\"];\n $datastoadd = [];\n }", " if (isset($data['transname']) && !empty($data['transname'])) {\n $outputval = $data['transname'];\n } else if ($field == 'itemtype' && class_exists($data['itemtype'])) {\n $tmpitem = new $data[$field]();\n if ($tmpitem->getFromDB($data['items_id'])) {\n $outputval = sprintf(__('%1$s - %2$s'), $tmpitem->getTypeName(), $tmpitem->getName());\n } else {\n $outputval = $tmpitem->getTypeName();\n }\n } else if ($item instanceof CommonDCModelDropdown) {\n $outputval =sprintf(__('%1$s - %2$s'), $data[$field], $data['product_number']);\n } else {\n $outputval = $data[$field];\n }", " $ID = $data['id'];\n $addcomment = \"\";\n $title = $outputval;\n if (isset($data[\"comment\"])) {\n if (isset($data['transcomment']) && !empty($data['transcomment'])) {\n $addcomment .= $data['transcomment'];\n } else {\n $addcomment .= $data[\"comment\"];\n }", " $title = sprintf(__('%1$s - %2$s'), $title, $addcomment);\n }\n if ($_SESSION[\"glpiis_ids_visible\"]\n || (strlen($outputval) == 0)) {\n //TRANS: %1$s is the name, %2$s the ID\n $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);\n }\n if ($displaywith) {\n foreach ($post['displaywith'] as $key) {\n if (isset($data[$key])) {\n $withoutput = $data[$key];\n if (isForeignKeyField($key)) {\n $withoutput = Dropdown::getDropdownName(getTableNameForForeignKeyField($key),\n $data[$key]);\n }\n if ((strlen($withoutput) > 0) && ($withoutput != '&nbsp;')) {\n $outputval = sprintf(__('%1$s - %2$s'), $outputval, $withoutput);\n }\n }\n }\n }\n $datastoadd[] = [\n 'id' => $ID,\n 'text' => $outputval,\n 'title' => $title\n ];\n $count++;\n }\n if ($multi) {\n if (count($datastoadd)) {\n $datas[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datastoadd\n ];\n }\n } else {\n if (count($datastoadd)) {\n $datas = array_merge($datas, $datastoadd);\n }\n }\n }\n }", " $ret['results'] = Toolbox::unclean_cross_side_scripting_deep($datas);\n $ret['count'] = $count;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown connect\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownConnect($post, $json = true) {\n global $DB, $CFG_GLPI;", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post)) {\n return;\n }", " if (!isset($post['fromtype']) || !($fromitem = getItemForItemtype($post['fromtype']))) {\n return;\n }", " $fromitem->checkGlobal(UPDATE);\n $used = [];\n if (isset( $post[\"used\"])) {\n $used = $post[\"used\"];", " if (isset($used[$post['itemtype']])) {\n $used = $used[$post['itemtype']];\n } else {\n $used = [];\n }\n }", " // Make a select box\n $table = getTableForItemType($post[\"itemtype\"]);\n if (!$item = getItemForItemtype($post['itemtype'])) {\n return;\n }", " $where = [];", " if ($item->maybeDeleted()) {\n $where[\"$table.is_deleted\"] = 0;\n }\n if ($item->maybeTemplate()) {\n $where[\"$table.is_template\"] = 0;\n }", " if (isset($post['searchText']) && (strlen($post['searchText']) > 0)) {\n $search = Search::makeTextSearchValue($post['searchText']);\n $where['OR'] = [\n \"$table.name\" => ['LIKE', $search],\n \"$table.otherserial\" => ['LIKE', $search],\n \"$table.serial\" => ['LIKE', $search]\n ];\n }", " $multi = $item->maybeRecursive();", " if (isset($post[\"entity_restrict\"]) && !($post[\"entity_restrict\"] < 0)) {\n $where = $where + getEntitiesRestrictCriteria($table, '', $post[\"entity_restrict\"], $multi);\n if (is_array($post[\"entity_restrict\"]) && (count($post[\"entity_restrict\"]) > 1)) {\n $multi = true;\n }", " } else {\n $where = $where + getEntitiesRestrictCriteria($table, '', $_SESSION['glpiactiveentities'], $multi);\n if (count($_SESSION['glpiactiveentities']) > 1) {\n $multi = true;\n }\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " if (!isset($post['onlyglobal'])) {\n $post['onlyglobal'] = false;\n }", " if ($post[\"onlyglobal\"]\n && ($post[\"itemtype\"] != 'Computer')) {\n $where[\"$table.is_global\"] = 1;\n } else {\n $where_used = [];\n if (!empty($used)) {\n $where_used[] = ['NOT' => [\"$table.id\" => $used]];\n }", " if ($post[\"itemtype\"] == 'Computer') {\n $where = $where + $where_used;\n } else {\n $where[] = [\n 'OR' => [\n [\n 'glpi_computers_items.id' => null\n ] + $where_used,\n \"$table.is_global\" => 1\n ]\n ];\n }\n }", " $criteria = [\n 'SELECT' => [\n \"$table.id\",\n \"$table.name AS name\",\n \"$table.serial AS serial\",\n \"$table.otherserial AS otherserial\",\n \"$table.entities_id AS entities_id\"\n ],\n 'DISTINCT' => true,\n 'FROM' => $table,\n 'WHERE' => $where,\n 'ORDERBY' => ['entities_id', 'name ASC'],\n 'LIMIT' => $limit,\n 'START' => $start\n ];", " if (($post[\"itemtype\"] != 'Computer') && !$post[\"onlyglobal\"]) {\n $criteria['LEFT JOIN'] = [\n 'glpi_computers_items' => [\n 'ON' => [\n $table => 'id',\n 'glpi_computers_items' => 'items_id', [\n 'AND' => [\n 'glpi_computers_items.itemtype' => $post['itemtype']\n ]\n ]\n ]\n ]\n ];\n }", " $iterator = $DB->request($criteria);", " $results = [];\n // Display first if no search\n if (empty($post['searchText'])) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n }\n if (count($iterator)) {\n $prev = -1;\n $datatoadd = [];", " while ($data = $iterator->next()) {\n if ($multi && ($data[\"entities_id\"] != $prev)) {\n if (count($datatoadd)) {\n $results[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datatoadd\n ];\n }\n $prev = $data[\"entities_id\"];\n // Reset last level displayed :\n $datatoadd = [];\n }\n $output = $data['name'];\n $ID = $data['id'];", " if ($_SESSION[\"glpiis_ids_visible\"]\n || empty($output)) {\n $output = sprintf(__('%1$s (%2$s)'), $output, $ID);\n }\n if (!empty($data['serial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data[\"serial\"]);\n }\n if (!empty($data['otherserial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data[\"otherserial\"]);\n }\n $datatoadd[] = [\n 'id' => $ID,\n 'text' => $output\n ];\n }", " if ($multi) {\n if (count($datatoadd)) {\n $results[] = [\n 'text' => Dropdown::getDropdownName(\"glpi_entities\", $prev),\n 'children' => $datatoadd\n ];\n }\n } else {\n if (count($datatoadd)) {\n $results = array_merge($results, $datatoadd);\n }\n }\n }", " $ret['results'] = $results;\n return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown find num\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownFindNum($post, $json = true) {\n global $DB, $CFG_GLPI;", " // Security\n if (!$DB->tableExists($post['table'])) {\n return;\n }", " $itemtypeisplugin = isPluginItemType($post['itemtype']);", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post)) {\n return;\n }", " if (!$item = getItemForItemtype($post['itemtype'])) {\n return;\n }", " $where = [];\n if (isset($post['used']) && !empty($post['used'])) {\n $where['NOT'] = ['id' => $post['used']];\n }", " if ($item->maybeDeleted()) {\n $where['is_deleted'] = 0;\n }", " if ($item->maybeTemplate()) {\n $where['is_template'] = 0;\n }", " if (isset($_POST['searchText']) && (strlen($post['searchText']) > 0)) {\n $search = ['LIKE', Search::makeTextSearchValue($post['searchText'])];\n $orwhere =[\n 'name' => $search,\n 'id' => $post['searchText']\n ];", " if ($DB->fieldExists($post['table'], \"contact\")) {\n $orwhere['contact'] = $search;\n }\n if ($DB->fieldExists($post['table'], \"serial\")) {\n $orwhere['serial'] = $search;\n }\n if ($DB->fieldExists($post['table'], \"otherserial\")) {\n $orwhere['otherserial'] = $search;\n }\n $where[] = ['OR' => $orwhere];\n }", " // If software or plugins : filter to display only the objects that are allowed to be visible in Helpdesk\n $filterHelpdesk = in_array($post['itemtype'], $CFG_GLPI[\"helpdesk_visible_types\"]);", " if (isset($post['context'])\n && $post['context'] == \"impact\"\n && Impact::isEnabled($post['itemtype'])\n ) {\n $filterHelpdesk = false;\n }", " if ($filterHelpdesk) {\n $where['is_helpdesk_visible'] = 1;\n }", " if ($item->isEntityAssign()) {\n if (isset($post[\"entity_restrict\"]) && ($post[\"entity_restrict\"] >= 0)) {\n $entity = $post[\"entity_restrict\"];\n } else {\n $entity = '';\n }", " // allow opening ticket on recursive object (printer, software, ...)\n $recursive = $item->maybeRecursive();\n $where = $where + getEntitiesRestrictCriteria($post['table'], '', $entity, $recursive);\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " $iterator = $DB->request([\n 'FROM' => $post['table'],\n 'WHERE' => $where,\n 'ORDER' => $item->getNameField(),\n 'LIMIT' => $limit,\n 'START' => $start\n ]);", " $results = [];", " // Display first if no search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n }\n $count = 0;\n if (count($iterator)) {\n while ($data = $iterator->next()) {\n $output = $data[$item->getNameField()];", " if (isset($data['contact']) && !empty($data['contact'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data['contact']);\n }\n if (isset($data['serial']) && !empty($data['serial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);\n }\n if (isset($data['otherserial']) && !empty($data['otherserial'])) {\n $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);\n }", " if (empty($output)\n || $_SESSION['glpiis_ids_visible']) {\n $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);\n }", " $results[] = [\n 'id' => $data['id'],\n 'text' => $output\n ];\n $count++;\n }\n }", " $ret['count'] = $count;\n $ret['results'] = $results;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown netpoint\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownNetpoint($post, $json = true) {\n global $DB, $CFG_GLPI;", " // Make a select box with preselected values\n $results = [];\n $location_restrict = false;", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $limit = intval($post['page_limit']);", " $criteria = [\n 'SELECT' => [\n 'glpi_netpoints.comment AS comment',\n 'glpi_netpoints.id',\n 'glpi_netpoints.name AS netpname',\n 'glpi_locations.completename AS loc'\n ],\n 'FROM' => 'glpi_netpoints',\n 'LEFT JOIN' => [\n 'glpi_locations' => [\n 'ON' => [\n 'glpi_netpoints' => 'locations_id',\n 'glpi_locations' => 'id'\n ]\n ]\n ],\n 'WHERE' => [],\n 'ORDERBY' => [\n 'glpi_locations.completename',\n 'glpi_netpoints.name'\n ],\n 'START' => $start,\n 'LIMIT' => $limit\n ];", " if (!(isset($post[\"devtype\"])\n && ($post[\"devtype\"] != 'NetworkEquipment')\n && isset($post[\"locations_id\"])\n && ($post[\"locations_id\"] > 0))) {", " if (isset($post[\"entity_restrict\"]) && ($post[\"entity_restrict\"] >= 0)) {\n $criteria['WHERE']['glpi_netpoints.entities_id'] = $post['entity_restrict'];\n } else {\n $criteria['WHERE'] = $criteria['WHERE'] + getEntitiesRestrictCriteria('glpi_locations');\n }\n }", " if (isset($post['searchText']) && strlen($post['searchText']) > 0) {\n $criteria['WHERE']['OR'] = [\n 'glpi_netpoints.name' => ['LIKE', Search::makeTextSearchValue($post['searchText'])],\n 'glpi_locations.completename' => ['LIKE', Search::makeTextSearchValue($post['searchText'])]\n ];\n }", " if (isset($post[\"devtype\"]) && !empty($post[\"devtype\"])) {\n $criteria['LEFT JOIN']['glpi_networkportethernets'] = [\n 'ON' => [\n 'glpi_networkportethernets' => 'netpoints_id',\n 'glpi_netpoints' => 'id'\n ]\n ];", " $extra_and = [];\n if ($post[\"devtype\"] == 'NetworkEquipment') {\n $extra_and['glpi_networkports.itemtype'] = 'NetworkEquipment';\n } else {\n $extra_and['NOT'] = ['glpi_networkports.itemtype' => 'NetworkEquipment'];\n if (isset($post[\"locations_id\"]) && ($post[\"locations_id\"] >= 0)) {\n $location_restrict = true;\n $criteria['WHERE']['glpi_netpoints.locations_id'] = $post['locations_id'];\n }\n }", " $criteria['LEFT JOIN']['glpi_networkports'] = [\n 'ON' => [\n 'glpi_networkportethernets' => 'id',\n 'glpi_networkports' => 'id', [\n 'AND' => [\n 'glpi_networkports.instantiation_type' => 'NetworkPortEthernet',\n ] + $extra_and\n ]\n ]\n ];\n $criteria['WHERE']['glpi_networkportethernets.netpoints_id'] = null;\n } else if (isset($post[\"locations_id\"]) && ($post[\"locations_id\"] >= 0)) {\n $location_restrict = true;\n $criteria['WHERE']['glpi_netpoints.locations_id'] = $post['locations_id'];\n }", " $iterator = $DB->request($criteria);", " // Display first if no search\n if (empty($post['searchText'])) {\n if ($post['page'] == 1) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n }\n }", " $count = 0;\n if (count($iterator)) {\n while ($data = $iterator->next()) {\n $output = $data['netpname'];\n $loc = $data['loc'];\n $ID = $data['id'];\n $title = $output;\n if (isset($data[\"comment\"])) {\n //TRANS: %1$s is the location, %2$s is the comment\n $title = sprintf(__('%1$s - %2$s'), $title, $loc);\n $title = sprintf(__('%1$s - %2$s'), $title, $data[\"comment\"]);\n }\n if (!$location_restrict) {\n $output = sprintf(__('%1$s (%2$s)'), $output, $loc);\n }", " $results[] = [\n 'id' => $ID,\n 'text' => $output,\n 'title' => $title\n ];\n $count++;\n }\n }", " $ret['count'] = $count;\n $ret['results'] = $results;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown number\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownNumber($post, $json = true) {\n global $CFG_GLPI;", " $used = [];", " if (isset($post['used'])) {\n $used = $post['used'];\n }", " if (!isset($post['value'])) {\n $post['value'] = 0;\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " if (isset($post['toadd'])) {\n $toadd = $post['toadd'];\n } else {\n $toadd = [];\n }", " $data = [];\n // Count real items returned\n $count = 0;", " if ($post['page'] == 1) {\n if (count($toadd)) {\n foreach ($toadd as $key => $val) {\n $data[] = ['id' => $key,\n 'text' => (string)stripslashes($val)];\n }\n }\n }", " $values = [];", " if (!isset($post['min'])) {\n $post['min'] = 1;\n }", " if (!isset($post['step'])) {\n $post['step'] = 1;\n }", " if (!isset($post['max'])) {\n //limit max entries to avoid loop issues\n $post['max'] = $CFG_GLPI['dropdown_max'] * $post['step'];\n }", " for ($i=$post['min']; $i<=$post['max']; $i+=$post['step']) {\n if (!empty($post['searchText']) && strstr($i, $post['searchText']) || empty($post['searchText'])) {\n if (!in_array($i, $used)) {\n $values[\"$i\"] = $i;\n }\n }\n }", " if (count($values)) {\n $start = ($post['page']-1)*$post['page_limit'];\n $tosend = array_splice($values, $start, $post['page_limit']);\n foreach ($tosend as $i) {\n $txt = $i;\n if (isset($post['unit'])) {\n $txt = Dropdown::getValueWithUnit($i, $post['unit']);\n }\n $data[] = ['id' => $i,\n 'text' => (string)$txt];\n $count++;\n }", " } else {\n if (!isset($toadd[-1])) {\n $value = -1;\n if (isset($post['min']) && $value < $post['min']) {\n $value = $post['min'];\n } else if (isset($post['max']) && $value > $post['max']) {\n $value = $post['max'];\n }", " if (isset($post['unit'])) {\n $txt = Dropdown::getValueWithUnit($value, $post['unit']);\n }\n $data[] = [\n 'id' => $value,\n 'text' => (string)stripslashes($txt)\n ];\n $count++;\n }\n }", " $ret['results'] = $data;\n $ret['count'] = $count;", " return ($json === true) ? json_encode($ret) : $ret;\n }", " /**\n * Get dropdown users\n *\n * @param array $post Posted values\n * @param boolean $json Encode to JSON, default to true\n *\n * @return string|array\n */\n public static function getDropdownUsers($post, $json = true) {\n global $CFG_GLPI;", " // check if asked itemtype is the one originaly requested by the form\n if (!Session::validateIDOR($post + ['itemtype' => 'User', 'right' => ($post['right'] ?? \"\")])) {\n return;\n }", " if (!isset($post['right'])) {\n $post['right'] = \"all\";\n }", " // Default view : Nobody\n if (!isset($post['all'])) {\n $post['all'] = 0;\n }", " $used = [];", " if (isset($post['used'])) {\n $used = $post['used'];\n }", " if (!isset($post['value'])) {\n $post['value'] = 0;\n }", " if (!isset($post['page'])) {\n $post['page'] = 1;\n $post['page_limit'] = $CFG_GLPI['dropdown_max'];\n }", " $entity_restrict = -1;\n if (isset($post['entity_restrict'])) {\n $entity_restrict = Toolbox::jsonDecode($post['entity_restrict']);\n }", " $start = intval(($post['page']-1)*$post['page_limit']);\n $searchText = (isset($post['searchText']) ? $post['searchText'] : null);\n $inactive_deleted = isset($post['inactive_deleted']) ? $post['inactive_deleted'] : 0;\n $result = User::getSqlSearchResult(\n false,\n $post['right'],\n $entity_restrict,\n $post['value'],\n $used,\n $searchText,\n $start,\n (int)$post['page_limit'],\n $inactive_deleted\n );", " $users = [];", " // Count real items returned\n $count = 0;\n if (count($result)) {\n while ($data = $result->next()) {\n $users[$data[\"id\"]] = formatUserName($data[\"id\"], $data[\"name\"], $data[\"realname\"],\n $data[\"firstname\"]);\n $logins[$data[\"id\"]] = $data[\"name\"];\n }\n }", " $results = [];", " // Display first if empty search\n if ($post['page'] == 1 && empty($post['searchText'])) {\n if ($post['all'] == 0) {\n $results[] = [\n 'id' => 0,\n 'text' => Dropdown::EMPTY_VALUE\n ];\n } else if ($post['all'] == 1) {\n $results[] = [\n 'id' => 0,\n 'text' => __('All')\n ];\n }\n }", " if (count($users)) {\n foreach ($users as $ID => $output) {\n $title = sprintf(__('%1$s - %2$s'), $output, $logins[$ID]);", " $results[] = [\n 'id' => $ID,\n 'text' => $output,\n 'title' => $title\n ];\n $count++;\n }\n }", " $ret['results'] = $results;\n $ret['count'] = $count;", " return ($json === true) ? json_encode($ret) : $ret;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access this file directly\");\n}", "use Sabre\\VObject;\nuse Glpi\\Exception\\ForgetPasswordException;\nuse Glpi\\Exception\\PasswordTooWeakException;", "class User extends CommonDBTM {", " // From CommonDBTM\n public $dohistory = true;\n public $history_blacklist = ['date_mod', 'date_sync', 'last_login',\n 'publicbookmarkorder', 'privatebookmarkorder'];", " // NAME FIRSTNAME ORDER TYPE\n const REALNAME_BEFORE = 0;\n const FIRSTNAME_BEFORE = 1;", " const IMPORTEXTAUTHUSERS = 1024;\n const READAUTHENT = 2048;\n const UPDATEAUTHENT = 4096;", " static $rightname = 'user';", " static $undisclosedFields = [\n 'password',\n 'personal_token',\n 'api_token',\n 'cookie_token',\n ];", " private $entities = null;", "\n static function getTypeName($nb = 0) {\n return _n('User', 'Users', $nb);\n }", " static function getMenuShorcut() {\n return 'u';\n }", " static function getAdditionalMenuOptions() {", " if (Session::haveRight('user', self::IMPORTEXTAUTHUSERS)) {\n return [\n 'ldap' => [\n 'title' => AuthLDAP::getTypeName(Session::getPluralNumber()),\n 'page' => '/front/ldap.php',\n ],\n ];\n }\n return false;\n }", "\n function canViewItem() {\n if (Session::canViewAllEntities()\n || Session::haveAccessToOneOfEntities($this->getEntities())) {\n return true;\n }\n return false;\n }", "\n function canCreateItem() {", " // Will be created from form, with selected entity/profile\n if (isset($this->input['_profiles_id']) && ($this->input['_profiles_id'] > 0)\n && Profile::currentUserHaveMoreRightThan([$this->input['_profiles_id']])\n && isset($this->input['_entities_id'])\n && Session::haveAccessToEntity($this->input['_entities_id'])) {\n return true;\n }\n // Will be created with default value\n if (Session::haveAccessToEntity(0) // Access to root entity (required when no default profile)\n || (Profile::getDefault() > 0)) {\n return true;\n }", " if (($_SESSION['glpiactive_entity'] > 0)\n && (Profile::getDefault() == 0)) {\n echo \"<div class='tab_cadre_fixe warning'>\".\n __('You must define a default profile to create a new user').\"</div>\";\n }", " return false;\n }", "\n function canUpdateItem() {", " $entities = Profile_User::getUserEntities($this->fields['id'], false);\n if (Session::canViewAllEntities()\n || Session::haveAccessToOneOfEntities($entities)) {\n return true;\n }\n return false;\n }", "\n function canDeleteItem() {\n if (Session::canViewAllEntities()\n || Session::haveAccessToAllOfEntities($this->getEntities())) {\n return true;\n }\n return false;\n }", "\n function canPurgeItem() {\n return $this->canDeleteItem();\n }", "\n function isEntityAssign() {\n // glpi_users.entities_id is only a pref.\n return false;\n }", "\n /**\n * Compute preferences for the current user mixing config and user data.\n *\n * @return void\n */\n function computePreferences() {\n global $CFG_GLPI;", " if (isset($this->fields['id'])) {\n foreach ($CFG_GLPI['user_pref_field'] as $f) {\n if (is_null($this->fields[$f])) {\n $this->fields[$f] = $CFG_GLPI[$f];\n }\n }\n }\n /// Specific case for show_count_on_tabs : global config can forbid\n if ($CFG_GLPI['show_count_on_tabs'] == -1) {\n $this->fields['show_count_on_tabs'] = 0;\n }\n }", "\n /**\n * Load minimal session for user.\n *\n * @param integer $entities_id Entity to use\n * @param boolean $is_recursive Whether to load entities recursivly or not\n *\n * @return void\n *\n * @since 0.83.7\n */\n function loadMinimalSession($entities_id, $is_recursive) {\n global $CFG_GLPI;", " if (isset($this->fields['id']) && !isset($_SESSION[\"glpiID\"])) {\n Session::destroy();\n Session::start();\n $_SESSION[\"glpiID\"] = $this->fields['id'];\n $_SESSION[\"glpi_use_mode\"] = Session::NORMAL_MODE;\n Session::loadEntity($entities_id, $is_recursive);\n $this->computePreferences();\n foreach ($CFG_GLPI['user_pref_field'] as $field) {\n if (isset($this->fields[$field])) {\n $_SESSION[\"glpi$field\"] = $this->fields[$field];\n }\n }\n Session::loadGroups();\n Session::loadLanguage();\n }\n }", "\n function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {", " switch ($item->getType()) {\n case __CLASS__ :\n $ong = [];\n $ong[1] = __('Used items');\n $ong[2] = __('Managed items');\n return $ong;", " case 'Preference' :\n return __('Main');\n }\n return '';\n }", "\n static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {\n global $CFG_GLPI;", " switch ($item->getType()) {\n case __CLASS__ :\n $item->showItems($tabnum==2);\n return true;", " case 'Preference' :\n $user = new self();\n $user->showMyForm($CFG_GLPI['root_doc'].\"/front/preference.php\",\n Session::getLoginUserID());\n return true;\n }\n return false;\n }", "\n function defineTabs($options = []) {", " $ong = [];\n $this->addDefaultFormTab($ong);\n $this->addImpactTab($ong, $options);\n $this->addStandardTab('Profile_User', $ong, $options);\n $this->addStandardTab('Group_User', $ong, $options);\n $this->addStandardTab('Config', $ong, $options);\n $this->addStandardTab(__CLASS__, $ong, $options);\n $this->addStandardTab('Ticket', $ong, $options);\n $this->addStandardTab('Item_Problem', $ong, $options);\n $this->addStandardTab('Change_Item', $ong, $options);\n $this->addStandardTab('Document_Item', $ong, $options);\n $this->addStandardTab('Reservation', $ong, $options);\n $this->addStandardTab('Auth', $ong, $options);\n $this->addStandardTab('Link', $ong, $options);\n $this->addStandardTab('Certificate_Item', $ong, $options);\n $this->addStandardTab('Log', $ong, $options);", " return $ong;\n }", "\n function post_getEmpty() {\n global $CFG_GLPI;", " $this->fields[\"is_active\"] = 1;\n if (isset($CFG_GLPI[\"language\"])) {\n $this->fields['language'] = $CFG_GLPI[\"language\"];\n } else {\n $this->fields['language'] = \"en_GB\";\n }\n }", "\n function pre_deleteItem() {\n global $DB;", " $entities = $this->getEntities();\n $view_all = Session::canViewAllEntities();\n // Have right on all entities ?\n $all = true;\n if (!$view_all) {\n foreach ($entities as $ent) {\n if (!Session::haveAccessToEntity($ent)) {\n $all = false;\n }\n }\n }\n if ($all) { // Mark as deleted\n return true;\n }\n // only delete profile\n foreach ($entities as $ent) {\n if (Session::haveAccessToEntity($ent)) {\n $all = false;\n $DB->delete(\n 'glpi_profiles_users', [\n 'users_id' => $this->fields['id'],\n 'entities_id' => $ent\n ]\n );\n }\n return false;\n }\n }", "\n function cleanDBonPurge() {", " global $DB;", " // ObjectLock does not extends CommonDBConnexity\n $ol = new ObjectLock();\n $ol->deleteByCriteria(['users_id' => $this->fields['id']]);", " // Reminder does not extends CommonDBConnexity\n $r = new Reminder();\n $r->deleteByCriteria(['users_id' => $this->fields['id']]);", " // Delete private bookmark\n $ss = new SavedSearch();\n $ss->deleteByCriteria(\n [\n 'users_id' => $this->fields['id'],\n 'is_private' => 1,\n ]\n );", " // Set no user to public bookmark\n $DB->update(\n SavedSearch::getTable(), [\n 'users_id' => 0\n ], [\n 'users_id' => $this->fields['id']\n ]\n );", " // Set no user to consumables\n $DB->update(\n 'glpi_consumables', [\n 'items_id' => 0,\n 'itemtype' => 'NULL',\n 'date_out' => 'NULL'\n ], [\n 'items_id' => $this->fields['id'],\n 'itemtype' => 'User'\n ]\n );", " $this->deleteChildrenAndRelationsFromDb(\n [\n Certificate_Item::class,\n Change_User::class,\n Group_User::class,\n KnowbaseItem_User::class,\n Problem_User::class,\n Profile_User::class,\n ProjectTaskTeam::class,\n ProjectTeam::class,\n Reminder_User::class,\n RSSFeed_User::class,\n SavedSearch_User::class,\n Ticket_User::class,\n UserEmail::class,\n ]\n );", " if ($this->fields['id'] > 0) { // Security\n // DisplayPreference does not extends CommonDBConnexity\n $dp = new DisplayPreference();\n $dp->deleteByCriteria(['users_id' => $this->fields['id']]);\n }", " $this->dropPictureFiles($this->fields['picture']);", " // Ticket rules use various _users_id_*\n Rule::cleanForItemAction($this, '_users_id%');\n Rule::cleanForItemCriteria($this, '_users_id%');", " // Alert does not extends CommonDBConnexity\n $alert = new Alert();\n $alert->cleanDBonItemDelete($this->getType(), $this->fields['id']);\n }", "\n /**\n * Retrieve a user from the database using its login.\n *\n * @param string $name Login of the user\n *\n * @return boolean\n */\n function getFromDBbyName($name) {\n return $this->getFromDBByCrit(['name' => $name]);\n }", " /**\n * Retrieve a user from the database using its login.\n *\n * @param string $name Login of the user\n * @param integer $authtype Auth type (see Auth constants)\n * @param integer $auths_id ID of auth server\n *\n * @return boolean\n */\n function getFromDBbyNameAndAuth($name, $authtype, $auths_id) {\n return $this->getFromDBByCrit([\n 'name' => $name,\n 'authtype' => $authtype,\n 'auths_id' => $auths_id\n ]);\n }", " /**\n * Retrieve a user from the database using value of the sync field.\n *\n * @param string $value Value of the sync field\n *\n * @return boolean\n */\n function getFromDBbySyncField($value) {\n return $this->getFromDBByCrit(['sync_field' => $value]);\n }", " /**\n * Retrieve a user from the database using it's dn.\n *\n * @since 0.84\n *\n * @param string $user_dn dn of the user\n *\n * @return boolean\n */\n function getFromDBbyDn($user_dn) {\n return $this->getFromDBByCrit(['user_dn' => $user_dn]);\n }", "\n /**\n * Retrieve a user from the database using its email.\n *\n * @since 9.3 Can pass condition as a parameter\n *\n * @param string $email user email\n * @param array $condition add condition\n *\n * @return boolean\n */\n function getFromDBbyEmail($email, $condition = []) {\n global $DB;", " $crit = [\n 'SELECT' => $this->getTable() . '.id',\n 'FROM' => $this->getTable(),\n 'LEFT JOIN' => [\n 'glpi_useremails' => [\n 'FKEY' => [\n $this->getTable() => 'id',\n 'glpi_useremails' => 'users_id'\n ]\n ]\n ],\n 'WHERE' => ['glpi_useremails.email' => $email] + $condition\n ];", " $iter = $DB->request($crit);\n if ($iter->numrows()==1) {\n $row = $iter->next();\n return $this->getFromDB($row['id']);\n }\n return false;\n }", "\n /**\n * Get the default email of the user.\n *\n * @return string\n */\n function getDefaultEmail() {", " if (!isset($this->fields['id'])) {\n return '';\n }", " return UserEmail::getDefaultForUser($this->fields['id']);\n }", "\n /**\n * Get all emails of the user.\n *\n * @return string[]\n */\n function getAllEmails() {", " if (!isset($this->fields['id'])) {\n return [];\n }\n return UserEmail::getAllForUser($this->fields['id']);\n }", "\n /**\n * Check if the email is attached to the current user.\n *\n * @param string $email\n *\n * @return boolean\n */\n function isEmail($email) {", " if (!isset($this->fields['id'])) {\n return false;\n }\n return UserEmail::isEmailForUser($this->fields['id'], $email);\n }", "\n /**\n * Retrieve a user from the database using its personal token.\n *\n * @param string $token user token\n * @param string $field the field storing the token\n *\n * @return boolean\n */\n function getFromDBbyToken($token, $field = 'personal_token') {\n $fields = ['personal_token', 'api_token'];\n if (!in_array($field, $fields)) {\n Toolbox::logWarning('User::getFromDBbyToken() can only be called with $field parameter with theses values: \\'' . implode('\\', \\'', $fields) . '\\'');\n return false;\n }", " return $this->getFromDBByCrit([$this->getTable() . \".$field\" => $token]);\n }", "\n function prepareInputForAdd($input) {\n global $DB;", " if (isset($input['_stop_import'])) {\n return false;\n }", " if (!Auth::isValidLogin(stripslashes($input['name']))) {\n Session::addMessageAfterRedirect(__('The login is not valid. Unable to add the user.'),\n false, ERROR);\n return false;\n }", " // avoid xss (picture field is autogenerated)\n if (isset($input['picture'])) {\n $input['picture'] = 'NULL';\n }", " if (!isset($input[\"authtype\"])) {\n $input[\"authtype\"] = Auth::DB_GLPI;\n }", " if (!isset($input[\"auths_id\"])) {\n $input[\"auths_id\"] = 0;\n }", " // Check if user does not exists\n $iterator = $DB->request([\n 'FROM' => $this->getTable(),\n 'WHERE' => [\n 'name' => $input['name'],\n 'authtype' => $input['authtype'],\n 'auths_id' => $input['auths_id']\n ],\n 'LIMIT' => 1\n ]);", " if (count($iterator)) {\n Session::addMessageAfterRedirect(__('Unable to add. The user already exists.'),\n false, ERROR);\n return false;\n }", " if (isset($input[\"password2\"])) {\n if (empty($input[\"password\"])) {\n unset ($input[\"password\"]);", " } else {\n if ($input[\"password\"] == $input[\"password2\"]) {\n if (Config::validatePassword($input[\"password\"])) {\n $input[\"password\"]\n = Auth::getPasswordHash(Toolbox::unclean_cross_side_scripting_deep(stripslashes($input[\"password\"])));", " $input['password_last_update'] = $_SESSION['glpi_currenttime'];\n } else {\n unset($input[\"password\"]);\n }\n unset($input[\"password2\"]);\n } else {\n Session::addMessageAfterRedirect(__('Error: the two passwords do not match'),\n false, ERROR);\n return false;\n }\n }\n }", " if (isset($input[\"_extauth\"])) {\n $input[\"password\"] = \"\";\n }", " // Force DB default values : not really needed\n if (!isset($input[\"is_active\"])) {\n $input[\"is_active\"] = 1;\n }", " if (!isset($input[\"is_deleted\"])) {\n $input[\"is_deleted\"] = 0;\n }", " if (!isset($input[\"entities_id\"])) {\n $input[\"entities_id\"] = 0;\n }", " if (!isset($input[\"profiles_id\"])) {\n $input[\"profiles_id\"] = 0;\n }", " return $input;\n }", " public function prepareInputForClone($input) {\n if (isset($input['name'])) {\n $suffix = 1;\n $possibleName = $input['name'].$suffix;\n while ($this->getFromDBbyName($possibleName)) {\n $suffix++;\n $possibleName = $input['name'].$suffix;\n }\n $input['name'] = $possibleName;\n }\n return $input;\n }", "\n function post_addItem() {", " $this->updateUserEmails();\n $this->syncLdapGroups();\n $this->syncDynamicEmails();", " $this->applyGroupsRules();\n $rulesplayed = $this->applyRightRules();\n $picture = $this->syncLdapPhoto();", " //add picture in user fields\n if (!empty($picture)) {\n $this->update(['id' => $this->fields['id'],\n 'picture' => $picture]);\n }", " // Add default profile\n if (!$rulesplayed) {\n $affectation = [];\n if (isset($this->input['_profiles_id']) && $this->input['_profiles_id']\n && Profile::currentUserHaveMoreRightThan([$this->input['_profiles_id']])\n ) {\n $profile = $this->input['_profiles_id'];\n // Choosen in form, so not dynamic\n $affectation['is_dynamic'] = 0;\n } else {\n $profile = Profile::getDefault();\n // Default right as dynamic. If dynamic rights are set it will disappear.\n $affectation['is_dynamic'] = 1;\n $affectation['is_default_profile'] = 1;\n }", " if ($profile) {\n if (isset($this->input[\"_entities_id\"])) {\n // entities_id (user's pref) always set in prepareInputForAdd\n // use _entities_id for default right\n $affectation[\"entities_id\"] = $this->input[\"_entities_id\"];", " } else if (isset($_SESSION['glpiactive_entity'])) {\n $affectation[\"entities_id\"] = $_SESSION['glpiactive_entity'];", " } else {\n $affectation[\"entities_id\"] = 0;\n }\n if (isset($this->input[\"_is_recursive\"])) {\n $affectation[\"is_recursive\"] = $this->input[\"_is_recursive\"];\n } else {\n $affectation[\"is_recursive\"] = 0;\n }", " $affectation[\"profiles_id\"] = $profile;\n $affectation[\"users_id\"] = $this->fields[\"id\"];\n $right = new Profile_User();\n $right->add($affectation);\n }\n }\n }", "\n function prepareInputForUpdate($input) {\n global $CFG_GLPI;", " // avoid xss (picture name is autogenerated when uploading/synchronising the picture)\n unset($input['picture']);", " //picture manually uploaded by user\n if (isset($input[\"_blank_picture\"]) && $input[\"_blank_picture\"]) {\n self::dropPictureFiles($this->fields['picture']);\n $input['picture'] = 'NULL';\n } else {\n $newPicture = false;\n if (!isAPI()) {\n if (isset($input[\"_picture\"][0]) && !empty($input[\"_picture\"][0])) {\n $input[\"_picture\"] = $input[\"_picture\"][0];\n }\n }\n if (isset($input[\"_picture\"]) && !empty($input[\"_picture\"])) {\n $newPicture = true;\n }\n if ($newPicture) {\n $fullpath = GLPI_TMP_DIR.\"/\".$input[\"_picture\"];\n if (Toolbox::getMime($fullpath, 'image')) {\n // Unlink old picture (clean on changing format)\n self::dropPictureFiles($this->fields['picture']);\n // Move uploaded file\n $filename = uniqid($this->fields['id'].'_');\n $sub = substr($filename, -2); /* 2 hex digit */", " // output images with possible transparency to png, other to jpg\n $extension = strtolower(pathinfo($fullpath, PATHINFO_EXTENSION));\n $extension = in_array($extension, ['png', 'gif'])\n ? 'png'\n : 'jpg';", " @mkdir(GLPI_PICTURE_DIR . \"/$sub\");\n $picture_path = GLPI_PICTURE_DIR . \"/$sub/${filename}.$extension\";\n self::dropPictureFiles(\"$sub/${filename}.$extension\");", " if (Document::isImage($fullpath)\n && Document::renameForce($fullpath, $picture_path)) {\n Session::addMessageAfterRedirect(__('The file is valid. Upload is successful.'));\n // For display\n $input['picture'] = \"$sub/${filename}.$extension\";", " //prepare a thumbnail\n $thumb_path = GLPI_PICTURE_DIR . \"/$sub/${filename}_min.$extension\";\n Toolbox::resizePicture($picture_path, $thumb_path);\n } else {\n Session::addMessageAfterRedirect(__('Potential upload attack or file too large. Moving temporary file failed.'),\n false, ERROR);\n }\n } else {\n Session::addMessageAfterRedirect(__('The file is not an image file.'),\n false, ERROR);\n }\n } else {\n //ldap jpegphoto synchronisation.\n $picture = $this->syncLdapPhoto();\n if (!empty($picture)) {\n $input['picture'] = $picture;\n }\n }\n }", " if (isset($input[\"password2\"])) {\n // Empty : do not update\n if (empty($input[\"password\"])) {\n unset($input[\"password\"]);", " } else {\n if ($input[\"password\"] == $input[\"password2\"]) {\n // Check right : my password of user with lesser rights\n if (isset($input['id'])\n && !Auth::checkPassword($input['password'], $this->fields['password']) // Validate that password is not same as previous\n && Config::validatePassword($input[\"password\"])\n && (($input['id'] == Session::getLoginUserID())\n || $this->currentUserHaveMoreRightThan($input['id'])\n // Permit to change password with token and email\n || (($input['password_forget_token'] == $this->fields['password_forget_token'])\n && (abs(strtotime($_SESSION[\"glpi_currenttime\"])\n -strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP)\n && $this->isEmail($input['email'])))) {\n $input[\"password\"]\n = Auth::getPasswordHash(Toolbox::unclean_cross_side_scripting_deep(stripslashes($input[\"password\"])));", " $input['password_last_update'] = $_SESSION[\"glpi_currenttime\"];\n } else {\n unset($input[\"password\"]);\n }\n unset($input[\"password2\"]);", " } else {\n Session::addMessageAfterRedirect(__('Error: the two passwords do not match'),\n false, ERROR);\n return false;\n }\n }", " } else if (isset($input[\"password\"])) { // From login\n unset($input[\"password\"]);\n }", " // blank password when authtype changes\n if (isset($input[\"authtype\"])\n && $input[\"authtype\"] != Auth::DB_GLPI\n && $input[\"authtype\"] != $this->getField('authtype')) {\n $input[\"password\"] = \"\";\n }", " // Update User in the database\n if (!isset($input[\"id\"])\n && isset($input[\"name\"])) {\n if ($this->getFromDBbyName($input[\"name\"])) {\n $input[\"id\"] = $this->fields[\"id\"];\n }\n }", " if (isset($input[\"entities_id\"])\n && (Session::getLoginUserID() == $input['id'])) {\n $_SESSION[\"glpidefault_entity\"] = $input[\"entities_id\"];\n }", " // Security on default profile update\n if (isset($input['profiles_id'])) {\n if (!in_array($input['profiles_id'], Profile_User::getUserProfiles($input['id']))) {\n unset($input['profiles_id']);\n }\n }", " // Security on default entity update\n if (isset($input['entities_id'])) {\n if (!in_array($input['entities_id'], Profile_User::getUserEntities($input['id']))) {\n unset($input['entities_id']);\n }\n }", " // Security on default group update\n if (isset($input['groups_id'])\n && !Group_User::isUserInGroup($input['id'], $input['groups_id'])) {\n unset($input['groups_id']);\n }", " if (isset($input['_reset_personal_token'])\n && $input['_reset_personal_token']) {\n $input['personal_token'] = self::getUniqueToken('personal_token');\n $input['personal_token_date'] = $_SESSION['glpi_currenttime'];\n }", " if (isset($input['_reset_api_token'])\n && $input['_reset_api_token']) {\n $input['api_token'] = self::getUniqueToken('api_token');\n $input['api_token_date'] = $_SESSION['glpi_currenttime'];\n }", " // Manage preferences fields\n if (Session::getLoginUserID() == $input['id']) {\n if (isset($input['use_mode'])\n && ($_SESSION['glpi_use_mode'] != $input['use_mode'])) {\n $_SESSION['glpi_use_mode'] = $input['use_mode'];\n unset($_SESSION['glpimenu']); // Force menu regeneration\n //Session::loadLanguage();\n }\n }", " foreach ($CFG_GLPI['user_pref_field'] as $f) {\n if (isset($input[$f])) {\n if (Session::getLoginUserID() == $input['id']) {\n if ($_SESSION[\"glpi$f\"] != $input[$f]) {\n $_SESSION[\"glpi$f\"] = $input[$f];\n // reinit translations\n if ($f == 'language') {\n $_SESSION['glpi_dropdowntranslations'] = DropdownTranslation::getAvailableTranslations($_SESSION[\"glpilanguage\"]);\n unset($_SESSION['glpimenu']);\n }\n }\n }\n if ($input[$f] == $CFG_GLPI[$f]) {\n $input[$f] = \"NULL\";\n }\n }\n }", " if (isset($input['language']) && GLPI_DEMO_MODE) {\n unset($input['language']);\n }", " if (array_key_exists('timezone', $input) && empty($input['timezone'])) {\n $input['timezone'] = 'NULL';\n }", " return $input;\n }", "\n function post_updateItem($history = 1) {\n //handle timezone change for current user\n if ($this->fields['id'] == Session::getLoginUserID()) {\n if (null == $this->fields['timezone'] || 'null' === strtolower($this->fields['timezone'])) {\n unset($_SESSION['glpi_tz']);\n } else {\n $_SESSION['glpi_tz'] = $this->fields['timezone'];\n }\n }", " $this->updateUserEmails();\n $this->syncLdapGroups();\n $this->syncDynamicEmails();\n $this->applyGroupsRules();\n $this->applyRightRules();", " if (in_array('password', $this->updates)) {\n $alert = new Alert();\n $alert->deleteByCriteria(\n [\n 'itemtype' => $this->getType(),\n 'items_id' => $this->fields['id'],\n ],\n true\n );\n }\n }", "", " /**\n * Apply rules to determine dynamic rights of the user.\n *\n * @return boolean true if rules are applied, false otherwise\n */\n function applyRightRules() {", " $return = false;", " if (isset($this->fields['_ruleright_process'])\n || isset($this->input['_ruleright_process'])) {", " $dynamic_profiles = Profile_User::getForUser($this->fields[\"id\"], true);", " if (isset($this->fields[\"id\"])\n && ($this->fields[\"id\"] > 0)\n && isset($this->input[\"_ldap_rules\"])\n && count($this->input[\"_ldap_rules\"])) {", " //and add/update/delete only if it's necessary !\n if (isset($this->input[\"_ldap_rules\"][\"rules_entities_rights\"])) {\n $entities_rules = $this->input[\"_ldap_rules\"][\"rules_entities_rights\"];\n } else {\n $entities_rules = [];\n }", " if (isset($this->input[\"_ldap_rules\"][\"rules_entities\"])) {\n $entities = $this->input[\"_ldap_rules\"][\"rules_entities\"];\n } else {\n $entities = [];\n }", " if (isset($this->input[\"_ldap_rules\"][\"rules_rights\"])) {\n $rights = $this->input[\"_ldap_rules\"][\"rules_rights\"];\n } else {\n $rights = [];\n }", " $retrieved_dynamic_profiles = [];", " //For each affectation -> write it in DB\n foreach ($entities_rules as $entity) {\n //Multiple entities assignation\n if (is_array($entity[0])) {\n foreach ($entity[0] as $ent) {\n $retrieved_dynamic_profiles[] = [\n 'entities_id' => $ent,\n 'profiles_id' => $entity[1],\n 'is_recursive' => $entity[2],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n } else {\n $retrieved_dynamic_profiles[] = [\n 'entities_id' => $entity[0],\n 'profiles_id' => $entity[1],\n 'is_recursive' => $entity[2],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n }", " if ((count($entities) > 0)\n && (count($rights) == 0)) {\n if ($def_prof = Profile::getDefault()) {\n $rights[] = $def_prof;\n }\n }", " if ((count($rights) > 0)\n && (count($entities) > 0)) {\n foreach ($rights as $right) {\n foreach ($entities as $entity) {\n $retrieved_dynamic_profiles[] = [\n 'entities_id' => $entity[0],\n 'profiles_id' => $right,\n 'is_recursive' => $entity[1],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n }\n }", " // Compare retrived profiles to existing ones : clean arrays to do purge and add\n if (count($retrieved_dynamic_profiles)) {\n foreach ($retrieved_dynamic_profiles as $keyretr => $retr_profile) {\n $found = false;", " foreach ($dynamic_profiles as $keydb => $db_profile) {\n // Found existing profile : unset values in array\n if (!$found\n && ($db_profile['entities_id'] == $retr_profile['entities_id'])\n && ($db_profile['profiles_id'] == $retr_profile['profiles_id'])\n && ($db_profile['is_recursive'] == $retr_profile['is_recursive'])) {", " unset($retrieved_dynamic_profiles[$keyretr]);\n unset($dynamic_profiles[$keydb]);\n }\n }\n }\n }", " // Add new dynamic profiles\n if (count($retrieved_dynamic_profiles)) {\n $right = new Profile_User();\n foreach ($retrieved_dynamic_profiles as $keyretr => $retr_profile) {\n $right->add($retr_profile);\n }\n }", " //Unset all the temporary tables\n unset($this->input[\"_ldap_rules\"]);", " $return = true;\n } else if (count($dynamic_profiles) == 1) {\n $dynamic_profile = reset($dynamic_profiles);", " // If no rule applied and only one dynamic profile found, check if\n // it is the default profile\n if ($dynamic_profile['is_default_profile'] == true) {\n $default_profile = Profile::getDefault();", " // Remove from to be deleted list\n $dynamic_profiles = [];", " // Update profile if need to match the current default profile\n if ($dynamic_profile['profiles_id'] !== $default_profile) {\n $pu = new Profile_User();\n $dynamic_profile['profiles_id'] = $default_profile;\n $pu->add($dynamic_profile);\n $pu->delete([\n 'id' => $dynamic_profile['id']\n ]);\n }\n }\n }", " // Delete old dynamic profiles\n if (count($dynamic_profiles)) {\n $right = new Profile_User();\n foreach ($dynamic_profiles as $keydb => $db_profile) {\n $right->delete($db_profile);\n }\n }", " }\n return $return;\n }", "\n /**\n * Synchronise LDAP group of the user.\n *\n * @return void\n */\n function syncLdapGroups() {\n global $DB;", " // input[\"_groups\"] not set when update from user.form or preference\n if (isset($this->fields[\"authtype\"])\n && isset($this->input[\"_groups\"])\n && (($this->fields[\"authtype\"] == Auth::LDAP)\n || Auth::isAlternateAuth($this->fields['authtype']))) {", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n $authtype = Auth::getMethodsByID($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);", " if (count($authtype)) {\n // Clean groups\n $this->input[\"_groups\"] = array_unique ($this->input[\"_groups\"]);", " // Delete not available groups like to LDAP\n $iterator = $DB->request([\n 'SELECT' => [\n 'glpi_groups_users.id',\n 'glpi_groups_users.groups_id',\n 'glpi_groups_users.is_dynamic'\n ],\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_groups' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'groups_id',\n 'glpi_groups' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.users_id' => $this->fields['id']\n ]\n ]);", " $groupuser = new Group_User();\n while ($data = $iterator->next()) {", " if (in_array($data[\"groups_id\"], $this->input[\"_groups\"])) {\n // Delete found item in order not to add it again\n unset($this->input[\"_groups\"][array_search($data[\"groups_id\"],\n $this->input[\"_groups\"])]);", " } else if ($data['is_dynamic']) {\n $groupuser->delete(['id' => $data[\"id\"]]);\n }\n }", " //If the user needs to be added to one group or more\n if (count($this->input[\"_groups\"]) > 0) {\n foreach ($this->input[\"_groups\"] as $group) {\n $groupuser->add(['users_id' => $this->fields[\"id\"],\n 'groups_id' => $group,\n 'is_dynamic' => 1]);\n }\n unset ($this->input[\"_groups\"]);\n }\n }\n }\n }\n }", "\n /**\n * Synchronize picture (photo) of the user.\n *\n * @since 0.85\n *\n * @return string|boolean Filename to be stored in user picture field, false if no picture found\n */\n function syncLdapPhoto() {", " if (isset($this->fields[\"authtype\"])\n && (($this->fields[\"authtype\"] == Auth::LDAP)\n || ($this->fields[\"authtype\"] == Auth::NOT_YET_AUTHENTIFIED\n && !empty($this->fields[\"auths_id\"]))\n || Auth::isAlternateAuth($this->fields['authtype']))) {", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n $config_ldap = new AuthLDAP();\n $ds = false;", " //connect ldap server\n if ($config_ldap->getFromDB($this->fields['auths_id'])) {\n $ds = $config_ldap->connect();\n }", " if ($ds) {\n //get picture fields\n $picture_field = $config_ldap->fields['picture_field'];\n if (empty($picture_field)) {\n return false;\n }", " //get picture content in ldap\n $info = AuthLDAP::getUserByDn($ds, $this->fields['user_dn'],\n [$picture_field], false);", " //getUserByDn returns an array. If the picture is empty,\n //$info[$picture_field][0] is null\n if (!isset($info[$picture_field][0]) || empty($info[$picture_field][0])) {\n return \"\";\n }\n //prepare paths\n $img = array_pop($info[$picture_field]);\n $filename = uniqid($this->fields['id'].'_');\n $sub = substr($filename, -2); /* 2 hex digit */\n $file = GLPI_PICTURE_DIR . \"/$sub/${filename}.jpg\";", " if (array_key_exists('picture', $this->fields)) {\n $oldfile = GLPI_PICTURE_DIR . \"/\" . $this->fields[\"picture\"];\n } else {\n $oldfile = null;\n }", " // update picture if not exist or changed\n if (empty($this->fields[\"picture\"])\n || !file_exists($oldfile)\n || sha1_file($oldfile) !== sha1($img)) {\n if (!is_dir(GLPI_PICTURE_DIR . \"/$sub\")) {\n mkdir(GLPI_PICTURE_DIR . \"/$sub\");\n }", " //save picture\n $outjpeg = fopen($file, 'wb');\n fwrite($outjpeg, $img);\n fclose ($outjpeg);", " //save thumbnail\n $thumb = GLPI_PICTURE_DIR . \"/$sub/${filename}_min.jpg\";\n Toolbox::resizePicture($file, $thumb);", " return \"$sub/${filename}.jpg\";\n }\n return $this->fields[\"picture\"];\n }\n }\n }", " return false;\n }", "\n /**\n * Update emails of the user.\n * Uses _useremails set from UI, not _emails set from LDAP.\n *\n * @return void\n */\n function updateUserEmails() {\n // Update emails (use _useremails set from UI, not _emails set from LDAP)", " $userUpdated = false;", " if (isset($this->input['_useremails']) && count($this->input['_useremails'])) {\n $useremail = new UserEmail();\n foreach ($this->input['_useremails'] as $id => $email) {\n $email = trim($email);", " // existing email\n if ($id > 0) {\n $params = ['id' => $id];", " // empty email : delete\n if (strlen($email) == 0) {\n $deleted = $useremail->delete($params);\n $userUpdated = $userUpdated || $deleted;", " } else { // Update email\n $params['email'] = $email;\n $params['is_default'] = $this->input['_default_email'] == $id ? 1 : 0;", " $existingUserEmail = new UserEmail();\n $existingUserEmail->getFromDB($id);\n if ($params['email'] == $existingUserEmail->fields['email']\n && $params['is_default'] == $existingUserEmail->fields['is_default']) {\n // Do not update if email has not changed\n continue;\n }", " $updated = $useremail->update($params);\n $userUpdated = $userUpdated || $updated;\n }", " } else { // New email\n $email_input = ['email' => $email,\n 'users_id' => $this->fields['id']];\n if (isset($this->input['_default_email'])\n && ($this->input['_default_email'] == $id)) {\n $email_input['is_default'] = 1;\n } else {\n $email_input['is_default'] = 0;\n }\n $added = $useremail->add($email_input);\n $userUpdated = $userUpdated || $added;\n }\n }\n }", " if ($userUpdated) {\n // calling $this->update() here leads to loss in $this->input\n $user = new User();\n $user->update(['id' => $this->fields['id'], 'date_mod' => $_SESSION['glpi_currenttime']]);\n }\n }", "\n /**\n * Synchronise Dynamics emails of the user.\n * Uses _emails (set from getFromLDAP), not _usermails set from UI.\n *\n * @return void\n */\n function syncDynamicEmails() {\n global $DB;", " $userUpdated = false;", " // input[\"_emails\"] not set when update from user.form or preference\n if (isset($this->fields[\"authtype\"])\n && isset($this->input[\"_emails\"])\n && (($this->fields[\"authtype\"] == Auth::LDAP)\n || Auth::isAlternateAuth($this->fields['authtype'])\n || ($this->fields[\"authtype\"] == Auth::MAIL))) {", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n $authtype = Auth::getMethodsByID($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);", " if (count($authtype)\n || $this->fields[\"authtype\"] == Auth::EXTERNAL) {\n // Clean emails\n // Do a case insensitive comparison as it seems that some LDAP servers\n // may return same email with different case sensitivity.\n $unique_emails = [];\n foreach ($this->input[\"_emails\"] as $email) {\n if (!in_array(strtolower($email), array_map('strtolower', $unique_emails))) {\n $unique_emails[] = $email;\n }\n }\n $this->input[\"_emails\"] = $unique_emails;", " // Delete not available groups like to LDAP\n $iterator = $DB->request([\n 'SELECT' => [\n 'id',\n 'users_id',\n 'email',\n 'is_dynamic'\n ],\n 'FROM' => 'glpi_useremails',\n 'WHERE' => ['users_id' => $this->fields['id']]\n ]);", " $useremail = new UserEmail();\n while ($data = $iterator->next()) {\n // Do a case insensitive comparison as email may be stored with a different case\n $i = array_search(strtolower($data[\"email\"]), array_map('strtolower', $this->input[\"_emails\"]));\n if ($i !== false) {\n // Delete found item in order not to add it again\n unset($this->input[\"_emails\"][$i]);\n } else if ($data['is_dynamic']) {\n // Delete not found email\n $deleted = $useremail->delete(['id' => $data[\"id\"]]);\n $userUpdated = $userUpdated || $deleted;\n }\n }", " //If the email need to be added\n if (count($this->input[\"_emails\"]) > 0) {\n foreach ($this->input[\"_emails\"] as $email) {\n $added = $useremail->add(['users_id' => $this->fields[\"id\"],\n 'email' => $email,\n 'is_dynamic' => 1]);\n $userUpdated = $userUpdated || $added;\n }\n unset ($this->input[\"_emails\"]);\n }\n }\n }\n }", " if ($userUpdated) {\n // calling $this->update() here leads to loss in $this->input\n $user = new User();\n $user->update(['id' => $this->fields['id'], 'date_mod' => $_SESSION['glpi_currenttime']]);\n }\n }", " protected function computeFriendlyName() {\n global $CFG_GLPI;", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n //computeFriendlyName should not add ID\n $bkp_conf = $CFG_GLPI['is_ids_visible'];\n $CFG_GLPI['is_ids_visible'] = 0;\n $bkp_sessconf = (isset($_SESSION['glpiis_ids_visible']) ? $_SESSION[\"glpiis_ids_visible\"] : 0);\n $_SESSION[\"glpiis_ids_visible\"] = 0;\n $name = formatUserName($this->fields[\"id\"],\n $this->fields[\"name\"],\n (isset($this->fields[\"realname\"]) ? $this->fields[\"realname\"] : ''),\n (isset($this->fields[\"firstname\"]) ? $this->fields[\"firstname\"] : ''));", " $CFG_GLPI['is_ids_visible'] = $bkp_conf;\n $_SESSION[\"glpiis_ids_visible\"] = $bkp_sessconf;\n return $name;\n }\n return '';\n }", "\n /**\n * Function that tries to load the user membership from LDAP\n * by searching in the attributes of the User.\n *\n * @param resource $ldap_connection LDAP connection\n * @param array $ldap_method LDAP method\n * @param string $userdn Basedn of the user\n * @param string $login User login\n *\n * @return string|boolean Basedn of the user / false if not found\n */\n private function getFromLDAPGroupVirtual($ldap_connection, array $ldap_method, $userdn, $login) {\n global $DB;", " // Search in DB the ldap_field we need to search for in LDAP\n $iterator = $DB->request([\n 'SELECT' => 'ldap_field',\n 'DISTINCT' => true,\n 'FROM' => 'glpi_groups',\n 'WHERE' => ['NOT' => ['ldap_field' => '']],\n 'ORDER' => 'ldap_field'\n ]);\n $group_fields = [];", " while ($data = $iterator->next()) {\n $group_fields[] = Toolbox::strtolower($data[\"ldap_field\"]);\n }\n if (count($group_fields)) {\n //Need to sort the array because edirectory don't like it!\n sort($group_fields);", " // If the groups must be retrieve from the ldap user object\n $sr = @ ldap_read($ldap_connection, $userdn, \"objectClass=*\", $group_fields);\n $v = AuthLDAP::get_entries_clean($ldap_connection, $sr);", " for ($i=0; $i < $v['count']; $i++) {\n //Try to find is DN in present and needed: if yes, then extract only the OU from it\n if ((($ldap_method[\"group_field\"] == 'dn') || in_array('ou', $group_fields))\n && isset($v[$i]['dn'])) {", " $v[$i]['ou'] = [];\n for ($tmp=$v[$i]['dn']; count($tmptab = explode(',', $tmp, 2))==2; $tmp=$tmptab[1]) {\n $v[$i]['ou'][] = $tmptab[1];\n }", " // Search in DB for group with ldap_group_dn\n if (($ldap_method[\"group_field\"] == 'dn')\n && (count($v[$i]['ou']) > 0)) {\n $group_iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_groups',\n 'WHERE' => ['ldap_group_dn' => Toolbox::addslashes_deep($v[$i]['ou'])]\n ]);", " while ($group = $group_iterator->next()) {\n $this->fields[\"_groups\"][] = $group['id'];\n }\n }", " // searching with ldap_field='OU' and ldap_value is also possible\n $v[$i]['ou']['count'] = count($v[$i]['ou']);\n }", " // For each attribute retrieve from LDAP, search in the DB\n foreach ($group_fields as $field) {\n if (isset($v[$i][$field])\n && isset($v[$i][$field]['count'])\n && ($v[$i][$field]['count'] > 0)) {", " unset($v[$i][$field]['count']);\n $lgroups = [];\n foreach (Toolbox::addslashes_deep($v[$i][$field]) as $lgroup) {\n $lgroups[] = [\n new \\QueryExpression($DB::quoteValue($lgroup).\n \" LIKE \".\n $DB::quoteName('ldap_value'))\n ];\n }\n $group_iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_groups',\n 'WHERE' => [\n 'ldap_field' => $field,\n 'OR' => $lgroups\n ]\n ]);", " while ($group = $group_iterator->next()) {\n $this->fields[\"_groups\"][] = $group['id'];\n }\n }\n }\n } // for each ldapresult\n } // count($group_fields)\n }", "\n /**\n * Function that tries to load the user membership from LDAP\n * by searching in the attributes of the Groups.\n *\n * @param resource $ldap_connection LDAP connection\n * @param array $ldap_method LDAP method\n * @param string $userdn Basedn of the user\n * @param string $login User login\n *\n * @return boolean true if search is applicable, false otherwise\n */\n private function getFromLDAPGroupDiscret($ldap_connection, array $ldap_method, $userdn, $login) {\n global $DB;", " // No group_member_field : unable to get group\n if (empty($ldap_method[\"group_member_field\"])) {\n return false;\n }", " if ($ldap_method[\"use_dn\"]) {\n $user_tmp = $userdn;\n } else {\n //Don't add $ldap_method[\"login_field\"].\"=\", because sometimes it may not work (for example with posixGroup)\n $user_tmp = $login;\n }", " $v = $this->ldap_get_user_groups($ldap_connection, $ldap_method[\"basedn\"],\n $user_tmp,\n $ldap_method[\"group_condition\"],\n $ldap_method[\"group_member_field\"],\n $ldap_method[\"use_dn\"],\n $ldap_method[\"login_field\"]);\n foreach ($v as $result) {\n if (isset($result[$ldap_method[\"group_member_field\"]])\n && is_array($result[$ldap_method[\"group_member_field\"]])\n && (count($result[$ldap_method[\"group_member_field\"]]) > 0)) {", " $iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_groups',\n 'WHERE' => ['ldap_group_dn' => Toolbox::addslashes_deep($result[$ldap_method[\"group_member_field\"]])]\n ]);", " while ($group = $iterator->next()) {\n $this->fields[\"_groups\"][] = $group['id'];\n }\n }\n }\n return true;\n }", "\n /**\n * Function that tries to load the user informations from LDAP.\n *\n * @param resource $ldap_connection LDAP connection\n * @param array $ldap_method LDAP method\n * @param string $userdn Basedn of the user\n * @param string $login User Login\n * @param boolean $import true for import, false for update\n *\n * @return boolean true if found / false if not\n */\n function getFromLDAP($ldap_connection, array $ldap_method, $userdn, $login, $import = true) {\n global $DB, $CFG_GLPI;", " // we prevent some delay...\n if (empty($ldap_method[\"host\"])) {\n return false;\n }", " if (is_resource($ldap_connection)) {\n //Set all the search fields\n $this->fields['password'] = \"\";", " $fields = AuthLDAP::getSyncFields($ldap_method);", " //Hook to allow plugin to request more attributes from ldap\n $fields = Plugin::doHookFunction(\"retrieve_more_field_from_ldap\", $fields);", " $fields = array_filter($fields);\n $f = self::getLdapFieldNames($fields);", " $sr = @ ldap_read($ldap_connection, $userdn, \"objectClass=*\", $f);\n $v = AuthLDAP::get_entries_clean($ldap_connection, $sr);", " if (!is_array($v)\n || ( count($v) == 0)\n || empty($v[0][$fields['name']][0])) {\n return false;\n }", " //Store user's dn\n $this->fields['user_dn'] = addslashes($userdn);\n //Store date_sync\n $this->fields['date_sync'] = $_SESSION['glpi_currenttime'];\n // Empty array to ensure than syncDynamicEmails will be done\n $this->fields[\"_emails\"] = [];\n // force authtype as we retrieve this user by ldap (we could have login with SSO)\n $this->fields[\"authtype\"] = Auth::LDAP;", " foreach ($fields as $k => $e) {\n $val = AuthLDAP::getFieldValue(\n [$e => self::getLdapFieldValue($e, $v)],\n $e\n );\n if (empty($val)) {\n switch ($k) {\n case \"language\" :\n // Not set value : managed but user class\n break;", " case \"usertitles_id\" :\n case \"usercategories_id\" :\n case 'locations_id' :\n case 'users_id_supervisor' :\n $this->fields[$k] = 0;\n break;", " default :\n $this->fields[$k] = \"\";\n }", " } else {\n $val = Toolbox::addslashes_deep($val);\n switch ($k) {\n case \"email1\" :\n case \"email2\" :\n case \"email3\" :\n case \"email4\" :\n // Manage multivaluable fields\n if (!empty($v[0][$e])) {\n foreach ($v[0][$e] as $km => $m) {\n if (!preg_match('/count/', $km)) {\n $this->fields[\"_emails\"][] = addslashes($m);\n }\n }\n // Only get them once if duplicated\n $this->fields[\"_emails\"] = array_unique($this->fields[\"_emails\"]);\n }\n break;", " case \"language\" :\n $language = Config::getLanguage($val);\n if ($language != '') {\n $this->fields[$k] = $language;\n }\n break;", " case \"usertitles_id\" :\n $this->fields[$k] = Dropdown::importExternal('UserTitle', $val);\n break;", " case 'locations_id' :\n // use import to build the location tree\n $this->fields[$k] = Dropdown::import('Location',\n ['completename' => $val,\n 'entities_id' => 0,\n 'is_recursive' => 1]);\n break;", " case \"usercategories_id\" :\n $this->fields[$k] = Dropdown::importExternal('UserCategory', $val);\n break;", " case 'users_id_supervisor':\n $this->fields[$k] = self::getIdByField('user_dn', $val, false);\n break;", " default :\n $this->fields[$k] = $val;\n }\n }\n }", " // Empty array to ensure than syncLdapGroups will be done\n $this->fields[\"_groups\"] = [];", " ///The groups are retrieved by looking into an ldap user object\n if (($ldap_method[\"group_search_type\"] == 0)\n || ($ldap_method[\"group_search_type\"] == 2)) {\n $this->getFromLDAPGroupVirtual($ldap_connection, $ldap_method, $userdn, $login);\n }", " ///The groups are retrived by looking into an ldap group object\n if (($ldap_method[\"group_search_type\"] == 1)\n || ($ldap_method[\"group_search_type\"] == 2)) {\n $this->getFromLDAPGroupDiscret($ldap_connection, $ldap_method, $userdn, $login);\n }", " ///Only process rules if working on the master database\n if (!$DB->isSlave()) {\n //Instanciate the affectation's rule\n $rule = new RuleRightCollection();", " //Process affectation rules :\n //we don't care about the function's return because all\n //the datas are stored in session temporary\n if (isset($this->fields[\"_groups\"])) {\n $groups = $this->fields[\"_groups\"];\n } else {\n $groups = [];\n }", " $this->fields = $rule->processAllRules($groups, Toolbox::stripslashes_deep($this->fields), [\n 'type' => Auth::LDAP,\n 'ldap_server' => $ldap_method[\"id\"],\n 'connection' => $ldap_connection,\n 'userdn' => $userdn,\n 'login' => $this->fields['name'],\n 'mail_email' => $this->fields['_emails']\n ]);", " $this->fields['_ruleright_process'] = true;", " //If rule action is ignore import\n if ($import\n && isset($this->fields[\"_stop_import\"])) {\n return false;\n }\n //or no rights found & do not import users with no rights\n if ($import\n && !$CFG_GLPI[\"use_noright_users_add\"]) {\n $ok = false;\n if (isset($this->fields[\"_ldap_rules\"])\n && count($this->fields[\"_ldap_rules\"])) {\n if (isset($this->fields[\"_ldap_rules\"][\"rules_entities_rights\"])\n && count($this->fields[\"_ldap_rules\"][\"rules_entities_rights\"])) {\n $ok = true;\n }\n if (!$ok) {\n $entity_count = 0;\n $right_count = 0;\n if (Profile::getDefault()) {\n $right_count++;\n }\n if (isset($this->fields[\"_ldap_rules\"][\"rules_entities\"])) {\n $entity_count += count($this->fields[\"_ldap_rules\"][\"rules_entities\"]);\n }\n if (isset($this->input[\"_ldap_rules\"][\"rules_rights\"])) {\n $right_count += count($this->fields[\"_ldap_rules\"][\"rules_rights\"]);\n }\n if ($entity_count && $right_count) {\n $ok = true;\n }\n }\n }\n if (!$ok) {\n $this->fields[\"_stop_import\"] = true;\n return false;\n }\n }", " // Add ldap result to data send to the hook\n $this->fields['_ldap_result'] = $v;\n $this->fields['_ldap_conn'] = $ldap_connection;\n //Hook to retrieve more information for ldap\n $this->fields = Plugin::doHookFunction(\"retrieve_more_data_from_ldap\", $this->fields);\n unset($this->fields['_ldap_result']);\n }\n return true;\n }\n return false;", " } // getFromLDAP()", "\n /**\n * Get all groups a user belongs to.\n *\n * @param resource $ds ldap connection\n * @param string $ldap_base_dn Basedn used\n * @param string $user_dn Basedn of the user\n * @param string $group_condition group search condition\n * @param string $group_member_field group field member in a user object\n * @param boolean $use_dn search dn of user ($login_field=$user_dn) in group_member_field\n * @param string $login_field user login field\n *\n * @return array Groups of the user located in [0][$group_member_field] in returned array\n */\n function ldap_get_user_groups($ds, $ldap_base_dn, $user_dn, $group_condition,\n $group_member_field, $use_dn, $login_field) {", " $groups = [];\n $listgroups = [];", " //User dn may contain ( or ), need to espace it!\n $user_dn = str_replace([\"(\", \")\", \"\\,\", \"\\+\"], [\"\\(\", \"\\)\", \"\\\\\\,\", \"\\\\\\+\"],\n $user_dn);", " //Only retrive cn and member attributes from groups\n $attrs = ['dn'];", " if (!$use_dn) {\n $filter = \"(& $group_condition (|($group_member_field=$user_dn)\n ($group_member_field=$login_field=$user_dn)))\";\n } else {\n $filter = \"(& $group_condition ($group_member_field=$user_dn))\";\n }", " //Perform the search\n $filter = Toolbox::unclean_cross_side_scripting_deep($filter);\n $sr = ldap_search($ds, $ldap_base_dn, $filter, $attrs);", " //Get the result of the search as an array\n $info = AuthLDAP::get_entries_clean($ds, $sr);\n //Browse all the groups\n $info_count = count($info);\n for ($i = 0; $i < $info_count; $i++) {\n //Get the cn of the group and add it to the list of groups\n if (isset($info[$i][\"dn\"]) && ($info[$i][\"dn\"] != '')) {\n $listgroups[$i] = $info[$i][\"dn\"];\n }\n }", " //Create an array with the list of groups of the user\n $groups[0][$group_member_field] = $listgroups;\n //Return the groups of the user\n return $groups;\n }", "\n /**\n * Function that tries to load the user informations from IMAP.\n *\n * @param array $mail_method mail method description array\n * @param string $name login of the user\n *\n * @return boolean true if method is applicable, false otherwise\n */\n function getFromIMAP(array $mail_method, $name) {\n global $DB;", " // we prevent some delay..\n if (empty($mail_method[\"host\"])) {\n return false;\n }", " // some defaults...\n $this->fields['password'] = \"\";\n // Empty array to ensure than syncDynamicEmails will be done\n $this->fields[\"_emails\"] = [];\n $email = '';\n if (strpos($name, \"@\")) {\n $email = $name;\n } else {\n $email = $name . \"@\" . $mail_method[\"host\"];\n }\n $this->fields[\"_emails\"][] = $email;", " $this->fields['name'] = $name;\n //Store date_sync\n $this->fields['date_sync'] = $_SESSION['glpi_currenttime'];\n // force authtype as we retrieve this user by imap (we could have login with SSO)\n $this->fields[\"authtype\"] = Auth::MAIL;", " if (!$DB->isSlave()) {\n //Instanciate the affectation's rule\n $rule = new RuleRightCollection();", " //Process affectation rules :\n //we don't care about the function's return because all the datas are stored in session temporary\n if (isset($this->fields[\"_groups\"])) {\n $groups = $this->fields[\"_groups\"];\n } else {\n $groups = [];\n }\n $this->fields = $rule->processAllRules($groups, Toolbox::stripslashes_deep($this->fields), [\n 'type' => Auth::MAIL,\n 'mail_server' => $mail_method[\"id\"],\n 'login' => $name,\n 'email' => $email]\n );\n $this->fields['_ruleright_process'] = true;\n }\n return true;\n }", "\n /**\n * Function that tries to load the user informations from the SSO server.\n *\n * @since 0.84\n *\n * @return boolean true if method is applicable, false otherwise\n */\n function getFromSSO() {\n global $DB, $CFG_GLPI;", " $a_field = [];\n foreach ($CFG_GLPI as $key=>$value) {\n if (!is_array($value) && !empty($value)\n && strstr($key, \"_ssofield\")) {\n $key = str_replace('_ssofield', '', $key);\n $a_field[$key] = $value;\n }\n }", " if (count($a_field) == 0) {\n return true;\n }\n $this->fields['_ruleright_process'] = true;\n foreach ($a_field as $field=>$value) {\n if (!isset($_SERVER[$value])\n || empty($_SERVER[$value])) {", " switch ($field) {\n case \"title\" :\n $this->fields['usertitles_id'] = 0;\n break;", " case \"category\" :\n $this->fields['usercategories_id'] = 0;\n break;", " default :\n $this->fields[$field] = \"\";\n }", " } else {\n switch ($field) {\n case \"email1\" :\n case \"email2\" :\n case \"email3\" :\n case \"email4\" :\n // Manage multivaluable fields\n if (!preg_match('/count/', $_SERVER[$value])) {\n $this->fields[\"_emails\"][] = addslashes($_SERVER[$value]);\n }\n // Only get them once if duplicated\n $this->fields[\"_emails\"] = array_unique($this->fields[\"_emails\"]);\n break;", " case \"language\" :\n $language = Config::getLanguage($_SERVER[$value]);\n if ($language != '') {\n $this->fields[$field] = $language;\n }\n break;", " case \"title\" :\n $this->fields['usertitles_id']\n = Dropdown::importExternal('UserTitle', addslashes($_SERVER[$value]));\n break;", " case \"category\" :\n $this->fields['usercategories_id']\n = Dropdown::importExternal('UserCategory', addslashes($_SERVER[$value]));\n break;", " default :\n $this->fields[$field] = $_SERVER[$value];\n break;", " }\n }\n }\n ///Only process rules if working on the master database\n if (!$DB->isSlave()) {\n //Instanciate the affectation's rule\n $rule = new RuleRightCollection();", " $this->fields = $rule->processAllRules([], Toolbox::stripslashes_deep($this->fields), [\n 'type' => Auth::EXTERNAL,\n 'email' => $this->fields[\"_emails\"],\n 'login' => $this->fields[\"name\"]\n ]);", " //If rule action is ignore import\n if (isset($this->fields[\"_stop_import\"])) {\n return false;\n }\n }\n return true;\n }", "\n /**\n * Blank passwords field of a user in the DB.\n * Needed for external auth users.\n *\n * @return void\n */\n function blankPassword() {\n global $DB;", " if (!empty($this->fields[\"name\"])) {\n $DB->update(\n $this->getTable(), [\n 'password' => ''\n ], [\n 'name' => $this->fields['name']\n ]\n );\n }\n }", "\n /**\n * Print a good title for user pages.\n *\n * @return void\n */\n function title() {\n global $CFG_GLPI;", " $buttons = [];\n $title = self::getTypeName(Session::getPluralNumber());", " if (static::canCreate()) {\n $buttons[\"user.form.php\"] = __('Add user...');\n $title = \"\";", " if (Auth::useAuthExt()\n && Session::haveRight(\"user\", self::IMPORTEXTAUTHUSERS)) {\n // This requires write access because don't use entity config.\n $buttons[\"user.form.php?new=1&amp;ext_auth=1\"] = __('... From an external source');\n }\n }\n if (Session::haveRight(\"user\", self::IMPORTEXTAUTHUSERS)\n && (static::canCreate() || static::canUpdate())) {\n if (AuthLDAP::useAuthLdap()) {\n $buttons[\"ldap.php\"] = __('LDAP directory link');\n }\n }\n Html::displayTitle($CFG_GLPI[\"root_doc\"] . \"/pics/users.png\", self::getTypeName(Session::getPluralNumber()), $title,\n $buttons);\n }", "\n /**\n * Check if current user have more right than the specified one.\n *\n * @param integer $ID ID of the user\n *\n * @return boolean\n */\n function currentUserHaveMoreRightThan($ID) {", " $user_prof = Profile_User::getUserProfiles($ID);\n return Profile::currentUserHaveMoreRightThan($user_prof);\n }", "\n /**\n * Print the user form.\n *\n * @param integer $ID ID of the user\n * @param array $options Options\n * - string target Form target\n * - boolean withtemplate Template or basic item\n *\n * @return boolean true if user found, false otherwise\n */\n function showForm($ID, array $options = []) {\n global $CFG_GLPI, $DB;", " // Affiche un formulaire User\n if (($ID != Session::getLoginUserID()) && !self::canView()) {\n return false;\n }", " $this->initForm($ID, $options);", " $ismyself = $ID == Session::getLoginUserID();\n $higherrights = $this->currentUserHaveMoreRightThan($ID);\n if ($ID) {\n $caneditpassword = $higherrights || ($ismyself && Session::haveRight('password_update', 1));\n } else {\n // can edit on creation form\n $caneditpassword = true;\n }", " $extauth = !(($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || (($this->fields[\"authtype\"] == Auth::NOT_YET_AUTHENTIFIED)\n && !empty($this->fields[\"password\"])));", " $formtitle = $this->getTypeName(1);", " if ($ID > 0) {\n $formtitle .= \"<a class='pointer far fa-address-card fa-lg' target='_blank' href='\".\n User::getFormURLWithID($ID).\"&amp;getvcard=1' title='\".__s('Download user VCard').\n \"'><span class='sr-only'>\". __('Vcard').\"</span></a>\";\n if (Session::canImpersonate($ID)) {\n $formtitle .= '<button type=\"button\" class=\"pointer btn-linkstyled btn-impersonate\" name=\"impersonate\" value=\"1\">'\n . '<i class=\"fas fa-user-secret fa-lg\" title=\"' . __s('Impersonate') . '\"></i> '\n . '<span class=\"sr-only\">' . __s('Impersonate') . '</span>'\n . '</button>';", " // \"impersonate\" button type is set to \"button\" on form display to prevent it to be used\n // by default (as it is the first found in current form) when pressing \"enter\" key.\n // When clicking it, switch to \"submit\" type to make it submit current user form.\n $impersonate_js = <<<JAVASCRIPT\n (function($) {\n $('button[type=\"button\"][name=\"impersonate\"]').click(\n function () {\n $(this).attr('type', 'submit');\n }\n );\n })(jQuery);\nJAVASCRIPT;\n $formtitle .= Html::scriptBlock($impersonate_js);\n }\n }", " $options['formtitle'] = $formtitle;\n $options['formoptions'] = ($options['formoptions'] ?? '') . \" enctype='multipart/form-data'\";\n $this->showFormHeader($options);\n $rand = mt_rand();", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='name'>\" . __('Login') . \"</label></td>\";\n if ($this->fields[\"name\"] == \"\" ||\n !empty($this->fields[\"password\"])\n || ($this->fields[\"authtype\"] == Auth::DB_GLPI)) {\n //display login field for new records, or if this is not external auth\n echo \"<td><input name='name' id='name' value=\\\"\" . $this->fields[\"name\"] . \"\\\"></td>\";\n } else {\n echo \"<td class='b'>\" . $this->fields[\"name\"];\n echo \"<input type='hidden' name='name' value=\\\"\" . $this->fields[\"name\"] . \"\\\"></td>\";\n }", " if (!empty($this->fields[\"name\"])) {\n echo \"<td rowspan='7'>\" . __('Picture') . \"</td>\";\n echo \"<td rowspan='7'>\";\n echo \"<div class='user_picture_border_small' id='picture$rand'>\";\n echo \"<img class='user_picture_small' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getThumbnailURLForPicture($this->fields['picture']).\"'>\";\n // echo \"<img src='\".self::getURLForPicture($this->fields[\"picture\"]).\"' class='user_picture'/>\";\n echo \"</div>\";\n $full_picture = \"<div class='user_picture_border'>\";\n $full_picture .= \"<img class='user_picture' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getURLForPicture($this->fields['picture']).\"'>\";\n $full_picture .= \"</div>\";", " Html::showTooltip($full_picture, ['applyto' => \"picture$rand\"]);\n echo Html::file(['name' => 'picture', 'display' => false, 'onlyimages' => true]);\n echo \"<input type='checkbox' name='_blank_picture'>&nbsp;\".__('Clear');\n echo \"</td>\";\n } else {\n echo \"<td rowspan='7'></td>\";\n echo \"<td rowspan='7'></td>\";\n }\n echo \"</tr>\";", " //If it's an external auth, check if the sync_field must be displayed\n if ($extauth\n && $this->fields['auths_id']\n && AuthLDAP::isSyncFieldConfigured($this->fields['auths_id'])) {\n $syncrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_sync_field$syncrand'>\" . __('Synchronization field') . \"</label></td><td>\";\n if (self::canUpdate()\n && (!$extauth || empty($ID))) {\n Html::autocompletionTextField($this, \"sync_field\", ['rand' => $syncrand]);\n } else {\n if (empty($this->fields['sync_field'])) {\n echo Dropdown::EMPTY_VALUE;\n } else {\n echo $this->fields['sync_field'];\n }\n }\n echo \"</td></tr>\";\n } else {\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n }", " $surnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_realname$surnamerand'>\" . __('Surname') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"realname\", ['rand' => $surnamerand]);\n echo \"</td></tr>\";", " $firstnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_firstname$firstnamerand'>\" . __('First name') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"firstname\", ['rand' => $firstnamerand]);\n echo \"</td></tr>\";", " //do some rights verification\n if (self::canUpdate()\n && (!$extauth || empty($ID))\n && $caneditpassword) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password'>\" . __('Password').\"</label></td>\";\n echo \"<td><input id='password' type='password' name='password' value='' size='20'\n autocomplete='new-password' onkeyup=\\\"return passwordCheck();\\\"></td>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password2'>\" . __('Password confirmation') . \"</label></td>\";\n echo \"<td><input type='password' id='password2' name='password2' value='' size='20' autocomplete='new-password'>\";\n echo \"</td></tr>\";", " if ($CFG_GLPI[\"use_password_security\"]) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td rowspan='2'>\";\n echo __('Password security policy');\n echo \"</td>\";\n echo \"<td rowspan='2'>\";\n Config::displayPasswordSecurityChecks();\n echo \"</td>\";\n echo \"</tr>\";\n }", " } else {\n echo \"<tr class='tab_bg_1'><td></td><td></td></tr>\";\n echo \"<tr class='tab_bg_1'><td></td><td></td></tr>\";\n }", " $tz_warning = '';\n $tz_available = $DB->areTimezonesAvailable($tz_warning);\n if ($tz_available || Session::haveRight(\"config\", READ)) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='timezone'>\".__('Time zone').\"</label></td><td>\";\n if ($tz_available) {\n $timezones = $DB->getTimezones();\n Dropdown::showFromArray(\n 'timezone',\n $timezones, [\n 'value' => $this->fields[\"timezone\"],\n 'display_emptychoice' => true\n ]\n );\n } else if (Session::haveRight(\"config\", READ)) {\n // Display a warning but only if user is more or less an admin\n echo \"<img src=\\\"{$CFG_GLPI['root_doc']}/pics/warning_min.png\\\">\";\n echo $tz_warning;\n }\n echo \"</td></tr>\";\n }", " echo \"<tr class='tab_bg_1'>\";\n if (!GLPI_DEMO_MODE) {\n $activerand = mt_rand();\n echo \"<td><label for='dropdown_is_active$activerand'>\".__('Active').\"</label></td><td>\";\n Dropdown::showYesNo('is_active', $this->fields['is_active'], -1, ['rand' => $activerand]);\n echo \"</td>\";\n } else {\n echo \"<td colspan='2'></td>\";\n }\n echo \"<td>\" . _n('Email', 'Emails', Session::getPluralNumber());\n UserEmail::showAddEmailButton($this);\n echo \"</td><td>\";\n UserEmail::showForUser($this);\n echo \"</td>\";\n echo \"</tr>\";", " if (!GLPI_DEMO_MODE) {\n $sincerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='showdate$sincerand'>\".__('Valid since').\"</label></td><td>\";\n Html::showDateTimeField(\"begin_date\", ['value' => $this->fields[\"begin_date\"],\n 'rand' => $sincerand,\n 'maybeempty' => true]);\n echo \"</td>\";", " $untilrand = mt_rand();\n echo \"<td><label for='showdate$untilrand'>\".__('Valid until').\"</label></td><td>\";\n Html::showDateTimeField(\"end_date\", ['value' => $this->fields[\"end_date\"],\n 'rand' => $untilrand,\n 'maybeempty' => true]);\n echo \"</td></tr>\";\n }", " $phonerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='textfield_phone$phonerand'>\" . Phone::getTypeName(1) . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"phone\", ['rand' => $phonerand]);\n echo \"</td>\";\n //Authentications information : auth method used and server used\n //don't display is creation of a new user'\n if (!empty($ID)) {\n if (Session::haveRight(self::$rightname, self::READAUTHENT)) {\n echo \"<td>\" . __('Authentication') . \"</td><td>\";\n echo Auth::getMethodName($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);\n if (!empty($this->fields[\"date_sync\"])) {\n //TRANS: %s is the date of last sync\n echo '<br>'.sprintf(__('Last synchronization on %s'),\n Html::convDateTime($this->fields[\"date_sync\"]));\n }\n if (!empty($this->fields[\"user_dn\"])) {\n //TRANS: %s is the user dn\n echo '<br>'.sprintf(__('%1$s: %2$s'), __('User DN'), $this->fields[\"user_dn\"]);\n }\n if ($this->fields['is_deleted_ldap']) {\n echo '<br>'.__('User missing in LDAP directory');\n }", " echo \"</td>\";\n } else {\n echo \"<td colspan='2'>&nbsp;</td>\";\n }\n } else {\n echo \"<td colspan='2'><input type='hidden' name='authtype' value='1'></td>\";\n }", " echo \"</tr>\";", " $mobilerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='textfield_mobile$mobilerand'>\" . __('Mobile phone') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"mobile\", ['rand' => $mobilerand]);\n echo \"</td>\";\n $catrand = mt_rand();\n echo \"<td><label for='dropdown_usercategories_id$catrand'>\" . __('Category') . \"</label></td><td>\";\n UserCategory::dropdown(['value' => $this->fields[\"usercategories_id\"], 'rand' => $catrand]);\n echo \"</td></tr>\";", " $phone2rand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='textfield_phone2$phone2rand'>\" . __('Phone 2') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"phone2\", ['rand' => $phone2rand]);\n echo \"</td>\";\n echo \"<td rowspan='4' class='middle'><label for='comment'>\" . __('Comments') . \"</label></td>\";\n echo \"<td class='center middle' rowspan='4'>\";\n echo \"<textarea cols='45' rows='6' id='comment' name='comment' >\".$this->fields[\"comment\"].\"</textarea>\";\n echo \"</td></tr>\";", " $admnumrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_registration_number$admnumrand'>\" . __('Administrative number') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"registration_number\", ['rand' => $admnumrand]);\n echo \"</td></tr>\";", " $titlerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='dropdown_usertitles_id$titlerand'>\" . _x('person', 'Title') . \"</label></td><td>\";\n UserTitle::dropdown(['value' => $this->fields[\"usertitles_id\"], 'rand' => $titlerand]);\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n if (!empty($ID)) {\n $locrand = mt_rand();\n echo \"<td><label for='dropdown_locations_id$locrand'>\" . Location::getTypeName(1) . \"</label></td><td>\";\n $entities = $this->getEntities();\n if (count($entities) <= 0) {\n $entities = -1;\n }\n Location::dropdown(['value' => $this->fields[\"locations_id\"],\n 'rand' => $locrand,\n 'entity' => $entities]);\n echo \"</td>\";\n }\n echo \"</tr>\";", " if (empty($ID)) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<th colspan='2'>\"._n('Authorization', 'Authorizations', 1).\"</th>\";\n $recurrand = mt_rand();\n echo \"<td><label for='dropdown__is_recursive$recurrand'>\" . __('Recursive') . \"</label></td><td>\";\n Dropdown::showYesNo(\"_is_recursive\", 0, -1, ['rand' => $recurrand]);\n echo \"</td></tr>\";\n $profilerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='dropdown__profiles_id$profilerand'>\" . Profile::getTypeName(1) . \"</label></td><td>\";\n Profile::dropdownUnder(['name' => '_profiles_id',\n 'rand' => $profilerand,\n 'value' => Profile::getDefault()]);", " $entrand = mt_rand();\n echo \"</td><td><label for='dropdown__entities_id$entrand'>\" . Entity::getTypeName(1) . \"</label></td><td>\";\n Entity::dropdown(['name' => '_entities_id',\n 'display_emptychoice' => false,\n 'rand' => $entrand,\n 'entity' => $_SESSION['glpiactiveentities']]);\n echo \"</td></tr>\";\n } else {\n if ($higherrights || $ismyself) {\n $profilerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='dropdown_profiles_id$profilerand'>\" . __('Default profile') . \"</label></td><td>\";", " $options = Dropdown::getDropdownArrayNames('glpi_profiles',\n Profile_User::getUserProfiles($this->fields['id']));", " Dropdown::showFromArray(\"profiles_id\", $options,\n ['value' => $this->fields[\"profiles_id\"],\n 'rand' => $profilerand,\n 'display_emptychoice' => true]);\n }\n if ($higherrights) {\n $entrand = mt_rand();\n echo \"</td><td><label for='dropdown_entities_id$entrand'>\" . __('Default entity') . \"</label></td><td>\";\n $entities = $this->getEntities();\n Entity::dropdown(['value' => $this->fields[\"entities_id\"],\n 'rand' => $entrand,\n 'entity' => $entities]);\n echo \"</td></tr>\";", " $grouprand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='dropdown_profiles_id$grouprand'>\" . __('Default group') . \"</label></td><td>\";", " $options = [];\n foreach (Group_User::getUserGroups($this->fields['id']) as $group) {\n $options[$group['id']] = $group['completename'];\n }", " Dropdown::showFromArray(\"groups_id\", $options,\n ['value' => $this->fields[\"groups_id\"],\n 'rand' => $grouprand,\n 'display_emptychoice' => true]);", " echo \"</td>\";\n $userrand = mt_rand();\n echo \"<td><label for='dropdown_users_id_supervisor_$userrand'>\" . __('Responsible') . \"</label></td><td>\";", " User::dropdown(['name' => 'users_id_supervisor',\n 'value' => $this->fields[\"users_id_supervisor\"],\n 'rand' => $userrand,\n 'entity' => $_SESSION[\"glpiactive_entity\"],\n 'right' => 'all']);\n echo \"</td></tr>\";\n }", " if ($this->can($ID, UPDATE)) {\n echo \"<tr class='tab_bg_1'><th colspan='4'>\". __('Remote access keys') .\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"Personal token\");\n echo \"</td><td colspan='2'>\";", " if (!empty($this->fields[\"personal_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_personal_token', [\n 'value' => $this->fields[\"personal_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"personal_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_personal_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"API token\");\n echo \"</td><td colspan='2'>\";\n if (!empty($this->fields[\"api_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_api_token', [\n 'value' => $this->fields[\"api_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"api_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_api_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";\n }", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td colspan='2' class='center'>\";\n if ($this->fields[\"last_login\"]) {\n printf(__('Last login on %s'), Html::convDateTime($this->fields[\"last_login\"]));\n }\n echo \"</td><td colspan='2'class='center'>\";", " echo \"</td></tr>\";\n }", " $this->showFormButtons($options);", " return true;\n }", "\n /** Print the user personnal information for check.\n *\n * @param integer $userid ID of the user\n *\n * @return void|boolean false if user is not the current user, otherwise print form\n *\n * @since 0.84\n */\n static function showPersonalInformation($userid) {\n global $CFG_GLPI;", " $user = new self();\n if (!$user->can($userid, READ)\n && ($userid != Session::getLoginUserID())) {\n return false;\n }\n echo \"<table class='tab_glpi left' width='100%'>\";\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b' width='20%'>\";\n echo __('Name');\n echo \"</td><td width='30%'>\";\n echo getUserName($userid);\n echo \"</td>\";\n echo \"<td class='b' width='20%'>\";\n echo Phone::getTypeName(1);\n echo \"</td><td width='30%'>\";\n echo $user->getField('phone');\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b'>\";\n echo __('Phone 2');\n echo \"</td><td>\";\n echo $user->getField('phone2');\n echo \"</td>\";\n echo \"<td class='b'>\";\n echo __('Mobile phone');\n echo \"</td><td>\";\n echo $user->getField('mobile');\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b'>\";\n echo _n('Email', 'Emails', 1);\n echo \"</td><td>\";\n echo $user->getDefaultEmail();\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b'>\";\n echo Location::getTypeName(1);\n echo \"</td><td>\";\n echo Dropdown::getDropdownName('glpi_locations', $user->getField('locations_id'));\n echo \"</td>\";\n echo \"<td colspan='2' class='center'>\";\n if ($userid == Session::getLoginUserID()) {\n echo \"<a href='\".$CFG_GLPI['root_doc'].\"/front/preference.php' class='vsubmit'>\".\n __('Edit').\"</a>\";\n } else {\n echo \"&nbsp;\";\n }\n echo \"</td>\";\n echo \"</tr>\";\n echo \"</table>\";\n }", "\n /**\n * Print the user preference form.\n *\n * @param string $target Form target\n * @param integer $ID ID of the user\n *\n * @return boolean true if user found, false otherwise\n */\n function showMyForm($target, $ID) {\n global $CFG_GLPI, $DB;", " // Affiche un formulaire User\n if (($ID != Session::getLoginUserID())\n && !$this->currentUserHaveMoreRightThan($ID)) {\n return false;\n }\n if ($this->getFromDB($ID)) {\n $rand = mt_rand();\n $authtype = $this->getAuthMethodsByID();", " $extauth = !(($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || (($this->fields[\"authtype\"] == Auth::NOT_YET_AUTHENTIFIED)\n && !empty($this->fields[\"password\"])));", " // No autocopletion :\n $save_autocompletion = $CFG_GLPI[\"use_ajax_autocompletion\"];\n $CFG_GLPI[\"use_ajax_autocompletion\"] = false;", " echo \"<div class='center'>\";\n echo \"<form method='post' name='user_manager' enctype='multipart/form-data' action='\".$target.\"' autocomplete='off'>\";\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr><th colspan='4'>\".sprintf(__('%1$s: %2$s'), __('Login'), $this->fields[\"name\"]);\n echo \"<input type='hidden' name='name' value='\" . $this->fields[\"name\"] . \"'>\";\n echo \"<input type='hidden' name='id' value='\" . $this->fields[\"id\"] . \"'>\";\n echo \"</th></tr>\";", " $surnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_realname$surnamerand'>\" . __('Surname') . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['realname_field'])\n && !empty($authtype['realname_field'])) {", " echo $this->fields[\"realname\"];\n } else {\n Html::autocompletionTextField($this, \"realname\", ['rand' => $surnamerand]);\n }\n echo \"</td>\";", " if (!empty($this->fields[\"name\"])) {\n echo \"<td rowspan='7'>\" . __('Picture') . \"</td>\";\n echo \"<td rowspan='7'>\";\n echo \"<div class='user_picture_border_small' id='picture$rand'>\";\n echo \"<img class='user_picture_small' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getThumbnailURLForPicture($this->fields['picture']).\"'>\";\n echo \"</div>\";\n $full_picture = \"<div class='user_picture_border'>\";\n $full_picture .= \"<img class='user_picture' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getURLForPicture($this->fields['picture']).\"'>\";\n $full_picture .= \"</div>\";", " Html::showTooltip($full_picture, ['applyto' => \"picture$rand\"]);\n echo Html::file(['name' => 'picture', 'display' => false, 'onlyimages' => true]);", " echo \"&nbsp;\";\n Html::showCheckbox(['name' => '_blank_picture', 'title' => __('Clear')]);\n echo \"&nbsp;\".__('Clear');", " echo \"</td>\";\n echo \"</tr>\";\n }", " $firstnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_firstname$firstnamerand'>\" . __('First name') . \"</label></td><td>\";\n if ($extauth\n && isset($authtype['firstname_field'])\n && !empty($authtype['firstname_field'])) {", " echo $this->fields[\"firstname\"];\n } else {\n Html::autocompletionTextField($this, \"firstname\", ['rand' => $firstnamerand]);\n }\n echo \"</td></tr>\";", " if ($extauth\n && $this->fields['auths_id']\n && AuthLDAP::isSyncFieldConfigured($this->fields['auths_id'])) {\n echo \"<tr class='tab_bg_1'><td>\" . __('Synchronization field') . \"</td><td>\";\n if (empty($this->fields['sync_field'])) {\n echo Dropdown::EMPTY_VALUE;\n } else {\n echo $this->fields['sync_field'];\n }\n echo \"</td></tr>\";\n } else {\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n }", " echo \"<tr class='tab_bg_1'>\";", " if (!GLPI_DEMO_MODE) {\n $langrand = mt_rand();\n echo \"<td><label for='dropdown_language$langrand'>\" . __('Language') . \"</label></td><td>\";\n // Language is stored as null in DB if value is same as the global config.\n $language = $this->fields[\"language\"];\n if (null === $this->fields[\"language\"]) {\n $language = $CFG_GLPI['language'];\n }\n Dropdown::showLanguages(\n \"language\",\n [\n 'rand' => $langrand,\n 'value' => $language,\n ]\n );\n echo \"</td>\";\n } else {\n echo \"<td colspan='2'>&nbsp;</td>\";\n }\n echo \"</tr>\";", " //do some rights verification\n if (!$extauth\n && Session::haveRight(\"password_update\", \"1\")) {", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password'>\" . __('Password') . \"</label></td>\";\n echo \"<td><input id='password' type='password' name='password' value='' size='30' autocomplete='new-password' onkeyup=\\\"return passwordCheck();\\\">\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password2'>\" . __('Password confirmation') . \"</label></td>\";\n echo \"<td><input type='password' name='password2' id='password2' value='' size='30' autocomplete='new-password'>\";\n echo \"</td></tr>\";", " if ($CFG_GLPI[\"use_password_security\"]) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td rowspan='2'>\";\n echo __('Password security policy');\n echo \"</td>\";\n echo \"<td rowspan='2'>\";\n Config::displayPasswordSecurityChecks();\n echo \"</td>\";\n echo \"</tr>\";\n }\n } else {\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n }", " $tz_warning = '';\n $tz_available = $DB->areTimezonesAvailable($tz_warning);\n if ($tz_available || Session::haveRight(\"config\", READ)) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='timezone'>\".__('Time zone').\"</label></td><td>\";\n if ($tz_available) {\n $timezones = $DB->getTimezones();\n Dropdown::showFromArray(\n 'timezone',\n $timezones, [\n 'value' => $this->fields[\"timezone\"],\n 'display_emptychoice' => true\n ]\n );\n } else if (Session::haveRight(\"config\", READ)) {\n // Display a warning but only if user is more or less an admin\n echo \"<img src=\\\"{$CFG_GLPI['root_doc']}/pics/warning_min.png\\\">\";\n echo $tz_warning;\n }\n echo \"</td>\";\n if ($extauth\n || !Session::haveRight(\"password_update\", \"1\")) {\n echo \"<td colspan='2'></td>\";\n }\n echo \"</tr>\";\n }", " $phonerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_phone$phonerand'>\" . Phone::getTypeName(1) . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['phone_field']) && !empty($authtype['phone_field'])) {\n echo $this->fields[\"phone\"];\n } else {\n Html::autocompletionTextField($this, \"phone\", ['rand' => $phonerand]);\n }\n echo \"</td>\";\n echo \"<td class='top'>\" . _n('Email', 'Emails', Session::getPluralNumber());\n UserEmail::showAddEmailButton($this);\n echo \"</td><td>\";\n UserEmail::showForUser($this);\n echo \"</td>\";\n echo \"</tr>\";", " $mobilerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_mobile$mobilerand'>\" . __('Mobile phone') . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['mobile_field']) && !empty($authtype['mobile_field'])) {\n echo $this->fields[\"mobile\"];\n } else {\n Html::autocompletionTextField($this, \"mobile\", ['rand' => $mobilerand]);\n }\n echo \"</td>\";", " if (count($_SESSION['glpiprofiles']) >1) {\n $profilerand = mt_rand();\n echo \"<td><label for='dropdown_profiles_id$profilerand'>\" . __('Default profile') . \"</label></td><td>\";", " $options = Dropdown::getDropdownArrayNames('glpi_profiles',\n Profile_User::getUserProfiles($this->fields['id']));\n Dropdown::showFromArray(\"profiles_id\", $options,\n ['value' => $this->fields[\"profiles_id\"],\n 'rand' => $profilerand,\n 'display_emptychoice' => true]);\n echo \"</td>\";", " } else {\n echo \"<td colspan='2'>&nbsp;</td>\";\n }\n echo \"</tr>\";", " $phone2rand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_phone2$phone2rand'>\" . __('Phone 2') . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['phone2_field']) && !empty($authtype['phone2_field'])) {\n echo $this->fields[\"phone2\"];\n } else {\n Html::autocompletionTextField($this, \"phone2\", ['rand' => $phone2rand]);\n }\n echo \"</td>\";", " $entities = $this->getEntities();\n if (!GLPI_DEMO_MODE\n && (count($_SESSION['glpiactiveentities']) > 1)) {\n $entrand = mt_rand();\n echo \"<td><label for='dropdown_entities_id$entrand'>\" . __('Default entity') . \"</td><td>\";\n Entity::dropdown(['value' => $this->fields['entities_id'],\n 'rand' => $entrand,\n 'entity' => $entities]);\n } else {\n echo \"<td colspan='2'>&nbsp;\";\n }\n echo \"</td></tr>\";", " $admnumrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_registration_number$admnumrand'>\" . __('Administrative number') . \"</label></td><td>\";\n if ($extauth\n && isset($authtype['registration_number_field']) && !empty($authtype['registration_number_field'])) {\n echo $this->fields[\"registration_number\"];\n } else {\n Html::autocompletionTextField($this, \"registration_number\", ['rand' => $admnumrand]);\n }\n echo \"</td><td colspan='2'></td></tr>\";", " $locrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='dropdown_locations_id$locrand'>\" . Location::getTypeName(1) . \"</label></td><td>\";\n Location::dropdown(['value' => $this->fields['locations_id'],\n 'rand' => $locrand,\n 'entity' => $entities]);", " if (Config::canUpdate()) {\n $moderand = mt_rand();\n echo \"<td><label for='dropdown_use_mode$moderand'>\" . __('Use GLPI in mode') . \"</label></td><td>\";\n $modes = [\n Session::NORMAL_MODE => __('Normal'),\n Session::DEBUG_MODE => __('Debug'),\n ];\n Dropdown::showFromArray('use_mode', $modes, ['value' => $this->fields[\"use_mode\"], 'rand' => $moderand]);\n } else {\n echo \"<td colspan='2'>&nbsp;\";\n }\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><th colspan='4'>\". __('Remote access keys') .\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"Personal token\");\n echo \"</td><td colspan='2'>\";", " if (!empty($this->fields[\"personal_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_personal_token', [\n 'value' => $this->fields[\"personal_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"personal_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_personal_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"API token\");\n echo \"</td><td colspan='2'>\";\n if (!empty($this->fields[\"api_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_api_token', [\n 'value' => $this->fields[\"api_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"api_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_api_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";", " echo \"<tr><td class='tab_bg_2 center' colspan='4'>\";\n echo \"<input type='submit' name='update' value=\\\"\"._sx('button', 'Save').\"\\\" class='submit'>\";\n echo \"</td></tr>\";", " echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n $CFG_GLPI[\"use_ajax_autocompletion\"] = $save_autocompletion;\n return true;\n }\n return false;\n }", "\n /**\n * Get all the authentication method parameters for the current user.\n *\n * @return array\n */\n function getAuthMethodsByID() {\n return Auth::getMethodsByID($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);\n }", "\n function pre_updateInDB() {\n global $DB;", " if (($key = array_search('name', $this->updates)) !== false) {\n /// Check if user does not exists\n $iterator = $DB->request([\n 'FROM' => $this->getTable(),\n 'WHERE' => [\n 'name' => $this->input['name'],\n 'id' => ['<>', $this->input['id']]\n ]\n ]);", " if (count($iterator)) {\n //To display a message\n $this->fields['name'] = $this->oldvalues['name'];\n unset($this->updates[$key]);\n unset($this->oldvalues['name']);\n Session::addMessageAfterRedirect(__('Unable to update login. A user already exists.'),\n false, ERROR);\n }", " if (!Auth::isValidLogin(stripslashes($this->input['name']))) {\n $this->fields['name'] = $this->oldvalues['name'];\n unset($this->updates[$key]);\n unset($this->oldvalues['name']);\n Session::addMessageAfterRedirect(__('The login is not valid. Unable to update login.'),\n false, ERROR);\n }", " }", " // ## Security system except for login update:\n //\n // An **external** (ldap, mail) user without User::UPDATE right\n // should not be able to update its own fields\n // (for example, fields concerned by ldap synchronisation)\n // except on login action (which triggers synchronisation).\n if (Session::getLoginUserID() === (int)$this->input['id']\n && !Session::haveRight(\"user\", UPDATE)\n && !strpos($_SERVER['PHP_SELF'], \"/front/login.php\")\n && isset($this->fields[\"authtype\"])) {", " // extauth ldap case\n if ($_SESSION[\"glpiextauth\"]\n && ($this->fields[\"authtype\"] == Auth::LDAP\n || Auth::isAlternateAuth($this->fields[\"authtype\"]))) {", " $authtype = Auth::getMethodsByID($this->fields[\"authtype\"],\n $this->fields[\"auths_id\"]);\n if (count($authtype)) {\n $fields = AuthLDAP::getSyncFields($authtype);\n foreach ($fields as $key => $val) {\n if (!empty($val)\n && (($key2 = array_search($key, $this->updates)) !== false)) {", " unset ($this->updates[$key2]);\n unset($this->oldvalues[$key]);", " }\n }\n }\n }", " if (($key = array_search(\"is_active\", $this->updates)) !== false) {\n unset ($this->updates[$key]);\n unset($this->oldvalues['is_active']);\n }", " if (($key = array_search(\"comment\", $this->updates)) !== false) {\n unset ($this->updates[$key]);\n unset($this->oldvalues['comment']);\n }\n }\n }", " function getSpecificMassiveActions($checkitem = null) {", " $isadmin = static::canUpdate();\n $actions = parent::getSpecificMassiveActions($checkitem);\n if ($isadmin) {\n $actions['Group_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'add']\n = \"<i class='ma-icon fas fa-users'></i>\".\n __('Associate to a group');\n $actions['Group_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'remove']\n = __('Dissociate from a group');\n $actions['Profile_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'add']\n = \"<i class='ma-icon fas fa-user-shield'></i>\".\n __('Associate to a profile');\n $actions['Profile_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'remove']\n = __('Dissociate from a profile');\n $actions['Group_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'change_group_user']\n = \"<i class='ma-icon fas fa-users-cog'></i>\".\n __(\"Move to group\");\n }", " if (Session::haveRight(self::$rightname, self::UPDATEAUTHENT)) {\n $prefix = __CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR;\n $actions[$prefix.'change_authtype'] = \"<i class='ma-icon fas fa-user-cog'></i>\".\n _x('button', 'Change the authentication method');\n $actions[$prefix.'force_user_ldap_update'] = \"<i class='ma-icon fas fa-sync'></i>\".\n __('Force synchronization');\n }\n return $actions;\n }", " static function showMassiveActionsSubForm(MassiveAction $ma) {\n global $CFG_GLPI;", " switch ($ma->getAction()) {\n case 'change_authtype' :\n $rand = Auth::dropdown(['name' => 'authtype']);\n $paramsmassaction = ['authtype' => '__VALUE__'];\n Ajax::updateItemOnSelectEvent(\"dropdown_authtype$rand\", \"show_massiveaction_field\",\n $CFG_GLPI[\"root_doc\"].\n \"/ajax/dropdownMassiveActionAuthMethods.php\",\n $paramsmassaction);\n echo \"<span id='show_massiveaction_field'><br><br>\";\n echo Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']).\"</span>\";\n return true;\n }\n return parent::showMassiveActionsSubForm($ma);\n }", " static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item,\n array $ids) {", " switch ($ma->getAction()) {\n case 'force_user_ldap_update' :\n foreach ($ids as $id) {\n if ($item->can($id, UPDATE)) {\n if (($item->fields[\"authtype\"] == Auth::LDAP)\n || ($item->fields[\"authtype\"] == Auth::EXTERNAL)) {\n if (AuthLDAP::forceOneUserSynchronization($item, false)) {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n }\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n }\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);\n $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));\n }\n }\n return;", " case 'change_authtype' :\n $input = $ma->getInput();\n if (!isset($input[\"authtype\"])\n || !isset($input[\"auths_id\"])) {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n return;\n }\n if (Session::haveRight(self::$rightname, self::UPDATEAUTHENT)) {\n if (User::changeAuthMethod($ids, $input[\"authtype\"], $input[\"auths_id\"])) {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_OK);\n } else {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);\n }\n } else {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_NORIGHT);\n $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));\n }\n return;\n }\n parent::processMassiveActionsForOneItemtype($ma, $item, $ids);\n }", "\n function rawSearchOptions() {\n // forcegroup by on name set force group by for all items\n $tab = [];", " $tab[] = [\n 'id' => 'common',\n 'name' => __('Characteristics')\n ];", " $tab[] = [\n 'id' => '1',\n 'table' => $this->getTable(),\n 'field' => 'name',\n 'name' => __('Login'),\n 'datatype' => 'itemlink',\n 'forcegroupby' => true,\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '2',\n 'table' => $this->getTable(),\n 'field' => 'id',\n 'name' => __('ID'),\n 'massiveaction' => false,\n 'datatype' => 'number'\n ];", " $tab[] = [\n 'id' => '34',\n 'table' => $this->getTable(),\n 'field' => 'realname',\n 'name' => __('Last name'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '9',\n 'table' => $this->getTable(),\n 'field' => 'firstname',\n 'name' => __('First name'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '5',\n 'table' => 'glpi_useremails',\n 'field' => 'email',\n 'name' => _n('Email', 'Emails', Session::getPluralNumber()),\n 'datatype' => 'email',\n 'joinparams' => [\n 'jointype' => 'child'\n ],\n 'forcegroupby' => true,\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '150',\n 'table' => $this->getTable(),\n 'field' => 'picture',\n 'name' => __('Picture'),\n 'datatype' => 'specific',\n 'nosearch' => true,\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '28',\n 'table' => $this->getTable(),\n 'field' => 'sync_field',\n 'name' => __('Synchronization field'),\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab = array_merge($tab, Location::rawSearchOptionsToAdd());", " $tab[] = [\n 'id' => '8',\n 'table' => $this->getTable(),\n 'field' => 'is_active',\n 'name' => __('Active'),\n 'datatype' => 'bool'\n ];", " $tab[] = [\n 'id' => '6',\n 'table' => $this->getTable(),\n 'field' => 'phone',\n 'name' => Phone::getTypeName(1),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '10',\n 'table' => $this->getTable(),\n 'field' => 'phone2',\n 'name' => __('Phone 2'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '11',\n 'table' => $this->getTable(),\n 'field' => 'mobile',\n 'name' => __('Mobile phone'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '13',\n 'table' => 'glpi_groups',\n 'field' => 'completename',\n 'name' => Group::getTypeName(Session::getPluralNumber()),\n 'forcegroupby' => true,\n 'datatype' => 'itemlink',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_groups_users',\n 'joinparams' => [\n 'jointype' => 'child'\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '14',\n 'table' => $this->getTable(),\n 'field' => 'last_login',\n 'name' => __('Last login'),\n 'datatype' => 'datetime',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '15',\n 'table' => $this->getTable(),\n 'field' => 'authtype',\n 'name' => __('Authentication'),\n 'massiveaction' => false,\n 'datatype' => 'specific',\n 'searchtype' => 'equals',\n 'additionalfields' => [\n '0' => 'auths_id'\n ]\n ];", " $tab[] = [\n 'id' => '30',\n 'table' => 'glpi_authldaps',\n 'field' => 'name',\n 'linkfield' => 'auths_id',\n 'name' => __('LDAP directory for authentication'),\n 'massiveaction' => false,\n 'joinparams' => [\n 'condition' => 'AND REFTABLE.`authtype` = ' . Auth::LDAP\n ],\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '31',\n 'table' => 'glpi_authmails',\n 'field' => 'name',\n 'linkfield' => 'auths_id',\n 'name' => __('Email server for authentication'),\n 'massiveaction' => false,\n 'joinparams' => [\n 'condition' => 'AND REFTABLE.`authtype` = ' . Auth::MAIL\n ],\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '16',\n 'table' => $this->getTable(),\n 'field' => 'comment',\n 'name' => __('Comments'),\n 'datatype' => 'text'\n ];", " $tab[] = [\n 'id' => '17',\n 'table' => $this->getTable(),\n 'field' => 'language',\n 'name' => __('Language'),\n 'datatype' => 'language',\n 'display_emptychoice' => true,\n 'emptylabel' => 'Default value'\n ];", " $tab[] = [\n 'id' => '19',\n 'table' => $this->getTable(),\n 'field' => 'date_mod',\n 'name' => __('Last update'),\n 'datatype' => 'datetime',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '121',\n 'table' => $this->getTable(),\n 'field' => 'date_creation',\n 'name' => __('Creation date'),\n 'datatype' => 'datetime',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '20',\n 'table' => 'glpi_profiles',\n 'field' => 'name',\n 'name' => sprintf(__('%1$s (%2$s)'), Profile::getTypeName(Session::getPluralNumber()),\n Entity::getTypeName(1)),\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'datatype' => 'dropdown',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_profiles_users',\n 'joinparams' => [\n 'jointype' => 'child'\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '21',\n 'table' => $this->getTable(),\n 'field' => 'user_dn',\n 'name' => __('User DN'),\n 'massiveaction' => false,\n 'datatype' => 'text'\n ];", " $tab[] = [\n 'id' => '22',\n 'table' => $this->getTable(),\n 'field' => 'registration_number',\n 'name' => __('Administrative number'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '23',\n 'table' => $this->getTable(),\n 'field' => 'date_sync',\n 'datatype' => 'datetime',\n 'name' => __('Last synchronization'),\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '24',\n 'table' => $this->getTable(),\n 'field' => 'is_deleted_ldap',\n 'name' => __('Deleted user in LDAP directory'),\n 'datatype' => 'bool',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '80',\n 'table' => 'glpi_entities',\n 'linkfield' => 'entities_id',\n 'field' => 'completename',\n 'name' => sprintf(__('%1$s (%2$s)'), Entity::getTypeName(Session::getPluralNumber()),\n Profile::getTypeName(1)),\n 'forcegroupby' => true,\n 'datatype' => 'dropdown',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_profiles_users',\n 'joinparams' => [\n 'jointype' => 'child'\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '81',\n 'table' => 'glpi_usertitles',\n 'field' => 'name',\n 'name' => __('Title'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '82',\n 'table' => 'glpi_usercategories',\n 'field' => 'name',\n 'name' => __('Category'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '79',\n 'table' => 'glpi_profiles',\n 'field' => 'name',\n 'name' => __('Default profile'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '77',\n 'table' => 'glpi_entities',\n 'field' => 'name',\n 'massiveaction' => true,\n 'name' => __('Default entity'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '62',\n 'table' => $this->getTable(),\n 'field' => 'begin_date',\n 'name' => __('Begin date'),\n 'datatype' => 'datetime'\n ];", " $tab[] = [\n 'id' => '63',\n 'table' => $this->getTable(),\n 'field' => 'end_date',\n 'name' => __('End date'),\n 'datatype' => 'datetime'\n ];", " $tab[] = [\n 'id' => '60',\n 'table' => 'glpi_tickets',\n 'field' => 'id',\n 'name' => __('Number of tickets as requester'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_tickets_users',\n 'joinparams' => [\n 'jointype' => 'child',\n 'condition' => 'AND NEWTABLE.`type` = ' . CommonITILActor::REQUESTER\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '61',\n 'table' => 'glpi_tickets',\n 'field' => 'id',\n 'name' => __('Number of written tickets'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'child',\n 'linkfield' => 'users_id_recipient'\n ]\n ];", " $tab[] = [\n 'id' => '64',\n 'table' => 'glpi_tickets',\n 'field' => 'id',\n 'name' => __('Number of assigned tickets'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_tickets_users',\n 'joinparams' => [\n 'jointype' => 'child',\n 'condition' => 'AND NEWTABLE.`type` = '.CommonITILActor::ASSIGN\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '99',\n 'table' => 'glpi_users',\n 'field' => 'name',\n 'linkfield' => 'users_id_supervisor',\n 'name' => __('Responsible'),\n 'datatype' => 'dropdown',\n 'massiveaction' => false,\n ];", " // add objectlock search options\n $tab = array_merge($tab, ObjectLock::rawSearchOptionsToAdd(get_class($this)));", " return $tab;\n }", " static function getSpecificValueToDisplay($field, $values, array $options = []) {", " if (!is_array($values)) {\n $values = [$field => $values];\n }\n switch ($field) {\n case 'authtype':\n $auths_id = 0;\n if (isset($values['auths_id']) && !empty($values['auths_id'])) {\n $auths_id = $values['auths_id'];\n }\n return Auth::getMethodName($values[$field], $auths_id);\n case 'picture':\n if (isset($options['html']) && $options['html']) {\n return Html::image(self::getThumbnailURLForPicture($values['picture']),\n ['class' => 'user_picture_small', 'alt' => __('Picture')]);\n }\n }\n return parent::getSpecificValueToDisplay($field, $values, $options);\n }", " static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {", " if (!is_array($values)) {\n $values = [$field => $values];\n }\n $options['display'] = false;\n switch ($field) {\n case 'authtype' :\n $options['name'] = $name;\n $options['value'] = $values[$field];\n return Auth::dropdown($options);\n }\n return parent::getSpecificValueToSelect($field, $name, $values, $options);\n }", "\n /**\n * Get all groups where the current user have delegating.\n *\n * @since 0.83\n *\n * @param integer|string $entities_id ID of the entity to restrict\n *\n * @return integer[]\n */\n static function getDelegateGroupsForUser($entities_id = '') {\n global $DB;", " $iterator = $DB->request([\n 'SELECT' => 'glpi_groups_users.groups_id',\n 'DISTINCT' => true,\n 'FROM' => 'glpi_groups_users',\n 'INNER JOIN' => [\n 'glpi_groups' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'groups_id',\n 'glpi_groups' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.users_id' => Session::getLoginUserID(),\n 'glpi_groups_users.is_userdelegate' => 1\n ] + getEntitiesRestrictCriteria('glpi_groups', '', $entities_id, 1)\n ]);", " $groups = [];\n while ($data = $iterator->next()) {\n $groups[$data['groups_id']] = $data['groups_id'];\n }\n return $groups;\n }", "\n /**\n * Execute the query to select box with all glpi users where select key = name\n *\n * Internaly used by showGroup_Users, dropdownUsers and ajax/getDropdownUsers.php\n *\n * @param boolean $count true if execute an count(*) (true by default)\n * @param string|string[] $right limit user who have specific right (default 'all')\n * @param integer $entity_restrict Restrict to a defined entity (default -1)\n * @param integer $value default value (default 0)\n * @param integer[] $used Already used items ID: not to display in dropdown\n * @param string $search pattern (default '')\n * @param integer $start start LIMIT value (default 0)\n * @param integer $limit limit LIMIT value (default -1 no limit)\n * @param boolean $inactive_deleted true to retreive also inactive or deleted users\n *\n * @return mysqli_result|boolean\n */\n static function getSqlSearchResult ($count = true, $right = \"all\", $entity_restrict = -1, $value = 0,\n array $used = [], $search = '', $start = 0, $limit = -1,\n $inactive_deleted = 0) {\n global $DB;", " // No entity define : use active ones\n if ($entity_restrict < 0) {\n $entity_restrict = $_SESSION[\"glpiactiveentities\"];\n }", " $joinprofile = false;\n $joinprofileright = false;\n $WHERE = [];", " switch ($right) {\n case \"interface\" :\n $joinprofile = true;\n $WHERE = [\n 'glpi_profiles.interface' => 'central'\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1);\n break;", " case \"id\" :\n $WHERE = ['glpi_users.id' => Session::getLoginUserID()];\n break;", " case \"delegate\" :\n $groups = self::getDelegateGroupsForUser($entity_restrict);\n $users = [];\n if (count($groups)) {\n $iterator = $DB->request([\n 'SELECT' => 'glpi_users.id',\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_users' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.groups_id' => $groups,\n 'glpi_groups_users.users_id' => ['<>', Session::getLoginUserID()]\n ]\n ]);\n while ($data = $iterator->next()) {\n $users[$data[\"id\"]] = $data[\"id\"];\n }\n }\n // Add me to users list for central\n if (Session::getCurrentInterface() == 'central') {\n $users[Session::getLoginUserID()] = Session::getLoginUserID();\n }", " if (count($users)) {\n $WHERE = ['glpi_users.id' => $users];\n }\n break;", " case \"groups\" :\n $groups = [];\n if (isset($_SESSION['glpigroups'])) {\n $groups = $_SESSION['glpigroups'];\n }\n $users = [];\n if (count($groups)) {\n $iterator = $DB->request([\n 'SELECT' => 'glpi_users.id',\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_users' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.groups_id' => $groups,\n 'glpi_groups_users.users_id' => ['<>', Session::getLoginUserID()]\n ]\n ]);\n while ($data = $iterator->next()) {\n $users[$data[\"id\"]] = $data[\"id\"];\n }\n }\n // Add me to users list for central\n if (Session::getCurrentInterface() == 'central') {\n $users[Session::getLoginUserID()] = Session::getLoginUserID();\n }", " if (count($users)) {\n $WHERE = ['glpi_users.id' => $users];\n }", " break;", " case \"all\" :\n $WHERE = [\n 'glpi_users.id' => ['>', 0],\n 'OR' => [\n 'glpi_profiles_users.entities_id' => null\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " default :\n $joinprofile = true;\n $joinprofileright = true;\n if (!is_array($right)) {\n $right = [$right];\n }\n $forcecentral = true;", " $ORWHERE = [];\n foreach ($right as $r) {\n switch ($r) {\n case 'own_ticket' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticket',\n 'glpi_profilerights.rights' => ['&', Ticket::OWN]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'create_ticket_validate' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticketvalidation',\n 'OR' => [\n ['glpi_profilerights.rights' => ['&', TicketValidation::CREATEREQUEST]],\n ['glpi_profilerights.rights' => ['&', TicketValidation::CREATEINCIDENT]]\n ]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n $forcecentral = false;\n break;", " case 'validate_request' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticketvalidation',\n 'glpi_profilerights.rights' => ['&', TicketValidation::VALIDATEREQUEST]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n $forcecentral = false;\n break;", " case 'validate_incident' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticketvalidation',\n 'glpi_profilerights.rights' => ['&', TicketValidation::VALIDATEINCIDENT]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n $forcecentral = false;\n break;", " case 'validate' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'changevalidation',\n 'glpi_profilerights.rights' => ['&', ChangeValidation::VALIDATE]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'create_validate' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'changevalidation',\n 'glpi_profilerights.rights' => ['&', ChangeValidation::CREATE]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'see_project' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'project',\n 'glpi_profilerights.rights' => ['&', Project::READMY]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'faq' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'knowbase',\n 'glpi_profilerights.rights' => ['&', KnowbaseItem::READFAQ]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];", " default :\n // Check read or active for rights\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => $r,\n 'glpi_profilerights.rights' => [\n '&',\n READ | CREATE | UPDATE | DELETE | PURGE\n ]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n }\n if (in_array($r, Profile::$helpdesk_rights)) {\n $forcecentral = false;\n }\n }", " if (count($ORWHERE)) {\n $WHERE[] = ['OR' => $ORWHERE];\n }", " if ($forcecentral) {\n $WHERE['glpi_profiles.interface'] = 'central';\n }\n }", " if (!$inactive_deleted) {\n $WHERE = array_merge(\n $WHERE, [\n 'glpi_users.is_deleted' => 0,\n 'glpi_users.is_active' => 1,\n [\n 'OR' => [\n ['glpi_users.begin_date' => null],\n ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]\n ]\n ],\n [\n 'OR' => [\n ['glpi_users.end_date' => null],\n ['glpi_users.end_date' => ['>', new QueryExpression('NOW()')]]\n ]\n ]", " ]\n );\n }", " if ((is_numeric($value) && $value)\n || count($used)) {", " $WHERE[] = [\n 'NOT' => [\n 'glpi_users.id' => $used\n ]\n ];\n }", " $criteria = [\n 'FROM' => 'glpi_users',\n 'LEFT JOIN' => [\n 'glpi_useremails' => [\n 'ON' => [\n 'glpi_useremails' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ],\n 'glpi_profiles_users' => [\n 'ON' => [\n 'glpi_profiles_users' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ]\n ];\n if ($count) {\n $criteria['SELECT'] = ['COUNT' => 'glpi_users.id AS CPT'];\n $criteria['DISTINCT'] = true;\n } else {\n $criteria['SELECT'] = 'glpi_users.*';\n $criteria['DISTINCT'] = true;\n }", " if ($joinprofile) {\n $criteria['LEFT JOIN']['glpi_profiles'] = [\n 'ON' => [\n 'glpi_profiles_users' => 'profiles_id',\n 'glpi_profiles' => 'id'\n ]\n ];\n if ($joinprofileright) {\n $criteria['LEFT JOIN']['glpi_profilerights'] = [\n 'ON' => [\n 'glpi_profilerights' => 'profiles_id',\n 'glpi_profiles' => 'id'\n ]\n ];\n }\n }", " if (!$count) {\n if ((strlen($search) > 0)) {\n $txt_search = Search::makeTextSearchValue($search);", " $firstname_field = $DB->quoteName(self::getTableField('firstname'));\n $realname_field = $DB->quoteName(self::getTableField('realname'));\n $fields = $_SESSION[\"glpinames_format\"] == self::FIRSTNAME_BEFORE\n ? [$firstname_field, $realname_field]\n : [$realname_field, $firstname_field];", " $concat = new \\QueryExpression(\n 'CONCAT(' . implode(',' . $DB->quoteValue(' ') . ',', $fields) . ')'\n . ' LIKE ' . $DB->quoteValue($txt_search)\n );\n $WHERE[] = [\n 'OR' => [\n 'glpi_users.name' => ['LIKE', $txt_search],\n 'glpi_users.realname' => ['LIKE', $txt_search],\n 'glpi_users.firstname' => ['LIKE', $txt_search],\n 'glpi_users.phone' => ['LIKE', $txt_search],\n 'glpi_useremails.email' => ['LIKE', $txt_search],\n $concat\n ]\n ];\n }", " if ($_SESSION[\"glpinames_format\"] == self::FIRSTNAME_BEFORE) {\n $criteria['ORDERBY'] = [\n 'glpi_users.firstname',\n 'glpi_users.realname',\n 'glpi_users.name'\n ];\n } else {\n $criteria['ORDERBY'] = [\n 'glpi_users.realname',\n 'glpi_users.firstname',\n 'glpi_users.name'\n ];\n }", " if ($limit > 0) {\n $criteria['LIMIT'] = $limit;\n $criteria['START'] = $start;\n }\n }\n $criteria['WHERE'] = $WHERE;\n return $DB->request($criteria);\n }", "\n /**\n * Make a select box with all glpi users where select key = name\n *\n * @param $options array of possible options:\n * - name : string / name of the select (default is users_id)\n * - value\n * - values : in case of select[multiple], pass the array of multiple values\n * - right : string / limit user who have specific right :\n * id -> only current user (default case);\n * interface -> central;\n * all -> all users;\n * specific right like Ticket::READALL, CREATE.... (is array passed one of all passed right is needed)\n * - comments : boolean / is the comments displayed near the dropdown (default true)\n * - entity : integer or array / restrict to a defined entity or array of entities\n * (default -1 : no restriction)\n * - entity_sons : boolean / if entity restrict specified auto select its sons\n * only available if entity is a single value not an array(default false)\n * - all : Nobody or All display for none selected\n * all=0 (default) -> Nobody\n * all=1 -> All\n * all=-1-> nothing\n * - rand : integer / already computed rand value\n * - toupdate : array / Update a specific item on select change on dropdown\n * (need value_fieldname, to_update, url\n * (see Ajax::updateItemOnSelectEvent for information)\n * and may have moreparams)\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - ldap_import\n * - on_change : string / value to transmit to \"onChange\"\n * - display : boolean / display or get string (default true)\n * - width : specific width needed (default 80%)\n * - specific_tags : array of HTML5 tags to add to the field\n * - url : url of the ajax php code which should return the json data to show in\n * the dropdown (default /ajax/getDropdownUsers.php)\n * - inactive_deleted : retreive also inactive or deleted users\n *\n * @return integer|string Random value if displayed, string otherwise\n */\n static function dropdown($options = []) {\n global $CFG_GLPI;", " // Default values\n $p = [\n 'name' => 'users_id',\n 'value' => '',\n 'values' => [],\n 'right' => 'id',\n 'all' => 0,\n 'display_emptychoice' => true,\n 'placeholder' => '',\n 'on_change' => '',\n 'comments' => 1,\n 'width' => '80%',\n 'entity' => -1,\n 'entity_sons' => false,\n 'used' => [],\n 'ldap_import' => false,\n 'toupdate' => '',\n 'rand' => mt_rand(),\n 'display' => true,\n '_user_index' => 0,\n 'specific_tags' => [],\n 'url' => $CFG_GLPI['root_doc'] . \"/ajax/getDropdownUsers.php\",\n 'inactive_deleted' => 0,\n ];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " // check default value (in case of multiple observers)\n if (is_array($p['value'])) {\n $p['value'] = $p['value'][$p['_user_index']] ?? 0;\n }", " // Check default value for dropdown : need to be a numeric\n if ((strlen($p['value']) == 0) || !is_numeric($p['value'])) {\n $p['value'] = 0;\n }", " $output = '';\n if (!($p['entity'] < 0) && $p['entity_sons']) {\n if (is_array($p['entity'])) {\n $output .= \"entity_sons options is not available with array of entity\";\n } else {\n $p['entity'] = getSonsOf('glpi_entities', $p['entity']);\n }\n }", " // Make a select box with all glpi users\n $user = getUserName($p['value'], 2);", " $view_users = self::canView();", " if (!empty($p['value']) && ($p['value'] > 0)) {\n $default = $user[\"name\"];\n } else {\n if ($p['all']) {\n $default = __('All');\n } else {\n $default = Dropdown::EMPTY_VALUE;\n }\n }", " // get multiple values name\n $valuesnames = [];\n foreach ($p['values'] as $value) {\n if (!empty($value) && ($value > 0)) {\n $user = getUserName($value, 2);\n $valuesnames[] = $user[\"name\"];\n }\n }", " $field_id = Html::cleanId(\"dropdown_\" . $p['name'] . $p['rand']);\n $param = [\n 'value' => $p['value'],\n 'values' => $p['values'],\n 'valuename' => $default,\n 'valuesnames' => $valuesnames,\n 'width' => $p['width'],\n 'all' => $p['all'],\n 'display_emptychoice' => $p['display_emptychoice'],\n 'placeholder' => $p['placeholder'],\n 'right' => $p['right'],\n 'on_change' => $p['on_change'],\n 'used' => $p['used'],\n 'inactive_deleted' => $p['inactive_deleted'],", " 'entity_restrict' => (is_array($p['entity']) ? json_encode(array_values($p['entity'])) : $p['entity']),", " 'specific_tags' => $p['specific_tags'],", " '_idor_token' => Session::getNewIDORToken(__CLASS__, ['right' => $p['right']]),", " ];", " $output = Html::jsAjaxDropdown($p['name'], $field_id,\n $p['url'],\n $param);", " // Display comment\n if ($p['comments']) {\n $comment_id = Html::cleanId(\"comment_\".$p['name'].$p['rand']);\n $link_id = Html::cleanId(\"comment_link_\".$p[\"name\"].$p['rand']);\n if (!$view_users) {\n $user[\"link\"] = '';\n } else if (empty($user[\"link\"])) {\n $user[\"link\"] = $CFG_GLPI['root_doc'].\"/front/user.php\";\n }", " if (empty($user['comment'])) {\n $user['comment'] = Toolbox::ucfirst(\n sprintf(\n __('Show %1$s'),\n self::getTypeName(Session::getPluralNumber())\n )\n );\n }\n $output .= \"&nbsp;\".Html::showToolTip($user[\"comment\"],\n ['contentid' => $comment_id,\n 'display' => false,\n 'link' => $user[\"link\"],\n 'linkid' => $link_id]);", " $paramscomment = [\n 'value' => '__VALUE__',\n 'itemtype' => User::getType()\n ];", " if ($view_users) {\n $paramscomment['withlink'] = $link_id;\n }\n $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/comments.php\",\n $paramscomment, false);\n }\n $output .= Ajax::commonDropdownUpdateItem($p, false);", " if (Session::haveRight('user', self::IMPORTEXTAUTHUSERS)\n && $p['ldap_import']\n && Entity::isEntityDirectoryConfigured($_SESSION['glpiactive_entity'])) {", " $output .= \"<span title=\\\"\".__s('Import a user').\"\\\" class='fa fa-plus pointer'\".\n \" onClick=\\\"\".Html::jsGetElementbyID('userimport'.$p['rand']).\".dialog('open');\\\">\n <span class='sr-only'>\" . __s('Import a user') . \"</span></span>\";\n $output .= Ajax::createIframeModalWindow('userimport'.$p['rand'],\n $CFG_GLPI[\"root_doc\"].\n \"/front/ldap.import.php?entity=\".\n $_SESSION['glpiactive_entity'],\n ['title' => __('Import a user'),\n 'display' => false]);\n }", " if ($p['display']) {\n echo $output;\n return $p['rand'];\n }\n return $output;\n }", "\n /**\n * Show simple add user form for external auth.\n *\n * @return void|boolean false if user does not have rights to import users from external sources,\n * print form otherwise\n */\n static function showAddExtAuthForm() {", " if (!Session::haveRight(\"user\", self::IMPORTEXTAUTHUSERS)) {\n return false;\n }", " echo \"<div class='center'>\\n\";\n echo \"<form method='post' action='\".Toolbox::getItemTypeFormURL('User').\"'>\\n\";", " echo \"<table class='tab_cadre'>\\n\";\n echo \"<tr><th colspan='4'>\".__('Automatically add a user of an external source').\"</th></tr>\\n\";", " echo \"<tr class='tab_bg_1'><td>\".__('Login').\"</td>\\n\";\n echo \"<td><input type='text' name='login'></td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='tab_bg_2 center' colspan='2'>\\n\";\n echo \"<input type='submit' name='add_ext_auth_ldap' value=\\\"\".__s('Import from directories').\"\\\"\n class='submit'>\\n\";\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='tab_bg_2 center' colspan='2'>\\n\";\n echo \"<input type='submit' name='add_ext_auth_simple' value=\\\"\".__s('Import from other sources').\"\\\"\n class='submit'>\\n\";\n echo \"</td></tr>\\n\";", " echo \"</table>\";\n Html::closeForm();\n echo \"</div>\\n\";\n }", "\n /**\n * Change auth method for given users.\n *\n * @param integer[] $IDs IDs of users\n * @param integer $authtype Auth type (see Auth constants)\n * @param integer $server ID of auth server\n *\n * @return boolean\n */\n static function changeAuthMethod(array $IDs = [], $authtype = 1, $server = -1) {\n global $DB;", " if (!Session::haveRight(self::$rightname, self::UPDATEAUTHENT)) {\n return false;\n }", " if (!empty($IDs)\n && in_array($authtype, [Auth::DB_GLPI, Auth::LDAP, Auth::MAIL, Auth::EXTERNAL])) {", " $result = $DB->update(\n self::getTable(), [\n 'authtype' => $authtype,\n 'auths_id' => $server,\n 'password' => '',\n 'is_deleted_ldap' => 0\n ], [\n 'id' => $IDs\n ]\n );\n if ($result) {\n foreach ($IDs as $ID) {\n $changes = [\n 0,\n '',\n addslashes(\n sprintf(\n __('%1$s: %2$s'),\n __('Update authentification method to'),\n Auth::getMethodName($authtype, $server)\n )\n )\n ];\n Log::history($ID, __CLASS__, $changes, '', Log::HISTORY_LOG_SIMPLE_MESSAGE);\n }", " return true;\n }\n }\n return false;\n }", "\n /**\n * Generate vcard for the current user.\n *\n * @return void\n */\n function generateVcard() {", " // prepare properties for the Vcard\n if (!empty($this->fields[\"realname\"])\n || !empty($this->fields[\"firstname\"])) {\n $name = [$this->fields[\"realname\"], $this->fields[\"firstname\"], \"\", \"\", \"\"];\n } else {\n $name = [$this->fields[\"name\"], \"\", \"\", \"\", \"\"];\n }", " // create vcard\n $vcard = new VObject\\Component\\VCard([\n 'N' => $name,\n 'EMAIL' => $this->getDefaultEmail(),\n 'NOTE' => $this->fields[\"comment\"],\n ]);\n $vcard->add('TEL', $this->fields[\"phone\"], ['type' => 'PREF;WORK;VOICE']);\n $vcard->add('TEL', $this->fields[\"phone2\"], ['type' => 'HOME;VOICE']);\n $vcard->add('TEL', $this->fields[\"mobile\"], ['type' => 'WORK;CELL']);", " // send the VCard\n $output = $vcard->serialize();\n $filename = implode(\"_\", array_filter($name)).\".vcf\";", " @header(\"Content-Disposition: attachment; filename=\\\"$filename\\\"\");\n @header(\"Content-Length: \".Toolbox::strlen($output));\n @header(\"Connection: close\");\n @header(\"content-type: text/x-vcard; charset=UTF-8\");", " echo $output;\n }", "\n /**\n * Show items of the current user.\n *\n * @param boolean $tech false to display items owned by user, true to display items managed by user\n *\n * @return void\n */\n function showItems($tech) {\n global $DB, $CFG_GLPI;", " $ID = $this->getField('id');", " if ($tech) {\n $type_user = $CFG_GLPI['linkuser_tech_types'];\n $type_group = $CFG_GLPI['linkgroup_tech_types'];\n $field_user = 'users_id_tech';\n $field_group = 'groups_id_tech';\n } else {\n $type_user = $CFG_GLPI['linkuser_types'];\n $type_group = $CFG_GLPI['linkgroup_types'];\n $field_user = 'users_id';\n $field_group = 'groups_id';\n }", " $group_where = \"\";\n $groups = [];", " $iterator = $DB->request([\n 'SELECT' => [\n 'glpi_groups_users.groups_id',\n 'glpi_groups.name'\n ],\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_groups' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'groups_id',\n 'glpi_groups' => 'id'\n ]\n ]\n ],\n 'WHERE' => ['glpi_groups_users.users_id' => $ID]\n ]);\n $number = count($iterator);", " $group_where = [];\n while ($data = $iterator->next()) {\n $group_where[$field_group][] = $data['groups_id'];\n $groups[$data[\"groups_id\"]] = $data[\"name\"];\n }", " echo \"<div class='spaced'><table class='tab_cadre_fixehov'>\";\n $header = \"<tr><th>\"._n('Type', 'Types', 1).\"</th>\";\n $header .= \"<th>\".Entity::getTypeName(1).\"</th>\";\n $header .= \"<th>\".__('Name').\"</th>\";\n $header .= \"<th>\".__('Serial number').\"</th>\";\n $header .= \"<th>\".__('Inventory number').\"</th>\";\n $header .= \"<th>\".__('Status').\"</th>\";\n $header .= \"<th>&nbsp;</th></tr>\";\n echo $header;", " foreach ($type_user as $itemtype) {\n if (!($item = getItemForItemtype($itemtype))) {\n continue;\n }\n if ($item->canView()) {\n $itemtable = getTableForItemType($itemtype);\n $iterator_params = [\n 'FROM' => $itemtable,\n 'WHERE' => [$field_user => $ID]\n ];", " if ($item->maybeTemplate()) {\n $iterator_params['WHERE']['is_template'] = 0;\n }\n if ($item->maybeDeleted()) {\n $iterator_params['WHERE']['is_deleted'] = 0;\n }", " $item_iterator = $DB->request($iterator_params);", " $type_name = $item->getTypeName();", " while ($data = $item_iterator->next()) {\n $cansee = $item->can($data[\"id\"], READ);\n $link = $data[\"name\"];\n if ($cansee) {\n $link_item = $item::getFormURLWithID($data['id']);\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($link)) {\n $link = sprintf(__('%1$s (%2$s)'), $link, $data[\"id\"]);\n }\n $link = \"<a href='\".$link_item.\"'>\".$link.\"</a>\";\n }\n $linktype = \"\";\n if ($data[$field_user] == $ID) {\n $linktype = self::getTypeName(1);\n }\n echo \"<tr class='tab_bg_1'><td class='center'>$type_name</td>\";\n echo \"<td class='center'>\".Dropdown::getDropdownName(\"glpi_entities\",\n $data[\"entities_id\"]).\"</td>\";\n echo \"<td class='center'>$link</td>\";\n echo \"<td class='center'>\";\n if (isset($data[\"serial\"]) && !empty($data[\"serial\"])) {\n echo $data[\"serial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"otherserial\"]) && !empty($data[\"otherserial\"])) {\n echo $data[\"otherserial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"states_id\"])) {\n echo Dropdown::getDropdownName(\"glpi_states\", $data['states_id']);\n } else {\n echo '&nbsp;';\n }", " echo \"</td><td class='center'>$linktype</td></tr>\";\n }\n }\n }\n if ($number) {\n echo $header;\n }\n echo \"</table></div>\";", " if (count($group_where)) {\n echo \"<div class='spaced'><table class='tab_cadre_fixehov'>\";\n $header = \"<tr>\".\n \"<th>\"._n('Type', 'Types', 1).\"</th>\".\n \"<th>\".Entity::getTypeName(1).\"</th>\".\n \"<th>\".__('Name').\"</th>\".\n \"<th>\".__('Serial number').\"</th>\".\n \"<th>\".__('Inventory number').\"</th>\".\n \"<th>\".__('Status').\"</th>\".\n \"<th>&nbsp;</th></tr>\";\n echo $header;\n $nb = 0;\n foreach ($type_group as $itemtype) {\n if (!($item = getItemForItemtype($itemtype))) {\n continue;\n }\n if ($item->canView() && $item->isField($field_group)) {\n $itemtable = getTableForItemType($itemtype);\n $iterator_params = [\n 'FROM' => $itemtable,\n 'WHERE' => ['OR' => $group_where]\n ];", " if ($item->maybeTemplate()) {\n $iterator_params['WHERE']['is_template'] = 0;\n }\n if ($item->maybeDeleted()) {\n $iterator_params['WHERE']['is_deleted'] = 0;\n }", " $group_iterator = $DB->request($iterator_params);", " $type_name = $item->getTypeName();", " while ($data = $group_iterator->next()) {\n $nb++;\n $cansee = $item->can($data[\"id\"], READ);\n $link = $data[\"name\"];\n if ($cansee) {\n $link_item = $item::getFormURLWithID($data['id']);\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($link)) {\n $link = sprintf(__('%1$s (%2$s)'), $link, $data[\"id\"]);\n }\n $link = \"<a href='\".$link_item.\"'>\".$link.\"</a>\";\n }\n $linktype = \"\";\n if (isset($groups[$data[$field_group]])) {\n $linktype = sprintf(__('%1$s = %2$s'), Group::getTypeName(1),\n $groups[$data[$field_group]]);\n }\n echo \"<tr class='tab_bg_1'><td class='center'>$type_name</td>\";\n echo \"<td class='center'>\".Dropdown::getDropdownName(\"glpi_entities\",\n $data[\"entities_id\"]);\n echo \"</td><td class='center'>$link</td>\";\n echo \"<td class='center'>\";\n if (isset($data[\"serial\"]) && !empty($data[\"serial\"])) {\n echo $data[\"serial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"otherserial\"]) && !empty($data[\"otherserial\"])) {\n echo $data[\"otherserial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"states_id\"])) {\n echo Dropdown::getDropdownName(\"glpi_states\", $data['states_id']);\n } else {\n echo '&nbsp;';\n }", " echo \"</td><td class='center'>$linktype</td></tr>\";\n }\n }\n }\n if ($nb) {\n echo $header;\n }\n echo \"</table></div>\";\n }\n }", "\n /**\n * Get user by email, importing it from LDAP if not existing.\n *\n * @param string $email\n *\n * @return integer ID of user, 0 if not found nor imported\n */\n static function getOrImportByEmail($email = '') {\n global $DB, $CFG_GLPI;", " $iterator = $DB->request([\n 'SELECT' => 'users_id AS id',\n 'FROM' => 'glpi_useremails',\n 'LEFT JOIN' => [\n 'glpi_users' => [\n 'FKEY' => [\n 'glpi_useremails' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_useremails.email' => $DB->escape(stripslashes($email))\n ],\n 'ORDER' => ['glpi_users.is_active DESC', 'is_deleted ASC']\n ]);", " //User still exists in DB\n if (count($iterator)) {\n $result = $iterator->next();\n return $result['id'];\n } else {\n if ($CFG_GLPI[\"is_users_auto_add\"]) {\n //Get all ldap servers with email field configured\n $ldaps = AuthLDAP::getServersWithImportByEmailActive();\n //Try to find the user by his email on each ldap server", " foreach ($ldaps as $ldap) {\n $params = [\n 'method' => AuthLDAP::IDENTIFIER_EMAIL,\n 'value' => $email,\n ];\n $res = AuthLDAP::ldapImportUserByServerId($params,\n AuthLDAP::ACTION_IMPORT,\n $ldap);", " if (isset($res['id'])) {\n return $res['id'];\n }\n }\n }\n }\n return 0;\n }", "\n /**\n * Handle user deleted in LDAP using configured policy.\n *\n * @param integer $users_id\n *\n * @return void\n */\n static function manageDeletedUserInLdap($users_id) {\n global $CFG_GLPI;", " //The only case where users_id can be null if when a user has been imported into GLPI\n //it's dn still exists, but doesn't match the connection filter anymore\n //In this case, do not try to process the user\n if (!$users_id) {\n return;\n }", " //User is present in DB but not in the directory : it's been deleted in LDAP\n $tmp = [\n 'id' => $users_id,\n 'is_deleted_ldap' => 1,\n ];\n $myuser = new self();\n $myuser->getFromDB($users_id);", " //User is already considered as delete from ldap\n if ($myuser->fields['is_deleted_ldap'] == 1) {\n return;\n }", " switch ($CFG_GLPI['user_deleted_ldap']) {\n //DO nothing\n default :\n case AuthLDAP::DELETED_USER_PRESERVE:\n $myuser->update($tmp);\n break;", " //Put user in trashbin\n case AuthLDAP::DELETED_USER_DELETE:\n $myuser->delete($tmp);\n break;", " //Delete all user dynamic habilitations and groups\n case AuthLDAP::DELETED_USER_WITHDRAWDYNINFO:\n Profile_User::deleteRights($users_id, true);\n Group_User::deleteGroups($users_id, true);\n $myuser->update($tmp);\n break;", " //Deactivate the user\n case AuthLDAP::DELETED_USER_DISABLE:\n $tmp['is_active'] = 0;\n $myuser->update($tmp);\n break;", " //Deactivate the user+ Delete all user dynamic habilitations and groups\n case AuthLDAP::DELETED_USER_DISABLEANDWITHDRAWDYNINFO:\n $tmp['is_active'] = 0;\n $myuser->update($tmp);\n Profile_User::deleteRights($users_id, true);\n Group_User::deleteGroups($users_id, true);\n break;", " }\n /*\n $changes[0] = '0';\n $changes[1] = '';\n $changes[2] = __('Deleted user in LDAP directory');\n Log::history($users_id, 'User', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);*/\n }", " /**\n * Get user ID from its name.\n *\n * @param string $name User name\n *\n * @return integer\n */\n static function getIdByName($name) {\n return self::getIdByField('name', $name);\n }", "\n /**\n * Get user ID from a field\n *\n * @since 0.84\n *\n * @param string $field Field name\n * @param string $value Field value\n *\n * @return integer\n */\n static function getIdByField($field, $value, $escape = true) {\n global $DB;", " if ($escape) {\n $value = addslashes($value);\n }", " $iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => self::getTable(),\n 'WHERE' => [$field => $value]\n ]);", " if (count($iterator) == 1) {\n $row = $iterator->next();\n return (int)$row['id'];\n }\n return false;\n }", "\n /**\n * Show password update form for current user.\n *\n * @param array $error_messages\n *\n * @return void\n */\n public function showPasswordUpdateForm(array $error_messages = []) {\n global $CFG_GLPI;", " echo '<form method=\"post\" action=\"' . $CFG_GLPI['root_doc'] . '/front/updatepassword.php\">';\n echo '<table class=\"tab_cadre\">';\n echo '<tr><th colspan=\"2\">' . __('Password update') . '</th></tr>';", " if (Session::mustChangePassword()) {\n echo '<tr class=\"tab_bg_2 center\">';\n echo '<td colspan=\"2\" class=\"red b\">';\n echo __('Your password has expired. You must change it to be able to login.');\n echo '</td>';\n echo '</tr>';\n }", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo __('Login');\n echo '</td>';\n echo '<td>';\n echo '<input type=\"text\" name=\"name\" value=\"' . $this->fields['name'] . '\" readonly=\"readonly\" />';\n echo '</td>';\n echo '</tr>';", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo '<label for=\"current_password\">' . __('Current password') . '</label>';\n echo '</td>';\n echo '<td>';\n echo '<input type=\"password\" id=\"current_password\" name=\"current_password\" />';\n echo '</td>';\n echo '</tr>';", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo '<label for=\"password\">' . __('New password') . '</label>';\n echo '</td>';\n echo '<td>';\n echo '<input type=\"password\" id=\"password\" name=\"password\" autocomplete=\"new-password\" onkeyup=\"return passwordCheck();\" />';\n echo '</td>';\n echo '</tr>';", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo '<label for=\"password2\">' . __('New password confirmation') . '</label>';\n echo '</td>';\n echo '<td>';\n echo '<input type=\"password\" id=\"password2\" name=\"password2\" autocomplete=\"new-password\" />';\n echo '</td>';\n echo '</tr>';", " if ($CFG_GLPI['use_password_security']) {\n echo '<tr class=\"tab_bg_1\">';\n echo '<td>' . __('Password security policy') . '</td>';\n echo '<td>';\n Config::displayPasswordSecurityChecks();\n echo '</td>';\n echo '</tr>';\n }", " echo '<tr class=\"tab_bg_2 center\">';\n echo '<td colspan=\"2\">';\n echo '<input type=\"submit\" name=\"update\" value=\"' . __s('Save') . '\" class=\"submit\" />';\n echo '</td>';\n echo '</tr>';", " if (!empty($error_messages)) {\n echo '<tr class=\"tab_bg_2 center\">';\n echo '<td colspan=\"2\" class=\"red b\">';\n echo implode('<br/>', $error_messages);\n echo '</td>';\n echo '</tr>';\n }", " echo '</table>';\n Html::closeForm();\n }", "\n /**\n * Show new password form of password recovery process.\n *\n * @param $token\n *\n * @return void\n */\n static function showPasswordForgetChangeForm($token) {\n global $CFG_GLPI, $DB;", " // Verif token.\n $token_ok = false;\n $iterator = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'password_forget_token' => $token,\n new \\QueryExpression('NOW() < ADDDATE(' . $DB->quoteName('password_forget_token_date') . ', INTERVAL 1 DAY)')\n ]\n ]);", " if (count($iterator) == 1) {\n $token_ok = true;\n }\n echo \"<div class='center'>\";", " if ($token_ok) {\n echo \"<form method='post' name='forgetpassword' action='\".$CFG_GLPI['root_doc'].\n \"/front/lostpassword.php'>\";\n echo \"<table class='tab_cadre'>\";\n echo \"<tr><th colspan='2'>\" . __('Forgotten password?').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td colspan='2'>\". __('Please confirm your email address and enter your new password.').\n \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\" . _n('Email', 'Emails', 1).\"</td>\";\n echo \"<td><input type='text' name='email' value='' size='60'></td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\" . __('Password').\"</td>\";\n echo \"<td><input id='password' type='password' name='password' value='' size='20'\n autocomplete='new-password' onkeyup=\\\"return passwordCheck();\\\">\";\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\" . __('Password confirmation').\"</td>\";\n echo \"<td><input type='password' name='password2' value='' size='20' autocomplete='new-password'>\";\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\".__('Password security policy').\"</td>\";\n echo \"<td>\";\n Config::displayPasswordSecurityChecks();\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_2 center'><td colspan='2'>\";\n echo \"<input type='hidden' name='password_forget_token' value='$token'>\";\n echo \"<input type='submit' name='update' value=\\\"\".__s('Save').\"\\\" class='submit'>\";\n echo \"</td></tr>\";", " echo \"</table>\";\n Html::closeForm();", " } else {\n echo __('Your password reset request has expired or is invalid. Please renew it.');\n }\n echo \"</div>\";\n }", "\n /**\n * Show request form of password recovery process.\n *\n * @return void\n */\n static function showPasswordForgetRequestForm() {\n global $CFG_GLPI;", " echo \"<div class='center'>\";\n echo \"<form method='post' name='forgetpassword' action='\".$CFG_GLPI['root_doc'].\n \"/front/lostpassword.php'>\";\n echo \"<table class='tab_cadre'>\";\n echo \"<tr><th colspan='2'>\" . __('Forgotten password?').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td colspan='2'>\" .\n __('Please enter your email address. An email will be sent to you and you will be able to choose a new password.').\n \"</td></tr>\";", " echo \"<tr class='tab_bg_2 center'>\";\n echo \"<td><input type='text' size='60' name='email' value=''></td>\";\n echo \"<td><input type='submit' name='update' value=\\\"\".__s('Save').\"\\\" class='submit'>\";\n echo \"</td></tr>\";", " echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }", "\n /**\n * Handle password recovery form submission.\n *\n * @param array $input\n *\n * @throws ForgetPasswordException when requirements are not met\n *\n * @return boolean true if password successfully changed, false otherwise\n */\n public function updateForgottenPassword(array $input) {\n $condition = [\n 'glpi_users.is_active' => 1,\n 'glpi_users.is_deleted' => 0, [\n 'OR' => [\n ['glpi_users.begin_date' => null],\n ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]\n ],\n ], [\n 'OR' => [\n ['glpi_users.end_date' => null],\n ['glpi_users.end_date' => ['>', new QueryExpression('NOW()')]]\n ]\n ]\n ];\n if ($this->getFromDBbyEmail($input['email'], $condition)) {\n if (($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || !Auth::useAuthExt()) {", " if (($input['password_forget_token'] == $this->fields['password_forget_token'])\n && (abs(strtotime($_SESSION[\"glpi_currenttime\"])\n -strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP)) {", " $input['id'] = $this->fields['id'];\n Config::validatePassword($input[\"password\"], false); // Throws exception if password is invalid\n if (!$this->update($input)) {\n return false;\n }\n $input2 = [\n 'password_forget_token' => '',\n 'password_forget_token_date' => 'NULL',\n 'id' => $this->fields['id']\n ];\n $this->update($input2);\n return true;", " } else {\n throw new ForgetPasswordException(__('Your password reset request has expired or is invalid. Please renew it.'));\n }", " } else {\n throw new ForgetPasswordException(__(\"The authentication method configuration doesn't allow you to change your password.\"));\n }", " } else {\n throw new ForgetPasswordException(__('Email address not found.'));\n }", " return false;\n }", "\n /**\n * Displays password recovery result.\n *\n * @param array $input\n *\n * @return void\n */\n public function showUpdateForgottenPassword(array $input) {\n global $CFG_GLPI;", " echo \"<div class='center'>\";\n try {\n if (!$this->updateForgottenPassword($input)) {\n Html::displayMessageAfterRedirect();\n } else {\n echo __('Reset password successful.');\n }\n } catch (ForgetPasswordException $e) {\n echo $e->getMessage();\n } catch (PasswordTooWeakException $e) {\n // Force display on error\n foreach ($e->getMessages() as $message) {\n Session::addMessageAfterRedirect($message);\n }\n Html::displayMessageAfterRedirect();\n }", " echo \"<br>\";\n echo \"<a href=\\\"\".$CFG_GLPI['root_doc'].\"/index.php\\\">\".__s('Back').\"</a>\";\n echo \"</div>\";\n }", "\n /**\n * Send password recovery for a user and display result message.\n *\n * @param string $email email of the user\n *\n * @return void\n */\n public function showForgetPassword($email) {", " echo \"<div class='center'>\";\n try {\n $this->forgetPassword($email);\n } catch (ForgetPasswordException $e) {\n echo $e->getMessage();\n return;\n }\n echo __('An email has been sent to your email address. The email contains information for reset your password.');\n }", " /**\n * Send password recovery email for a user.\n *\n * @param string $email\n *\n * @throws ForgetPasswordException when requirements are not met\n *\n * @return boolean true if notification successfully created, false if user not found\n */\n public function forgetPassword($email) {\n $condition = [\n 'glpi_users.is_active' => 1,\n 'glpi_users.is_deleted' => 0, [\n 'OR' => [\n ['glpi_users.begin_date' => null],\n ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]\n ],\n ], [\n 'OR' => [\n ['glpi_users.end_date' => null],\n ['glpi_users.end_date' => ['>', new QueryExpression('NOW()')]]\n ]\n ]\n ];", " if ($this->getFromDBbyEmail($email, $condition)) {", " // Send token if auth DB or not external auth defined\n if (($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || !Auth::useAuthExt()) {", " if (NotificationMailing::isUserAddressValid($email)) {\n $input = [\n 'password_forget_token' => sha1(Toolbox::getRandomString(30)),\n 'password_forget_token_date' => $_SESSION[\"glpi_currenttime\"],\n 'id' => $this->fields['id'],\n ];\n $this->update($input);\n // Notication on root entity (glpi_users.entities_id is only a pref)\n NotificationEvent::raiseEvent('passwordforget', $this, ['entities_id' => 0]);\n QueuedNotification::forceSendFor($this->getType(), $this->fields['id']);\n return true;\n } else {\n throw new ForgetPasswordException(__('Invalid email address'));\n }", " } else {\n throw new ForgetPasswordException(__(\"The authentication method configuration doesn't allow you to change your password.\"));\n }", " }", " throw new ForgetPasswordException(__('Email address not found.'));\n }", "\n /**\n * Display information from LDAP server for user.\n *\n * @return void\n */\n private function showLdapDebug() {", " if ($this->fields['authtype'] != Auth::LDAP) {\n return false;\n }\n echo \"<div class='spaced'>\";\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr><th colspan='4'>\".AuthLDAP::getTypeName(1).\"</th></tr>\";", " echo \"<tr class='tab_bg_2'><td>\".__('User DN').\"</td>\";\n echo \"<td>\".$this->fields['user_dn'].\"</td></tr>\\n\";", " if ($this->fields['user_dn']) {\n echo \"<tr class='tab_bg_2'><td>\".__('User information').\"</td><td>\";\n $config_ldap = new AuthLDAP();\n $ds = false;", " if ($config_ldap->getFromDB($this->fields['auths_id'])) {\n $ds = $config_ldap->connect();\n }", " if ($ds) {\n $info = AuthLDAP::getUserByDn($ds, $this->fields['user_dn'],\n ['*', 'createTimeStamp', 'modifyTimestamp']);\n if (is_array($info)) {\n Html::printCleanArray($info);\n } else {\n echo __('No item to display');\n }", " } else {\n echo __('Connection failed');\n }", " echo \"</td></tr>\\n\";\n }", " echo \"</table></div>\";\n }", "\n /**\n * Display debug information for current object.\n *\n * @return void\n */\n function showDebug() {", " NotificationEvent::debugEvent($this);\n $this->showLdapDebug();\n }", " function getUnicityFieldsToDisplayInErrorMessage() {", " return ['id' => __('ID'),\n 'entities_id' => Entity::getTypeName(1)];\n }", "\n function getUnallowedFieldsForUnicity() {", " return array_merge(parent::getUnallowedFieldsForUnicity(),\n ['auths_id', 'date_sync', 'entities_id', 'last_login', 'profiles_id']);\n }", "\n /**\n * Get a unique generated token.\n *\n * @param string $field Field storing the token\n *\n * @return string\n */\n static function getUniqueToken($field = 'personal_token') {\n global $DB;", " $ok = false;\n do {\n $key = Toolbox::getRandomString(40);\n $row = $DB->request([\n 'COUNT' => 'cpt',\n 'FROM' => self::getTable(),\n 'WHERE' => [$field => $key]\n ])->next();", " if ($row['cpt'] == 0) {\n return $key;\n }\n } while (!$ok);", " }", "\n /**\n * Get token of a user. If not exists generate it.\n *\n * @param integer $ID User ID\n * @param string $field Field storing the token\n *\n * @return string|boolean User token, false if user does not exist\n */\n static function getToken($ID, $field = 'personal_token') {", " $user = new self();\n if ($user->getFromDB($ID)) {\n return $user->getAuthToken($field);\n }", " return false;\n }", " /**\n * Get token of a user. If it does not exists then generate it.\n *\n * @since 9.4\n *\n * @param string $field the field storing the token\n * @param boolean $force_new force generation of a new token\n *\n * @return string|false token or false in case of error\n */\n public function getAuthToken($field = 'personal_token', $force_new = false) {\n global $CFG_GLPI;", " if ($this->isNewItem()) {\n return false;\n }", " // check date validity for cookie token\n $outdated = false;\n if ($field === 'cookie_token') {\n $date_create = new DateTime($this->fields[$field.\"_date\"]);\n $date_expir = $date_create->add(new DateInterval('PT'.$CFG_GLPI[\"login_remember_time\"].'S'));", " if ($date_expir < new DateTime()) {\n $outdated = true;\n }\n }", " // token exists, is not oudated, and we may use it\n if (!empty($this->fields[$field]) && !$force_new && !$outdated) {\n return $this->fields[$field];\n }", " // else get a new token\n $token = self::getUniqueToken($field);", " // for cookie token, we need to store it hashed\n $hash = $token;\n if ($field === 'cookie_token') {\n $hash = Auth::getPasswordHash($token);\n }", " // save this token in db\n $this->update(['id' => $this->getID(),\n $field => $hash,\n $field . \"_date\" => $_SESSION['glpi_currenttime']]);", " return $token;\n }", "\n /**\n * Get name of users using default passwords\n *\n * @return string[]\n */\n static function checkDefaultPasswords() {\n global $DB;", " $passwords = ['glpi' => 'glpi',\n 'tech' => 'tech',\n 'normal' => 'normal',\n 'post-only' => 'postonly'];\n $default_password_set = [];", " $crit = ['FIELDS' => ['name', 'password'],\n 'is_active' => 1,\n 'is_deleted' => 0,\n 'name' => array_keys($passwords)];", " foreach ($DB->request('glpi_users', $crit) as $data) {\n if (Auth::checkPassword($passwords[strtolower($data['name'])], $data['password'])) {\n $default_password_set[] = $data['name'];\n }\n }", " return $default_password_set;\n }", "\n /**\n * Get picture URL from picture field.\n *\n * @since 0.85\n *\n * @param string $picture Picture field value\n *\n * @return string\n */\n static function getURLForPicture($picture) {\n global $CFG_GLPI;", " $url = Toolbox::getPictureUrl($picture);\n if (null !== $url) {\n return $url;\n }", " return $CFG_GLPI[\"root_doc\"].\"/pics/picture.png\";\n }", "\n /**\n * Get thumbnail URL from picture field.\n *\n * @since 0.85\n *\n * @param string $picture Picture field value\n *\n * @return string\n */\n static function getThumbnailURLForPicture($picture) {\n global $CFG_GLPI;", " // prevent xss\n $picture = Html::cleanInputText($picture);", " if (!empty($picture)) {\n $tmp = explode(\".\", $picture);\n if (count($tmp) ==2) {\n return $CFG_GLPI[\"root_doc\"].\"/front/document.send.php?file=_pictures/\".$tmp[0].\n \"_min.\".$tmp[1];\n }\n return $CFG_GLPI[\"root_doc\"].\"/pics/picture_min.png\";\n }\n return $CFG_GLPI[\"root_doc\"].\"/pics/picture_min.png\";", " }", "\n /**\n * Drop existing files for user picture.\n *\n * @since 0.85\n *\n * @param string $picture Picture field value\n *\n * @return void\n */\n static function dropPictureFiles($picture) {", " if (!empty($picture)) {\n // unlink main file\n if (file_exists(GLPI_PICTURE_DIR.\"/$picture\")) {\n @unlink(GLPI_PICTURE_DIR.\"/$picture\");\n }\n // unlink Thunmnail\n $tmp = explode(\".\", $picture);\n if (count($tmp) == 2) {\n if (file_exists(GLPI_PICTURE_DIR.\"/\".$tmp[0].\"_min.\".$tmp[1])) {\n @unlink(GLPI_PICTURE_DIR.\"/\".$tmp[0].\"_min.\".$tmp[1]);\n }\n }\n }\n }", " function getRights($interface = 'central') {", " $values = parent::getRights();\n //TRANS: short for : Add users from an external source\n $values[self::IMPORTEXTAUTHUSERS] = ['short' => __('Add external'),\n 'long' => __('Add users from an external source')];\n //TRANS: short for : Read method for user authentication and synchronization\n $values[self::READAUTHENT] = ['short' => __('Read auth'),\n 'long' => __('Read user authentication and synchronization method')];\n //TRANS: short for : Update method for user authentication and synchronization\n $values[self::UPDATEAUTHENT] = ['short' => __('Update auth and sync'),\n 'long' => __('Update method for user authentication and synchronization')];", " return $values;\n }", "\n /**\n * Retrieve the list of LDAP field names from a list of fields\n * allow pattern substitution, e.g. %{name}.\n *\n * @since 9.1\n *\n * @param string[] $map array of fields\n *\n * @return string[]\n */\n private static function getLdapFieldNames(array $map) {", " $ret = [];\n foreach ($map as $v) {\n /** @var array $reg */\n if (preg_match_all('/%{(.*)}/U', $v, $reg)) {\n // e.g. \"%{country} > %{city} > %{site}\"\n foreach ($reg [1] as $f) {\n $ret [] = $f;\n }\n } else {\n // single field name\n $ret [] = $v;\n }\n }\n return $ret;\n }", "\n /**\n * Retrieve the value of a fields from a LDAP result applying needed substitution of %{value}.\n *\n * @since 9.1\n *\n * @param string $map String with field format\n * @param array $res LDAP result\n *\n * @return string\n */\n private static function getLdapFieldValue($map, array $res) {", " $map = Toolbox::unclean_cross_side_scripting_deep($map);\n $ret = preg_replace_callback('/%{(.*)}/U',\n function ($matches) use ($res) {\n return (isset($res[0][$matches[1]][0]) ? $res[0][$matches[1]][0] : '');\n }, $map );", " return $ret == $map ? (isset($res[0][$map][0]) ? $res[0][$map][0] : '') : $ret;\n }", " /**\n * Get/Print the switch language form.\n *\n * @param boolean $display Whether to display or return output\n * @param array $options Options\n * - string value Selected language value\n * - boolean showbutton Whether to display or not submit button\n *\n * @return void|string Nothing if displayed, string to display otherwise\n */\n function showSwitchLangForm($display = true, array $options = []) {", " $params = [\n 'value' => $_SESSION[\"glpilanguage\"],\n 'display' => false,\n 'showbutton' => true\n ];", " foreach ($options as $key => $value) {\n $params[$key] = $value;\n }", " $out = '';\n $out .= \"<form method='post' name='switchlang' action='\".User::getFormURL().\"' autocomplete='off'>\";\n $out .= \"<p class='center'>\";\n $out .= Dropdown::showLanguages(\"language\", $params);\n if ($params['showbutton'] === true) {\n $out .= \"&nbsp;<input type='submit' name='update' value=\\\"\"._sx('button', 'Save').\"\\\" class='submit'>\";\n }\n $out .= \"</p>\";\n $out .= Html::closeForm(false);", " if ($display === true) {\n echo $out;\n } else {\n return $out;\n }\n }", " /**\n * Get list of entities ids for current user.\n *\n * @return integer[]\n */\n private function getEntities() {\n //get user entities\n if ($this->entities == null) {\n $this->entities = Profile_User::getUserEntities($this->fields['id'], true);\n }\n return $this->entities;\n }", "\n /**\n * Give cron information.\n *\n * @param string $name Task's name\n *\n * @return array\n */\n public static function cronInfo(string $name): array {", " $info = [];\n switch ($name) {\n case 'passwordexpiration':\n $info = [\n 'description' => __('Handle users passwords expiration policy'),\n 'parameter' => __('Maximum expiration notifications to send at once'),\n ];\n break;\n }\n return $info;\n }", " /**\n * Cron that notify users about when their password expire and deactivate their account\n * depending on password expiration policy.\n *\n * @param CronTask $task\n *\n * @return integer\n */\n public static function cronPasswordExpiration(CronTask $task) {\n global $CFG_GLPI, $DB;", " $expiration_delay = (int)$CFG_GLPI['password_expiration_delay'];\n $notice_time = (int)$CFG_GLPI['password_expiration_notice'];\n $notification_limit = (int)$task->fields['param'];\n $lock_delay = (int)$CFG_GLPI['password_expiration_lock_delay'];", " if (-1 === $expiration_delay || (-1 === $notice_time && -1 === $lock_delay)) {\n // Nothing to do if passwords does not expire\n // or if password expires without notice and with no lock delay\n return 0;\n }", " // Notify users about expiration of their password.\n $to_notify_count = 0;\n if (-1 !== $notice_time) {\n $notification_request = [\n 'FROM' => self::getTable(),\n 'LEFT JOIN' => [\n Alert::getTable() => [\n 'ON' => [\n Alert::getTable() => 'items_id',\n self::getTable() => 'id',\n [\n 'AND' => [\n Alert::getTableField('itemtype') => self::getType(),\n ]\n ],\n ]\n ]\n ],\n 'WHERE' => [\n self::getTableField('is_deleted') => 0,\n self::getTableField('is_active') => 1,\n self::getTableField('authtype') => Auth::DB_GLPI,\n new QueryExpression(\n sprintf(\n 'NOW() > ADDDATE(%s, INTERVAL %s DAY)',\n $DB->quoteName(self::getTableField('password_last_update')),\n $expiration_delay - $notice_time\n )\n ),\n // Get only users that has not yet been notified within last day\n 'OR' => [\n [Alert::getTableField('date') => null],\n [Alert::getTableField('date') => ['<', new QueryExpression('CURRENT_TIMESTAMP() - INTERVAL 1 day')]],\n ],\n ],\n ];", " $to_notify_count_request = array_merge(\n $notification_request,\n [\n 'COUNT' => 'cpt',\n ]\n );\n $to_notify_count = $DB->request($to_notify_count_request)->next()['cpt'];", " $notification_data_request = array_merge(\n $notification_request,\n [\n 'SELECT' => [\n self::getTableField('id as user_id'),\n Alert::getTableField('id as alert_id'),\n ],\n 'LIMIT' => $notification_limit,\n ]\n );\n $notification_data_iterator = $DB->request($notification_data_request);", " foreach ($notification_data_iterator as $notification_data) {\n $user_id = $notification_data['user_id'];\n $alert_id = $notification_data['alert_id'];", " $user = new User();\n $user->getFromDB($user_id);", " $is_notification_send = NotificationEvent::raiseEvent(\n 'passwordexpires',\n $user,\n ['entities_id' => 0] // Notication on root entity (glpi_users.entities_id is only a pref)\n );\n if (!$is_notification_send) {\n continue;\n }", " $task->addVolume(1);", " $alert = new Alert();", " // Delete existing alert if any\n if (null !== $alert_id) {\n $alert->delete(['id' => $alert_id]);\n }", " // Add an alert to not warn user for at least one day\n $alert->add(\n [\n 'itemtype' => 'User',\n 'items_id' => $user_id,\n 'type' => Alert::NOTICE,\n ]\n );\n }\n }", " // Disable users if their password has expire for too long.\n if (-1 !== $lock_delay) {\n $DB->update(\n self::getTable(),\n [\n 'is_active' => 0,\n 'cookie_token' => null,\n 'cookie_token_date' => null,\n ],\n [\n 'is_deleted' => 0,\n 'is_active' => 1,\n 'authtype' => Auth::DB_GLPI,\n new QueryExpression(\n sprintf(\n 'NOW() > ADDDATE(ADDDATE(%s, INTERVAL %d DAY), INTERVAL %s DAY)',\n $DB->quoteName(self::getTableField('password_last_update')),\n $expiration_delay,\n $lock_delay\n )\n ),\n ]\n );\n }", " return -1 !== $notice_time && $to_notify_count > $notification_limit\n ? -1 // -1 for partial process (remaining notifications to send)\n : 1; // 1 for fully process\n }", " /**\n * Get password expiration time.\n *\n * @return null|int Password expiration time, or null if expiration mechanism is not active.\n */\n public function getPasswordExpirationTime() {\n global $CFG_GLPI;", " if (!array_key_exists('id', $this->fields) || $this->fields['id'] < 1) {\n return null;\n }", " $expiration_delay = (int)$CFG_GLPI['password_expiration_delay'];", " if (-1 === $expiration_delay) {\n return null;\n }", " return strtotime(\n '+ ' . $expiration_delay . ' days',\n strtotime($this->fields['password_last_update'])\n );\n }", " /**\n * Check if password should be changed (if it expires soon).\n *\n * @return boolean\n */\n public function shouldChangePassword() {\n global $CFG_GLPI;", " if ($this->hasPasswordExpired()) {\n return true; // too late to change password, but returning false would not be logical here\n }", " $expiration_time = $this->getPasswordExpirationTime();\n if (null === $expiration_time) {\n return false;\n }", " $notice_delay = (int)$CFG_GLPI['password_expiration_notice'];\n if (-1 === $notice_delay) {\n return false;\n }", " $notice_time = strtotime('- ' . $notice_delay . ' days', $expiration_time);", " return $notice_time < time();\n }", " /**\n * Check if password expired.\n *\n * @return boolean\n */\n public function hasPasswordExpired() {", " $expiration_time = $this->getPasswordExpirationTime();\n if (null === $expiration_time) {\n return false;\n }", " return $expiration_time < time();\n }", " public static function getFriendlyNameSearchCriteria(string $filter): array {\n $table = self::getTable();\n $login = DBmysql::quoteName(\"$table.name\");\n $firstname = DBmysql::quoteName(\"$table.firstname\");\n $lastname = DBmysql::quoteName(\"$table.realname\");", " $filter = strtolower($filter);\n $filter_no_spaces = str_replace(\" \", \"\", $filter);", " return [\n 'OR' => [\n ['RAW' => [\"LOWER($login)\" => ['LIKE', \"%$filter%\"]]],\n ['RAW' => [\"LOWER(REPLACE(CONCAT($firstname, $lastname), ' ', ''))\" => ['LIKE', \"%$filter_no_spaces%\"]]],\n ['RAW' => [\"LOWER(REPLACE(CONCAT($lastname, $firstname), ' ', ''))\" => ['LIKE', \"%$filter_no_spaces%\"]]],\n ]\n ];\n }", " public static function getFriendlyNameFields(string $alias = \"name\") {\n $config = Config::getConfigurationValues('core');\n if ($config['names_format'] == User::FIRSTNAME_BEFORE) {\n $first = \"firstname\";\n $second = \"realname\";\n } else {\n $first = \"realname\";\n $second = \"firstname\";\n }", " $table = self::getTable();\n $first = DB::quoteName(\"$table.$first\");\n $second = DB::quoteName(\"$table.$second\");\n $alias = DB::quoteName($alias);\n $name = DB::quoteName(self::getNameField());", " return new QueryExpression(\"IF(\n $first <> '' && $second <> '',\n CONCAT($first, ' ', $second),\n $name\n ) AS $alias\"\n );\n }", " static function getIcon() {\n return \"fas fa-user\";\n }", " /**\n * Add groups stored in \"_ldap_rules/groups_id\" special input\n */\n public function applyGroupsRules() {\n if (!isset($this->input[\"_ldap_rules\"]['groups_id'])) {\n return;\n }", " $group_ids = array_unique($this->input[\"_ldap_rules\"]['groups_id']);\n foreach ($group_ids as $group_id) {\n $group_user = new Group_User();", " $data = [\n 'groups_id' => $group_id,\n 'users_id' => $this->getId()\n ];", " if (!$group_user->getFromDBByCrit($data)) {\n $group_user->add($data);\n }", " }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access this file directly\");\n}", "use Sabre\\VObject;\nuse Glpi\\Exception\\ForgetPasswordException;\nuse Glpi\\Exception\\PasswordTooWeakException;", "class User extends CommonDBTM {", " // From CommonDBTM\n public $dohistory = true;\n public $history_blacklist = ['date_mod', 'date_sync', 'last_login',\n 'publicbookmarkorder', 'privatebookmarkorder'];", " // NAME FIRSTNAME ORDER TYPE\n const REALNAME_BEFORE = 0;\n const FIRSTNAME_BEFORE = 1;", " const IMPORTEXTAUTHUSERS = 1024;\n const READAUTHENT = 2048;\n const UPDATEAUTHENT = 4096;", " static $rightname = 'user';", " static $undisclosedFields = [\n 'password',\n 'personal_token',\n 'api_token',\n 'cookie_token',\n ];", " private $entities = null;", "\n static function getTypeName($nb = 0) {\n return _n('User', 'Users', $nb);\n }", " static function getMenuShorcut() {\n return 'u';\n }", " static function getAdditionalMenuOptions() {", " if (Session::haveRight('user', self::IMPORTEXTAUTHUSERS)) {\n return [\n 'ldap' => [\n 'title' => AuthLDAP::getTypeName(Session::getPluralNumber()),\n 'page' => '/front/ldap.php',\n ],\n ];\n }\n return false;\n }", "\n function canViewItem() {\n if (Session::canViewAllEntities()\n || Session::haveAccessToOneOfEntities($this->getEntities())) {\n return true;\n }\n return false;\n }", "\n function canCreateItem() {", " // Will be created from form, with selected entity/profile\n if (isset($this->input['_profiles_id']) && ($this->input['_profiles_id'] > 0)\n && Profile::currentUserHaveMoreRightThan([$this->input['_profiles_id']])\n && isset($this->input['_entities_id'])\n && Session::haveAccessToEntity($this->input['_entities_id'])) {\n return true;\n }\n // Will be created with default value\n if (Session::haveAccessToEntity(0) // Access to root entity (required when no default profile)\n || (Profile::getDefault() > 0)) {\n return true;\n }", " if (($_SESSION['glpiactive_entity'] > 0)\n && (Profile::getDefault() == 0)) {\n echo \"<div class='tab_cadre_fixe warning'>\".\n __('You must define a default profile to create a new user').\"</div>\";\n }", " return false;\n }", "\n function canUpdateItem() {", " $entities = Profile_User::getUserEntities($this->fields['id'], false);\n if (Session::canViewAllEntities()\n || Session::haveAccessToOneOfEntities($entities)) {\n return true;\n }\n return false;\n }", "\n function canDeleteItem() {\n if (Session::canViewAllEntities()\n || Session::haveAccessToAllOfEntities($this->getEntities())) {\n return true;\n }\n return false;\n }", "\n function canPurgeItem() {\n return $this->canDeleteItem();\n }", "\n function isEntityAssign() {\n // glpi_users.entities_id is only a pref.\n return false;\n }", "\n /**\n * Compute preferences for the current user mixing config and user data.\n *\n * @return void\n */\n function computePreferences() {\n global $CFG_GLPI;", " if (isset($this->fields['id'])) {\n foreach ($CFG_GLPI['user_pref_field'] as $f) {\n if (is_null($this->fields[$f])) {\n $this->fields[$f] = $CFG_GLPI[$f];\n }\n }\n }\n /// Specific case for show_count_on_tabs : global config can forbid\n if ($CFG_GLPI['show_count_on_tabs'] == -1) {\n $this->fields['show_count_on_tabs'] = 0;\n }\n }", "\n /**\n * Load minimal session for user.\n *\n * @param integer $entities_id Entity to use\n * @param boolean $is_recursive Whether to load entities recursivly or not\n *\n * @return void\n *\n * @since 0.83.7\n */\n function loadMinimalSession($entities_id, $is_recursive) {\n global $CFG_GLPI;", " if (isset($this->fields['id']) && !isset($_SESSION[\"glpiID\"])) {\n Session::destroy();\n Session::start();\n $_SESSION[\"glpiID\"] = $this->fields['id'];\n $_SESSION[\"glpi_use_mode\"] = Session::NORMAL_MODE;\n Session::loadEntity($entities_id, $is_recursive);\n $this->computePreferences();\n foreach ($CFG_GLPI['user_pref_field'] as $field) {\n if (isset($this->fields[$field])) {\n $_SESSION[\"glpi$field\"] = $this->fields[$field];\n }\n }\n Session::loadGroups();\n Session::loadLanguage();\n }\n }", "\n function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {", " switch ($item->getType()) {\n case __CLASS__ :\n $ong = [];\n $ong[1] = __('Used items');\n $ong[2] = __('Managed items');\n return $ong;", " case 'Preference' :\n return __('Main');\n }\n return '';\n }", "\n static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {\n global $CFG_GLPI;", " switch ($item->getType()) {\n case __CLASS__ :\n $item->showItems($tabnum==2);\n return true;", " case 'Preference' :\n $user = new self();\n $user->showMyForm($CFG_GLPI['root_doc'].\"/front/preference.php\",\n Session::getLoginUserID());\n return true;\n }\n return false;\n }", "\n function defineTabs($options = []) {", " $ong = [];\n $this->addDefaultFormTab($ong);\n $this->addImpactTab($ong, $options);\n $this->addStandardTab('Profile_User', $ong, $options);\n $this->addStandardTab('Group_User', $ong, $options);\n $this->addStandardTab('Config', $ong, $options);\n $this->addStandardTab(__CLASS__, $ong, $options);\n $this->addStandardTab('Ticket', $ong, $options);\n $this->addStandardTab('Item_Problem', $ong, $options);\n $this->addStandardTab('Change_Item', $ong, $options);\n $this->addStandardTab('Document_Item', $ong, $options);\n $this->addStandardTab('Reservation', $ong, $options);\n $this->addStandardTab('Auth', $ong, $options);\n $this->addStandardTab('Link', $ong, $options);\n $this->addStandardTab('Certificate_Item', $ong, $options);\n $this->addStandardTab('Log', $ong, $options);", " return $ong;\n }", "\n function post_getEmpty() {\n global $CFG_GLPI;", " $this->fields[\"is_active\"] = 1;\n if (isset($CFG_GLPI[\"language\"])) {\n $this->fields['language'] = $CFG_GLPI[\"language\"];\n } else {\n $this->fields['language'] = \"en_GB\";\n }\n }", "\n function pre_deleteItem() {\n global $DB;", " $entities = $this->getEntities();\n $view_all = Session::canViewAllEntities();\n // Have right on all entities ?\n $all = true;\n if (!$view_all) {\n foreach ($entities as $ent) {\n if (!Session::haveAccessToEntity($ent)) {\n $all = false;\n }\n }\n }\n if ($all) { // Mark as deleted\n return true;\n }\n // only delete profile\n foreach ($entities as $ent) {\n if (Session::haveAccessToEntity($ent)) {\n $all = false;\n $DB->delete(\n 'glpi_profiles_users', [\n 'users_id' => $this->fields['id'],\n 'entities_id' => $ent\n ]\n );\n }\n return false;\n }\n }", "\n function cleanDBonPurge() {", " global $DB;", " // ObjectLock does not extends CommonDBConnexity\n $ol = new ObjectLock();\n $ol->deleteByCriteria(['users_id' => $this->fields['id']]);", " // Reminder does not extends CommonDBConnexity\n $r = new Reminder();\n $r->deleteByCriteria(['users_id' => $this->fields['id']]);", " // Delete private bookmark\n $ss = new SavedSearch();\n $ss->deleteByCriteria(\n [\n 'users_id' => $this->fields['id'],\n 'is_private' => 1,\n ]\n );", " // Set no user to public bookmark\n $DB->update(\n SavedSearch::getTable(), [\n 'users_id' => 0\n ], [\n 'users_id' => $this->fields['id']\n ]\n );", " // Set no user to consumables\n $DB->update(\n 'glpi_consumables', [\n 'items_id' => 0,\n 'itemtype' => 'NULL',\n 'date_out' => 'NULL'\n ], [\n 'items_id' => $this->fields['id'],\n 'itemtype' => 'User'\n ]\n );", " $this->deleteChildrenAndRelationsFromDb(\n [\n Certificate_Item::class,\n Change_User::class,\n Group_User::class,\n KnowbaseItem_User::class,\n Problem_User::class,\n Profile_User::class,\n ProjectTaskTeam::class,\n ProjectTeam::class,\n Reminder_User::class,\n RSSFeed_User::class,\n SavedSearch_User::class,\n Ticket_User::class,\n UserEmail::class,\n ]\n );", " if ($this->fields['id'] > 0) { // Security\n // DisplayPreference does not extends CommonDBConnexity\n $dp = new DisplayPreference();\n $dp->deleteByCriteria(['users_id' => $this->fields['id']]);\n }", " $this->dropPictureFiles($this->fields['picture']);", " // Ticket rules use various _users_id_*\n Rule::cleanForItemAction($this, '_users_id%');\n Rule::cleanForItemCriteria($this, '_users_id%');", " // Alert does not extends CommonDBConnexity\n $alert = new Alert();\n $alert->cleanDBonItemDelete($this->getType(), $this->fields['id']);\n }", "\n /**\n * Retrieve a user from the database using its login.\n *\n * @param string $name Login of the user\n *\n * @return boolean\n */\n function getFromDBbyName($name) {\n return $this->getFromDBByCrit(['name' => $name]);\n }", " /**\n * Retrieve a user from the database using its login.\n *\n * @param string $name Login of the user\n * @param integer $authtype Auth type (see Auth constants)\n * @param integer $auths_id ID of auth server\n *\n * @return boolean\n */\n function getFromDBbyNameAndAuth($name, $authtype, $auths_id) {\n return $this->getFromDBByCrit([\n 'name' => $name,\n 'authtype' => $authtype,\n 'auths_id' => $auths_id\n ]);\n }", " /**\n * Retrieve a user from the database using value of the sync field.\n *\n * @param string $value Value of the sync field\n *\n * @return boolean\n */\n function getFromDBbySyncField($value) {\n return $this->getFromDBByCrit(['sync_field' => $value]);\n }", " /**\n * Retrieve a user from the database using it's dn.\n *\n * @since 0.84\n *\n * @param string $user_dn dn of the user\n *\n * @return boolean\n */\n function getFromDBbyDn($user_dn) {\n return $this->getFromDBByCrit(['user_dn' => $user_dn]);\n }", "\n /**\n * Retrieve a user from the database using its email.\n *\n * @since 9.3 Can pass condition as a parameter\n *\n * @param string $email user email\n * @param array $condition add condition\n *\n * @return boolean\n */\n function getFromDBbyEmail($email, $condition = []) {\n global $DB;", " $crit = [\n 'SELECT' => $this->getTable() . '.id',\n 'FROM' => $this->getTable(),\n 'LEFT JOIN' => [\n 'glpi_useremails' => [\n 'FKEY' => [\n $this->getTable() => 'id',\n 'glpi_useremails' => 'users_id'\n ]\n ]\n ],\n 'WHERE' => ['glpi_useremails.email' => $email] + $condition\n ];", " $iter = $DB->request($crit);\n if ($iter->numrows()==1) {\n $row = $iter->next();\n return $this->getFromDB($row['id']);\n }\n return false;\n }", "\n /**\n * Get the default email of the user.\n *\n * @return string\n */\n function getDefaultEmail() {", " if (!isset($this->fields['id'])) {\n return '';\n }", " return UserEmail::getDefaultForUser($this->fields['id']);\n }", "\n /**\n * Get all emails of the user.\n *\n * @return string[]\n */\n function getAllEmails() {", " if (!isset($this->fields['id'])) {\n return [];\n }\n return UserEmail::getAllForUser($this->fields['id']);\n }", "\n /**\n * Check if the email is attached to the current user.\n *\n * @param string $email\n *\n * @return boolean\n */\n function isEmail($email) {", " if (!isset($this->fields['id'])) {\n return false;\n }\n return UserEmail::isEmailForUser($this->fields['id'], $email);\n }", "\n /**\n * Retrieve a user from the database using its personal token.\n *\n * @param string $token user token\n * @param string $field the field storing the token\n *\n * @return boolean\n */\n function getFromDBbyToken($token, $field = 'personal_token') {\n $fields = ['personal_token', 'api_token'];\n if (!in_array($field, $fields)) {\n Toolbox::logWarning('User::getFromDBbyToken() can only be called with $field parameter with theses values: \\'' . implode('\\', \\'', $fields) . '\\'');\n return false;\n }", " return $this->getFromDBByCrit([$this->getTable() . \".$field\" => $token]);\n }", "\n function prepareInputForAdd($input) {\n global $DB;", " if (isset($input['_stop_import'])) {\n return false;\n }", " if (!Auth::isValidLogin(stripslashes($input['name']))) {\n Session::addMessageAfterRedirect(__('The login is not valid. Unable to add the user.'),\n false, ERROR);\n return false;\n }", " // avoid xss (picture field is autogenerated)\n if (isset($input['picture'])) {\n $input['picture'] = 'NULL';\n }", " if (!isset($input[\"authtype\"])) {\n $input[\"authtype\"] = Auth::DB_GLPI;\n }", " if (!isset($input[\"auths_id\"])) {\n $input[\"auths_id\"] = 0;\n }", " // Check if user does not exists\n $iterator = $DB->request([\n 'FROM' => $this->getTable(),\n 'WHERE' => [\n 'name' => $input['name'],\n 'authtype' => $input['authtype'],\n 'auths_id' => $input['auths_id']\n ],\n 'LIMIT' => 1\n ]);", " if (count($iterator)) {\n Session::addMessageAfterRedirect(__('Unable to add. The user already exists.'),\n false, ERROR);\n return false;\n }", " if (isset($input[\"password2\"])) {\n if (empty($input[\"password\"])) {\n unset ($input[\"password\"]);", " } else {\n if ($input[\"password\"] == $input[\"password2\"]) {\n if (Config::validatePassword($input[\"password\"])) {\n $input[\"password\"]\n = Auth::getPasswordHash(Toolbox::unclean_cross_side_scripting_deep(stripslashes($input[\"password\"])));", " $input['password_last_update'] = $_SESSION['glpi_currenttime'];\n } else {\n unset($input[\"password\"]);\n }\n unset($input[\"password2\"]);\n } else {\n Session::addMessageAfterRedirect(__('Error: the two passwords do not match'),\n false, ERROR);\n return false;\n }\n }\n }", " if (isset($input[\"_extauth\"])) {\n $input[\"password\"] = \"\";\n }", " // Force DB default values : not really needed\n if (!isset($input[\"is_active\"])) {\n $input[\"is_active\"] = 1;\n }", " if (!isset($input[\"is_deleted\"])) {\n $input[\"is_deleted\"] = 0;\n }", " if (!isset($input[\"entities_id\"])) {\n $input[\"entities_id\"] = 0;\n }", " if (!isset($input[\"profiles_id\"])) {\n $input[\"profiles_id\"] = 0;\n }", " return $input;\n }", " public function prepareInputForClone($input) {\n if (isset($input['name'])) {\n $suffix = 1;\n $possibleName = $input['name'].$suffix;\n while ($this->getFromDBbyName($possibleName)) {\n $suffix++;\n $possibleName = $input['name'].$suffix;\n }\n $input['name'] = $possibleName;\n }\n return $input;\n }", "\n function post_addItem() {", " $this->updateUserEmails();\n $this->syncLdapGroups();\n $this->syncDynamicEmails();", " $this->applyGroupsRules();\n $rulesplayed = $this->applyRightRules();\n $picture = $this->syncLdapPhoto();", " //add picture in user fields\n if (!empty($picture)) {\n $this->update(['id' => $this->fields['id'],\n 'picture' => $picture]);\n }", " // Add default profile\n if (!$rulesplayed) {\n $affectation = [];\n if (isset($this->input['_profiles_id']) && $this->input['_profiles_id']\n && Profile::currentUserHaveMoreRightThan([$this->input['_profiles_id']])\n ) {\n $profile = $this->input['_profiles_id'];\n // Choosen in form, so not dynamic\n $affectation['is_dynamic'] = 0;\n } else {\n $profile = Profile::getDefault();\n // Default right as dynamic. If dynamic rights are set it will disappear.\n $affectation['is_dynamic'] = 1;\n $affectation['is_default_profile'] = 1;\n }", " if ($profile) {\n if (isset($this->input[\"_entities_id\"])) {\n // entities_id (user's pref) always set in prepareInputForAdd\n // use _entities_id for default right\n $affectation[\"entities_id\"] = $this->input[\"_entities_id\"];", " } else if (isset($_SESSION['glpiactive_entity'])) {\n $affectation[\"entities_id\"] = $_SESSION['glpiactive_entity'];", " } else {\n $affectation[\"entities_id\"] = 0;\n }\n if (isset($this->input[\"_is_recursive\"])) {\n $affectation[\"is_recursive\"] = $this->input[\"_is_recursive\"];\n } else {\n $affectation[\"is_recursive\"] = 0;\n }", " $affectation[\"profiles_id\"] = $profile;\n $affectation[\"users_id\"] = $this->fields[\"id\"];\n $right = new Profile_User();\n $right->add($affectation);\n }\n }\n }", "\n function prepareInputForUpdate($input) {\n global $CFG_GLPI;", " // avoid xss (picture name is autogenerated when uploading/synchronising the picture)\n unset($input['picture']);", " //picture manually uploaded by user\n if (isset($input[\"_blank_picture\"]) && $input[\"_blank_picture\"]) {\n self::dropPictureFiles($this->fields['picture']);\n $input['picture'] = 'NULL';\n } else {\n $newPicture = false;\n if (!isAPI()) {\n if (isset($input[\"_picture\"][0]) && !empty($input[\"_picture\"][0])) {\n $input[\"_picture\"] = $input[\"_picture\"][0];\n }\n }\n if (isset($input[\"_picture\"]) && !empty($input[\"_picture\"])) {\n $newPicture = true;\n }\n if ($newPicture) {\n $fullpath = GLPI_TMP_DIR.\"/\".$input[\"_picture\"];\n if (Toolbox::getMime($fullpath, 'image')) {\n // Unlink old picture (clean on changing format)\n self::dropPictureFiles($this->fields['picture']);\n // Move uploaded file\n $filename = uniqid($this->fields['id'].'_');\n $sub = substr($filename, -2); /* 2 hex digit */", " // output images with possible transparency to png, other to jpg\n $extension = strtolower(pathinfo($fullpath, PATHINFO_EXTENSION));\n $extension = in_array($extension, ['png', 'gif'])\n ? 'png'\n : 'jpg';", " @mkdir(GLPI_PICTURE_DIR . \"/$sub\");\n $picture_path = GLPI_PICTURE_DIR . \"/$sub/${filename}.$extension\";\n self::dropPictureFiles(\"$sub/${filename}.$extension\");", " if (Document::isImage($fullpath)\n && Document::renameForce($fullpath, $picture_path)) {\n Session::addMessageAfterRedirect(__('The file is valid. Upload is successful.'));\n // For display\n $input['picture'] = \"$sub/${filename}.$extension\";", " //prepare a thumbnail\n $thumb_path = GLPI_PICTURE_DIR . \"/$sub/${filename}_min.$extension\";\n Toolbox::resizePicture($picture_path, $thumb_path);\n } else {\n Session::addMessageAfterRedirect(__('Potential upload attack or file too large. Moving temporary file failed.'),\n false, ERROR);\n }\n } else {\n Session::addMessageAfterRedirect(__('The file is not an image file.'),\n false, ERROR);\n }\n } else {\n //ldap jpegphoto synchronisation.\n $picture = $this->syncLdapPhoto();\n if (!empty($picture)) {\n $input['picture'] = $picture;\n }\n }\n }", " if (isset($input[\"password2\"])) {\n // Empty : do not update\n if (empty($input[\"password\"])) {\n unset($input[\"password\"]);", " } else {\n if ($input[\"password\"] == $input[\"password2\"]) {\n // Check right : my password of user with lesser rights\n if (isset($input['id'])\n && !Auth::checkPassword($input['password'], $this->fields['password']) // Validate that password is not same as previous\n && Config::validatePassword($input[\"password\"])\n && (($input['id'] == Session::getLoginUserID())\n || $this->currentUserHaveMoreRightThan($input['id'])\n // Permit to change password with token and email\n || (($input['password_forget_token'] == $this->fields['password_forget_token'])\n && (abs(strtotime($_SESSION[\"glpi_currenttime\"])\n -strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP)\n && $this->isEmail($input['email'])))) {\n $input[\"password\"]\n = Auth::getPasswordHash(Toolbox::unclean_cross_side_scripting_deep(stripslashes($input[\"password\"])));", " $input['password_last_update'] = $_SESSION[\"glpi_currenttime\"];\n } else {\n unset($input[\"password\"]);\n }\n unset($input[\"password2\"]);", " } else {\n Session::addMessageAfterRedirect(__('Error: the two passwords do not match'),\n false, ERROR);\n return false;\n }\n }", " } else if (isset($input[\"password\"])) { // From login\n unset($input[\"password\"]);\n }", " // blank password when authtype changes\n if (isset($input[\"authtype\"])\n && $input[\"authtype\"] != Auth::DB_GLPI\n && $input[\"authtype\"] != $this->getField('authtype')) {\n $input[\"password\"] = \"\";\n }", " // Update User in the database\n if (!isset($input[\"id\"])\n && isset($input[\"name\"])) {\n if ($this->getFromDBbyName($input[\"name\"])) {\n $input[\"id\"] = $this->fields[\"id\"];\n }\n }", " if (isset($input[\"entities_id\"])\n && (Session::getLoginUserID() == $input['id'])) {\n $_SESSION[\"glpidefault_entity\"] = $input[\"entities_id\"];\n }", " // Security on default profile update\n if (isset($input['profiles_id'])) {\n if (!in_array($input['profiles_id'], Profile_User::getUserProfiles($input['id']))) {\n unset($input['profiles_id']);\n }\n }", " // Security on default entity update\n if (isset($input['entities_id'])) {\n if (!in_array($input['entities_id'], Profile_User::getUserEntities($input['id']))) {\n unset($input['entities_id']);\n }\n }", " // Security on default group update\n if (isset($input['groups_id'])\n && !Group_User::isUserInGroup($input['id'], $input['groups_id'])) {\n unset($input['groups_id']);\n }", " if (isset($input['_reset_personal_token'])\n && $input['_reset_personal_token']) {\n $input['personal_token'] = self::getUniqueToken('personal_token');\n $input['personal_token_date'] = $_SESSION['glpi_currenttime'];\n }", " if (isset($input['_reset_api_token'])\n && $input['_reset_api_token']) {\n $input['api_token'] = self::getUniqueToken('api_token');\n $input['api_token_date'] = $_SESSION['glpi_currenttime'];\n }", " // Manage preferences fields\n if (Session::getLoginUserID() == $input['id']) {\n if (isset($input['use_mode'])\n && ($_SESSION['glpi_use_mode'] != $input['use_mode'])) {\n $_SESSION['glpi_use_mode'] = $input['use_mode'];\n unset($_SESSION['glpimenu']); // Force menu regeneration\n //Session::loadLanguage();\n }\n }", " foreach ($CFG_GLPI['user_pref_field'] as $f) {\n if (isset($input[$f])) {\n if (Session::getLoginUserID() == $input['id']) {\n if ($_SESSION[\"glpi$f\"] != $input[$f]) {\n $_SESSION[\"glpi$f\"] = $input[$f];\n // reinit translations\n if ($f == 'language') {\n $_SESSION['glpi_dropdowntranslations'] = DropdownTranslation::getAvailableTranslations($_SESSION[\"glpilanguage\"]);\n unset($_SESSION['glpimenu']);\n }\n }\n }\n if ($input[$f] == $CFG_GLPI[$f]) {\n $input[$f] = \"NULL\";\n }\n }\n }", " if (isset($input['language']) && GLPI_DEMO_MODE) {\n unset($input['language']);\n }", " if (array_key_exists('timezone', $input) && empty($input['timezone'])) {\n $input['timezone'] = 'NULL';\n }", " return $input;\n }", "\n function post_updateItem($history = 1) {\n //handle timezone change for current user\n if ($this->fields['id'] == Session::getLoginUserID()) {\n if (null == $this->fields['timezone'] || 'null' === strtolower($this->fields['timezone'])) {\n unset($_SESSION['glpi_tz']);\n } else {\n $_SESSION['glpi_tz'] = $this->fields['timezone'];\n }\n }", " $this->updateUserEmails();\n $this->syncLdapGroups();\n $this->syncDynamicEmails();\n $this->applyGroupsRules();\n $this->applyRightRules();", " if (in_array('password', $this->updates)) {\n $alert = new Alert();\n $alert->deleteByCriteria(\n [\n 'itemtype' => $this->getType(),\n 'items_id' => $this->fields['id'],\n ],\n true\n );\n }\n }", "", " /**\n * Apply rules to determine dynamic rights of the user.\n *\n * @return boolean true if rules are applied, false otherwise\n */\n function applyRightRules() {", " $return = false;", " if (isset($this->fields['_ruleright_process'])\n || isset($this->input['_ruleright_process'])) {", " $dynamic_profiles = Profile_User::getForUser($this->fields[\"id\"], true);", " if (isset($this->fields[\"id\"])\n && ($this->fields[\"id\"] > 0)\n && isset($this->input[\"_ldap_rules\"])\n && count($this->input[\"_ldap_rules\"])) {", " //and add/update/delete only if it's necessary !\n if (isset($this->input[\"_ldap_rules\"][\"rules_entities_rights\"])) {\n $entities_rules = $this->input[\"_ldap_rules\"][\"rules_entities_rights\"];\n } else {\n $entities_rules = [];\n }", " if (isset($this->input[\"_ldap_rules\"][\"rules_entities\"])) {\n $entities = $this->input[\"_ldap_rules\"][\"rules_entities\"];\n } else {\n $entities = [];\n }", " if (isset($this->input[\"_ldap_rules\"][\"rules_rights\"])) {\n $rights = $this->input[\"_ldap_rules\"][\"rules_rights\"];\n } else {\n $rights = [];\n }", " $retrieved_dynamic_profiles = [];", " //For each affectation -> write it in DB\n foreach ($entities_rules as $entity) {\n //Multiple entities assignation\n if (is_array($entity[0])) {\n foreach ($entity[0] as $ent) {\n $retrieved_dynamic_profiles[] = [\n 'entities_id' => $ent,\n 'profiles_id' => $entity[1],\n 'is_recursive' => $entity[2],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n } else {\n $retrieved_dynamic_profiles[] = [\n 'entities_id' => $entity[0],\n 'profiles_id' => $entity[1],\n 'is_recursive' => $entity[2],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n }", " if ((count($entities) > 0)\n && (count($rights) == 0)) {\n if ($def_prof = Profile::getDefault()) {\n $rights[] = $def_prof;\n }\n }", " if ((count($rights) > 0)\n && (count($entities) > 0)) {\n foreach ($rights as $right) {\n foreach ($entities as $entity) {\n $retrieved_dynamic_profiles[] = [\n 'entities_id' => $entity[0],\n 'profiles_id' => $right,\n 'is_recursive' => $entity[1],\n 'users_id' => $this->fields['id'],\n 'is_dynamic' => 1,\n ];\n }\n }\n }", " // Compare retrived profiles to existing ones : clean arrays to do purge and add\n if (count($retrieved_dynamic_profiles)) {\n foreach ($retrieved_dynamic_profiles as $keyretr => $retr_profile) {\n $found = false;", " foreach ($dynamic_profiles as $keydb => $db_profile) {\n // Found existing profile : unset values in array\n if (!$found\n && ($db_profile['entities_id'] == $retr_profile['entities_id'])\n && ($db_profile['profiles_id'] == $retr_profile['profiles_id'])\n && ($db_profile['is_recursive'] == $retr_profile['is_recursive'])) {", " unset($retrieved_dynamic_profiles[$keyretr]);\n unset($dynamic_profiles[$keydb]);\n }\n }\n }\n }", " // Add new dynamic profiles\n if (count($retrieved_dynamic_profiles)) {\n $right = new Profile_User();\n foreach ($retrieved_dynamic_profiles as $keyretr => $retr_profile) {\n $right->add($retr_profile);\n }\n }", " //Unset all the temporary tables\n unset($this->input[\"_ldap_rules\"]);", " $return = true;\n } else if (count($dynamic_profiles) == 1) {\n $dynamic_profile = reset($dynamic_profiles);", " // If no rule applied and only one dynamic profile found, check if\n // it is the default profile\n if ($dynamic_profile['is_default_profile'] == true) {\n $default_profile = Profile::getDefault();", " // Remove from to be deleted list\n $dynamic_profiles = [];", " // Update profile if need to match the current default profile\n if ($dynamic_profile['profiles_id'] !== $default_profile) {\n $pu = new Profile_User();\n $dynamic_profile['profiles_id'] = $default_profile;\n $pu->add($dynamic_profile);\n $pu->delete([\n 'id' => $dynamic_profile['id']\n ]);\n }\n }\n }", " // Delete old dynamic profiles\n if (count($dynamic_profiles)) {\n $right = new Profile_User();\n foreach ($dynamic_profiles as $keydb => $db_profile) {\n $right->delete($db_profile);\n }\n }", " }\n return $return;\n }", "\n /**\n * Synchronise LDAP group of the user.\n *\n * @return void\n */\n function syncLdapGroups() {\n global $DB;", " // input[\"_groups\"] not set when update from user.form or preference\n if (isset($this->fields[\"authtype\"])\n && isset($this->input[\"_groups\"])\n && (($this->fields[\"authtype\"] == Auth::LDAP)\n || Auth::isAlternateAuth($this->fields['authtype']))) {", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n $authtype = Auth::getMethodsByID($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);", " if (count($authtype)) {\n // Clean groups\n $this->input[\"_groups\"] = array_unique ($this->input[\"_groups\"]);", " // Delete not available groups like to LDAP\n $iterator = $DB->request([\n 'SELECT' => [\n 'glpi_groups_users.id',\n 'glpi_groups_users.groups_id',\n 'glpi_groups_users.is_dynamic'\n ],\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_groups' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'groups_id',\n 'glpi_groups' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.users_id' => $this->fields['id']\n ]\n ]);", " $groupuser = new Group_User();\n while ($data = $iterator->next()) {", " if (in_array($data[\"groups_id\"], $this->input[\"_groups\"])) {\n // Delete found item in order not to add it again\n unset($this->input[\"_groups\"][array_search($data[\"groups_id\"],\n $this->input[\"_groups\"])]);", " } else if ($data['is_dynamic']) {\n $groupuser->delete(['id' => $data[\"id\"]]);\n }\n }", " //If the user needs to be added to one group or more\n if (count($this->input[\"_groups\"]) > 0) {\n foreach ($this->input[\"_groups\"] as $group) {\n $groupuser->add(['users_id' => $this->fields[\"id\"],\n 'groups_id' => $group,\n 'is_dynamic' => 1]);\n }\n unset ($this->input[\"_groups\"]);\n }\n }\n }\n }\n }", "\n /**\n * Synchronize picture (photo) of the user.\n *\n * @since 0.85\n *\n * @return string|boolean Filename to be stored in user picture field, false if no picture found\n */\n function syncLdapPhoto() {", " if (isset($this->fields[\"authtype\"])\n && (($this->fields[\"authtype\"] == Auth::LDAP)\n || ($this->fields[\"authtype\"] == Auth::NOT_YET_AUTHENTIFIED\n && !empty($this->fields[\"auths_id\"]))\n || Auth::isAlternateAuth($this->fields['authtype']))) {", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n $config_ldap = new AuthLDAP();\n $ds = false;", " //connect ldap server\n if ($config_ldap->getFromDB($this->fields['auths_id'])) {\n $ds = $config_ldap->connect();\n }", " if ($ds) {\n //get picture fields\n $picture_field = $config_ldap->fields['picture_field'];\n if (empty($picture_field)) {\n return false;\n }", " //get picture content in ldap\n $info = AuthLDAP::getUserByDn($ds, $this->fields['user_dn'],\n [$picture_field], false);", " //getUserByDn returns an array. If the picture is empty,\n //$info[$picture_field][0] is null\n if (!isset($info[$picture_field][0]) || empty($info[$picture_field][0])) {\n return \"\";\n }\n //prepare paths\n $img = array_pop($info[$picture_field]);\n $filename = uniqid($this->fields['id'].'_');\n $sub = substr($filename, -2); /* 2 hex digit */\n $file = GLPI_PICTURE_DIR . \"/$sub/${filename}.jpg\";", " if (array_key_exists('picture', $this->fields)) {\n $oldfile = GLPI_PICTURE_DIR . \"/\" . $this->fields[\"picture\"];\n } else {\n $oldfile = null;\n }", " // update picture if not exist or changed\n if (empty($this->fields[\"picture\"])\n || !file_exists($oldfile)\n || sha1_file($oldfile) !== sha1($img)) {\n if (!is_dir(GLPI_PICTURE_DIR . \"/$sub\")) {\n mkdir(GLPI_PICTURE_DIR . \"/$sub\");\n }", " //save picture\n $outjpeg = fopen($file, 'wb');\n fwrite($outjpeg, $img);\n fclose ($outjpeg);", " //save thumbnail\n $thumb = GLPI_PICTURE_DIR . \"/$sub/${filename}_min.jpg\";\n Toolbox::resizePicture($file, $thumb);", " return \"$sub/${filename}.jpg\";\n }\n return $this->fields[\"picture\"];\n }\n }\n }", " return false;\n }", "\n /**\n * Update emails of the user.\n * Uses _useremails set from UI, not _emails set from LDAP.\n *\n * @return void\n */\n function updateUserEmails() {\n // Update emails (use _useremails set from UI, not _emails set from LDAP)", " $userUpdated = false;", " if (isset($this->input['_useremails']) && count($this->input['_useremails'])) {\n $useremail = new UserEmail();\n foreach ($this->input['_useremails'] as $id => $email) {\n $email = trim($email);", " // existing email\n if ($id > 0) {\n $params = ['id' => $id];", " // empty email : delete\n if (strlen($email) == 0) {\n $deleted = $useremail->delete($params);\n $userUpdated = $userUpdated || $deleted;", " } else { // Update email\n $params['email'] = $email;\n $params['is_default'] = $this->input['_default_email'] == $id ? 1 : 0;", " $existingUserEmail = new UserEmail();\n $existingUserEmail->getFromDB($id);\n if ($params['email'] == $existingUserEmail->fields['email']\n && $params['is_default'] == $existingUserEmail->fields['is_default']) {\n // Do not update if email has not changed\n continue;\n }", " $updated = $useremail->update($params);\n $userUpdated = $userUpdated || $updated;\n }", " } else { // New email\n $email_input = ['email' => $email,\n 'users_id' => $this->fields['id']];\n if (isset($this->input['_default_email'])\n && ($this->input['_default_email'] == $id)) {\n $email_input['is_default'] = 1;\n } else {\n $email_input['is_default'] = 0;\n }\n $added = $useremail->add($email_input);\n $userUpdated = $userUpdated || $added;\n }\n }\n }", " if ($userUpdated) {\n // calling $this->update() here leads to loss in $this->input\n $user = new User();\n $user->update(['id' => $this->fields['id'], 'date_mod' => $_SESSION['glpi_currenttime']]);\n }\n }", "\n /**\n * Synchronise Dynamics emails of the user.\n * Uses _emails (set from getFromLDAP), not _usermails set from UI.\n *\n * @return void\n */\n function syncDynamicEmails() {\n global $DB;", " $userUpdated = false;", " // input[\"_emails\"] not set when update from user.form or preference\n if (isset($this->fields[\"authtype\"])\n && isset($this->input[\"_emails\"])\n && (($this->fields[\"authtype\"] == Auth::LDAP)\n || Auth::isAlternateAuth($this->fields['authtype'])\n || ($this->fields[\"authtype\"] == Auth::MAIL))) {", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n $authtype = Auth::getMethodsByID($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);", " if (count($authtype)\n || $this->fields[\"authtype\"] == Auth::EXTERNAL) {\n // Clean emails\n // Do a case insensitive comparison as it seems that some LDAP servers\n // may return same email with different case sensitivity.\n $unique_emails = [];\n foreach ($this->input[\"_emails\"] as $email) {\n if (!in_array(strtolower($email), array_map('strtolower', $unique_emails))) {\n $unique_emails[] = $email;\n }\n }\n $this->input[\"_emails\"] = $unique_emails;", " // Delete not available groups like to LDAP\n $iterator = $DB->request([\n 'SELECT' => [\n 'id',\n 'users_id',\n 'email',\n 'is_dynamic'\n ],\n 'FROM' => 'glpi_useremails',\n 'WHERE' => ['users_id' => $this->fields['id']]\n ]);", " $useremail = new UserEmail();\n while ($data = $iterator->next()) {\n // Do a case insensitive comparison as email may be stored with a different case\n $i = array_search(strtolower($data[\"email\"]), array_map('strtolower', $this->input[\"_emails\"]));\n if ($i !== false) {\n // Delete found item in order not to add it again\n unset($this->input[\"_emails\"][$i]);\n } else if ($data['is_dynamic']) {\n // Delete not found email\n $deleted = $useremail->delete(['id' => $data[\"id\"]]);\n $userUpdated = $userUpdated || $deleted;\n }\n }", " //If the email need to be added\n if (count($this->input[\"_emails\"]) > 0) {\n foreach ($this->input[\"_emails\"] as $email) {\n $added = $useremail->add(['users_id' => $this->fields[\"id\"],\n 'email' => $email,\n 'is_dynamic' => 1]);\n $userUpdated = $userUpdated || $added;\n }\n unset ($this->input[\"_emails\"]);\n }\n }\n }\n }", " if ($userUpdated) {\n // calling $this->update() here leads to loss in $this->input\n $user = new User();\n $user->update(['id' => $this->fields['id'], 'date_mod' => $_SESSION['glpi_currenttime']]);\n }\n }", " protected function computeFriendlyName() {\n global $CFG_GLPI;", " if (isset($this->fields[\"id\"]) && ($this->fields[\"id\"] > 0)) {\n //computeFriendlyName should not add ID\n $bkp_conf = $CFG_GLPI['is_ids_visible'];\n $CFG_GLPI['is_ids_visible'] = 0;\n $bkp_sessconf = (isset($_SESSION['glpiis_ids_visible']) ? $_SESSION[\"glpiis_ids_visible\"] : 0);\n $_SESSION[\"glpiis_ids_visible\"] = 0;\n $name = formatUserName($this->fields[\"id\"],\n $this->fields[\"name\"],\n (isset($this->fields[\"realname\"]) ? $this->fields[\"realname\"] : ''),\n (isset($this->fields[\"firstname\"]) ? $this->fields[\"firstname\"] : ''));", " $CFG_GLPI['is_ids_visible'] = $bkp_conf;\n $_SESSION[\"glpiis_ids_visible\"] = $bkp_sessconf;\n return $name;\n }\n return '';\n }", "\n /**\n * Function that tries to load the user membership from LDAP\n * by searching in the attributes of the User.\n *\n * @param resource $ldap_connection LDAP connection\n * @param array $ldap_method LDAP method\n * @param string $userdn Basedn of the user\n * @param string $login User login\n *\n * @return string|boolean Basedn of the user / false if not found\n */\n private function getFromLDAPGroupVirtual($ldap_connection, array $ldap_method, $userdn, $login) {\n global $DB;", " // Search in DB the ldap_field we need to search for in LDAP\n $iterator = $DB->request([\n 'SELECT' => 'ldap_field',\n 'DISTINCT' => true,\n 'FROM' => 'glpi_groups',\n 'WHERE' => ['NOT' => ['ldap_field' => '']],\n 'ORDER' => 'ldap_field'\n ]);\n $group_fields = [];", " while ($data = $iterator->next()) {\n $group_fields[] = Toolbox::strtolower($data[\"ldap_field\"]);\n }\n if (count($group_fields)) {\n //Need to sort the array because edirectory don't like it!\n sort($group_fields);", " // If the groups must be retrieve from the ldap user object\n $sr = @ ldap_read($ldap_connection, $userdn, \"objectClass=*\", $group_fields);\n $v = AuthLDAP::get_entries_clean($ldap_connection, $sr);", " for ($i=0; $i < $v['count']; $i++) {\n //Try to find is DN in present and needed: if yes, then extract only the OU from it\n if ((($ldap_method[\"group_field\"] == 'dn') || in_array('ou', $group_fields))\n && isset($v[$i]['dn'])) {", " $v[$i]['ou'] = [];\n for ($tmp=$v[$i]['dn']; count($tmptab = explode(',', $tmp, 2))==2; $tmp=$tmptab[1]) {\n $v[$i]['ou'][] = $tmptab[1];\n }", " // Search in DB for group with ldap_group_dn\n if (($ldap_method[\"group_field\"] == 'dn')\n && (count($v[$i]['ou']) > 0)) {\n $group_iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_groups',\n 'WHERE' => ['ldap_group_dn' => Toolbox::addslashes_deep($v[$i]['ou'])]\n ]);", " while ($group = $group_iterator->next()) {\n $this->fields[\"_groups\"][] = $group['id'];\n }\n }", " // searching with ldap_field='OU' and ldap_value is also possible\n $v[$i]['ou']['count'] = count($v[$i]['ou']);\n }", " // For each attribute retrieve from LDAP, search in the DB\n foreach ($group_fields as $field) {\n if (isset($v[$i][$field])\n && isset($v[$i][$field]['count'])\n && ($v[$i][$field]['count'] > 0)) {", " unset($v[$i][$field]['count']);\n $lgroups = [];\n foreach (Toolbox::addslashes_deep($v[$i][$field]) as $lgroup) {\n $lgroups[] = [\n new \\QueryExpression($DB::quoteValue($lgroup).\n \" LIKE \".\n $DB::quoteName('ldap_value'))\n ];\n }\n $group_iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_groups',\n 'WHERE' => [\n 'ldap_field' => $field,\n 'OR' => $lgroups\n ]\n ]);", " while ($group = $group_iterator->next()) {\n $this->fields[\"_groups\"][] = $group['id'];\n }\n }\n }\n } // for each ldapresult\n } // count($group_fields)\n }", "\n /**\n * Function that tries to load the user membership from LDAP\n * by searching in the attributes of the Groups.\n *\n * @param resource $ldap_connection LDAP connection\n * @param array $ldap_method LDAP method\n * @param string $userdn Basedn of the user\n * @param string $login User login\n *\n * @return boolean true if search is applicable, false otherwise\n */\n private function getFromLDAPGroupDiscret($ldap_connection, array $ldap_method, $userdn, $login) {\n global $DB;", " // No group_member_field : unable to get group\n if (empty($ldap_method[\"group_member_field\"])) {\n return false;\n }", " if ($ldap_method[\"use_dn\"]) {\n $user_tmp = $userdn;\n } else {\n //Don't add $ldap_method[\"login_field\"].\"=\", because sometimes it may not work (for example with posixGroup)\n $user_tmp = $login;\n }", " $v = $this->ldap_get_user_groups($ldap_connection, $ldap_method[\"basedn\"],\n $user_tmp,\n $ldap_method[\"group_condition\"],\n $ldap_method[\"group_member_field\"],\n $ldap_method[\"use_dn\"],\n $ldap_method[\"login_field\"]);\n foreach ($v as $result) {\n if (isset($result[$ldap_method[\"group_member_field\"]])\n && is_array($result[$ldap_method[\"group_member_field\"]])\n && (count($result[$ldap_method[\"group_member_field\"]]) > 0)) {", " $iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => 'glpi_groups',\n 'WHERE' => ['ldap_group_dn' => Toolbox::addslashes_deep($result[$ldap_method[\"group_member_field\"]])]\n ]);", " while ($group = $iterator->next()) {\n $this->fields[\"_groups\"][] = $group['id'];\n }\n }\n }\n return true;\n }", "\n /**\n * Function that tries to load the user informations from LDAP.\n *\n * @param resource $ldap_connection LDAP connection\n * @param array $ldap_method LDAP method\n * @param string $userdn Basedn of the user\n * @param string $login User Login\n * @param boolean $import true for import, false for update\n *\n * @return boolean true if found / false if not\n */\n function getFromLDAP($ldap_connection, array $ldap_method, $userdn, $login, $import = true) {\n global $DB, $CFG_GLPI;", " // we prevent some delay...\n if (empty($ldap_method[\"host\"])) {\n return false;\n }", " if (is_resource($ldap_connection)) {\n //Set all the search fields\n $this->fields['password'] = \"\";", " $fields = AuthLDAP::getSyncFields($ldap_method);", " //Hook to allow plugin to request more attributes from ldap\n $fields = Plugin::doHookFunction(\"retrieve_more_field_from_ldap\", $fields);", " $fields = array_filter($fields);\n $f = self::getLdapFieldNames($fields);", " $sr = @ ldap_read($ldap_connection, $userdn, \"objectClass=*\", $f);\n $v = AuthLDAP::get_entries_clean($ldap_connection, $sr);", " if (!is_array($v)\n || ( count($v) == 0)\n || empty($v[0][$fields['name']][0])) {\n return false;\n }", " //Store user's dn\n $this->fields['user_dn'] = addslashes($userdn);\n //Store date_sync\n $this->fields['date_sync'] = $_SESSION['glpi_currenttime'];\n // Empty array to ensure than syncDynamicEmails will be done\n $this->fields[\"_emails\"] = [];\n // force authtype as we retrieve this user by ldap (we could have login with SSO)\n $this->fields[\"authtype\"] = Auth::LDAP;", " foreach ($fields as $k => $e) {\n $val = AuthLDAP::getFieldValue(\n [$e => self::getLdapFieldValue($e, $v)],\n $e\n );\n if (empty($val)) {\n switch ($k) {\n case \"language\" :\n // Not set value : managed but user class\n break;", " case \"usertitles_id\" :\n case \"usercategories_id\" :\n case 'locations_id' :\n case 'users_id_supervisor' :\n $this->fields[$k] = 0;\n break;", " default :\n $this->fields[$k] = \"\";\n }", " } else {\n $val = Toolbox::addslashes_deep($val);\n switch ($k) {\n case \"email1\" :\n case \"email2\" :\n case \"email3\" :\n case \"email4\" :\n // Manage multivaluable fields\n if (!empty($v[0][$e])) {\n foreach ($v[0][$e] as $km => $m) {\n if (!preg_match('/count/', $km)) {\n $this->fields[\"_emails\"][] = addslashes($m);\n }\n }\n // Only get them once if duplicated\n $this->fields[\"_emails\"] = array_unique($this->fields[\"_emails\"]);\n }\n break;", " case \"language\" :\n $language = Config::getLanguage($val);\n if ($language != '') {\n $this->fields[$k] = $language;\n }\n break;", " case \"usertitles_id\" :\n $this->fields[$k] = Dropdown::importExternal('UserTitle', $val);\n break;", " case 'locations_id' :\n // use import to build the location tree\n $this->fields[$k] = Dropdown::import('Location',\n ['completename' => $val,\n 'entities_id' => 0,\n 'is_recursive' => 1]);\n break;", " case \"usercategories_id\" :\n $this->fields[$k] = Dropdown::importExternal('UserCategory', $val);\n break;", " case 'users_id_supervisor':\n $this->fields[$k] = self::getIdByField('user_dn', $val, false);\n break;", " default :\n $this->fields[$k] = $val;\n }\n }\n }", " // Empty array to ensure than syncLdapGroups will be done\n $this->fields[\"_groups\"] = [];", " ///The groups are retrieved by looking into an ldap user object\n if (($ldap_method[\"group_search_type\"] == 0)\n || ($ldap_method[\"group_search_type\"] == 2)) {\n $this->getFromLDAPGroupVirtual($ldap_connection, $ldap_method, $userdn, $login);\n }", " ///The groups are retrived by looking into an ldap group object\n if (($ldap_method[\"group_search_type\"] == 1)\n || ($ldap_method[\"group_search_type\"] == 2)) {\n $this->getFromLDAPGroupDiscret($ldap_connection, $ldap_method, $userdn, $login);\n }", " ///Only process rules if working on the master database\n if (!$DB->isSlave()) {\n //Instanciate the affectation's rule\n $rule = new RuleRightCollection();", " //Process affectation rules :\n //we don't care about the function's return because all\n //the datas are stored in session temporary\n if (isset($this->fields[\"_groups\"])) {\n $groups = $this->fields[\"_groups\"];\n } else {\n $groups = [];\n }", " $this->fields = $rule->processAllRules($groups, Toolbox::stripslashes_deep($this->fields), [\n 'type' => Auth::LDAP,\n 'ldap_server' => $ldap_method[\"id\"],\n 'connection' => $ldap_connection,\n 'userdn' => $userdn,\n 'login' => $this->fields['name'],\n 'mail_email' => $this->fields['_emails']\n ]);", " $this->fields['_ruleright_process'] = true;", " //If rule action is ignore import\n if ($import\n && isset($this->fields[\"_stop_import\"])) {\n return false;\n }\n //or no rights found & do not import users with no rights\n if ($import\n && !$CFG_GLPI[\"use_noright_users_add\"]) {\n $ok = false;\n if (isset($this->fields[\"_ldap_rules\"])\n && count($this->fields[\"_ldap_rules\"])) {\n if (isset($this->fields[\"_ldap_rules\"][\"rules_entities_rights\"])\n && count($this->fields[\"_ldap_rules\"][\"rules_entities_rights\"])) {\n $ok = true;\n }\n if (!$ok) {\n $entity_count = 0;\n $right_count = 0;\n if (Profile::getDefault()) {\n $right_count++;\n }\n if (isset($this->fields[\"_ldap_rules\"][\"rules_entities\"])) {\n $entity_count += count($this->fields[\"_ldap_rules\"][\"rules_entities\"]);\n }\n if (isset($this->input[\"_ldap_rules\"][\"rules_rights\"])) {\n $right_count += count($this->fields[\"_ldap_rules\"][\"rules_rights\"]);\n }\n if ($entity_count && $right_count) {\n $ok = true;\n }\n }\n }\n if (!$ok) {\n $this->fields[\"_stop_import\"] = true;\n return false;\n }\n }", " // Add ldap result to data send to the hook\n $this->fields['_ldap_result'] = $v;\n $this->fields['_ldap_conn'] = $ldap_connection;\n //Hook to retrieve more information for ldap\n $this->fields = Plugin::doHookFunction(\"retrieve_more_data_from_ldap\", $this->fields);\n unset($this->fields['_ldap_result']);\n }\n return true;\n }\n return false;", " } // getFromLDAP()", "\n /**\n * Get all groups a user belongs to.\n *\n * @param resource $ds ldap connection\n * @param string $ldap_base_dn Basedn used\n * @param string $user_dn Basedn of the user\n * @param string $group_condition group search condition\n * @param string $group_member_field group field member in a user object\n * @param boolean $use_dn search dn of user ($login_field=$user_dn) in group_member_field\n * @param string $login_field user login field\n *\n * @return array Groups of the user located in [0][$group_member_field] in returned array\n */\n function ldap_get_user_groups($ds, $ldap_base_dn, $user_dn, $group_condition,\n $group_member_field, $use_dn, $login_field) {", " $groups = [];\n $listgroups = [];", " //User dn may contain ( or ), need to espace it!\n $user_dn = str_replace([\"(\", \")\", \"\\,\", \"\\+\"], [\"\\(\", \"\\)\", \"\\\\\\,\", \"\\\\\\+\"],\n $user_dn);", " //Only retrive cn and member attributes from groups\n $attrs = ['dn'];", " if (!$use_dn) {\n $filter = \"(& $group_condition (|($group_member_field=$user_dn)\n ($group_member_field=$login_field=$user_dn)))\";\n } else {\n $filter = \"(& $group_condition ($group_member_field=$user_dn))\";\n }", " //Perform the search\n $filter = Toolbox::unclean_cross_side_scripting_deep($filter);\n $sr = ldap_search($ds, $ldap_base_dn, $filter, $attrs);", " //Get the result of the search as an array\n $info = AuthLDAP::get_entries_clean($ds, $sr);\n //Browse all the groups\n $info_count = count($info);\n for ($i = 0; $i < $info_count; $i++) {\n //Get the cn of the group and add it to the list of groups\n if (isset($info[$i][\"dn\"]) && ($info[$i][\"dn\"] != '')) {\n $listgroups[$i] = $info[$i][\"dn\"];\n }\n }", " //Create an array with the list of groups of the user\n $groups[0][$group_member_field] = $listgroups;\n //Return the groups of the user\n return $groups;\n }", "\n /**\n * Function that tries to load the user informations from IMAP.\n *\n * @param array $mail_method mail method description array\n * @param string $name login of the user\n *\n * @return boolean true if method is applicable, false otherwise\n */\n function getFromIMAP(array $mail_method, $name) {\n global $DB;", " // we prevent some delay..\n if (empty($mail_method[\"host\"])) {\n return false;\n }", " // some defaults...\n $this->fields['password'] = \"\";\n // Empty array to ensure than syncDynamicEmails will be done\n $this->fields[\"_emails\"] = [];\n $email = '';\n if (strpos($name, \"@\")) {\n $email = $name;\n } else {\n $email = $name . \"@\" . $mail_method[\"host\"];\n }\n $this->fields[\"_emails\"][] = $email;", " $this->fields['name'] = $name;\n //Store date_sync\n $this->fields['date_sync'] = $_SESSION['glpi_currenttime'];\n // force authtype as we retrieve this user by imap (we could have login with SSO)\n $this->fields[\"authtype\"] = Auth::MAIL;", " if (!$DB->isSlave()) {\n //Instanciate the affectation's rule\n $rule = new RuleRightCollection();", " //Process affectation rules :\n //we don't care about the function's return because all the datas are stored in session temporary\n if (isset($this->fields[\"_groups\"])) {\n $groups = $this->fields[\"_groups\"];\n } else {\n $groups = [];\n }\n $this->fields = $rule->processAllRules($groups, Toolbox::stripslashes_deep($this->fields), [\n 'type' => Auth::MAIL,\n 'mail_server' => $mail_method[\"id\"],\n 'login' => $name,\n 'email' => $email]\n );\n $this->fields['_ruleright_process'] = true;\n }\n return true;\n }", "\n /**\n * Function that tries to load the user informations from the SSO server.\n *\n * @since 0.84\n *\n * @return boolean true if method is applicable, false otherwise\n */\n function getFromSSO() {\n global $DB, $CFG_GLPI;", " $a_field = [];\n foreach ($CFG_GLPI as $key=>$value) {\n if (!is_array($value) && !empty($value)\n && strstr($key, \"_ssofield\")) {\n $key = str_replace('_ssofield', '', $key);\n $a_field[$key] = $value;\n }\n }", " if (count($a_field) == 0) {\n return true;\n }\n $this->fields['_ruleright_process'] = true;\n foreach ($a_field as $field=>$value) {\n if (!isset($_SERVER[$value])\n || empty($_SERVER[$value])) {", " switch ($field) {\n case \"title\" :\n $this->fields['usertitles_id'] = 0;\n break;", " case \"category\" :\n $this->fields['usercategories_id'] = 0;\n break;", " default :\n $this->fields[$field] = \"\";\n }", " } else {\n switch ($field) {\n case \"email1\" :\n case \"email2\" :\n case \"email3\" :\n case \"email4\" :\n // Manage multivaluable fields\n if (!preg_match('/count/', $_SERVER[$value])) {\n $this->fields[\"_emails\"][] = addslashes($_SERVER[$value]);\n }\n // Only get them once if duplicated\n $this->fields[\"_emails\"] = array_unique($this->fields[\"_emails\"]);\n break;", " case \"language\" :\n $language = Config::getLanguage($_SERVER[$value]);\n if ($language != '') {\n $this->fields[$field] = $language;\n }\n break;", " case \"title\" :\n $this->fields['usertitles_id']\n = Dropdown::importExternal('UserTitle', addslashes($_SERVER[$value]));\n break;", " case \"category\" :\n $this->fields['usercategories_id']\n = Dropdown::importExternal('UserCategory', addslashes($_SERVER[$value]));\n break;", " default :\n $this->fields[$field] = $_SERVER[$value];\n break;", " }\n }\n }\n ///Only process rules if working on the master database\n if (!$DB->isSlave()) {\n //Instanciate the affectation's rule\n $rule = new RuleRightCollection();", " $this->fields = $rule->processAllRules([], Toolbox::stripslashes_deep($this->fields), [\n 'type' => Auth::EXTERNAL,\n 'email' => $this->fields[\"_emails\"],\n 'login' => $this->fields[\"name\"]\n ]);", " //If rule action is ignore import\n if (isset($this->fields[\"_stop_import\"])) {\n return false;\n }\n }\n return true;\n }", "\n /**\n * Blank passwords field of a user in the DB.\n * Needed for external auth users.\n *\n * @return void\n */\n function blankPassword() {\n global $DB;", " if (!empty($this->fields[\"name\"])) {\n $DB->update(\n $this->getTable(), [\n 'password' => ''\n ], [\n 'name' => $this->fields['name']\n ]\n );\n }\n }", "\n /**\n * Print a good title for user pages.\n *\n * @return void\n */\n function title() {\n global $CFG_GLPI;", " $buttons = [];\n $title = self::getTypeName(Session::getPluralNumber());", " if (static::canCreate()) {\n $buttons[\"user.form.php\"] = __('Add user...');\n $title = \"\";", " if (Auth::useAuthExt()\n && Session::haveRight(\"user\", self::IMPORTEXTAUTHUSERS)) {\n // This requires write access because don't use entity config.\n $buttons[\"user.form.php?new=1&amp;ext_auth=1\"] = __('... From an external source');\n }\n }\n if (Session::haveRight(\"user\", self::IMPORTEXTAUTHUSERS)\n && (static::canCreate() || static::canUpdate())) {\n if (AuthLDAP::useAuthLdap()) {\n $buttons[\"ldap.php\"] = __('LDAP directory link');\n }\n }\n Html::displayTitle($CFG_GLPI[\"root_doc\"] . \"/pics/users.png\", self::getTypeName(Session::getPluralNumber()), $title,\n $buttons);\n }", "\n /**\n * Check if current user have more right than the specified one.\n *\n * @param integer $ID ID of the user\n *\n * @return boolean\n */\n function currentUserHaveMoreRightThan($ID) {", " $user_prof = Profile_User::getUserProfiles($ID);\n return Profile::currentUserHaveMoreRightThan($user_prof);\n }", "\n /**\n * Print the user form.\n *\n * @param integer $ID ID of the user\n * @param array $options Options\n * - string target Form target\n * - boolean withtemplate Template or basic item\n *\n * @return boolean true if user found, false otherwise\n */\n function showForm($ID, array $options = []) {\n global $CFG_GLPI, $DB;", " // Affiche un formulaire User\n if (($ID != Session::getLoginUserID()) && !self::canView()) {\n return false;\n }", " $this->initForm($ID, $options);", " $ismyself = $ID == Session::getLoginUserID();\n $higherrights = $this->currentUserHaveMoreRightThan($ID);\n if ($ID) {\n $caneditpassword = $higherrights || ($ismyself && Session::haveRight('password_update', 1));\n } else {\n // can edit on creation form\n $caneditpassword = true;\n }", " $extauth = !(($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || (($this->fields[\"authtype\"] == Auth::NOT_YET_AUTHENTIFIED)\n && !empty($this->fields[\"password\"])));", " $formtitle = $this->getTypeName(1);", " if ($ID > 0) {\n $formtitle .= \"<a class='pointer far fa-address-card fa-lg' target='_blank' href='\".\n User::getFormURLWithID($ID).\"&amp;getvcard=1' title='\".__s('Download user VCard').\n \"'><span class='sr-only'>\". __('Vcard').\"</span></a>\";\n if (Session::canImpersonate($ID)) {\n $formtitle .= '<button type=\"button\" class=\"pointer btn-linkstyled btn-impersonate\" name=\"impersonate\" value=\"1\">'\n . '<i class=\"fas fa-user-secret fa-lg\" title=\"' . __s('Impersonate') . '\"></i> '\n . '<span class=\"sr-only\">' . __s('Impersonate') . '</span>'\n . '</button>';", " // \"impersonate\" button type is set to \"button\" on form display to prevent it to be used\n // by default (as it is the first found in current form) when pressing \"enter\" key.\n // When clicking it, switch to \"submit\" type to make it submit current user form.\n $impersonate_js = <<<JAVASCRIPT\n (function($) {\n $('button[type=\"button\"][name=\"impersonate\"]').click(\n function () {\n $(this).attr('type', 'submit');\n }\n );\n })(jQuery);\nJAVASCRIPT;\n $formtitle .= Html::scriptBlock($impersonate_js);\n }\n }", " $options['formtitle'] = $formtitle;\n $options['formoptions'] = ($options['formoptions'] ?? '') . \" enctype='multipart/form-data'\";\n $this->showFormHeader($options);\n $rand = mt_rand();", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='name'>\" . __('Login') . \"</label></td>\";\n if ($this->fields[\"name\"] == \"\" ||\n !empty($this->fields[\"password\"])\n || ($this->fields[\"authtype\"] == Auth::DB_GLPI)) {\n //display login field for new records, or if this is not external auth\n echo \"<td><input name='name' id='name' value=\\\"\" . $this->fields[\"name\"] . \"\\\"></td>\";\n } else {\n echo \"<td class='b'>\" . $this->fields[\"name\"];\n echo \"<input type='hidden' name='name' value=\\\"\" . $this->fields[\"name\"] . \"\\\"></td>\";\n }", " if (!empty($this->fields[\"name\"])) {\n echo \"<td rowspan='7'>\" . __('Picture') . \"</td>\";\n echo \"<td rowspan='7'>\";\n echo \"<div class='user_picture_border_small' id='picture$rand'>\";\n echo \"<img class='user_picture_small' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getThumbnailURLForPicture($this->fields['picture']).\"'>\";\n // echo \"<img src='\".self::getURLForPicture($this->fields[\"picture\"]).\"' class='user_picture'/>\";\n echo \"</div>\";\n $full_picture = \"<div class='user_picture_border'>\";\n $full_picture .= \"<img class='user_picture' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getURLForPicture($this->fields['picture']).\"'>\";\n $full_picture .= \"</div>\";", " Html::showTooltip($full_picture, ['applyto' => \"picture$rand\"]);\n echo Html::file(['name' => 'picture', 'display' => false, 'onlyimages' => true]);\n echo \"<input type='checkbox' name='_blank_picture'>&nbsp;\".__('Clear');\n echo \"</td>\";\n } else {\n echo \"<td rowspan='7'></td>\";\n echo \"<td rowspan='7'></td>\";\n }\n echo \"</tr>\";", " //If it's an external auth, check if the sync_field must be displayed\n if ($extauth\n && $this->fields['auths_id']\n && AuthLDAP::isSyncFieldConfigured($this->fields['auths_id'])) {\n $syncrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_sync_field$syncrand'>\" . __('Synchronization field') . \"</label></td><td>\";\n if (self::canUpdate()\n && (!$extauth || empty($ID))) {\n Html::autocompletionTextField($this, \"sync_field\", ['rand' => $syncrand]);\n } else {\n if (empty($this->fields['sync_field'])) {\n echo Dropdown::EMPTY_VALUE;\n } else {\n echo $this->fields['sync_field'];\n }\n }\n echo \"</td></tr>\";\n } else {\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n }", " $surnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_realname$surnamerand'>\" . __('Surname') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"realname\", ['rand' => $surnamerand]);\n echo \"</td></tr>\";", " $firstnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_firstname$firstnamerand'>\" . __('First name') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"firstname\", ['rand' => $firstnamerand]);\n echo \"</td></tr>\";", " //do some rights verification\n if (self::canUpdate()\n && (!$extauth || empty($ID))\n && $caneditpassword) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password'>\" . __('Password').\"</label></td>\";\n echo \"<td><input id='password' type='password' name='password' value='' size='20'\n autocomplete='new-password' onkeyup=\\\"return passwordCheck();\\\"></td>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password2'>\" . __('Password confirmation') . \"</label></td>\";\n echo \"<td><input type='password' id='password2' name='password2' value='' size='20' autocomplete='new-password'>\";\n echo \"</td></tr>\";", " if ($CFG_GLPI[\"use_password_security\"]) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td rowspan='2'>\";\n echo __('Password security policy');\n echo \"</td>\";\n echo \"<td rowspan='2'>\";\n Config::displayPasswordSecurityChecks();\n echo \"</td>\";\n echo \"</tr>\";\n }", " } else {\n echo \"<tr class='tab_bg_1'><td></td><td></td></tr>\";\n echo \"<tr class='tab_bg_1'><td></td><td></td></tr>\";\n }", " $tz_warning = '';\n $tz_available = $DB->areTimezonesAvailable($tz_warning);\n if ($tz_available || Session::haveRight(\"config\", READ)) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='timezone'>\".__('Time zone').\"</label></td><td>\";\n if ($tz_available) {\n $timezones = $DB->getTimezones();\n Dropdown::showFromArray(\n 'timezone',\n $timezones, [\n 'value' => $this->fields[\"timezone\"],\n 'display_emptychoice' => true\n ]\n );\n } else if (Session::haveRight(\"config\", READ)) {\n // Display a warning but only if user is more or less an admin\n echo \"<img src=\\\"{$CFG_GLPI['root_doc']}/pics/warning_min.png\\\">\";\n echo $tz_warning;\n }\n echo \"</td></tr>\";\n }", " echo \"<tr class='tab_bg_1'>\";\n if (!GLPI_DEMO_MODE) {\n $activerand = mt_rand();\n echo \"<td><label for='dropdown_is_active$activerand'>\".__('Active').\"</label></td><td>\";\n Dropdown::showYesNo('is_active', $this->fields['is_active'], -1, ['rand' => $activerand]);\n echo \"</td>\";\n } else {\n echo \"<td colspan='2'></td>\";\n }\n echo \"<td>\" . _n('Email', 'Emails', Session::getPluralNumber());\n UserEmail::showAddEmailButton($this);\n echo \"</td><td>\";\n UserEmail::showForUser($this);\n echo \"</td>\";\n echo \"</tr>\";", " if (!GLPI_DEMO_MODE) {\n $sincerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='showdate$sincerand'>\".__('Valid since').\"</label></td><td>\";\n Html::showDateTimeField(\"begin_date\", ['value' => $this->fields[\"begin_date\"],\n 'rand' => $sincerand,\n 'maybeempty' => true]);\n echo \"</td>\";", " $untilrand = mt_rand();\n echo \"<td><label for='showdate$untilrand'>\".__('Valid until').\"</label></td><td>\";\n Html::showDateTimeField(\"end_date\", ['value' => $this->fields[\"end_date\"],\n 'rand' => $untilrand,\n 'maybeempty' => true]);\n echo \"</td></tr>\";\n }", " $phonerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='textfield_phone$phonerand'>\" . Phone::getTypeName(1) . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"phone\", ['rand' => $phonerand]);\n echo \"</td>\";\n //Authentications information : auth method used and server used\n //don't display is creation of a new user'\n if (!empty($ID)) {\n if (Session::haveRight(self::$rightname, self::READAUTHENT)) {\n echo \"<td>\" . __('Authentication') . \"</td><td>\";\n echo Auth::getMethodName($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);\n if (!empty($this->fields[\"date_sync\"])) {\n //TRANS: %s is the date of last sync\n echo '<br>'.sprintf(__('Last synchronization on %s'),\n Html::convDateTime($this->fields[\"date_sync\"]));\n }\n if (!empty($this->fields[\"user_dn\"])) {\n //TRANS: %s is the user dn\n echo '<br>'.sprintf(__('%1$s: %2$s'), __('User DN'), $this->fields[\"user_dn\"]);\n }\n if ($this->fields['is_deleted_ldap']) {\n echo '<br>'.__('User missing in LDAP directory');\n }", " echo \"</td>\";\n } else {\n echo \"<td colspan='2'>&nbsp;</td>\";\n }\n } else {\n echo \"<td colspan='2'><input type='hidden' name='authtype' value='1'></td>\";\n }", " echo \"</tr>\";", " $mobilerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='textfield_mobile$mobilerand'>\" . __('Mobile phone') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"mobile\", ['rand' => $mobilerand]);\n echo \"</td>\";\n $catrand = mt_rand();\n echo \"<td><label for='dropdown_usercategories_id$catrand'>\" . __('Category') . \"</label></td><td>\";\n UserCategory::dropdown(['value' => $this->fields[\"usercategories_id\"], 'rand' => $catrand]);\n echo \"</td></tr>\";", " $phone2rand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='textfield_phone2$phone2rand'>\" . __('Phone 2') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"phone2\", ['rand' => $phone2rand]);\n echo \"</td>\";\n echo \"<td rowspan='4' class='middle'><label for='comment'>\" . __('Comments') . \"</label></td>\";\n echo \"<td class='center middle' rowspan='4'>\";\n echo \"<textarea cols='45' rows='6' id='comment' name='comment' >\".$this->fields[\"comment\"].\"</textarea>\";\n echo \"</td></tr>\";", " $admnumrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_registration_number$admnumrand'>\" . __('Administrative number') . \"</label></td><td>\";\n Html::autocompletionTextField($this, \"registration_number\", ['rand' => $admnumrand]);\n echo \"</td></tr>\";", " $titlerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='dropdown_usertitles_id$titlerand'>\" . _x('person', 'Title') . \"</label></td><td>\";\n UserTitle::dropdown(['value' => $this->fields[\"usertitles_id\"], 'rand' => $titlerand]);\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n if (!empty($ID)) {\n $locrand = mt_rand();\n echo \"<td><label for='dropdown_locations_id$locrand'>\" . Location::getTypeName(1) . \"</label></td><td>\";\n $entities = $this->getEntities();\n if (count($entities) <= 0) {\n $entities = -1;\n }\n Location::dropdown(['value' => $this->fields[\"locations_id\"],\n 'rand' => $locrand,\n 'entity' => $entities]);\n echo \"</td>\";\n }\n echo \"</tr>\";", " if (empty($ID)) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<th colspan='2'>\"._n('Authorization', 'Authorizations', 1).\"</th>\";\n $recurrand = mt_rand();\n echo \"<td><label for='dropdown__is_recursive$recurrand'>\" . __('Recursive') . \"</label></td><td>\";\n Dropdown::showYesNo(\"_is_recursive\", 0, -1, ['rand' => $recurrand]);\n echo \"</td></tr>\";\n $profilerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='dropdown__profiles_id$profilerand'>\" . Profile::getTypeName(1) . \"</label></td><td>\";\n Profile::dropdownUnder(['name' => '_profiles_id',\n 'rand' => $profilerand,\n 'value' => Profile::getDefault()]);", " $entrand = mt_rand();\n echo \"</td><td><label for='dropdown__entities_id$entrand'>\" . Entity::getTypeName(1) . \"</label></td><td>\";\n Entity::dropdown(['name' => '_entities_id',\n 'display_emptychoice' => false,\n 'rand' => $entrand,\n 'entity' => $_SESSION['glpiactiveentities']]);\n echo \"</td></tr>\";\n } else {\n if ($higherrights || $ismyself) {\n $profilerand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='dropdown_profiles_id$profilerand'>\" . __('Default profile') . \"</label></td><td>\";", " $options = Dropdown::getDropdownArrayNames('glpi_profiles',\n Profile_User::getUserProfiles($this->fields['id']));", " Dropdown::showFromArray(\"profiles_id\", $options,\n ['value' => $this->fields[\"profiles_id\"],\n 'rand' => $profilerand,\n 'display_emptychoice' => true]);\n }\n if ($higherrights) {\n $entrand = mt_rand();\n echo \"</td><td><label for='dropdown_entities_id$entrand'>\" . __('Default entity') . \"</label></td><td>\";\n $entities = $this->getEntities();\n Entity::dropdown(['value' => $this->fields[\"entities_id\"],\n 'rand' => $entrand,\n 'entity' => $entities]);\n echo \"</td></tr>\";", " $grouprand = mt_rand();\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='dropdown_profiles_id$grouprand'>\" . __('Default group') . \"</label></td><td>\";", " $options = [];\n foreach (Group_User::getUserGroups($this->fields['id']) as $group) {\n $options[$group['id']] = $group['completename'];\n }", " Dropdown::showFromArray(\"groups_id\", $options,\n ['value' => $this->fields[\"groups_id\"],\n 'rand' => $grouprand,\n 'display_emptychoice' => true]);", " echo \"</td>\";\n $userrand = mt_rand();\n echo \"<td><label for='dropdown_users_id_supervisor_$userrand'>\" . __('Responsible') . \"</label></td><td>\";", " User::dropdown(['name' => 'users_id_supervisor',\n 'value' => $this->fields[\"users_id_supervisor\"],\n 'rand' => $userrand,\n 'entity' => $_SESSION[\"glpiactive_entity\"],\n 'right' => 'all']);\n echo \"</td></tr>\";\n }", " if ($this->can($ID, UPDATE)) {\n echo \"<tr class='tab_bg_1'><th colspan='4'>\". __('Remote access keys') .\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"Personal token\");\n echo \"</td><td colspan='2'>\";", " if (!empty($this->fields[\"personal_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_personal_token', [\n 'value' => $this->fields[\"personal_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"personal_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_personal_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"API token\");\n echo \"</td><td colspan='2'>\";\n if (!empty($this->fields[\"api_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_api_token', [\n 'value' => $this->fields[\"api_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"api_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_api_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";\n }", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td colspan='2' class='center'>\";\n if ($this->fields[\"last_login\"]) {\n printf(__('Last login on %s'), Html::convDateTime($this->fields[\"last_login\"]));\n }\n echo \"</td><td colspan='2'class='center'>\";", " echo \"</td></tr>\";\n }", " $this->showFormButtons($options);", " return true;\n }", "\n /** Print the user personnal information for check.\n *\n * @param integer $userid ID of the user\n *\n * @return void|boolean false if user is not the current user, otherwise print form\n *\n * @since 0.84\n */\n static function showPersonalInformation($userid) {\n global $CFG_GLPI;", " $user = new self();\n if (!$user->can($userid, READ)\n && ($userid != Session::getLoginUserID())) {\n return false;\n }\n echo \"<table class='tab_glpi left' width='100%'>\";\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b' width='20%'>\";\n echo __('Name');\n echo \"</td><td width='30%'>\";\n echo getUserName($userid);\n echo \"</td>\";\n echo \"<td class='b' width='20%'>\";\n echo Phone::getTypeName(1);\n echo \"</td><td width='30%'>\";\n echo $user->getField('phone');\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b'>\";\n echo __('Phone 2');\n echo \"</td><td>\";\n echo $user->getField('phone2');\n echo \"</td>\";\n echo \"<td class='b'>\";\n echo __('Mobile phone');\n echo \"</td><td>\";\n echo $user->getField('mobile');\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b'>\";\n echo _n('Email', 'Emails', 1);\n echo \"</td><td>\";\n echo $user->getDefaultEmail();\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='b'>\";\n echo Location::getTypeName(1);\n echo \"</td><td>\";\n echo Dropdown::getDropdownName('glpi_locations', $user->getField('locations_id'));\n echo \"</td>\";\n echo \"<td colspan='2' class='center'>\";\n if ($userid == Session::getLoginUserID()) {\n echo \"<a href='\".$CFG_GLPI['root_doc'].\"/front/preference.php' class='vsubmit'>\".\n __('Edit').\"</a>\";\n } else {\n echo \"&nbsp;\";\n }\n echo \"</td>\";\n echo \"</tr>\";\n echo \"</table>\";\n }", "\n /**\n * Print the user preference form.\n *\n * @param string $target Form target\n * @param integer $ID ID of the user\n *\n * @return boolean true if user found, false otherwise\n */\n function showMyForm($target, $ID) {\n global $CFG_GLPI, $DB;", " // Affiche un formulaire User\n if (($ID != Session::getLoginUserID())\n && !$this->currentUserHaveMoreRightThan($ID)) {\n return false;\n }\n if ($this->getFromDB($ID)) {\n $rand = mt_rand();\n $authtype = $this->getAuthMethodsByID();", " $extauth = !(($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || (($this->fields[\"authtype\"] == Auth::NOT_YET_AUTHENTIFIED)\n && !empty($this->fields[\"password\"])));", " // No autocopletion :\n $save_autocompletion = $CFG_GLPI[\"use_ajax_autocompletion\"];\n $CFG_GLPI[\"use_ajax_autocompletion\"] = false;", " echo \"<div class='center'>\";\n echo \"<form method='post' name='user_manager' enctype='multipart/form-data' action='\".$target.\"' autocomplete='off'>\";\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr><th colspan='4'>\".sprintf(__('%1$s: %2$s'), __('Login'), $this->fields[\"name\"]);\n echo \"<input type='hidden' name='name' value='\" . $this->fields[\"name\"] . \"'>\";\n echo \"<input type='hidden' name='id' value='\" . $this->fields[\"id\"] . \"'>\";\n echo \"</th></tr>\";", " $surnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_realname$surnamerand'>\" . __('Surname') . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['realname_field'])\n && !empty($authtype['realname_field'])) {", " echo $this->fields[\"realname\"];\n } else {\n Html::autocompletionTextField($this, \"realname\", ['rand' => $surnamerand]);\n }\n echo \"</td>\";", " if (!empty($this->fields[\"name\"])) {\n echo \"<td rowspan='7'>\" . __('Picture') . \"</td>\";\n echo \"<td rowspan='7'>\";\n echo \"<div class='user_picture_border_small' id='picture$rand'>\";\n echo \"<img class='user_picture_small' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getThumbnailURLForPicture($this->fields['picture']).\"'>\";\n echo \"</div>\";\n $full_picture = \"<div class='user_picture_border'>\";\n $full_picture .= \"<img class='user_picture' alt=\\\"\".__s('Picture').\"\\\" src='\".\n User::getURLForPicture($this->fields['picture']).\"'>\";\n $full_picture .= \"</div>\";", " Html::showTooltip($full_picture, ['applyto' => \"picture$rand\"]);\n echo Html::file(['name' => 'picture', 'display' => false, 'onlyimages' => true]);", " echo \"&nbsp;\";\n Html::showCheckbox(['name' => '_blank_picture', 'title' => __('Clear')]);\n echo \"&nbsp;\".__('Clear');", " echo \"</td>\";\n echo \"</tr>\";\n }", " $firstnamerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_firstname$firstnamerand'>\" . __('First name') . \"</label></td><td>\";\n if ($extauth\n && isset($authtype['firstname_field'])\n && !empty($authtype['firstname_field'])) {", " echo $this->fields[\"firstname\"];\n } else {\n Html::autocompletionTextField($this, \"firstname\", ['rand' => $firstnamerand]);\n }\n echo \"</td></tr>\";", " if ($extauth\n && $this->fields['auths_id']\n && AuthLDAP::isSyncFieldConfigured($this->fields['auths_id'])) {\n echo \"<tr class='tab_bg_1'><td>\" . __('Synchronization field') . \"</td><td>\";\n if (empty($this->fields['sync_field'])) {\n echo Dropdown::EMPTY_VALUE;\n } else {\n echo $this->fields['sync_field'];\n }\n echo \"</td></tr>\";\n } else {\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n }", " echo \"<tr class='tab_bg_1'>\";", " if (!GLPI_DEMO_MODE) {\n $langrand = mt_rand();\n echo \"<td><label for='dropdown_language$langrand'>\" . __('Language') . \"</label></td><td>\";\n // Language is stored as null in DB if value is same as the global config.\n $language = $this->fields[\"language\"];\n if (null === $this->fields[\"language\"]) {\n $language = $CFG_GLPI['language'];\n }\n Dropdown::showLanguages(\n \"language\",\n [\n 'rand' => $langrand,\n 'value' => $language,\n ]\n );\n echo \"</td>\";\n } else {\n echo \"<td colspan='2'>&nbsp;</td>\";\n }\n echo \"</tr>\";", " //do some rights verification\n if (!$extauth\n && Session::haveRight(\"password_update\", \"1\")) {", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password'>\" . __('Password') . \"</label></td>\";\n echo \"<td><input id='password' type='password' name='password' value='' size='30' autocomplete='new-password' onkeyup=\\\"return passwordCheck();\\\">\";\n echo \"</td>\";\n echo \"</tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='password2'>\" . __('Password confirmation') . \"</label></td>\";\n echo \"<td><input type='password' name='password2' id='password2' value='' size='30' autocomplete='new-password'>\";\n echo \"</td></tr>\";", " if ($CFG_GLPI[\"use_password_security\"]) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td rowspan='2'>\";\n echo __('Password security policy');\n echo \"</td>\";\n echo \"<td rowspan='2'>\";\n Config::displayPasswordSecurityChecks();\n echo \"</td>\";\n echo \"</tr>\";\n }\n } else {\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n echo \"<tr class='tab_bg_1'><td colspan='2'></td></tr>\";\n }", " $tz_warning = '';\n $tz_available = $DB->areTimezonesAvailable($tz_warning);\n if ($tz_available || Session::haveRight(\"config\", READ)) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td><label for='timezone'>\".__('Time zone').\"</label></td><td>\";\n if ($tz_available) {\n $timezones = $DB->getTimezones();\n Dropdown::showFromArray(\n 'timezone',\n $timezones, [\n 'value' => $this->fields[\"timezone\"],\n 'display_emptychoice' => true\n ]\n );\n } else if (Session::haveRight(\"config\", READ)) {\n // Display a warning but only if user is more or less an admin\n echo \"<img src=\\\"{$CFG_GLPI['root_doc']}/pics/warning_min.png\\\">\";\n echo $tz_warning;\n }\n echo \"</td>\";\n if ($extauth\n || !Session::haveRight(\"password_update\", \"1\")) {\n echo \"<td colspan='2'></td>\";\n }\n echo \"</tr>\";\n }", " $phonerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_phone$phonerand'>\" . Phone::getTypeName(1) . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['phone_field']) && !empty($authtype['phone_field'])) {\n echo $this->fields[\"phone\"];\n } else {\n Html::autocompletionTextField($this, \"phone\", ['rand' => $phonerand]);\n }\n echo \"</td>\";\n echo \"<td class='top'>\" . _n('Email', 'Emails', Session::getPluralNumber());\n UserEmail::showAddEmailButton($this);\n echo \"</td><td>\";\n UserEmail::showForUser($this);\n echo \"</td>\";\n echo \"</tr>\";", " $mobilerand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_mobile$mobilerand'>\" . __('Mobile phone') . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['mobile_field']) && !empty($authtype['mobile_field'])) {\n echo $this->fields[\"mobile\"];\n } else {\n Html::autocompletionTextField($this, \"mobile\", ['rand' => $mobilerand]);\n }\n echo \"</td>\";", " if (count($_SESSION['glpiprofiles']) >1) {\n $profilerand = mt_rand();\n echo \"<td><label for='dropdown_profiles_id$profilerand'>\" . __('Default profile') . \"</label></td><td>\";", " $options = Dropdown::getDropdownArrayNames('glpi_profiles',\n Profile_User::getUserProfiles($this->fields['id']));\n Dropdown::showFromArray(\"profiles_id\", $options,\n ['value' => $this->fields[\"profiles_id\"],\n 'rand' => $profilerand,\n 'display_emptychoice' => true]);\n echo \"</td>\";", " } else {\n echo \"<td colspan='2'>&nbsp;</td>\";\n }\n echo \"</tr>\";", " $phone2rand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_phone2$phone2rand'>\" . __('Phone 2') . \"</label></td><td>\";", " if ($extauth\n && isset($authtype['phone2_field']) && !empty($authtype['phone2_field'])) {\n echo $this->fields[\"phone2\"];\n } else {\n Html::autocompletionTextField($this, \"phone2\", ['rand' => $phone2rand]);\n }\n echo \"</td>\";", " $entities = $this->getEntities();\n if (!GLPI_DEMO_MODE\n && (count($_SESSION['glpiactiveentities']) > 1)) {\n $entrand = mt_rand();\n echo \"<td><label for='dropdown_entities_id$entrand'>\" . __('Default entity') . \"</td><td>\";\n Entity::dropdown(['value' => $this->fields['entities_id'],\n 'rand' => $entrand,\n 'entity' => $entities]);\n } else {\n echo \"<td colspan='2'>&nbsp;\";\n }\n echo \"</td></tr>\";", " $admnumrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='textfield_registration_number$admnumrand'>\" . __('Administrative number') . \"</label></td><td>\";\n if ($extauth\n && isset($authtype['registration_number_field']) && !empty($authtype['registration_number_field'])) {\n echo $this->fields[\"registration_number\"];\n } else {\n Html::autocompletionTextField($this, \"registration_number\", ['rand' => $admnumrand]);\n }\n echo \"</td><td colspan='2'></td></tr>\";", " $locrand = mt_rand();\n echo \"<tr class='tab_bg_1'><td><label for='dropdown_locations_id$locrand'>\" . Location::getTypeName(1) . \"</label></td><td>\";\n Location::dropdown(['value' => $this->fields['locations_id'],\n 'rand' => $locrand,\n 'entity' => $entities]);", " if (Config::canUpdate()) {\n $moderand = mt_rand();\n echo \"<td><label for='dropdown_use_mode$moderand'>\" . __('Use GLPI in mode') . \"</label></td><td>\";\n $modes = [\n Session::NORMAL_MODE => __('Normal'),\n Session::DEBUG_MODE => __('Debug'),\n ];\n Dropdown::showFromArray('use_mode', $modes, ['value' => $this->fields[\"use_mode\"], 'rand' => $moderand]);\n } else {\n echo \"<td colspan='2'>&nbsp;\";\n }\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><th colspan='4'>\". __('Remote access keys') .\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"Personal token\");\n echo \"</td><td colspan='2'>\";", " if (!empty($this->fields[\"personal_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_personal_token', [\n 'value' => $this->fields[\"personal_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"personal_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_personal_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\";\n echo __(\"API token\");\n echo \"</td><td colspan='2'>\";\n if (!empty($this->fields[\"api_token\"])) {\n echo \"<div class='copy_to_clipboard_wrapper'>\";\n echo Html::input('_api_token', [\n 'value' => $this->fields[\"api_token\"],\n 'style' => 'width:90%'\n ]);\n echo \"</div>\";\n echo \"(\".sprintf(__('generated on %s'),\n Html::convDateTime($this->fields[\"api_token_date\"])).\")\";\n }\n echo \"</td><td>\";\n Html::showCheckbox(['name' => '_reset_api_token',\n 'title' => __('Regenerate')]);\n echo \"&nbsp;&nbsp;\".__('Regenerate');\n echo \"</td></tr>\";", " echo \"<tr><td class='tab_bg_2 center' colspan='4'>\";\n echo \"<input type='submit' name='update' value=\\\"\"._sx('button', 'Save').\"\\\" class='submit'>\";\n echo \"</td></tr>\";", " echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n $CFG_GLPI[\"use_ajax_autocompletion\"] = $save_autocompletion;\n return true;\n }\n return false;\n }", "\n /**\n * Get all the authentication method parameters for the current user.\n *\n * @return array\n */\n function getAuthMethodsByID() {\n return Auth::getMethodsByID($this->fields[\"authtype\"], $this->fields[\"auths_id\"]);\n }", "\n function pre_updateInDB() {\n global $DB;", " if (($key = array_search('name', $this->updates)) !== false) {\n /// Check if user does not exists\n $iterator = $DB->request([\n 'FROM' => $this->getTable(),\n 'WHERE' => [\n 'name' => $this->input['name'],\n 'id' => ['<>', $this->input['id']]\n ]\n ]);", " if (count($iterator)) {\n //To display a message\n $this->fields['name'] = $this->oldvalues['name'];\n unset($this->updates[$key]);\n unset($this->oldvalues['name']);\n Session::addMessageAfterRedirect(__('Unable to update login. A user already exists.'),\n false, ERROR);\n }", " if (!Auth::isValidLogin(stripslashes($this->input['name']))) {\n $this->fields['name'] = $this->oldvalues['name'];\n unset($this->updates[$key]);\n unset($this->oldvalues['name']);\n Session::addMessageAfterRedirect(__('The login is not valid. Unable to update login.'),\n false, ERROR);\n }", " }", " // ## Security system except for login update:\n //\n // An **external** (ldap, mail) user without User::UPDATE right\n // should not be able to update its own fields\n // (for example, fields concerned by ldap synchronisation)\n // except on login action (which triggers synchronisation).\n if (Session::getLoginUserID() === (int)$this->input['id']\n && !Session::haveRight(\"user\", UPDATE)\n && !strpos($_SERVER['PHP_SELF'], \"/front/login.php\")\n && isset($this->fields[\"authtype\"])) {", " // extauth ldap case\n if ($_SESSION[\"glpiextauth\"]\n && ($this->fields[\"authtype\"] == Auth::LDAP\n || Auth::isAlternateAuth($this->fields[\"authtype\"]))) {", " $authtype = Auth::getMethodsByID($this->fields[\"authtype\"],\n $this->fields[\"auths_id\"]);\n if (count($authtype)) {\n $fields = AuthLDAP::getSyncFields($authtype);\n foreach ($fields as $key => $val) {\n if (!empty($val)\n && (($key2 = array_search($key, $this->updates)) !== false)) {", " unset ($this->updates[$key2]);\n unset($this->oldvalues[$key]);", " }\n }\n }\n }", " if (($key = array_search(\"is_active\", $this->updates)) !== false) {\n unset ($this->updates[$key]);\n unset($this->oldvalues['is_active']);\n }", " if (($key = array_search(\"comment\", $this->updates)) !== false) {\n unset ($this->updates[$key]);\n unset($this->oldvalues['comment']);\n }\n }\n }", " function getSpecificMassiveActions($checkitem = null) {", " $isadmin = static::canUpdate();\n $actions = parent::getSpecificMassiveActions($checkitem);\n if ($isadmin) {\n $actions['Group_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'add']\n = \"<i class='ma-icon fas fa-users'></i>\".\n __('Associate to a group');\n $actions['Group_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'remove']\n = __('Dissociate from a group');\n $actions['Profile_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'add']\n = \"<i class='ma-icon fas fa-user-shield'></i>\".\n __('Associate to a profile');\n $actions['Profile_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'remove']\n = __('Dissociate from a profile');\n $actions['Group_User'.MassiveAction::CLASS_ACTION_SEPARATOR.'change_group_user']\n = \"<i class='ma-icon fas fa-users-cog'></i>\".\n __(\"Move to group\");\n }", " if (Session::haveRight(self::$rightname, self::UPDATEAUTHENT)) {\n $prefix = __CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR;\n $actions[$prefix.'change_authtype'] = \"<i class='ma-icon fas fa-user-cog'></i>\".\n _x('button', 'Change the authentication method');\n $actions[$prefix.'force_user_ldap_update'] = \"<i class='ma-icon fas fa-sync'></i>\".\n __('Force synchronization');\n }\n return $actions;\n }", " static function showMassiveActionsSubForm(MassiveAction $ma) {\n global $CFG_GLPI;", " switch ($ma->getAction()) {\n case 'change_authtype' :\n $rand = Auth::dropdown(['name' => 'authtype']);\n $paramsmassaction = ['authtype' => '__VALUE__'];\n Ajax::updateItemOnSelectEvent(\"dropdown_authtype$rand\", \"show_massiveaction_field\",\n $CFG_GLPI[\"root_doc\"].\n \"/ajax/dropdownMassiveActionAuthMethods.php\",\n $paramsmassaction);\n echo \"<span id='show_massiveaction_field'><br><br>\";\n echo Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']).\"</span>\";\n return true;\n }\n return parent::showMassiveActionsSubForm($ma);\n }", " static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item,\n array $ids) {", " switch ($ma->getAction()) {\n case 'force_user_ldap_update' :\n foreach ($ids as $id) {\n if ($item->can($id, UPDATE)) {\n if (($item->fields[\"authtype\"] == Auth::LDAP)\n || ($item->fields[\"authtype\"] == Auth::EXTERNAL)) {\n if (AuthLDAP::forceOneUserSynchronization($item, false)) {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n }\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n }\n } else {\n $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);\n $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));\n }\n }\n return;", " case 'change_authtype' :\n $input = $ma->getInput();\n if (!isset($input[\"authtype\"])\n || !isset($input[\"auths_id\"])) {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);\n $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));\n return;\n }\n if (Session::haveRight(self::$rightname, self::UPDATEAUTHENT)) {\n if (User::changeAuthMethod($ids, $input[\"authtype\"], $input[\"auths_id\"])) {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_OK);\n } else {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);\n }\n } else {\n $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_NORIGHT);\n $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));\n }\n return;\n }\n parent::processMassiveActionsForOneItemtype($ma, $item, $ids);\n }", "\n function rawSearchOptions() {\n // forcegroup by on name set force group by for all items\n $tab = [];", " $tab[] = [\n 'id' => 'common',\n 'name' => __('Characteristics')\n ];", " $tab[] = [\n 'id' => '1',\n 'table' => $this->getTable(),\n 'field' => 'name',\n 'name' => __('Login'),\n 'datatype' => 'itemlink',\n 'forcegroupby' => true,\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '2',\n 'table' => $this->getTable(),\n 'field' => 'id',\n 'name' => __('ID'),\n 'massiveaction' => false,\n 'datatype' => 'number'\n ];", " $tab[] = [\n 'id' => '34',\n 'table' => $this->getTable(),\n 'field' => 'realname',\n 'name' => __('Last name'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '9',\n 'table' => $this->getTable(),\n 'field' => 'firstname',\n 'name' => __('First name'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '5',\n 'table' => 'glpi_useremails',\n 'field' => 'email',\n 'name' => _n('Email', 'Emails', Session::getPluralNumber()),\n 'datatype' => 'email',\n 'joinparams' => [\n 'jointype' => 'child'\n ],\n 'forcegroupby' => true,\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '150',\n 'table' => $this->getTable(),\n 'field' => 'picture',\n 'name' => __('Picture'),\n 'datatype' => 'specific',\n 'nosearch' => true,\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '28',\n 'table' => $this->getTable(),\n 'field' => 'sync_field',\n 'name' => __('Synchronization field'),\n 'massiveaction' => false,\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab = array_merge($tab, Location::rawSearchOptionsToAdd());", " $tab[] = [\n 'id' => '8',\n 'table' => $this->getTable(),\n 'field' => 'is_active',\n 'name' => __('Active'),\n 'datatype' => 'bool'\n ];", " $tab[] = [\n 'id' => '6',\n 'table' => $this->getTable(),\n 'field' => 'phone',\n 'name' => Phone::getTypeName(1),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '10',\n 'table' => $this->getTable(),\n 'field' => 'phone2',\n 'name' => __('Phone 2'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '11',\n 'table' => $this->getTable(),\n 'field' => 'mobile',\n 'name' => __('Mobile phone'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '13',\n 'table' => 'glpi_groups',\n 'field' => 'completename',\n 'name' => Group::getTypeName(Session::getPluralNumber()),\n 'forcegroupby' => true,\n 'datatype' => 'itemlink',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_groups_users',\n 'joinparams' => [\n 'jointype' => 'child'\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '14',\n 'table' => $this->getTable(),\n 'field' => 'last_login',\n 'name' => __('Last login'),\n 'datatype' => 'datetime',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '15',\n 'table' => $this->getTable(),\n 'field' => 'authtype',\n 'name' => __('Authentication'),\n 'massiveaction' => false,\n 'datatype' => 'specific',\n 'searchtype' => 'equals',\n 'additionalfields' => [\n '0' => 'auths_id'\n ]\n ];", " $tab[] = [\n 'id' => '30',\n 'table' => 'glpi_authldaps',\n 'field' => 'name',\n 'linkfield' => 'auths_id',\n 'name' => __('LDAP directory for authentication'),\n 'massiveaction' => false,\n 'joinparams' => [\n 'condition' => 'AND REFTABLE.`authtype` = ' . Auth::LDAP\n ],\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '31',\n 'table' => 'glpi_authmails',\n 'field' => 'name',\n 'linkfield' => 'auths_id',\n 'name' => __('Email server for authentication'),\n 'massiveaction' => false,\n 'joinparams' => [\n 'condition' => 'AND REFTABLE.`authtype` = ' . Auth::MAIL\n ],\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '16',\n 'table' => $this->getTable(),\n 'field' => 'comment',\n 'name' => __('Comments'),\n 'datatype' => 'text'\n ];", " $tab[] = [\n 'id' => '17',\n 'table' => $this->getTable(),\n 'field' => 'language',\n 'name' => __('Language'),\n 'datatype' => 'language',\n 'display_emptychoice' => true,\n 'emptylabel' => 'Default value'\n ];", " $tab[] = [\n 'id' => '19',\n 'table' => $this->getTable(),\n 'field' => 'date_mod',\n 'name' => __('Last update'),\n 'datatype' => 'datetime',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '121',\n 'table' => $this->getTable(),\n 'field' => 'date_creation',\n 'name' => __('Creation date'),\n 'datatype' => 'datetime',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '20',\n 'table' => 'glpi_profiles',\n 'field' => 'name',\n 'name' => sprintf(__('%1$s (%2$s)'), Profile::getTypeName(Session::getPluralNumber()),\n Entity::getTypeName(1)),\n 'forcegroupby' => true,\n 'massiveaction' => false,\n 'datatype' => 'dropdown',\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_profiles_users',\n 'joinparams' => [\n 'jointype' => 'child'\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '21',\n 'table' => $this->getTable(),\n 'field' => 'user_dn',\n 'name' => __('User DN'),\n 'massiveaction' => false,\n 'datatype' => 'text'\n ];", " $tab[] = [\n 'id' => '22',\n 'table' => $this->getTable(),\n 'field' => 'registration_number',\n 'name' => __('Administrative number'),\n 'datatype' => 'string',\n 'autocomplete' => true,\n ];", " $tab[] = [\n 'id' => '23',\n 'table' => $this->getTable(),\n 'field' => 'date_sync',\n 'datatype' => 'datetime',\n 'name' => __('Last synchronization'),\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '24',\n 'table' => $this->getTable(),\n 'field' => 'is_deleted_ldap',\n 'name' => __('Deleted user in LDAP directory'),\n 'datatype' => 'bool',\n 'massiveaction' => false\n ];", " $tab[] = [\n 'id' => '80',\n 'table' => 'glpi_entities',\n 'linkfield' => 'entities_id',\n 'field' => 'completename',\n 'name' => sprintf(__('%1$s (%2$s)'), Entity::getTypeName(Session::getPluralNumber()),\n Profile::getTypeName(1)),\n 'forcegroupby' => true,\n 'datatype' => 'dropdown',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_profiles_users',\n 'joinparams' => [\n 'jointype' => 'child'\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '81',\n 'table' => 'glpi_usertitles',\n 'field' => 'name',\n 'name' => __('Title'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '82',\n 'table' => 'glpi_usercategories',\n 'field' => 'name',\n 'name' => __('Category'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '79',\n 'table' => 'glpi_profiles',\n 'field' => 'name',\n 'name' => __('Default profile'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '77',\n 'table' => 'glpi_entities',\n 'field' => 'name',\n 'massiveaction' => true,\n 'name' => __('Default entity'),\n 'datatype' => 'dropdown'\n ];", " $tab[] = [\n 'id' => '62',\n 'table' => $this->getTable(),\n 'field' => 'begin_date',\n 'name' => __('Begin date'),\n 'datatype' => 'datetime'\n ];", " $tab[] = [\n 'id' => '63',\n 'table' => $this->getTable(),\n 'field' => 'end_date',\n 'name' => __('End date'),\n 'datatype' => 'datetime'\n ];", " $tab[] = [\n 'id' => '60',\n 'table' => 'glpi_tickets',\n 'field' => 'id',\n 'name' => __('Number of tickets as requester'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_tickets_users',\n 'joinparams' => [\n 'jointype' => 'child',\n 'condition' => 'AND NEWTABLE.`type` = ' . CommonITILActor::REQUESTER\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '61',\n 'table' => 'glpi_tickets',\n 'field' => 'id',\n 'name' => __('Number of written tickets'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'jointype' => 'child',\n 'linkfield' => 'users_id_recipient'\n ]\n ];", " $tab[] = [\n 'id' => '64',\n 'table' => 'glpi_tickets',\n 'field' => 'id',\n 'name' => __('Number of assigned tickets'),\n 'forcegroupby' => true,\n 'usehaving' => true,\n 'datatype' => 'count',\n 'massiveaction' => false,\n 'joinparams' => [\n 'beforejoin' => [\n 'table' => 'glpi_tickets_users',\n 'joinparams' => [\n 'jointype' => 'child',\n 'condition' => 'AND NEWTABLE.`type` = '.CommonITILActor::ASSIGN\n ]\n ]\n ]\n ];", " $tab[] = [\n 'id' => '99',\n 'table' => 'glpi_users',\n 'field' => 'name',\n 'linkfield' => 'users_id_supervisor',\n 'name' => __('Responsible'),\n 'datatype' => 'dropdown',\n 'massiveaction' => false,\n ];", " // add objectlock search options\n $tab = array_merge($tab, ObjectLock::rawSearchOptionsToAdd(get_class($this)));", " return $tab;\n }", " static function getSpecificValueToDisplay($field, $values, array $options = []) {", " if (!is_array($values)) {\n $values = [$field => $values];\n }\n switch ($field) {\n case 'authtype':\n $auths_id = 0;\n if (isset($values['auths_id']) && !empty($values['auths_id'])) {\n $auths_id = $values['auths_id'];\n }\n return Auth::getMethodName($values[$field], $auths_id);\n case 'picture':\n if (isset($options['html']) && $options['html']) {\n return Html::image(self::getThumbnailURLForPicture($values['picture']),\n ['class' => 'user_picture_small', 'alt' => __('Picture')]);\n }\n }\n return parent::getSpecificValueToDisplay($field, $values, $options);\n }", " static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {", " if (!is_array($values)) {\n $values = [$field => $values];\n }\n $options['display'] = false;\n switch ($field) {\n case 'authtype' :\n $options['name'] = $name;\n $options['value'] = $values[$field];\n return Auth::dropdown($options);\n }\n return parent::getSpecificValueToSelect($field, $name, $values, $options);\n }", "\n /**\n * Get all groups where the current user have delegating.\n *\n * @since 0.83\n *\n * @param integer|string $entities_id ID of the entity to restrict\n *\n * @return integer[]\n */\n static function getDelegateGroupsForUser($entities_id = '') {\n global $DB;", " $iterator = $DB->request([\n 'SELECT' => 'glpi_groups_users.groups_id',\n 'DISTINCT' => true,\n 'FROM' => 'glpi_groups_users',\n 'INNER JOIN' => [\n 'glpi_groups' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'groups_id',\n 'glpi_groups' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.users_id' => Session::getLoginUserID(),\n 'glpi_groups_users.is_userdelegate' => 1\n ] + getEntitiesRestrictCriteria('glpi_groups', '', $entities_id, 1)\n ]);", " $groups = [];\n while ($data = $iterator->next()) {\n $groups[$data['groups_id']] = $data['groups_id'];\n }\n return $groups;\n }", "\n /**\n * Execute the query to select box with all glpi users where select key = name\n *\n * Internaly used by showGroup_Users, dropdownUsers and ajax/getDropdownUsers.php\n *\n * @param boolean $count true if execute an count(*) (true by default)\n * @param string|string[] $right limit user who have specific right (default 'all')\n * @param integer $entity_restrict Restrict to a defined entity (default -1)\n * @param integer $value default value (default 0)\n * @param integer[] $used Already used items ID: not to display in dropdown\n * @param string $search pattern (default '')\n * @param integer $start start LIMIT value (default 0)\n * @param integer $limit limit LIMIT value (default -1 no limit)\n * @param boolean $inactive_deleted true to retreive also inactive or deleted users\n *\n * @return mysqli_result|boolean\n */\n static function getSqlSearchResult ($count = true, $right = \"all\", $entity_restrict = -1, $value = 0,\n array $used = [], $search = '', $start = 0, $limit = -1,\n $inactive_deleted = 0) {\n global $DB;", " // No entity define : use active ones\n if ($entity_restrict < 0) {\n $entity_restrict = $_SESSION[\"glpiactiveentities\"];\n }", " $joinprofile = false;\n $joinprofileright = false;\n $WHERE = [];", " switch ($right) {\n case \"interface\" :\n $joinprofile = true;\n $WHERE = [\n 'glpi_profiles.interface' => 'central'\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1);\n break;", " case \"id\" :\n $WHERE = ['glpi_users.id' => Session::getLoginUserID()];\n break;", " case \"delegate\" :\n $groups = self::getDelegateGroupsForUser($entity_restrict);\n $users = [];\n if (count($groups)) {\n $iterator = $DB->request([\n 'SELECT' => 'glpi_users.id',\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_users' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.groups_id' => $groups,\n 'glpi_groups_users.users_id' => ['<>', Session::getLoginUserID()]\n ]\n ]);\n while ($data = $iterator->next()) {\n $users[$data[\"id\"]] = $data[\"id\"];\n }\n }\n // Add me to users list for central\n if (Session::getCurrentInterface() == 'central') {\n $users[Session::getLoginUserID()] = Session::getLoginUserID();\n }", " if (count($users)) {\n $WHERE = ['glpi_users.id' => $users];\n }\n break;", " case \"groups\" :\n $groups = [];\n if (isset($_SESSION['glpigroups'])) {\n $groups = $_SESSION['glpigroups'];\n }\n $users = [];\n if (count($groups)) {\n $iterator = $DB->request([\n 'SELECT' => 'glpi_users.id',\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_users' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_groups_users.groups_id' => $groups,\n 'glpi_groups_users.users_id' => ['<>', Session::getLoginUserID()]\n ]\n ]);\n while ($data = $iterator->next()) {\n $users[$data[\"id\"]] = $data[\"id\"];\n }\n }\n // Add me to users list for central\n if (Session::getCurrentInterface() == 'central') {\n $users[Session::getLoginUserID()] = Session::getLoginUserID();\n }", " if (count($users)) {\n $WHERE = ['glpi_users.id' => $users];\n }", " break;", " case \"all\" :\n $WHERE = [\n 'glpi_users.id' => ['>', 0],\n 'OR' => [\n 'glpi_profiles_users.entities_id' => null\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " default :\n $joinprofile = true;\n $joinprofileright = true;\n if (!is_array($right)) {\n $right = [$right];\n }\n $forcecentral = true;", " $ORWHERE = [];\n foreach ($right as $r) {\n switch ($r) {\n case 'own_ticket' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticket',\n 'glpi_profilerights.rights' => ['&', Ticket::OWN]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'create_ticket_validate' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticketvalidation',\n 'OR' => [\n ['glpi_profilerights.rights' => ['&', TicketValidation::CREATEREQUEST]],\n ['glpi_profilerights.rights' => ['&', TicketValidation::CREATEINCIDENT]]\n ]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n $forcecentral = false;\n break;", " case 'validate_request' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticketvalidation',\n 'glpi_profilerights.rights' => ['&', TicketValidation::VALIDATEREQUEST]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n $forcecentral = false;\n break;", " case 'validate_incident' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'ticketvalidation',\n 'glpi_profilerights.rights' => ['&', TicketValidation::VALIDATEINCIDENT]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n $forcecentral = false;\n break;", " case 'validate' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'changevalidation',\n 'glpi_profilerights.rights' => ['&', ChangeValidation::VALIDATE]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'create_validate' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'changevalidation',\n 'glpi_profilerights.rights' => ['&', ChangeValidation::CREATE]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'see_project' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'project',\n 'glpi_profilerights.rights' => ['&', Project::READMY]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n break;", " case 'faq' :\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => 'knowbase',\n 'glpi_profilerights.rights' => ['&', KnowbaseItem::READFAQ]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];", " default :\n // Check read or active for rights\n $ORWHERE[] = [\n [\n 'glpi_profilerights.name' => $r,\n 'glpi_profilerights.rights' => [\n '&',\n READ | CREATE | UPDATE | DELETE | PURGE\n ]\n ] + getEntitiesRestrictCriteria('glpi_profiles_users', '', $entity_restrict, 1)\n ];\n }\n if (in_array($r, Profile::$helpdesk_rights)) {\n $forcecentral = false;\n }\n }", " if (count($ORWHERE)) {\n $WHERE[] = ['OR' => $ORWHERE];\n }", " if ($forcecentral) {\n $WHERE['glpi_profiles.interface'] = 'central';\n }\n }", " if (!$inactive_deleted) {\n $WHERE = array_merge(\n $WHERE, [\n 'glpi_users.is_deleted' => 0,\n 'glpi_users.is_active' => 1,\n [\n 'OR' => [\n ['glpi_users.begin_date' => null],\n ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]\n ]\n ],\n [\n 'OR' => [\n ['glpi_users.end_date' => null],\n ['glpi_users.end_date' => ['>', new QueryExpression('NOW()')]]\n ]\n ]", " ]\n );\n }", " if ((is_numeric($value) && $value)\n || count($used)) {", " $WHERE[] = [\n 'NOT' => [\n 'glpi_users.id' => $used\n ]\n ];\n }", " $criteria = [\n 'FROM' => 'glpi_users',\n 'LEFT JOIN' => [\n 'glpi_useremails' => [\n 'ON' => [\n 'glpi_useremails' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ],\n 'glpi_profiles_users' => [\n 'ON' => [\n 'glpi_profiles_users' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ]\n ];\n if ($count) {\n $criteria['SELECT'] = ['COUNT' => 'glpi_users.id AS CPT'];\n $criteria['DISTINCT'] = true;\n } else {\n $criteria['SELECT'] = 'glpi_users.*';\n $criteria['DISTINCT'] = true;\n }", " if ($joinprofile) {\n $criteria['LEFT JOIN']['glpi_profiles'] = [\n 'ON' => [\n 'glpi_profiles_users' => 'profiles_id',\n 'glpi_profiles' => 'id'\n ]\n ];\n if ($joinprofileright) {\n $criteria['LEFT JOIN']['glpi_profilerights'] = [\n 'ON' => [\n 'glpi_profilerights' => 'profiles_id',\n 'glpi_profiles' => 'id'\n ]\n ];\n }\n }", " if (!$count) {\n if ((strlen($search) > 0)) {\n $txt_search = Search::makeTextSearchValue($search);", " $firstname_field = $DB->quoteName(self::getTableField('firstname'));\n $realname_field = $DB->quoteName(self::getTableField('realname'));\n $fields = $_SESSION[\"glpinames_format\"] == self::FIRSTNAME_BEFORE\n ? [$firstname_field, $realname_field]\n : [$realname_field, $firstname_field];", " $concat = new \\QueryExpression(\n 'CONCAT(' . implode(',' . $DB->quoteValue(' ') . ',', $fields) . ')'\n . ' LIKE ' . $DB->quoteValue($txt_search)\n );\n $WHERE[] = [\n 'OR' => [\n 'glpi_users.name' => ['LIKE', $txt_search],\n 'glpi_users.realname' => ['LIKE', $txt_search],\n 'glpi_users.firstname' => ['LIKE', $txt_search],\n 'glpi_users.phone' => ['LIKE', $txt_search],\n 'glpi_useremails.email' => ['LIKE', $txt_search],\n $concat\n ]\n ];\n }", " if ($_SESSION[\"glpinames_format\"] == self::FIRSTNAME_BEFORE) {\n $criteria['ORDERBY'] = [\n 'glpi_users.firstname',\n 'glpi_users.realname',\n 'glpi_users.name'\n ];\n } else {\n $criteria['ORDERBY'] = [\n 'glpi_users.realname',\n 'glpi_users.firstname',\n 'glpi_users.name'\n ];\n }", " if ($limit > 0) {\n $criteria['LIMIT'] = $limit;\n $criteria['START'] = $start;\n }\n }\n $criteria['WHERE'] = $WHERE;\n return $DB->request($criteria);\n }", "\n /**\n * Make a select box with all glpi users where select key = name\n *\n * @param $options array of possible options:\n * - name : string / name of the select (default is users_id)\n * - value\n * - values : in case of select[multiple], pass the array of multiple values\n * - right : string / limit user who have specific right :\n * id -> only current user (default case);\n * interface -> central;\n * all -> all users;\n * specific right like Ticket::READALL, CREATE.... (is array passed one of all passed right is needed)\n * - comments : boolean / is the comments displayed near the dropdown (default true)\n * - entity : integer or array / restrict to a defined entity or array of entities\n * (default -1 : no restriction)\n * - entity_sons : boolean / if entity restrict specified auto select its sons\n * only available if entity is a single value not an array(default false)\n * - all : Nobody or All display for none selected\n * all=0 (default) -> Nobody\n * all=1 -> All\n * all=-1-> nothing\n * - rand : integer / already computed rand value\n * - toupdate : array / Update a specific item on select change on dropdown\n * (need value_fieldname, to_update, url\n * (see Ajax::updateItemOnSelectEvent for information)\n * and may have moreparams)\n * - used : array / Already used items ID: not to display in dropdown (default empty)\n * - ldap_import\n * - on_change : string / value to transmit to \"onChange\"\n * - display : boolean / display or get string (default true)\n * - width : specific width needed (default 80%)\n * - specific_tags : array of HTML5 tags to add to the field\n * - url : url of the ajax php code which should return the json data to show in\n * the dropdown (default /ajax/getDropdownUsers.php)\n * - inactive_deleted : retreive also inactive or deleted users\n *\n * @return integer|string Random value if displayed, string otherwise\n */\n static function dropdown($options = []) {\n global $CFG_GLPI;", " // Default values\n $p = [\n 'name' => 'users_id',\n 'value' => '',\n 'values' => [],\n 'right' => 'id',\n 'all' => 0,\n 'display_emptychoice' => true,\n 'placeholder' => '',\n 'on_change' => '',\n 'comments' => 1,\n 'width' => '80%',\n 'entity' => -1,\n 'entity_sons' => false,\n 'used' => [],\n 'ldap_import' => false,\n 'toupdate' => '',\n 'rand' => mt_rand(),\n 'display' => true,\n '_user_index' => 0,\n 'specific_tags' => [],\n 'url' => $CFG_GLPI['root_doc'] . \"/ajax/getDropdownUsers.php\",\n 'inactive_deleted' => 0,\n ];", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }", " // check default value (in case of multiple observers)\n if (is_array($p['value'])) {\n $p['value'] = $p['value'][$p['_user_index']] ?? 0;\n }", " // Check default value for dropdown : need to be a numeric\n if ((strlen($p['value']) == 0) || !is_numeric($p['value'])) {\n $p['value'] = 0;\n }", " $output = '';\n if (!($p['entity'] < 0) && $p['entity_sons']) {\n if (is_array($p['entity'])) {\n $output .= \"entity_sons options is not available with array of entity\";\n } else {\n $p['entity'] = getSonsOf('glpi_entities', $p['entity']);\n }\n }", " // Make a select box with all glpi users\n $user = getUserName($p['value'], 2);", " $view_users = self::canView();", " if (!empty($p['value']) && ($p['value'] > 0)) {\n $default = $user[\"name\"];\n } else {\n if ($p['all']) {\n $default = __('All');\n } else {\n $default = Dropdown::EMPTY_VALUE;\n }\n }", " // get multiple values name\n $valuesnames = [];\n foreach ($p['values'] as $value) {\n if (!empty($value) && ($value > 0)) {\n $user = getUserName($value, 2);\n $valuesnames[] = $user[\"name\"];\n }\n }", " $field_id = Html::cleanId(\"dropdown_\" . $p['name'] . $p['rand']);\n $param = [\n 'value' => $p['value'],\n 'values' => $p['values'],\n 'valuename' => $default,\n 'valuesnames' => $valuesnames,\n 'width' => $p['width'],\n 'all' => $p['all'],\n 'display_emptychoice' => $p['display_emptychoice'],\n 'placeholder' => $p['placeholder'],\n 'right' => $p['right'],\n 'on_change' => $p['on_change'],\n 'used' => $p['used'],\n 'inactive_deleted' => $p['inactive_deleted'],", " 'entity_restrict' => ($entity_restrict = (is_array($p['entity']) ? json_encode(array_values($p['entity'])) : $p['entity'])),", " 'specific_tags' => $p['specific_tags'],", " '_idor_token' => Session::getNewIDORToken(__CLASS__, [\n 'right' => $p['right'],\n 'entity_restrict' => $entity_restrict,\n ]),", " ];", " $output = Html::jsAjaxDropdown($p['name'], $field_id,\n $p['url'],\n $param);", " // Display comment\n if ($p['comments']) {\n $comment_id = Html::cleanId(\"comment_\".$p['name'].$p['rand']);\n $link_id = Html::cleanId(\"comment_link_\".$p[\"name\"].$p['rand']);\n if (!$view_users) {\n $user[\"link\"] = '';\n } else if (empty($user[\"link\"])) {\n $user[\"link\"] = $CFG_GLPI['root_doc'].\"/front/user.php\";\n }", " if (empty($user['comment'])) {\n $user['comment'] = Toolbox::ucfirst(\n sprintf(\n __('Show %1$s'),\n self::getTypeName(Session::getPluralNumber())\n )\n );\n }\n $output .= \"&nbsp;\".Html::showToolTip($user[\"comment\"],\n ['contentid' => $comment_id,\n 'display' => false,\n 'link' => $user[\"link\"],\n 'linkid' => $link_id]);", " $paramscomment = [\n 'value' => '__VALUE__',\n 'itemtype' => User::getType()\n ];", " if ($view_users) {\n $paramscomment['withlink'] = $link_id;\n }\n $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id,\n $CFG_GLPI[\"root_doc\"].\"/ajax/comments.php\",\n $paramscomment, false);\n }\n $output .= Ajax::commonDropdownUpdateItem($p, false);", " if (Session::haveRight('user', self::IMPORTEXTAUTHUSERS)\n && $p['ldap_import']\n && Entity::isEntityDirectoryConfigured($_SESSION['glpiactive_entity'])) {", " $output .= \"<span title=\\\"\".__s('Import a user').\"\\\" class='fa fa-plus pointer'\".\n \" onClick=\\\"\".Html::jsGetElementbyID('userimport'.$p['rand']).\".dialog('open');\\\">\n <span class='sr-only'>\" . __s('Import a user') . \"</span></span>\";\n $output .= Ajax::createIframeModalWindow('userimport'.$p['rand'],\n $CFG_GLPI[\"root_doc\"].\n \"/front/ldap.import.php?entity=\".\n $_SESSION['glpiactive_entity'],\n ['title' => __('Import a user'),\n 'display' => false]);\n }", " if ($p['display']) {\n echo $output;\n return $p['rand'];\n }\n return $output;\n }", "\n /**\n * Show simple add user form for external auth.\n *\n * @return void|boolean false if user does not have rights to import users from external sources,\n * print form otherwise\n */\n static function showAddExtAuthForm() {", " if (!Session::haveRight(\"user\", self::IMPORTEXTAUTHUSERS)) {\n return false;\n }", " echo \"<div class='center'>\\n\";\n echo \"<form method='post' action='\".Toolbox::getItemTypeFormURL('User').\"'>\\n\";", " echo \"<table class='tab_cadre'>\\n\";\n echo \"<tr><th colspan='4'>\".__('Automatically add a user of an external source').\"</th></tr>\\n\";", " echo \"<tr class='tab_bg_1'><td>\".__('Login').\"</td>\\n\";\n echo \"<td><input type='text' name='login'></td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='tab_bg_2 center' colspan='2'>\\n\";\n echo \"<input type='submit' name='add_ext_auth_ldap' value=\\\"\".__s('Import from directories').\"\\\"\n class='submit'>\\n\";\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td class='tab_bg_2 center' colspan='2'>\\n\";\n echo \"<input type='submit' name='add_ext_auth_simple' value=\\\"\".__s('Import from other sources').\"\\\"\n class='submit'>\\n\";\n echo \"</td></tr>\\n\";", " echo \"</table>\";\n Html::closeForm();\n echo \"</div>\\n\";\n }", "\n /**\n * Change auth method for given users.\n *\n * @param integer[] $IDs IDs of users\n * @param integer $authtype Auth type (see Auth constants)\n * @param integer $server ID of auth server\n *\n * @return boolean\n */\n static function changeAuthMethod(array $IDs = [], $authtype = 1, $server = -1) {\n global $DB;", " if (!Session::haveRight(self::$rightname, self::UPDATEAUTHENT)) {\n return false;\n }", " if (!empty($IDs)\n && in_array($authtype, [Auth::DB_GLPI, Auth::LDAP, Auth::MAIL, Auth::EXTERNAL])) {", " $result = $DB->update(\n self::getTable(), [\n 'authtype' => $authtype,\n 'auths_id' => $server,\n 'password' => '',\n 'is_deleted_ldap' => 0\n ], [\n 'id' => $IDs\n ]\n );\n if ($result) {\n foreach ($IDs as $ID) {\n $changes = [\n 0,\n '',\n addslashes(\n sprintf(\n __('%1$s: %2$s'),\n __('Update authentification method to'),\n Auth::getMethodName($authtype, $server)\n )\n )\n ];\n Log::history($ID, __CLASS__, $changes, '', Log::HISTORY_LOG_SIMPLE_MESSAGE);\n }", " return true;\n }\n }\n return false;\n }", "\n /**\n * Generate vcard for the current user.\n *\n * @return void\n */\n function generateVcard() {", " // prepare properties for the Vcard\n if (!empty($this->fields[\"realname\"])\n || !empty($this->fields[\"firstname\"])) {\n $name = [$this->fields[\"realname\"], $this->fields[\"firstname\"], \"\", \"\", \"\"];\n } else {\n $name = [$this->fields[\"name\"], \"\", \"\", \"\", \"\"];\n }", " // create vcard\n $vcard = new VObject\\Component\\VCard([\n 'N' => $name,\n 'EMAIL' => $this->getDefaultEmail(),\n 'NOTE' => $this->fields[\"comment\"],\n ]);\n $vcard->add('TEL', $this->fields[\"phone\"], ['type' => 'PREF;WORK;VOICE']);\n $vcard->add('TEL', $this->fields[\"phone2\"], ['type' => 'HOME;VOICE']);\n $vcard->add('TEL', $this->fields[\"mobile\"], ['type' => 'WORK;CELL']);", " // send the VCard\n $output = $vcard->serialize();\n $filename = implode(\"_\", array_filter($name)).\".vcf\";", " @header(\"Content-Disposition: attachment; filename=\\\"$filename\\\"\");\n @header(\"Content-Length: \".Toolbox::strlen($output));\n @header(\"Connection: close\");\n @header(\"content-type: text/x-vcard; charset=UTF-8\");", " echo $output;\n }", "\n /**\n * Show items of the current user.\n *\n * @param boolean $tech false to display items owned by user, true to display items managed by user\n *\n * @return void\n */\n function showItems($tech) {\n global $DB, $CFG_GLPI;", " $ID = $this->getField('id');", " if ($tech) {\n $type_user = $CFG_GLPI['linkuser_tech_types'];\n $type_group = $CFG_GLPI['linkgroup_tech_types'];\n $field_user = 'users_id_tech';\n $field_group = 'groups_id_tech';\n } else {\n $type_user = $CFG_GLPI['linkuser_types'];\n $type_group = $CFG_GLPI['linkgroup_types'];\n $field_user = 'users_id';\n $field_group = 'groups_id';\n }", " $group_where = \"\";\n $groups = [];", " $iterator = $DB->request([\n 'SELECT' => [\n 'glpi_groups_users.groups_id',\n 'glpi_groups.name'\n ],\n 'FROM' => 'glpi_groups_users',\n 'LEFT JOIN' => [\n 'glpi_groups' => [\n 'FKEY' => [\n 'glpi_groups_users' => 'groups_id',\n 'glpi_groups' => 'id'\n ]\n ]\n ],\n 'WHERE' => ['glpi_groups_users.users_id' => $ID]\n ]);\n $number = count($iterator);", " $group_where = [];\n while ($data = $iterator->next()) {\n $group_where[$field_group][] = $data['groups_id'];\n $groups[$data[\"groups_id\"]] = $data[\"name\"];\n }", " echo \"<div class='spaced'><table class='tab_cadre_fixehov'>\";\n $header = \"<tr><th>\"._n('Type', 'Types', 1).\"</th>\";\n $header .= \"<th>\".Entity::getTypeName(1).\"</th>\";\n $header .= \"<th>\".__('Name').\"</th>\";\n $header .= \"<th>\".__('Serial number').\"</th>\";\n $header .= \"<th>\".__('Inventory number').\"</th>\";\n $header .= \"<th>\".__('Status').\"</th>\";\n $header .= \"<th>&nbsp;</th></tr>\";\n echo $header;", " foreach ($type_user as $itemtype) {\n if (!($item = getItemForItemtype($itemtype))) {\n continue;\n }\n if ($item->canView()) {\n $itemtable = getTableForItemType($itemtype);\n $iterator_params = [\n 'FROM' => $itemtable,\n 'WHERE' => [$field_user => $ID]\n ];", " if ($item->maybeTemplate()) {\n $iterator_params['WHERE']['is_template'] = 0;\n }\n if ($item->maybeDeleted()) {\n $iterator_params['WHERE']['is_deleted'] = 0;\n }", " $item_iterator = $DB->request($iterator_params);", " $type_name = $item->getTypeName();", " while ($data = $item_iterator->next()) {\n $cansee = $item->can($data[\"id\"], READ);\n $link = $data[\"name\"];\n if ($cansee) {\n $link_item = $item::getFormURLWithID($data['id']);\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($link)) {\n $link = sprintf(__('%1$s (%2$s)'), $link, $data[\"id\"]);\n }\n $link = \"<a href='\".$link_item.\"'>\".$link.\"</a>\";\n }\n $linktype = \"\";\n if ($data[$field_user] == $ID) {\n $linktype = self::getTypeName(1);\n }\n echo \"<tr class='tab_bg_1'><td class='center'>$type_name</td>\";\n echo \"<td class='center'>\".Dropdown::getDropdownName(\"glpi_entities\",\n $data[\"entities_id\"]).\"</td>\";\n echo \"<td class='center'>$link</td>\";\n echo \"<td class='center'>\";\n if (isset($data[\"serial\"]) && !empty($data[\"serial\"])) {\n echo $data[\"serial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"otherserial\"]) && !empty($data[\"otherserial\"])) {\n echo $data[\"otherserial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"states_id\"])) {\n echo Dropdown::getDropdownName(\"glpi_states\", $data['states_id']);\n } else {\n echo '&nbsp;';\n }", " echo \"</td><td class='center'>$linktype</td></tr>\";\n }\n }\n }\n if ($number) {\n echo $header;\n }\n echo \"</table></div>\";", " if (count($group_where)) {\n echo \"<div class='spaced'><table class='tab_cadre_fixehov'>\";\n $header = \"<tr>\".\n \"<th>\"._n('Type', 'Types', 1).\"</th>\".\n \"<th>\".Entity::getTypeName(1).\"</th>\".\n \"<th>\".__('Name').\"</th>\".\n \"<th>\".__('Serial number').\"</th>\".\n \"<th>\".__('Inventory number').\"</th>\".\n \"<th>\".__('Status').\"</th>\".\n \"<th>&nbsp;</th></tr>\";\n echo $header;\n $nb = 0;\n foreach ($type_group as $itemtype) {\n if (!($item = getItemForItemtype($itemtype))) {\n continue;\n }\n if ($item->canView() && $item->isField($field_group)) {\n $itemtable = getTableForItemType($itemtype);\n $iterator_params = [\n 'FROM' => $itemtable,\n 'WHERE' => ['OR' => $group_where]\n ];", " if ($item->maybeTemplate()) {\n $iterator_params['WHERE']['is_template'] = 0;\n }\n if ($item->maybeDeleted()) {\n $iterator_params['WHERE']['is_deleted'] = 0;\n }", " $group_iterator = $DB->request($iterator_params);", " $type_name = $item->getTypeName();", " while ($data = $group_iterator->next()) {\n $nb++;\n $cansee = $item->can($data[\"id\"], READ);\n $link = $data[\"name\"];\n if ($cansee) {\n $link_item = $item::getFormURLWithID($data['id']);\n if ($_SESSION[\"glpiis_ids_visible\"] || empty($link)) {\n $link = sprintf(__('%1$s (%2$s)'), $link, $data[\"id\"]);\n }\n $link = \"<a href='\".$link_item.\"'>\".$link.\"</a>\";\n }\n $linktype = \"\";\n if (isset($groups[$data[$field_group]])) {\n $linktype = sprintf(__('%1$s = %2$s'), Group::getTypeName(1),\n $groups[$data[$field_group]]);\n }\n echo \"<tr class='tab_bg_1'><td class='center'>$type_name</td>\";\n echo \"<td class='center'>\".Dropdown::getDropdownName(\"glpi_entities\",\n $data[\"entities_id\"]);\n echo \"</td><td class='center'>$link</td>\";\n echo \"<td class='center'>\";\n if (isset($data[\"serial\"]) && !empty($data[\"serial\"])) {\n echo $data[\"serial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"otherserial\"]) && !empty($data[\"otherserial\"])) {\n echo $data[\"otherserial\"];\n } else {\n echo '&nbsp;';\n }\n echo \"</td><td class='center'>\";\n if (isset($data[\"states_id\"])) {\n echo Dropdown::getDropdownName(\"glpi_states\", $data['states_id']);\n } else {\n echo '&nbsp;';\n }", " echo \"</td><td class='center'>$linktype</td></tr>\";\n }\n }\n }\n if ($nb) {\n echo $header;\n }\n echo \"</table></div>\";\n }\n }", "\n /**\n * Get user by email, importing it from LDAP if not existing.\n *\n * @param string $email\n *\n * @return integer ID of user, 0 if not found nor imported\n */\n static function getOrImportByEmail($email = '') {\n global $DB, $CFG_GLPI;", " $iterator = $DB->request([\n 'SELECT' => 'users_id AS id',\n 'FROM' => 'glpi_useremails',\n 'LEFT JOIN' => [\n 'glpi_users' => [\n 'FKEY' => [\n 'glpi_useremails' => 'users_id',\n 'glpi_users' => 'id'\n ]\n ]\n ],\n 'WHERE' => [\n 'glpi_useremails.email' => $DB->escape(stripslashes($email))\n ],\n 'ORDER' => ['glpi_users.is_active DESC', 'is_deleted ASC']\n ]);", " //User still exists in DB\n if (count($iterator)) {\n $result = $iterator->next();\n return $result['id'];\n } else {\n if ($CFG_GLPI[\"is_users_auto_add\"]) {\n //Get all ldap servers with email field configured\n $ldaps = AuthLDAP::getServersWithImportByEmailActive();\n //Try to find the user by his email on each ldap server", " foreach ($ldaps as $ldap) {\n $params = [\n 'method' => AuthLDAP::IDENTIFIER_EMAIL,\n 'value' => $email,\n ];\n $res = AuthLDAP::ldapImportUserByServerId($params,\n AuthLDAP::ACTION_IMPORT,\n $ldap);", " if (isset($res['id'])) {\n return $res['id'];\n }\n }\n }\n }\n return 0;\n }", "\n /**\n * Handle user deleted in LDAP using configured policy.\n *\n * @param integer $users_id\n *\n * @return void\n */\n static function manageDeletedUserInLdap($users_id) {\n global $CFG_GLPI;", " //The only case where users_id can be null if when a user has been imported into GLPI\n //it's dn still exists, but doesn't match the connection filter anymore\n //In this case, do not try to process the user\n if (!$users_id) {\n return;\n }", " //User is present in DB but not in the directory : it's been deleted in LDAP\n $tmp = [\n 'id' => $users_id,\n 'is_deleted_ldap' => 1,\n ];\n $myuser = new self();\n $myuser->getFromDB($users_id);", " //User is already considered as delete from ldap\n if ($myuser->fields['is_deleted_ldap'] == 1) {\n return;\n }", " switch ($CFG_GLPI['user_deleted_ldap']) {\n //DO nothing\n default :\n case AuthLDAP::DELETED_USER_PRESERVE:\n $myuser->update($tmp);\n break;", " //Put user in trashbin\n case AuthLDAP::DELETED_USER_DELETE:\n $myuser->delete($tmp);\n break;", " //Delete all user dynamic habilitations and groups\n case AuthLDAP::DELETED_USER_WITHDRAWDYNINFO:\n Profile_User::deleteRights($users_id, true);\n Group_User::deleteGroups($users_id, true);\n $myuser->update($tmp);\n break;", " //Deactivate the user\n case AuthLDAP::DELETED_USER_DISABLE:\n $tmp['is_active'] = 0;\n $myuser->update($tmp);\n break;", " //Deactivate the user+ Delete all user dynamic habilitations and groups\n case AuthLDAP::DELETED_USER_DISABLEANDWITHDRAWDYNINFO:\n $tmp['is_active'] = 0;\n $myuser->update($tmp);\n Profile_User::deleteRights($users_id, true);\n Group_User::deleteGroups($users_id, true);\n break;", " }\n /*\n $changes[0] = '0';\n $changes[1] = '';\n $changes[2] = __('Deleted user in LDAP directory');\n Log::history($users_id, 'User', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);*/\n }", " /**\n * Get user ID from its name.\n *\n * @param string $name User name\n *\n * @return integer\n */\n static function getIdByName($name) {\n return self::getIdByField('name', $name);\n }", "\n /**\n * Get user ID from a field\n *\n * @since 0.84\n *\n * @param string $field Field name\n * @param string $value Field value\n *\n * @return integer\n */\n static function getIdByField($field, $value, $escape = true) {\n global $DB;", " if ($escape) {\n $value = addslashes($value);\n }", " $iterator = $DB->request([\n 'SELECT' => 'id',\n 'FROM' => self::getTable(),\n 'WHERE' => [$field => $value]\n ]);", " if (count($iterator) == 1) {\n $row = $iterator->next();\n return (int)$row['id'];\n }\n return false;\n }", "\n /**\n * Show password update form for current user.\n *\n * @param array $error_messages\n *\n * @return void\n */\n public function showPasswordUpdateForm(array $error_messages = []) {\n global $CFG_GLPI;", " echo '<form method=\"post\" action=\"' . $CFG_GLPI['root_doc'] . '/front/updatepassword.php\">';\n echo '<table class=\"tab_cadre\">';\n echo '<tr><th colspan=\"2\">' . __('Password update') . '</th></tr>';", " if (Session::mustChangePassword()) {\n echo '<tr class=\"tab_bg_2 center\">';\n echo '<td colspan=\"2\" class=\"red b\">';\n echo __('Your password has expired. You must change it to be able to login.');\n echo '</td>';\n echo '</tr>';\n }", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo __('Login');\n echo '</td>';\n echo '<td>';\n echo '<input type=\"text\" name=\"name\" value=\"' . $this->fields['name'] . '\" readonly=\"readonly\" />';\n echo '</td>';\n echo '</tr>';", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo '<label for=\"current_password\">' . __('Current password') . '</label>';\n echo '</td>';\n echo '<td>';\n echo '<input type=\"password\" id=\"current_password\" name=\"current_password\" />';\n echo '</td>';\n echo '</tr>';", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo '<label for=\"password\">' . __('New password') . '</label>';\n echo '</td>';\n echo '<td>';\n echo '<input type=\"password\" id=\"password\" name=\"password\" autocomplete=\"new-password\" onkeyup=\"return passwordCheck();\" />';\n echo '</td>';\n echo '</tr>';", " echo '<tr class=\"tab_bg_1\">';\n echo '<td>';\n echo '<label for=\"password2\">' . __('New password confirmation') . '</label>';\n echo '</td>';\n echo '<td>';\n echo '<input type=\"password\" id=\"password2\" name=\"password2\" autocomplete=\"new-password\" />';\n echo '</td>';\n echo '</tr>';", " if ($CFG_GLPI['use_password_security']) {\n echo '<tr class=\"tab_bg_1\">';\n echo '<td>' . __('Password security policy') . '</td>';\n echo '<td>';\n Config::displayPasswordSecurityChecks();\n echo '</td>';\n echo '</tr>';\n }", " echo '<tr class=\"tab_bg_2 center\">';\n echo '<td colspan=\"2\">';\n echo '<input type=\"submit\" name=\"update\" value=\"' . __s('Save') . '\" class=\"submit\" />';\n echo '</td>';\n echo '</tr>';", " if (!empty($error_messages)) {\n echo '<tr class=\"tab_bg_2 center\">';\n echo '<td colspan=\"2\" class=\"red b\">';\n echo implode('<br/>', $error_messages);\n echo '</td>';\n echo '</tr>';\n }", " echo '</table>';\n Html::closeForm();\n }", "\n /**\n * Show new password form of password recovery process.\n *\n * @param $token\n *\n * @return void\n */\n static function showPasswordForgetChangeForm($token) {\n global $CFG_GLPI, $DB;", " // Verif token.\n $token_ok = false;\n $iterator = $DB->request([\n 'FROM' => self::getTable(),\n 'WHERE' => [\n 'password_forget_token' => $token,\n new \\QueryExpression('NOW() < ADDDATE(' . $DB->quoteName('password_forget_token_date') . ', INTERVAL 1 DAY)')\n ]\n ]);", " if (count($iterator) == 1) {\n $token_ok = true;\n }\n echo \"<div class='center'>\";", " if ($token_ok) {\n echo \"<form method='post' name='forgetpassword' action='\".$CFG_GLPI['root_doc'].\n \"/front/lostpassword.php'>\";\n echo \"<table class='tab_cadre'>\";\n echo \"<tr><th colspan='2'>\" . __('Forgotten password?').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'>\";\n echo \"<td colspan='2'>\". __('Please confirm your email address and enter your new password.').\n \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\" . _n('Email', 'Emails', 1).\"</td>\";\n echo \"<td><input type='text' name='email' value='' size='60'></td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\" . __('Password').\"</td>\";\n echo \"<td><input id='password' type='password' name='password' value='' size='20'\n autocomplete='new-password' onkeyup=\\\"return passwordCheck();\\\">\";\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\" . __('Password confirmation').\"</td>\";\n echo \"<td><input type='password' name='password2' value='' size='20' autocomplete='new-password'>\";\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_1'><td>\".__('Password security policy').\"</td>\";\n echo \"<td>\";\n Config::displayPasswordSecurityChecks();\n echo \"</td></tr>\";", " echo \"<tr class='tab_bg_2 center'><td colspan='2'>\";\n echo \"<input type='hidden' name='password_forget_token' value='$token'>\";\n echo \"<input type='submit' name='update' value=\\\"\".__s('Save').\"\\\" class='submit'>\";\n echo \"</td></tr>\";", " echo \"</table>\";\n Html::closeForm();", " } else {\n echo __('Your password reset request has expired or is invalid. Please renew it.');\n }\n echo \"</div>\";\n }", "\n /**\n * Show request form of password recovery process.\n *\n * @return void\n */\n static function showPasswordForgetRequestForm() {\n global $CFG_GLPI;", " echo \"<div class='center'>\";\n echo \"<form method='post' name='forgetpassword' action='\".$CFG_GLPI['root_doc'].\n \"/front/lostpassword.php'>\";\n echo \"<table class='tab_cadre'>\";\n echo \"<tr><th colspan='2'>\" . __('Forgotten password?').\"</th></tr>\";", " echo \"<tr class='tab_bg_1'><td colspan='2'>\" .\n __('Please enter your email address. An email will be sent to you and you will be able to choose a new password.').\n \"</td></tr>\";", " echo \"<tr class='tab_bg_2 center'>\";\n echo \"<td><input type='text' size='60' name='email' value=''></td>\";\n echo \"<td><input type='submit' name='update' value=\\\"\".__s('Save').\"\\\" class='submit'>\";\n echo \"</td></tr>\";", " echo \"</table>\";\n Html::closeForm();\n echo \"</div>\";\n }", "\n /**\n * Handle password recovery form submission.\n *\n * @param array $input\n *\n * @throws ForgetPasswordException when requirements are not met\n *\n * @return boolean true if password successfully changed, false otherwise\n */\n public function updateForgottenPassword(array $input) {\n $condition = [\n 'glpi_users.is_active' => 1,\n 'glpi_users.is_deleted' => 0, [\n 'OR' => [\n ['glpi_users.begin_date' => null],\n ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]\n ],\n ], [\n 'OR' => [\n ['glpi_users.end_date' => null],\n ['glpi_users.end_date' => ['>', new QueryExpression('NOW()')]]\n ]\n ]\n ];\n if ($this->getFromDBbyEmail($input['email'], $condition)) {\n if (($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || !Auth::useAuthExt()) {", " if (($input['password_forget_token'] == $this->fields['password_forget_token'])\n && (abs(strtotime($_SESSION[\"glpi_currenttime\"])\n -strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP)) {", " $input['id'] = $this->fields['id'];\n Config::validatePassword($input[\"password\"], false); // Throws exception if password is invalid\n if (!$this->update($input)) {\n return false;\n }\n $input2 = [\n 'password_forget_token' => '',\n 'password_forget_token_date' => 'NULL',\n 'id' => $this->fields['id']\n ];\n $this->update($input2);\n return true;", " } else {\n throw new ForgetPasswordException(__('Your password reset request has expired or is invalid. Please renew it.'));\n }", " } else {\n throw new ForgetPasswordException(__(\"The authentication method configuration doesn't allow you to change your password.\"));\n }", " } else {\n throw new ForgetPasswordException(__('Email address not found.'));\n }", " return false;\n }", "\n /**\n * Displays password recovery result.\n *\n * @param array $input\n *\n * @return void\n */\n public function showUpdateForgottenPassword(array $input) {\n global $CFG_GLPI;", " echo \"<div class='center'>\";\n try {\n if (!$this->updateForgottenPassword($input)) {\n Html::displayMessageAfterRedirect();\n } else {\n echo __('Reset password successful.');\n }\n } catch (ForgetPasswordException $e) {\n echo $e->getMessage();\n } catch (PasswordTooWeakException $e) {\n // Force display on error\n foreach ($e->getMessages() as $message) {\n Session::addMessageAfterRedirect($message);\n }\n Html::displayMessageAfterRedirect();\n }", " echo \"<br>\";\n echo \"<a href=\\\"\".$CFG_GLPI['root_doc'].\"/index.php\\\">\".__s('Back').\"</a>\";\n echo \"</div>\";\n }", "\n /**\n * Send password recovery for a user and display result message.\n *\n * @param string $email email of the user\n *\n * @return void\n */\n public function showForgetPassword($email) {", " echo \"<div class='center'>\";\n try {\n $this->forgetPassword($email);\n } catch (ForgetPasswordException $e) {\n echo $e->getMessage();\n return;\n }\n echo __('An email has been sent to your email address. The email contains information for reset your password.');\n }", " /**\n * Send password recovery email for a user.\n *\n * @param string $email\n *\n * @throws ForgetPasswordException when requirements are not met\n *\n * @return boolean true if notification successfully created, false if user not found\n */\n public function forgetPassword($email) {\n $condition = [\n 'glpi_users.is_active' => 1,\n 'glpi_users.is_deleted' => 0, [\n 'OR' => [\n ['glpi_users.begin_date' => null],\n ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]\n ],\n ], [\n 'OR' => [\n ['glpi_users.end_date' => null],\n ['glpi_users.end_date' => ['>', new QueryExpression('NOW()')]]\n ]\n ]\n ];", " if ($this->getFromDBbyEmail($email, $condition)) {", " // Send token if auth DB or not external auth defined\n if (($this->fields[\"authtype\"] == Auth::DB_GLPI)\n || !Auth::useAuthExt()) {", " if (NotificationMailing::isUserAddressValid($email)) {\n $input = [\n 'password_forget_token' => sha1(Toolbox::getRandomString(30)),\n 'password_forget_token_date' => $_SESSION[\"glpi_currenttime\"],\n 'id' => $this->fields['id'],\n ];\n $this->update($input);\n // Notication on root entity (glpi_users.entities_id is only a pref)\n NotificationEvent::raiseEvent('passwordforget', $this, ['entities_id' => 0]);\n QueuedNotification::forceSendFor($this->getType(), $this->fields['id']);\n return true;\n } else {\n throw new ForgetPasswordException(__('Invalid email address'));\n }", " } else {\n throw new ForgetPasswordException(__(\"The authentication method configuration doesn't allow you to change your password.\"));\n }", " }", " throw new ForgetPasswordException(__('Email address not found.'));\n }", "\n /**\n * Display information from LDAP server for user.\n *\n * @return void\n */\n private function showLdapDebug() {", " if ($this->fields['authtype'] != Auth::LDAP) {\n return false;\n }\n echo \"<div class='spaced'>\";\n echo \"<table class='tab_cadre_fixe'>\";\n echo \"<tr><th colspan='4'>\".AuthLDAP::getTypeName(1).\"</th></tr>\";", " echo \"<tr class='tab_bg_2'><td>\".__('User DN').\"</td>\";\n echo \"<td>\".$this->fields['user_dn'].\"</td></tr>\\n\";", " if ($this->fields['user_dn']) {\n echo \"<tr class='tab_bg_2'><td>\".__('User information').\"</td><td>\";\n $config_ldap = new AuthLDAP();\n $ds = false;", " if ($config_ldap->getFromDB($this->fields['auths_id'])) {\n $ds = $config_ldap->connect();\n }", " if ($ds) {\n $info = AuthLDAP::getUserByDn($ds, $this->fields['user_dn'],\n ['*', 'createTimeStamp', 'modifyTimestamp']);\n if (is_array($info)) {\n Html::printCleanArray($info);\n } else {\n echo __('No item to display');\n }", " } else {\n echo __('Connection failed');\n }", " echo \"</td></tr>\\n\";\n }", " echo \"</table></div>\";\n }", "\n /**\n * Display debug information for current object.\n *\n * @return void\n */\n function showDebug() {", " NotificationEvent::debugEvent($this);\n $this->showLdapDebug();\n }", " function getUnicityFieldsToDisplayInErrorMessage() {", " return ['id' => __('ID'),\n 'entities_id' => Entity::getTypeName(1)];\n }", "\n function getUnallowedFieldsForUnicity() {", " return array_merge(parent::getUnallowedFieldsForUnicity(),\n ['auths_id', 'date_sync', 'entities_id', 'last_login', 'profiles_id']);\n }", "\n /**\n * Get a unique generated token.\n *\n * @param string $field Field storing the token\n *\n * @return string\n */\n static function getUniqueToken($field = 'personal_token') {\n global $DB;", " $ok = false;\n do {\n $key = Toolbox::getRandomString(40);\n $row = $DB->request([\n 'COUNT' => 'cpt',\n 'FROM' => self::getTable(),\n 'WHERE' => [$field => $key]\n ])->next();", " if ($row['cpt'] == 0) {\n return $key;\n }\n } while (!$ok);", " }", "\n /**\n * Get token of a user. If not exists generate it.\n *\n * @param integer $ID User ID\n * @param string $field Field storing the token\n *\n * @return string|boolean User token, false if user does not exist\n */\n static function getToken($ID, $field = 'personal_token') {", " $user = new self();\n if ($user->getFromDB($ID)) {\n return $user->getAuthToken($field);\n }", " return false;\n }", " /**\n * Get token of a user. If it does not exists then generate it.\n *\n * @since 9.4\n *\n * @param string $field the field storing the token\n * @param boolean $force_new force generation of a new token\n *\n * @return string|false token or false in case of error\n */\n public function getAuthToken($field = 'personal_token', $force_new = false) {\n global $CFG_GLPI;", " if ($this->isNewItem()) {\n return false;\n }", " // check date validity for cookie token\n $outdated = false;\n if ($field === 'cookie_token') {\n $date_create = new DateTime($this->fields[$field.\"_date\"]);\n $date_expir = $date_create->add(new DateInterval('PT'.$CFG_GLPI[\"login_remember_time\"].'S'));", " if ($date_expir < new DateTime()) {\n $outdated = true;\n }\n }", " // token exists, is not oudated, and we may use it\n if (!empty($this->fields[$field]) && !$force_new && !$outdated) {\n return $this->fields[$field];\n }", " // else get a new token\n $token = self::getUniqueToken($field);", " // for cookie token, we need to store it hashed\n $hash = $token;\n if ($field === 'cookie_token') {\n $hash = Auth::getPasswordHash($token);\n }", " // save this token in db\n $this->update(['id' => $this->getID(),\n $field => $hash,\n $field . \"_date\" => $_SESSION['glpi_currenttime']]);", " return $token;\n }", "\n /**\n * Get name of users using default passwords\n *\n * @return string[]\n */\n static function checkDefaultPasswords() {\n global $DB;", " $passwords = ['glpi' => 'glpi',\n 'tech' => 'tech',\n 'normal' => 'normal',\n 'post-only' => 'postonly'];\n $default_password_set = [];", " $crit = ['FIELDS' => ['name', 'password'],\n 'is_active' => 1,\n 'is_deleted' => 0,\n 'name' => array_keys($passwords)];", " foreach ($DB->request('glpi_users', $crit) as $data) {\n if (Auth::checkPassword($passwords[strtolower($data['name'])], $data['password'])) {\n $default_password_set[] = $data['name'];\n }\n }", " return $default_password_set;\n }", "\n /**\n * Get picture URL from picture field.\n *\n * @since 0.85\n *\n * @param string $picture Picture field value\n *\n * @return string\n */\n static function getURLForPicture($picture) {\n global $CFG_GLPI;", " $url = Toolbox::getPictureUrl($picture);\n if (null !== $url) {\n return $url;\n }", " return $CFG_GLPI[\"root_doc\"].\"/pics/picture.png\";\n }", "\n /**\n * Get thumbnail URL from picture field.\n *\n * @since 0.85\n *\n * @param string $picture Picture field value\n *\n * @return string\n */\n static function getThumbnailURLForPicture($picture) {\n global $CFG_GLPI;", " // prevent xss\n $picture = Html::cleanInputText($picture);", " if (!empty($picture)) {\n $tmp = explode(\".\", $picture);\n if (count($tmp) ==2) {\n return $CFG_GLPI[\"root_doc\"].\"/front/document.send.php?file=_pictures/\".$tmp[0].\n \"_min.\".$tmp[1];\n }\n return $CFG_GLPI[\"root_doc\"].\"/pics/picture_min.png\";\n }\n return $CFG_GLPI[\"root_doc\"].\"/pics/picture_min.png\";", " }", "\n /**\n * Drop existing files for user picture.\n *\n * @since 0.85\n *\n * @param string $picture Picture field value\n *\n * @return void\n */\n static function dropPictureFiles($picture) {", " if (!empty($picture)) {\n // unlink main file\n if (file_exists(GLPI_PICTURE_DIR.\"/$picture\")) {\n @unlink(GLPI_PICTURE_DIR.\"/$picture\");\n }\n // unlink Thunmnail\n $tmp = explode(\".\", $picture);\n if (count($tmp) == 2) {\n if (file_exists(GLPI_PICTURE_DIR.\"/\".$tmp[0].\"_min.\".$tmp[1])) {\n @unlink(GLPI_PICTURE_DIR.\"/\".$tmp[0].\"_min.\".$tmp[1]);\n }\n }\n }\n }", " function getRights($interface = 'central') {", " $values = parent::getRights();\n //TRANS: short for : Add users from an external source\n $values[self::IMPORTEXTAUTHUSERS] = ['short' => __('Add external'),\n 'long' => __('Add users from an external source')];\n //TRANS: short for : Read method for user authentication and synchronization\n $values[self::READAUTHENT] = ['short' => __('Read auth'),\n 'long' => __('Read user authentication and synchronization method')];\n //TRANS: short for : Update method for user authentication and synchronization\n $values[self::UPDATEAUTHENT] = ['short' => __('Update auth and sync'),\n 'long' => __('Update method for user authentication and synchronization')];", " return $values;\n }", "\n /**\n * Retrieve the list of LDAP field names from a list of fields\n * allow pattern substitution, e.g. %{name}.\n *\n * @since 9.1\n *\n * @param string[] $map array of fields\n *\n * @return string[]\n */\n private static function getLdapFieldNames(array $map) {", " $ret = [];\n foreach ($map as $v) {\n /** @var array $reg */\n if (preg_match_all('/%{(.*)}/U', $v, $reg)) {\n // e.g. \"%{country} > %{city} > %{site}\"\n foreach ($reg [1] as $f) {\n $ret [] = $f;\n }\n } else {\n // single field name\n $ret [] = $v;\n }\n }\n return $ret;\n }", "\n /**\n * Retrieve the value of a fields from a LDAP result applying needed substitution of %{value}.\n *\n * @since 9.1\n *\n * @param string $map String with field format\n * @param array $res LDAP result\n *\n * @return string\n */\n private static function getLdapFieldValue($map, array $res) {", " $map = Toolbox::unclean_cross_side_scripting_deep($map);\n $ret = preg_replace_callback('/%{(.*)}/U',\n function ($matches) use ($res) {\n return (isset($res[0][$matches[1]][0]) ? $res[0][$matches[1]][0] : '');\n }, $map );", " return $ret == $map ? (isset($res[0][$map][0]) ? $res[0][$map][0] : '') : $ret;\n }", " /**\n * Get/Print the switch language form.\n *\n * @param boolean $display Whether to display or return output\n * @param array $options Options\n * - string value Selected language value\n * - boolean showbutton Whether to display or not submit button\n *\n * @return void|string Nothing if displayed, string to display otherwise\n */\n function showSwitchLangForm($display = true, array $options = []) {", " $params = [\n 'value' => $_SESSION[\"glpilanguage\"],\n 'display' => false,\n 'showbutton' => true\n ];", " foreach ($options as $key => $value) {\n $params[$key] = $value;\n }", " $out = '';\n $out .= \"<form method='post' name='switchlang' action='\".User::getFormURL().\"' autocomplete='off'>\";\n $out .= \"<p class='center'>\";\n $out .= Dropdown::showLanguages(\"language\", $params);\n if ($params['showbutton'] === true) {\n $out .= \"&nbsp;<input type='submit' name='update' value=\\\"\"._sx('button', 'Save').\"\\\" class='submit'>\";\n }\n $out .= \"</p>\";\n $out .= Html::closeForm(false);", " if ($display === true) {\n echo $out;\n } else {\n return $out;\n }\n }", " /**\n * Get list of entities ids for current user.\n *\n * @return integer[]\n */\n private function getEntities() {\n //get user entities\n if ($this->entities == null) {\n $this->entities = Profile_User::getUserEntities($this->fields['id'], true);\n }\n return $this->entities;\n }", "\n /**\n * Give cron information.\n *\n * @param string $name Task's name\n *\n * @return array\n */\n public static function cronInfo(string $name): array {", " $info = [];\n switch ($name) {\n case 'passwordexpiration':\n $info = [\n 'description' => __('Handle users passwords expiration policy'),\n 'parameter' => __('Maximum expiration notifications to send at once'),\n ];\n break;\n }\n return $info;\n }", " /**\n * Cron that notify users about when their password expire and deactivate their account\n * depending on password expiration policy.\n *\n * @param CronTask $task\n *\n * @return integer\n */\n public static function cronPasswordExpiration(CronTask $task) {\n global $CFG_GLPI, $DB;", " $expiration_delay = (int)$CFG_GLPI['password_expiration_delay'];\n $notice_time = (int)$CFG_GLPI['password_expiration_notice'];\n $notification_limit = (int)$task->fields['param'];\n $lock_delay = (int)$CFG_GLPI['password_expiration_lock_delay'];", " if (-1 === $expiration_delay || (-1 === $notice_time && -1 === $lock_delay)) {\n // Nothing to do if passwords does not expire\n // or if password expires without notice and with no lock delay\n return 0;\n }", " // Notify users about expiration of their password.\n $to_notify_count = 0;\n if (-1 !== $notice_time) {\n $notification_request = [\n 'FROM' => self::getTable(),\n 'LEFT JOIN' => [\n Alert::getTable() => [\n 'ON' => [\n Alert::getTable() => 'items_id',\n self::getTable() => 'id',\n [\n 'AND' => [\n Alert::getTableField('itemtype') => self::getType(),\n ]\n ],\n ]\n ]\n ],\n 'WHERE' => [\n self::getTableField('is_deleted') => 0,\n self::getTableField('is_active') => 1,\n self::getTableField('authtype') => Auth::DB_GLPI,\n new QueryExpression(\n sprintf(\n 'NOW() > ADDDATE(%s, INTERVAL %s DAY)',\n $DB->quoteName(self::getTableField('password_last_update')),\n $expiration_delay - $notice_time\n )\n ),\n // Get only users that has not yet been notified within last day\n 'OR' => [\n [Alert::getTableField('date') => null],\n [Alert::getTableField('date') => ['<', new QueryExpression('CURRENT_TIMESTAMP() - INTERVAL 1 day')]],\n ],\n ],\n ];", " $to_notify_count_request = array_merge(\n $notification_request,\n [\n 'COUNT' => 'cpt',\n ]\n );\n $to_notify_count = $DB->request($to_notify_count_request)->next()['cpt'];", " $notification_data_request = array_merge(\n $notification_request,\n [\n 'SELECT' => [\n self::getTableField('id as user_id'),\n Alert::getTableField('id as alert_id'),\n ],\n 'LIMIT' => $notification_limit,\n ]\n );\n $notification_data_iterator = $DB->request($notification_data_request);", " foreach ($notification_data_iterator as $notification_data) {\n $user_id = $notification_data['user_id'];\n $alert_id = $notification_data['alert_id'];", " $user = new User();\n $user->getFromDB($user_id);", " $is_notification_send = NotificationEvent::raiseEvent(\n 'passwordexpires',\n $user,\n ['entities_id' => 0] // Notication on root entity (glpi_users.entities_id is only a pref)\n );\n if (!$is_notification_send) {\n continue;\n }", " $task->addVolume(1);", " $alert = new Alert();", " // Delete existing alert if any\n if (null !== $alert_id) {\n $alert->delete(['id' => $alert_id]);\n }", " // Add an alert to not warn user for at least one day\n $alert->add(\n [\n 'itemtype' => 'User',\n 'items_id' => $user_id,\n 'type' => Alert::NOTICE,\n ]\n );\n }\n }", " // Disable users if their password has expire for too long.\n if (-1 !== $lock_delay) {\n $DB->update(\n self::getTable(),\n [\n 'is_active' => 0,\n 'cookie_token' => null,\n 'cookie_token_date' => null,\n ],\n [\n 'is_deleted' => 0,\n 'is_active' => 1,\n 'authtype' => Auth::DB_GLPI,\n new QueryExpression(\n sprintf(\n 'NOW() > ADDDATE(ADDDATE(%s, INTERVAL %d DAY), INTERVAL %s DAY)',\n $DB->quoteName(self::getTableField('password_last_update')),\n $expiration_delay,\n $lock_delay\n )\n ),\n ]\n );\n }", " return -1 !== $notice_time && $to_notify_count > $notification_limit\n ? -1 // -1 for partial process (remaining notifications to send)\n : 1; // 1 for fully process\n }", " /**\n * Get password expiration time.\n *\n * @return null|int Password expiration time, or null if expiration mechanism is not active.\n */\n public function getPasswordExpirationTime() {\n global $CFG_GLPI;", " if (!array_key_exists('id', $this->fields) || $this->fields['id'] < 1) {\n return null;\n }", " $expiration_delay = (int)$CFG_GLPI['password_expiration_delay'];", " if (-1 === $expiration_delay) {\n return null;\n }", " return strtotime(\n '+ ' . $expiration_delay . ' days',\n strtotime($this->fields['password_last_update'])\n );\n }", " /**\n * Check if password should be changed (if it expires soon).\n *\n * @return boolean\n */\n public function shouldChangePassword() {\n global $CFG_GLPI;", " if ($this->hasPasswordExpired()) {\n return true; // too late to change password, but returning false would not be logical here\n }", " $expiration_time = $this->getPasswordExpirationTime();\n if (null === $expiration_time) {\n return false;\n }", " $notice_delay = (int)$CFG_GLPI['password_expiration_notice'];\n if (-1 === $notice_delay) {\n return false;\n }", " $notice_time = strtotime('- ' . $notice_delay . ' days', $expiration_time);", " return $notice_time < time();\n }", " /**\n * Check if password expired.\n *\n * @return boolean\n */\n public function hasPasswordExpired() {", " $expiration_time = $this->getPasswordExpirationTime();\n if (null === $expiration_time) {\n return false;\n }", " return $expiration_time < time();\n }", " public static function getFriendlyNameSearchCriteria(string $filter): array {\n $table = self::getTable();\n $login = DBmysql::quoteName(\"$table.name\");\n $firstname = DBmysql::quoteName(\"$table.firstname\");\n $lastname = DBmysql::quoteName(\"$table.realname\");", " $filter = strtolower($filter);\n $filter_no_spaces = str_replace(\" \", \"\", $filter);", " return [\n 'OR' => [\n ['RAW' => [\"LOWER($login)\" => ['LIKE', \"%$filter%\"]]],\n ['RAW' => [\"LOWER(REPLACE(CONCAT($firstname, $lastname), ' ', ''))\" => ['LIKE', \"%$filter_no_spaces%\"]]],\n ['RAW' => [\"LOWER(REPLACE(CONCAT($lastname, $firstname), ' ', ''))\" => ['LIKE', \"%$filter_no_spaces%\"]]],\n ]\n ];\n }", " public static function getFriendlyNameFields(string $alias = \"name\") {\n $config = Config::getConfigurationValues('core');\n if ($config['names_format'] == User::FIRSTNAME_BEFORE) {\n $first = \"firstname\";\n $second = \"realname\";\n } else {\n $first = \"realname\";\n $second = \"firstname\";\n }", " $table = self::getTable();\n $first = DB::quoteName(\"$table.$first\");\n $second = DB::quoteName(\"$table.$second\");\n $alias = DB::quoteName($alias);\n $name = DB::quoteName(self::getNameField());", " return new QueryExpression(\"IF(\n $first <> '' && $second <> '',\n CONCAT($first, ' ', $second),\n $name\n ) AS $alias\"\n );\n }", " static function getIcon() {\n return \"fas fa-user\";\n }", " /**\n * Add groups stored in \"_ldap_rules/groups_id\" special input\n */\n public function applyGroupsRules() {\n if (!isset($this->input[\"_ldap_rules\"]['groups_id'])) {\n return;\n }", " $group_ids = array_unique($this->input[\"_ldap_rules\"]['groups_id']);\n foreach ($group_ids as $group_id) {\n $group_user = new Group_User();", " $data = [\n 'groups_id' => $group_id,\n 'users_id' => $this->getId()\n ];", " if (!$group_user->getFromDBByCrit($data)) {\n $group_user->add($data);\n }", " }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n*/", "namespace tests\\units;", "use \\DbTestCase;", "/* Test for inc/dropdown.class.php */", "class Dropdown extends DbTestCase {", " public function testShowLanguages() {", " $opt = [ 'display_emptychoice' => true, 'display' => false ];\n $out = \\Dropdown::showLanguages('dropfoo', $opt);\n $this->string($out)\n ->contains(\"name='dropfoo'\")\n ->contains(\"value='' selected\")\n ->notContains(\"value='0'\")\n ->contains(\"value='fr_FR'\");", " $opt = ['display' => false, 'value' => 'cs_CZ', 'rand' => '1234'];\n $out = \\Dropdown::showLanguages('language', $opt);\n $this->string($out)\n ->notContains(\"value=''\")\n ->notContains(\"value='0'\")\n ->contains(\"name='language' id='dropdown_language1234\")\n ->contains(\"value='cs_CZ' selected\")\n ->contains(\"value='fr_FR'\");\n }", " public function dataTestImport() {\n return [\n // input, name, message\n [ [ ], '', 'missing name'],\n [ [ 'name' => ''], '', 'empty name'],\n [ [ 'name' => ' '], '', 'space name'],\n [ [ 'name' => ' a '], 'a', 'simple name'],\n [ [ 'name' => 'foo'], 'foo', 'simple name'],\n ];\n }", " /**\n * @dataProvider dataTestImport\n */\n public function testImport($input, $result, $msg) {\n $id = \\Dropdown::import('UserTitle', $input);\n if ($result) {\n $this->integer((int)$id)->isGreaterThan(0);\n $ut = new \\UserTitle();\n $this->boolean($ut->getFromDB($id))->isTrue();\n $this->string($ut->getField('name'))->isIdenticalTo($result);\n } else {\n $this->integer((int)$id)->isLessThan(0);\n }\n }", " public function dataTestTreeImport() {\n return [\n // input, name, completename, message\n [ [ ], '', '', 'missing name'],\n [ [ 'name' => ''], '', '', 'empty name'],\n [ [ 'name' => ' '], '', '', 'space name'],\n [ [ 'name' => ' a '], 'a', 'a', 'simple name'],\n [ [ 'name' => 'foo'], 'foo', 'foo', 'simple name'],\n [ [ 'completename' => 'foo > bar'], 'bar', 'foo > bar', 'two names'],\n [ [ 'completename' => ' '], '', '', 'only space'],\n [ [ 'completename' => '>'], '', '', 'only >'],\n [ [ 'completename' => ' > '], '', '', 'only > and spaces'],\n [ [ 'completename' => 'foo>bar'], 'bar', 'foo > bar', 'two names with no space'],\n [ [ 'completename' => '>foo>>bar>'], 'bar', 'foo > bar', 'two names with additional >'],\n [ [ 'completename' => ' foo > > bar > '], 'bar', 'foo > bar', 'two names with garbage'],\n ];\n }", " /**\n * @dataProvider dataTestTreeImport\n */\n public function testTreeImport($input, $result, $complete, $msg) {\n $input['entities_id'] = getItemByTypeName('Entity', '_test_root_entity', true);\n $id = \\Dropdown::import('Location', $input);\n if ($result) {\n $this->integer((int)$id, $msg)->isGreaterThan(0);\n $ut = new \\Location();\n $this->boolean($ut->getFromDB($id))->isTrue();\n $this->string($ut->getField('name'))->isIdenticalTo($result);\n $this->string($ut->getField('completename'))->isIdenticalTo($complete);\n } else {\n $this->integer((int)$id)->isLessThanOrEqualTo(0);\n }\n }", " public function testGetDropdownName() {\n global $CFG_GLPI;", " $ret = \\Dropdown::getDropdownName('not_a_known_table', 1);\n $this->string($ret)->isIdenticalTo('&nbsp;');", " $cat = getItemByTypeName('TaskCategory', '_cat_1');", " $subCat = getItemByTypeName('TaskCategory', '_subcat_1');", " // basic test returns string only\n $expected = $cat->fields['name'].\" > \".$subCat->fields['name'];\n $ret = \\Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $cat->fields['name'].\" > \".$subCat->fields['name'],\n 'comment' => \"<span class='b'>Complete name</span>: \".$cat->fields['name'].\" > \"\n .$subCat->fields['name'].\"<br><span class='b'>&nbsp;Comments&nbsp;</span>\"\n .$subCat->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_taskcategories', $subCat->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $cat->fields['name'].\" > \".$subCat->fields['name'],\n 'comment' => $subCat->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_taskcategories', $subCat->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return with translations\n $CFG_GLPI['translate_dropdowns'] = 1;\n $_SESSION[\"glpilanguage\"] = \\Session::loadLanguage( 'fr_FR' );\n $_SESSION['glpi_dropdowntranslations'] = \\DropdownTranslation::getAvailableTranslations($_SESSION[\"glpilanguage\"]);\n $expected = ['name' => 'FR - _cat_1 > FR - _subcat_1',\n 'comment' => 'FR - Commentaire pour sous-catégorie _subcat_1'];\n $ret = \\Dropdown::getDropdownName( 'glpi_taskcategories', $subCat->getID(), true, true, false );\n // switch back to default language\n $_SESSION[\"glpilanguage\"] = \\Session::loadLanguage('en_GB');\n $this->array($ret)->isIdenticalTo($expected);", " ////////////////////////////////\n // test for other dropdown types\n ////////////////////////////////", " ///////////\n // Computer\n $computer = getItemByTypeName( 'Computer', '_test_pc01' );\n $ret = \\Dropdown::getDropdownName( 'glpi_computers', $computer->getID());\n $this->string($ret)->isIdenticalTo($computer->getName());", " $expected = ['name' => $computer->getName(),\n 'comment' => $computer->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_computers', $computer->getID(), true);\n $this->array($ret)->isIdenticalTo($expected);", " //////////\n // Contact\n $contact = getItemByTypeName( 'Contact', '_contact01_name' );\n $expected = $contact->getName();\n $ret = \\Dropdown::getDropdownName( 'glpi_contacts', $contact->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $contact->getName(),\n 'comment' => \"Comment for contact _contact01_name<br><span class='b'>\".\n \"Phone: </span>0123456789<br><span class='b'>Phone 2: </span>0123456788<br><span class='b'>\".\n \"Mobile phone: </span>0623456789<br><span class='b'>Fax: </span>0123456787<br>\".\n \"<span class='b'>Email: </span>_contact01_firstname._contact01_name@glpi.com\"];\n $ret = \\Dropdown::getDropdownName( 'glpi_contacts', $contact->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $contact->getName(),\n 'comment' => $contact->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_contacts', $contact->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " ///////////\n // Supplier\n $supplier = getItemByTypeName( 'Supplier', '_suplier01_name' );\n $expected = $supplier->getName();\n $ret = \\Dropdown::getDropdownName( 'glpi_suppliers', $supplier->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $supplier->getName(),\n 'comment' => \"Comment for supplier _suplier01_name<br><span class='b'>Phone: </span>0123456789<br>\".\n \"<span class='b'>Fax: </span>0123456787<br><span class='b'>Email: </span>info@_supplier01_name.com\"];\n $ret = \\Dropdown::getDropdownName( 'glpi_suppliers', $supplier->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $supplier->getName(),\n 'comment' => $supplier->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_suppliers', $supplier->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " ///////////\n // Netpoint\n $netpoint = getItemByTypeName( 'Netpoint', '_netpoint01' );\n $location = getItemByTypeName( 'Location', '_location01' );\n $expected = $netpoint->getName().\" (\".$location->getName().\")\";\n $ret = \\Dropdown::getDropdownName( 'glpi_netpoints', $netpoint->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $expected,\n 'comment' => \"Comment for netpoint _netpoint01\"];\n $ret = \\Dropdown::getDropdownName( 'glpi_netpoints', $netpoint->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $ret = \\Dropdown::getDropdownName( 'glpi_netpoints', $netpoint->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " ///////////\n // Budget\n $budget = getItemByTypeName( 'Budget', '_budget01' );\n $expected = $budget->getName();\n $ret = \\Dropdown::getDropdownName( 'glpi_budgets', $budget->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $budget->getName(),\n 'comment' => \"Comment for budget _budget01<br><span class='b'>Location</span>: \".\n \"_location01<br><span class='b'>Type</span>: _budgettype01<br><span class='b'>\".\n \"Start date</span>: 2016-10-18 <br><span class='b'>End date</span>: 2016-12-31 \"];\n $ret = \\Dropdown::getDropdownName( 'glpi_budgets', $budget->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $budget->getName(),\n 'comment' => $budget->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_budgets', $budget->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);\n }", " public function testGetDropdownNetpoint() {\n $netpoint = getItemByTypeName( 'Netpoint', '_netpoint01' );\n $location = getItemByTypeName( 'Location', '_location01' );\n $ret = \\Dropdown::getDropdownNetpoint([], false);\n $this->array($ret)->hasKeys(['count', 'results'])->integer['count']->isIdenticalTo(1);\n $this->array($ret['results'])->isIdenticalTo([\n [\n 'id' => 0,\n 'text' => '-----'\n ], [\n 'id' => $netpoint->fields['id'],\n 'text' => $netpoint->getName() . ' (' . $location->getName() . ')',\n 'title' => $netpoint->getName() . ' - ' . $location->getName() . ' - ' . $netpoint->fields['comment']\n ]\n ]);\n }", " public function dataGetValueWithUnit() {\n return [\n [1, 'auto', '1024 Kio'],\n [1025, 'auto', '1 Gio'],\n ['1 025', 'auto', '1 Gio'],\n [1, 'year', '1 year'],\n [2, 'year', '2 years'],\n [3, '%', '3%'],\n ['foo', 'bar', 'foo bar'],\n [1, 'month', '1 month'],\n [2, 'month', '2 months'],\n ['any', '', 'any'],\n [1, 'day', '1 day'],\n [2, 'day', '2 days'],\n [1, 'hour', '1 hour'],\n [2, 'hour', '2 hours'],\n [1, 'minute', '1 minute'],\n [2, 'minute', '2 minutes'],\n [1, 'second', '1 second'],\n [2, 'second', '2 seconds'],\n [1, 'millisecond', '1 millisecond'],\n [2, 'millisecond', '2 milliseconds'],\n ];\n }", " /**\n * @dataProvider dataGetValueWithUnit\n */\n public function testGetValueWithUnit($input, $unit, $expected) {\n $this->string(\\Dropdown::getValueWithUnit($input, $unit))->isIdenticalTo($expected);\n }", " protected function getDropdownValueProvider() {\n return [\n [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 1,\n 'emptylabel' => 'EEEEEE',\n 'itemtype' => 'TaskCategory'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => 'EEEEEE'\n ],\n 1 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'used' => [getItemByTypeName('TaskCategory', '_cat_1', true)]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'Computer',\n 'entity_restrict' => getItemByTypeName('Entity', '_test_child_2', true)\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Computer', '_test_pc21', true),\n 'text' => '_test_pc21',\n 'title' => '_test_pc21',\n ],\n 1 => [\n 'id' => getItemByTypeName('Computer', '_test_pc22', true),\n 'text' => '_test_pc22',\n 'title' => '_test_pc22',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'Computer',\n 'entity_restrict' => '[' . getItemByTypeName('Entity', '_test_child_2', true) .']'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Computer', '_test_pc21', true),\n 'text' => '_test_pc21',\n 'title' => '_test_pc21',\n ],\n 1 => [\n 'id' => getItemByTypeName('Computer', '_test_pc22', true),\n 'text' => '_test_pc22',\n 'title' => '_test_pc22',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'Computer',\n 'entity_restrict' => getItemByTypeName('Entity', '_test_child_2', true),\n 'searchText' => '22'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Computer', '_test_pc22', true),\n 'text' => '_test_pc22',\n 'title' => '_test_pc22',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat',\n 'toadd' => ['key' => 'value']\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 'key',\n 'text' => 'value'\n ],\n 1 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_cat_1 > _subcat_1',\n 'level' => 0,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ],\n 'session_params' => [\n 'glpiuse_flat_dropdowntree' => true\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 0,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_cat_1 > _subcat_1',\n 'level' => 0,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 2\n ],\n 'session_params' => [\n 'glpiuse_flat_dropdowntree' => true\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat',\n 'permit_select_parent' => true\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n // search using id on CommonTreeDropdown but without \"glpiis_ids_visible\" set to true -> no results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n ],\n 'expected' => [\n 'results' => [\n ],\n 'count' => 0\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => false\n ]\n ], [\n // search using id on CommonTreeDropdown with \"glpiis_ids_visible\" set to true -> results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1 (' . getItemByTypeName('TaskCategory', '_subcat_1', true) . ')',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => true\n ]\n ], [\n // search using id on \"not a CommonTreeDropdown\" but without \"glpiis_ids_visible\" set to true -> no results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'DocumentType',\n 'searchText' => getItemByTypeName('DocumentType', 'markdown', true),\n ],\n 'expected' => [\n 'results' => [\n ],\n 'count' => 0\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => false\n ]\n ], [\n // search using id on \"not a CommonTreeDropdown\" with \"glpiis_ids_visible\" set to true -> results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'DocumentType',\n 'searchText' => getItemByTypeName('DocumentType', 'markdown', true),\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => getItemByTypeName('DocumentType', 'markdown', true),\n 'text' => 'markdown (' . getItemByTypeName('DocumentType', 'markdown', true) . ')',\n 'title' => 'markdown',\n ]\n ],\n 'count' => 1\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => true\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'ComputerModel',\n ],\n 'expected' => [\n 'results' => [\n [\n 'id' => getItemByTypeName('ComputerModel', '_test_computermodel_1', true),\n 'text' => '_test_computermodel_1 - CMP_ADEAF5E1',\n 'title' => '_test_computermodel_1 - CMP_ADEAF5E1',\n ],\n [\n 'id' => getItemByTypeName('ComputerModel', '_test_computermodel_2', true),\n 'text' => '_test_computermodel_2 - CMP_567AEC68',\n 'title' => '_test_computermodel_2 - CMP_567AEC68',\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'ComputerModel',\n 'searchText' => 'CMP_56',\n ],\n 'expected' => [\n 'results' => [\n [\n 'id' => getItemByTypeName('ComputerModel', '_test_computermodel_2', true),\n 'text' => '_test_computermodel_2 - CMP_567AEC68',\n 'title' => '_test_computermodel_2 - CMP_567AEC68',\n ]\n ],\n 'count' => 1\n ]\n ],\n ];\n }", " /**\n * @dataProvider getDropdownValueProvider\n */\n public function testGetDropdownValue($params, $expected, $session_params = []) {\n $this->login();", " $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n", " $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');", "\n $result = \\Dropdown::getDropdownValue($params, false);", " //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }", " $this->array($result)->isIdenticalTo($expected);\n }", " protected function getDropdownConnectProvider() {\n return [\n [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_all', true),\n 'text' => '_test_printer_all',\n ],\n 1 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent0', true),\n 'text' => '_test_printer_ent0',\n ]\n ]\n ],\n 2 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_1',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent1', true),\n 'text' => '_test_printer_ent1',\n ]\n ]\n ],\n 3 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent2', true),\n 'text' => '_test_printer_ent2',\n ]\n ]\n ]\n ]\n ]\n ], [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer',\n 'used' => [\n 'Printer' => [\n getItemByTypeName('Printer', '_test_printer_ent0', true),\n getItemByTypeName('Printer', '_test_printer_ent2', true)\n ]\n ]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_all', true),\n 'text' => '_test_printer_all',\n ]\n ]\n ],\n 2 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_1',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent1', true),\n 'text' => '_test_printer_ent1',\n ]\n ]\n ]\n ]\n ]\n ], [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer',\n 'searchText' => 'ent0'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent0', true),\n 'text' => '_test_printer_ent0',\n ]\n ]\n ]\n ]\n ]\n ], [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer',\n 'searchText' => 'ent0'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent0', true),\n 'text' => '_test_printer_ent0 (' .getItemByTypeName('Printer', '_test_printer_ent0', true) . ')',\n ]\n ]\n ]\n ]\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => true\n ]\n ]\n ];\n }", " /**\n * @dataProvider getDropdownConnectProvider\n */\n public function testGetDropdownConnect($params, $expected, $session_params = []) {\n $this->login();", " $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n", " $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');", "\n $result = \\Dropdown::getDropdownConnect($params, false);", " //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }", " $this->array($result)->isIdenticalTo($expected);\n }", " protected function getDropdownNumberProvider() {\n return [\n [\n 'params' => [],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 1,\n 'text' => '1'\n ],\n 1 => [\n 'id' => 2,\n 'text' => '2'\n ],\n 2 => [\n 'id' => 3,\n 'text' => '3'\n ],\n 3 => [\n 'id' => 4,\n 'text' => '4'\n ],\n 4 => [\n 'id' => 5,\n 'text' => '5'\n ],\n 5 => [\n 'id' => 6,\n 'text' => '6'\n ],\n 6 => [\n 'id' => 7,\n 'text' => '7'\n ],\n 7 => [\n 'id' => 8,\n 'text' => '8'\n ],\n 8 => [\n 'id' => 9,\n 'text' => '9'\n ],\n 9 => [\n 'id' => 10,\n 'text' => '10'\n ]\n ],\n 'count' => 10\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 10,\n 'text' => '10'\n ],\n 1 => [\n 'id' => 20,\n 'text' => '20'\n ],\n 2 => [\n 'id' => 30,\n 'text' => '30'\n ]\n ],\n 'count' => 3\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10,\n 'used' => [20]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 10,\n 'text' => '10'\n ],\n 1 => [\n 'id' => 30,\n 'text' => '30'\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10,\n 'used' => [20],\n 'toadd' => [5 => 'five']\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 5,\n 'text' =>'five'\n ],\n 1 => [\n 'id' => 10,\n 'text' => '10'\n ],\n 2 => [\n 'id' => 30,\n 'text' => '30'\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10,\n 'used' => [20],\n 'unit' => 'second'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 10,\n 'text' => '10 seconds'\n ],\n 1 => [\n 'id' => 30,\n 'text' => '30 seconds'\n ]\n ],\n 'count' => 2\n ]\n ]\n ];\n }", " /**\n * @dataProvider getDropdownNumberProvider\n */\n public function testGetDropdownNumber($params, $expected) {\n global $CFG_GLPI;\n $orig_max = $CFG_GLPI['dropdown_max'];\n $CFG_GLPI['dropdown_max'] = 10;\n $result = \\Dropdown::getDropdownNumber($params, false);\n $CFG_GLPI['dropdown_max'] = $orig_max;\n $this->array($result)->isIdenticalTo($expected);\n }", " protected function getDropdownUsersProvider() {\n return [\n [\n 'params' => [],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'id' => (int)getItemByTypeName('User', '_test_user', true),\n 'text' => '_test_user',\n 'title' => '_test_user - _test_user',\n ],\n 2 => [\n 'id' => (int)getItemByTypeName('User', 'glpi', true),\n 'text' => 'glpi',\n 'title' => 'glpi - glpi',\n ],\n 3 => [\n 'id' => (int)getItemByTypeName('User', 'normal', true),\n 'text' => 'normal',\n 'title' => 'normal - normal',\n ],\n 4 => [\n 'id' => (int)getItemByTypeName('User', 'post-only', true),\n 'text' => 'post-only',\n 'title' => 'post-only - post-only',\n ],\n 5 => [\n 'id' => (int)getItemByTypeName('User', 'tech', true),\n 'text' => 'tech',\n 'title' => 'tech - tech',\n ]\n ],\n 'count' => 5\n ]\n ], [\n 'params' => [\n 'used' => [\n getItemByTypeName('User', 'glpi', true),\n getItemByTypeName('User', 'tech', true)\n ]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'id' => (int)getItemByTypeName('User', '_test_user', true),\n 'text' => '_test_user',\n 'title' => '_test_user - _test_user',\n ],\n 2 => [\n 'id' => (int)getItemByTypeName('User', 'normal', true),\n 'text' => 'normal',\n 'title' => 'normal - normal',\n ],\n 3 => [\n 'id' => (int)getItemByTypeName('User', 'post-only', true),\n 'text' => 'post-only',\n 'title' => 'post-only - post-only',\n ]\n ],\n 'count' => 3\n ]\n ], [\n 'params' => [\n 'all' => true,\n 'used' => [\n getItemByTypeName('User', 'glpi', true),\n getItemByTypeName('User', 'tech', true),\n getItemByTypeName('User', 'normal', true),\n getItemByTypeName('User', 'post-only', true)\n ]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => 'All',\n ],\n 1 => [\n 'id' => (int)getItemByTypeName('User', '_test_user', true),\n 'text' => '_test_user',\n 'title' => '_test_user - _test_user',\n ]\n ],\n 'count' => 1\n ]\n ]\n ];\n }", " /**\n * @dataProvider getDropdownUsersProvider\n */\n public function testGetDropdownUsers($params, $expected) {\n $this->login();", " $params['_idor_token'] = \\Session::getNewIDORToken('User');\n $result = \\Dropdown::getDropdownUsers($params, false);\n $this->array($result)->isIdenticalTo($expected);\n }", " /**\n * Test getDropdownValue with paginated results on\n * an CommonTreeDropdown\n *\n * @return void\n */\n public function testGetDropdownValuePaginate() {\n //let's add some content in Locations\n $location = new \\Location();\n for ($i = 0; $i <= 20; ++$i) {\n $this->integer(\n (int)$location->add([\n 'name' => \"Test location $i\"\n ])\n )->isGreaterThan(0);\n }", " $post = [\n 'itemtype' => $location::getType(),\n 'display_emptychoice' => true,\n 'entity_restrict' => 0,\n 'page' => 1,\n 'page_limit' => 10,\n '_idor_token' => \\Session::getNewIDORToken($location::getType())\n ];\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(10)\n ->array['results']\n ->hasSize(2);", " $results = (array)$values['results'];\n $this->array((array)$results[0])\n ->isIdenticalTo([\n 'id' => 0,\n 'text' => '-----'\n ]);", " $list_results = (array)$results[1];\n $this->array($list_results)\n ->hasSize(2)\n ->string['text']->isIdenticalTo('Root entity');", " $children = (array)$list_results['children'];\n $this->array($children)->hasSize(10);\n $this->array((array)$children[0])\n ->hasKeys([\n 'id',\n 'text',\n 'level',\n 'title',\n 'selection_text'\n ]);", " $post['page'] = 2;\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(10);", " $this->array($values['results'])->hasSize(10);\n $this->array((array)$values['results'][0])\n ->hasKeys([\n 'id',\n 'text',\n 'level',\n 'title',\n 'selection_text'\n ]);", " //use a array condition\n $post = [\n 'itemtype' => $location::getType(),\n 'condition' => ['name' => ['LIKE', \"%3%\"]],\n 'display_emptychoice' => true,\n 'entity_restrict' => 0,\n 'page' => 1,\n 'page_limit' => 10,\n '_idor_token' => \\Session::getNewIDORToken($location::getType())\n ];\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(2)\n ->array['results']\n ->hasSize(2);", " //use a string condition\n // Put condition in session and post its key\n $condition_key = sha1(serialize($post['condition']));\n $_SESSION['glpicondition'][$condition_key] = $post['condition'];\n $post['condition'] = $condition_key;\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(2)\n ->array['results']\n ->hasSize(2);", " //use a condition that does not exists in session\n $post = [\n 'itemtype' => $location::getType(),\n 'condition' => '`name` LIKE \"%4%\"',\n 'display_emptychoice' => true,\n 'entity_restrict' => 0,\n 'page' => 1,\n 'page_limit' => 10,\n '_idor_token' => \\Session::getNewIDORToken($location::getType())\n ];\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(10)\n ->array['results']\n ->hasSize(2);", " }", "", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n*/", "namespace tests\\units;", "use \\DbTestCase;", "/* Test for inc/dropdown.class.php */", "class Dropdown extends DbTestCase {", " public function testShowLanguages() {", " $opt = [ 'display_emptychoice' => true, 'display' => false ];\n $out = \\Dropdown::showLanguages('dropfoo', $opt);\n $this->string($out)\n ->contains(\"name='dropfoo'\")\n ->contains(\"value='' selected\")\n ->notContains(\"value='0'\")\n ->contains(\"value='fr_FR'\");", " $opt = ['display' => false, 'value' => 'cs_CZ', 'rand' => '1234'];\n $out = \\Dropdown::showLanguages('language', $opt);\n $this->string($out)\n ->notContains(\"value=''\")\n ->notContains(\"value='0'\")\n ->contains(\"name='language' id='dropdown_language1234\")\n ->contains(\"value='cs_CZ' selected\")\n ->contains(\"value='fr_FR'\");\n }", " public function dataTestImport() {\n return [\n // input, name, message\n [ [ ], '', 'missing name'],\n [ [ 'name' => ''], '', 'empty name'],\n [ [ 'name' => ' '], '', 'space name'],\n [ [ 'name' => ' a '], 'a', 'simple name'],\n [ [ 'name' => 'foo'], 'foo', 'simple name'],\n ];\n }", " /**\n * @dataProvider dataTestImport\n */\n public function testImport($input, $result, $msg) {\n $id = \\Dropdown::import('UserTitle', $input);\n if ($result) {\n $this->integer((int)$id)->isGreaterThan(0);\n $ut = new \\UserTitle();\n $this->boolean($ut->getFromDB($id))->isTrue();\n $this->string($ut->getField('name'))->isIdenticalTo($result);\n } else {\n $this->integer((int)$id)->isLessThan(0);\n }\n }", " public function dataTestTreeImport() {\n return [\n // input, name, completename, message\n [ [ ], '', '', 'missing name'],\n [ [ 'name' => ''], '', '', 'empty name'],\n [ [ 'name' => ' '], '', '', 'space name'],\n [ [ 'name' => ' a '], 'a', 'a', 'simple name'],\n [ [ 'name' => 'foo'], 'foo', 'foo', 'simple name'],\n [ [ 'completename' => 'foo > bar'], 'bar', 'foo > bar', 'two names'],\n [ [ 'completename' => ' '], '', '', 'only space'],\n [ [ 'completename' => '>'], '', '', 'only >'],\n [ [ 'completename' => ' > '], '', '', 'only > and spaces'],\n [ [ 'completename' => 'foo>bar'], 'bar', 'foo > bar', 'two names with no space'],\n [ [ 'completename' => '>foo>>bar>'], 'bar', 'foo > bar', 'two names with additional >'],\n [ [ 'completename' => ' foo > > bar > '], 'bar', 'foo > bar', 'two names with garbage'],\n ];\n }", " /**\n * @dataProvider dataTestTreeImport\n */\n public function testTreeImport($input, $result, $complete, $msg) {\n $input['entities_id'] = getItemByTypeName('Entity', '_test_root_entity', true);\n $id = \\Dropdown::import('Location', $input);\n if ($result) {\n $this->integer((int)$id, $msg)->isGreaterThan(0);\n $ut = new \\Location();\n $this->boolean($ut->getFromDB($id))->isTrue();\n $this->string($ut->getField('name'))->isIdenticalTo($result);\n $this->string($ut->getField('completename'))->isIdenticalTo($complete);\n } else {\n $this->integer((int)$id)->isLessThanOrEqualTo(0);\n }\n }", " public function testGetDropdownName() {\n global $CFG_GLPI;", " $ret = \\Dropdown::getDropdownName('not_a_known_table', 1);\n $this->string($ret)->isIdenticalTo('&nbsp;');", " $cat = getItemByTypeName('TaskCategory', '_cat_1');", " $subCat = getItemByTypeName('TaskCategory', '_subcat_1');", " // basic test returns string only\n $expected = $cat->fields['name'].\" > \".$subCat->fields['name'];\n $ret = \\Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $cat->fields['name'].\" > \".$subCat->fields['name'],\n 'comment' => \"<span class='b'>Complete name</span>: \".$cat->fields['name'].\" > \"\n .$subCat->fields['name'].\"<br><span class='b'>&nbsp;Comments&nbsp;</span>\"\n .$subCat->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_taskcategories', $subCat->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $cat->fields['name'].\" > \".$subCat->fields['name'],\n 'comment' => $subCat->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_taskcategories', $subCat->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return with translations\n $CFG_GLPI['translate_dropdowns'] = 1;\n $_SESSION[\"glpilanguage\"] = \\Session::loadLanguage( 'fr_FR' );\n $_SESSION['glpi_dropdowntranslations'] = \\DropdownTranslation::getAvailableTranslations($_SESSION[\"glpilanguage\"]);\n $expected = ['name' => 'FR - _cat_1 > FR - _subcat_1',\n 'comment' => 'FR - Commentaire pour sous-catégorie _subcat_1'];\n $ret = \\Dropdown::getDropdownName( 'glpi_taskcategories', $subCat->getID(), true, true, false );\n // switch back to default language\n $_SESSION[\"glpilanguage\"] = \\Session::loadLanguage('en_GB');\n $this->array($ret)->isIdenticalTo($expected);", " ////////////////////////////////\n // test for other dropdown types\n ////////////////////////////////", " ///////////\n // Computer\n $computer = getItemByTypeName( 'Computer', '_test_pc01' );\n $ret = \\Dropdown::getDropdownName( 'glpi_computers', $computer->getID());\n $this->string($ret)->isIdenticalTo($computer->getName());", " $expected = ['name' => $computer->getName(),\n 'comment' => $computer->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_computers', $computer->getID(), true);\n $this->array($ret)->isIdenticalTo($expected);", " //////////\n // Contact\n $contact = getItemByTypeName( 'Contact', '_contact01_name' );\n $expected = $contact->getName();\n $ret = \\Dropdown::getDropdownName( 'glpi_contacts', $contact->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $contact->getName(),\n 'comment' => \"Comment for contact _contact01_name<br><span class='b'>\".\n \"Phone: </span>0123456789<br><span class='b'>Phone 2: </span>0123456788<br><span class='b'>\".\n \"Mobile phone: </span>0623456789<br><span class='b'>Fax: </span>0123456787<br>\".\n \"<span class='b'>Email: </span>_contact01_firstname._contact01_name@glpi.com\"];\n $ret = \\Dropdown::getDropdownName( 'glpi_contacts', $contact->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $contact->getName(),\n 'comment' => $contact->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_contacts', $contact->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " ///////////\n // Supplier\n $supplier = getItemByTypeName( 'Supplier', '_suplier01_name' );\n $expected = $supplier->getName();\n $ret = \\Dropdown::getDropdownName( 'glpi_suppliers', $supplier->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $supplier->getName(),\n 'comment' => \"Comment for supplier _suplier01_name<br><span class='b'>Phone: </span>0123456789<br>\".\n \"<span class='b'>Fax: </span>0123456787<br><span class='b'>Email: </span>info@_supplier01_name.com\"];\n $ret = \\Dropdown::getDropdownName( 'glpi_suppliers', $supplier->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $supplier->getName(),\n 'comment' => $supplier->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_suppliers', $supplier->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " ///////////\n // Netpoint\n $netpoint = getItemByTypeName( 'Netpoint', '_netpoint01' );\n $location = getItemByTypeName( 'Location', '_location01' );\n $expected = $netpoint->getName().\" (\".$location->getName().\")\";\n $ret = \\Dropdown::getDropdownName( 'glpi_netpoints', $netpoint->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $expected,\n 'comment' => \"Comment for netpoint _netpoint01\"];\n $ret = \\Dropdown::getDropdownName( 'glpi_netpoints', $netpoint->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $ret = \\Dropdown::getDropdownName( 'glpi_netpoints', $netpoint->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);", " ///////////\n // Budget\n $budget = getItemByTypeName( 'Budget', '_budget01' );\n $expected = $budget->getName();\n $ret = \\Dropdown::getDropdownName( 'glpi_budgets', $budget->getID());\n $this->string($ret)->isIdenticalTo($expected);", " // test of return with comments\n $expected = ['name' => $budget->getName(),\n 'comment' => \"Comment for budget _budget01<br><span class='b'>Location</span>: \".\n \"_location01<br><span class='b'>Type</span>: _budgettype01<br><span class='b'>\".\n \"Start date</span>: 2016-10-18 <br><span class='b'>End date</span>: 2016-12-31 \"];\n $ret = \\Dropdown::getDropdownName( 'glpi_budgets', $budget->getID(), true );\n $this->array($ret)->isIdenticalTo($expected);", " // test of return without $tooltip\n $expected = ['name' => $budget->getName(),\n 'comment' => $budget->fields['comment']];\n $ret = \\Dropdown::getDropdownName( 'glpi_budgets', $budget->getID(), true, true, false );\n $this->array($ret)->isIdenticalTo($expected);\n }", " public function testGetDropdownNetpoint() {\n $netpoint = getItemByTypeName( 'Netpoint', '_netpoint01' );\n $location = getItemByTypeName( 'Location', '_location01' );\n $ret = \\Dropdown::getDropdownNetpoint([], false);\n $this->array($ret)->hasKeys(['count', 'results'])->integer['count']->isIdenticalTo(1);\n $this->array($ret['results'])->isIdenticalTo([\n [\n 'id' => 0,\n 'text' => '-----'\n ], [\n 'id' => $netpoint->fields['id'],\n 'text' => $netpoint->getName() . ' (' . $location->getName() . ')',\n 'title' => $netpoint->getName() . ' - ' . $location->getName() . ' - ' . $netpoint->fields['comment']\n ]\n ]);\n }", " public function dataGetValueWithUnit() {\n return [\n [1, 'auto', '1024 Kio'],\n [1025, 'auto', '1 Gio'],\n ['1 025', 'auto', '1 Gio'],\n [1, 'year', '1 year'],\n [2, 'year', '2 years'],\n [3, '%', '3%'],\n ['foo', 'bar', 'foo bar'],\n [1, 'month', '1 month'],\n [2, 'month', '2 months'],\n ['any', '', 'any'],\n [1, 'day', '1 day'],\n [2, 'day', '2 days'],\n [1, 'hour', '1 hour'],\n [2, 'hour', '2 hours'],\n [1, 'minute', '1 minute'],\n [2, 'minute', '2 minutes'],\n [1, 'second', '1 second'],\n [2, 'second', '2 seconds'],\n [1, 'millisecond', '1 millisecond'],\n [2, 'millisecond', '2 milliseconds'],\n ];\n }", " /**\n * @dataProvider dataGetValueWithUnit\n */\n public function testGetValueWithUnit($input, $unit, $expected) {\n $this->string(\\Dropdown::getValueWithUnit($input, $unit))->isIdenticalTo($expected);\n }", " protected function getDropdownValueProvider() {\n return [\n [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 1,\n 'emptylabel' => 'EEEEEE',\n 'itemtype' => 'TaskCategory'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => 'EEEEEE'\n ],\n 1 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'used' => [getItemByTypeName('TaskCategory', '_cat_1', true)]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'Computer',\n 'entity_restrict' => getItemByTypeName('Entity', '_test_child_2', true)\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Computer', '_test_pc21', true),\n 'text' => '_test_pc21',\n 'title' => '_test_pc21',\n ],\n 1 => [\n 'id' => getItemByTypeName('Computer', '_test_pc22', true),\n 'text' => '_test_pc22',\n 'title' => '_test_pc22',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'Computer',\n 'entity_restrict' => '[' . getItemByTypeName('Entity', '_test_child_2', true) .']'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Computer', '_test_pc21', true),\n 'text' => '_test_pc21',\n 'title' => '_test_pc21',\n ],\n 1 => [\n 'id' => getItemByTypeName('Computer', '_test_pc22', true),\n 'text' => '_test_pc22',\n 'title' => '_test_pc22',\n ]\n ]\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'Computer',\n 'entity_restrict' => getItemByTypeName('Entity', '_test_child_2', true),\n 'searchText' => '22'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Computer', '_test_pc22', true),\n 'text' => '_test_pc22',\n 'title' => '_test_pc22',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat',\n 'toadd' => ['key' => 'value']\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 'key',\n 'text' => 'value'\n ],\n 1 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_cat_1 > _subcat_1',\n 'level' => 0,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ],\n 'session_params' => [\n 'glpiuse_flat_dropdowntree' => true\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 0,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_cat_1 > _subcat_1',\n 'level' => 0,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 2\n ],\n 'session_params' => [\n 'glpiuse_flat_dropdowntree' => true\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => 'subcat',\n 'permit_select_parent' => true\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'title' => '_cat_1 - Comment for category _cat_1',\n 'selection_text' => '_cat_1',\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ]\n ], [\n // search using id on CommonTreeDropdown but without \"glpiis_ids_visible\" set to true -> no results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n ],\n 'expected' => [\n 'results' => [\n ],\n 'count' => 0\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => false\n ]\n ], [\n // search using id on CommonTreeDropdown with \"glpiis_ids_visible\" set to true -> results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'TaskCategory',\n 'searchText' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('TaskCategory', '_cat_1', true),\n 'text' => '_cat_1',\n 'level' => 1,\n 'disabled' => true\n ],\n 1 => [\n 'id' => getItemByTypeName('TaskCategory', '_subcat_1', true),\n 'text' => '_subcat_1 (' . getItemByTypeName('TaskCategory', '_subcat_1', true) . ')',\n 'level' => 2,\n 'title' => '_cat_1 > _subcat_1 - Comment for sub-category _subcat_1',\n 'selection_text' => '_cat_1 > _subcat_1',\n ]\n ]\n ]\n ],\n 'count' => 1\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => true\n ]\n ], [\n // search using id on \"not a CommonTreeDropdown\" but without \"glpiis_ids_visible\" set to true -> no results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'DocumentType',\n 'searchText' => getItemByTypeName('DocumentType', 'markdown', true),\n ],\n 'expected' => [\n 'results' => [\n ],\n 'count' => 0\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => false\n ]\n ], [\n // search using id on \"not a CommonTreeDropdown\" with \"glpiis_ids_visible\" set to true -> results\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'DocumentType',\n 'searchText' => getItemByTypeName('DocumentType', 'markdown', true),\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => getItemByTypeName('DocumentType', 'markdown', true),\n 'text' => 'markdown (' . getItemByTypeName('DocumentType', 'markdown', true) . ')',\n 'title' => 'markdown',\n ]\n ],\n 'count' => 1\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => true\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'ComputerModel',\n ],\n 'expected' => [\n 'results' => [\n [\n 'id' => getItemByTypeName('ComputerModel', '_test_computermodel_1', true),\n 'text' => '_test_computermodel_1 - CMP_ADEAF5E1',\n 'title' => '_test_computermodel_1 - CMP_ADEAF5E1',\n ],\n [\n 'id' => getItemByTypeName('ComputerModel', '_test_computermodel_2', true),\n 'text' => '_test_computermodel_2 - CMP_567AEC68',\n 'title' => '_test_computermodel_2 - CMP_567AEC68',\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'display_emptychoice' => 0,\n 'itemtype' => 'ComputerModel',\n 'searchText' => 'CMP_56',\n ],\n 'expected' => [\n 'results' => [\n [\n 'id' => getItemByTypeName('ComputerModel', '_test_computermodel_2', true),\n 'text' => '_test_computermodel_2 - CMP_567AEC68',\n 'title' => '_test_computermodel_2 - CMP_567AEC68',\n ]\n ],\n 'count' => 1\n ]\n ],\n ];\n }", " /**\n * @dataProvider getDropdownValueProvider\n */\n public function testGetDropdownValue($params, $expected, $session_params = []) {\n $this->login();", " $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n", " $params['_idor_token'] = $this->generateIdor($params);", "\n $result = \\Dropdown::getDropdownValue($params, false);", " //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }", " $this->array($result)->isIdenticalTo($expected);\n }", " protected function getDropdownConnectProvider() {\n return [\n [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_all', true),\n 'text' => '_test_printer_all',\n ],\n 1 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent0', true),\n 'text' => '_test_printer_ent0',\n ]\n ]\n ],\n 2 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_1',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent1', true),\n 'text' => '_test_printer_ent1',\n ]\n ]\n ],\n 3 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_2',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent2', true),\n 'text' => '_test_printer_ent2',\n ]\n ]\n ]\n ]\n ]\n ], [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer',\n 'used' => [\n 'Printer' => [\n getItemByTypeName('Printer', '_test_printer_ent0', true),\n getItemByTypeName('Printer', '_test_printer_ent2', true)\n ]\n ]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_all', true),\n 'text' => '_test_printer_all',\n ]\n ]\n ],\n 2 => [\n 'text' => 'Root entity > _test_root_entity > _test_child_1',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent1', true),\n 'text' => '_test_printer_ent1',\n ]\n ]\n ]\n ]\n ]\n ], [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer',\n 'searchText' => 'ent0'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent0', true),\n 'text' => '_test_printer_ent0',\n ]\n ]\n ]\n ]\n ]\n ], [\n 'params' => [\n 'fromtype' => 'Computer',\n 'itemtype' => 'Printer',\n 'searchText' => 'ent0'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'text' => 'Root entity > _test_root_entity',\n 'children' => [\n 0 => [\n 'id' => getItemByTypeName('Printer', '_test_printer_ent0', true),\n 'text' => '_test_printer_ent0 (' .getItemByTypeName('Printer', '_test_printer_ent0', true) . ')',\n ]\n ]\n ]\n ]\n ],\n 'session_params' => [\n 'glpiis_ids_visible' => true\n ]\n ]\n ];\n }", " /**\n * @dataProvider getDropdownConnectProvider\n */\n public function testGetDropdownConnect($params, $expected, $session_params = []) {\n $this->login();", " $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n", " $params['_idor_token'] = $this->generateIdor($params);", "\n $result = \\Dropdown::getDropdownConnect($params, false);", " //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }", " $this->array($result)->isIdenticalTo($expected);\n }", " protected function getDropdownNumberProvider() {\n return [\n [\n 'params' => [],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 1,\n 'text' => '1'\n ],\n 1 => [\n 'id' => 2,\n 'text' => '2'\n ],\n 2 => [\n 'id' => 3,\n 'text' => '3'\n ],\n 3 => [\n 'id' => 4,\n 'text' => '4'\n ],\n 4 => [\n 'id' => 5,\n 'text' => '5'\n ],\n 5 => [\n 'id' => 6,\n 'text' => '6'\n ],\n 6 => [\n 'id' => 7,\n 'text' => '7'\n ],\n 7 => [\n 'id' => 8,\n 'text' => '8'\n ],\n 8 => [\n 'id' => 9,\n 'text' => '9'\n ],\n 9 => [\n 'id' => 10,\n 'text' => '10'\n ]\n ],\n 'count' => 10\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 10,\n 'text' => '10'\n ],\n 1 => [\n 'id' => 20,\n 'text' => '20'\n ],\n 2 => [\n 'id' => 30,\n 'text' => '30'\n ]\n ],\n 'count' => 3\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10,\n 'used' => [20]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 10,\n 'text' => '10'\n ],\n 1 => [\n 'id' => 30,\n 'text' => '30'\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10,\n 'used' => [20],\n 'toadd' => [5 => 'five']\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 5,\n 'text' =>'five'\n ],\n 1 => [\n 'id' => 10,\n 'text' => '10'\n ],\n 2 => [\n 'id' => 30,\n 'text' => '30'\n ]\n ],\n 'count' => 2\n ]\n ], [\n 'params' => [\n 'min' => 10,\n 'max' => 30,\n 'step' => 10,\n 'used' => [20],\n 'unit' => 'second'\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 10,\n 'text' => '10 seconds'\n ],\n 1 => [\n 'id' => 30,\n 'text' => '30 seconds'\n ]\n ],\n 'count' => 2\n ]\n ]\n ];\n }", " /**\n * @dataProvider getDropdownNumberProvider\n */\n public function testGetDropdownNumber($params, $expected) {\n global $CFG_GLPI;\n $orig_max = $CFG_GLPI['dropdown_max'];\n $CFG_GLPI['dropdown_max'] = 10;\n $result = \\Dropdown::getDropdownNumber($params, false);\n $CFG_GLPI['dropdown_max'] = $orig_max;\n $this->array($result)->isIdenticalTo($expected);\n }", " protected function getDropdownUsersProvider() {\n return [\n [\n 'params' => [],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'id' => (int)getItemByTypeName('User', '_test_user', true),\n 'text' => '_test_user',\n 'title' => '_test_user - _test_user',\n ],\n 2 => [\n 'id' => (int)getItemByTypeName('User', 'glpi', true),\n 'text' => 'glpi',\n 'title' => 'glpi - glpi',\n ],\n 3 => [\n 'id' => (int)getItemByTypeName('User', 'normal', true),\n 'text' => 'normal',\n 'title' => 'normal - normal',\n ],\n 4 => [\n 'id' => (int)getItemByTypeName('User', 'post-only', true),\n 'text' => 'post-only',\n 'title' => 'post-only - post-only',\n ],\n 5 => [\n 'id' => (int)getItemByTypeName('User', 'tech', true),\n 'text' => 'tech',\n 'title' => 'tech - tech',\n ]\n ],\n 'count' => 5\n ]\n ], [\n 'params' => [\n 'used' => [\n getItemByTypeName('User', 'glpi', true),\n getItemByTypeName('User', 'tech', true)\n ]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => '-----',\n ],\n 1 => [\n 'id' => (int)getItemByTypeName('User', '_test_user', true),\n 'text' => '_test_user',\n 'title' => '_test_user - _test_user',\n ],\n 2 => [\n 'id' => (int)getItemByTypeName('User', 'normal', true),\n 'text' => 'normal',\n 'title' => 'normal - normal',\n ],\n 3 => [\n 'id' => (int)getItemByTypeName('User', 'post-only', true),\n 'text' => 'post-only',\n 'title' => 'post-only - post-only',\n ]\n ],\n 'count' => 3\n ]\n ], [\n 'params' => [\n 'all' => true,\n 'used' => [\n getItemByTypeName('User', 'glpi', true),\n getItemByTypeName('User', 'tech', true),\n getItemByTypeName('User', 'normal', true),\n getItemByTypeName('User', 'post-only', true)\n ]\n ],\n 'expected' => [\n 'results' => [\n 0 => [\n 'id' => 0,\n 'text' => 'All',\n ],\n 1 => [\n 'id' => (int)getItemByTypeName('User', '_test_user', true),\n 'text' => '_test_user',\n 'title' => '_test_user - _test_user',\n ]\n ],\n 'count' => 1\n ]\n ]\n ];\n }", " /**\n * @dataProvider getDropdownUsersProvider\n */\n public function testGetDropdownUsers($params, $expected) {\n $this->login();", " $params['_idor_token'] = \\Session::getNewIDORToken('User');\n $result = \\Dropdown::getDropdownUsers($params, false);\n $this->array($result)->isIdenticalTo($expected);\n }", " /**\n * Test getDropdownValue with paginated results on\n * an CommonTreeDropdown\n *\n * @return void\n */\n public function testGetDropdownValuePaginate() {\n //let's add some content in Locations\n $location = new \\Location();\n for ($i = 0; $i <= 20; ++$i) {\n $this->integer(\n (int)$location->add([\n 'name' => \"Test location $i\"\n ])\n )->isGreaterThan(0);\n }", " $post = [\n 'itemtype' => $location::getType(),\n 'display_emptychoice' => true,\n 'entity_restrict' => 0,\n 'page' => 1,\n 'page_limit' => 10,\n '_idor_token' => \\Session::getNewIDORToken($location::getType())\n ];\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(10)\n ->array['results']\n ->hasSize(2);", " $results = (array)$values['results'];\n $this->array((array)$results[0])\n ->isIdenticalTo([\n 'id' => 0,\n 'text' => '-----'\n ]);", " $list_results = (array)$results[1];\n $this->array($list_results)\n ->hasSize(2)\n ->string['text']->isIdenticalTo('Root entity');", " $children = (array)$list_results['children'];\n $this->array($children)->hasSize(10);\n $this->array((array)$children[0])\n ->hasKeys([\n 'id',\n 'text',\n 'level',\n 'title',\n 'selection_text'\n ]);", " $post['page'] = 2;\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(10);", " $this->array($values['results'])->hasSize(10);\n $this->array((array)$values['results'][0])\n ->hasKeys([\n 'id',\n 'text',\n 'level',\n 'title',\n 'selection_text'\n ]);", " //use a array condition\n $post = [\n 'itemtype' => $location::getType(),\n 'condition' => ['name' => ['LIKE', \"%3%\"]],\n 'display_emptychoice' => true,\n 'entity_restrict' => 0,\n 'page' => 1,\n 'page_limit' => 10,\n '_idor_token' => \\Session::getNewIDORToken($location::getType())\n ];\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(2)\n ->array['results']\n ->hasSize(2);", " //use a string condition\n // Put condition in session and post its key\n $condition_key = sha1(serialize($post['condition']));\n $_SESSION['glpicondition'][$condition_key] = $post['condition'];\n $post['condition'] = $condition_key;\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(2)\n ->array['results']\n ->hasSize(2);", " //use a condition that does not exists in session\n $post = [\n 'itemtype' => $location::getType(),\n 'condition' => '`name` LIKE \"%4%\"',\n 'display_emptychoice' => true,\n 'entity_restrict' => 0,\n 'page' => 1,\n 'page_limit' => 10,\n '_idor_token' => \\Session::getNewIDORToken($location::getType())\n ];\n $values = \\Dropdown::getDropdownValue($post);\n $values = (array)json_decode($values);", " $this->array($values)\n ->integer['count']->isEqualTo(10)\n ->array['results']\n ->hasSize(2);", " }", "\n private function generateIdor(array $params = []) {\n $idor_add_params = [];\n if (isset($params['entity_restrict'])) {\n $idor_add_params['entity_restrict'] = $params['entity_restrict'];\n }\n return \\Session::getNewIDORToken(($params['itemtype'] ?? ''), $idor_add_params);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n*/", "namespace tests\\units;", "/* Test for inc/session.class.php */", "class Session extends \\DbTestCase {", " public function testAddMessageAfterRedirect() {\n $err_msg = 'Something is broken. Weird.';\n $warn_msg = 'There was a warning. Be carefull.';\n $info_msg = 'All goes well. Or not... Who knows ;)';", " $this->array($_SESSION)->notHasKey('MESSAGE_AFTER_REDIRECT');", " //test add message in cron mode\n $_SESSION['glpicronuserrunning'] = 'cron_phpunit';\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n //adding a message in \"cron mode\" does not add anything in the session\n $this->array($_SESSION)->notHasKey('MESSAGE_AFTER_REDIRECT');", " //set not running from cron\n unset($_SESSION['glpicronuserrunning']);", " //test all messages types\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($warn_msg, false, WARNING);\n \\Session::addMessageAfterRedirect($info_msg, false, INFO);", " $expected = [\n ERROR => [$err_msg],\n WARNING => [$warn_msg],\n INFO => [$info_msg]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )\n ->matches('/' . str_replace('.', '\\.', $err_msg) . '/')\n ->matches('/' . str_replace('.', '\\.', $warn_msg) . '/')\n ->matches('/' . str_replace(['.', ')'], ['\\.', '\\)'], $info_msg) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();", " //test multiple messages of same type\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);", " $expected = [\n ERROR => [$err_msg, $err_msg, $err_msg]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )->matches('/' . str_replace('.', '\\.', $err_msg) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();", " //test message deduplication\n $err_msg_bis = $err_msg . ' not the same';\n \\Session::addMessageAfterRedirect($err_msg, true, ERROR);\n \\Session::addMessageAfterRedirect($err_msg_bis, true, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, true, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, true, ERROR);", " $expected = [\n ERROR => [$err_msg, $err_msg_bis]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )\n ->matches('/' . str_replace('.', '\\.', $err_msg) . '/')\n ->matches('/' . str_replace('.', '\\.', $err_msg_bis) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();", " //test with reset\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($warn_msg, false, WARNING);\n \\Session::addMessageAfterRedirect($info_msg, false, INFO, true);", " $expected = [\n INFO => [$info_msg]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )->matches('/' . str_replace(['.', ')'], ['\\.', '\\)'], $info_msg) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();\n }", " public function testLoadGroups() {", " $entid_root = getItemByTypeName('Entity', '_test_root_entity', true);\n $entid_1 = getItemByTypeName('Entity', '_test_child_1', true);\n $entid_2 = getItemByTypeName('Entity', '_test_child_2', true);", " $entities_ids = [$entid_root, $entid_1, $entid_2];", " $uid = (int)getItemByTypeName('User', 'normal', true);", " $group = new \\Group();\n $group_user = new \\Group_User();", " $user_groups = [];", " foreach ($entities_ids as $entid) {\n $group_1 = [\n 'name' => \"Test group {$entid} recursive=no\",\n 'entities_id' => $entid,\n 'is_recursive' => 0,\n ];\n $gid_1 = (int)$group->add($group_1);\n $this->integer($gid_1)->isGreaterThan(0);\n $this->integer((int)$group_user->add(['groups_id' => $gid_1, 'users_id' => $uid]))->isGreaterThan(0);\n $group_1['id'] = $gid_1;\n $user_groups[] = $group_1;", " $group_2 = [\n 'name' => \"Test group {$entid} recursive=yes\",\n 'entities_id' => $entid,\n 'is_recursive' => 1,\n ];\n $gid_2 = (int)$group->add($group_2);\n $this->integer($gid_2)->isGreaterThan(0);\n $this->integer((int)$group_user->add(['groups_id' => $gid_2, 'users_id' => $uid]))->isGreaterThan(0);\n $group_2['id'] = $gid_2;\n $user_groups[] = $group_2;", " $group_3 = [\n 'name' => \"Test group {$entid} not attached to user\",\n 'entities_id' => $entid,\n 'is_recursive' => 1,\n ];\n $gid_3 = (int)$group->add($group_3);\n $this->integer($gid_3)->isGreaterThan(0);\n }", " $this->login('normal', 'normal');", " // Test groups from whole entity tree\n $session_backup = $_SESSION;\n $_SESSION['glpiactiveentities'] = $entities_ids;\n \\Session::loadGroups();\n $groups = $_SESSION['glpigroups'];\n $_SESSION = $session_backup;\n $expected_groups = array_map(\n function ($group) {\n return (string)$group['id'];\n },\n $user_groups\n );\n $this->array($groups)->isEqualTo($expected_groups);", " foreach ($entities_ids as $entid) {\n // Test groups from a given entity\n $expected_groups = [];\n foreach ($user_groups as $user_group) {\n if (($user_group['entities_id'] == $entid_root && $user_group['is_recursive'] == 1)\n || $user_group['entities_id'] == $entid) {\n $expected_groups[] = (string)$user_group['id'];\n }\n }", " $session_backup = $_SESSION;\n $_SESSION['glpiactiveentities'] = [$entid];\n \\Session::loadGroups();\n $groups = $_SESSION['glpigroups'];\n $_SESSION = $session_backup;\n $this->array($groups)->isEqualTo($expected_groups);\n }\n }", " public function testLocalI18n() {\n //load locales\n \\Session::loadLanguage('en_GB');\n $this->string(__('Login'))->isIdenticalTo('Login');", " //create directory for local i18n\n if (!file_exists(GLPI_LOCAL_I18N_DIR.'/core')) {\n mkdir(GLPI_LOCAL_I18N_DIR.'/core');\n }", " //write local MO file with i18n override\n copy(\n __DIR__ . '/../local_en_GB.mo',\n GLPI_LOCAL_I18N_DIR.'/core/en_GB.mo'\n );\n \\Session::loadLanguage('en_GB');", " $this->string(__('Login'))->isIdenticalTo('Login from local gettext');\n $this->string(__('Password'))->isIdenticalTo('Password');", " //write local PHP file with i18n override\n file_put_contents(\n GLPI_LOCAL_I18N_DIR.'/core/en_GB.php',\n \"<?php\\n\\$lang['Login'] = 'Login from local PHP';\\n\\$lang['Password'] = 'Password from local PHP';\\nreturn \\$lang;\"\n );\n \\Session::loadLanguage('en_GB');", " $this->string(__('Login'))->isIdenticalTo('Login from local gettext');\n $this->string(__('Password'))->isIdenticalTo('Password from local PHP');", " //cleanup -- keep at the end\n unlink(GLPI_LOCAL_I18N_DIR.'/core/en_GB.php');\n unlink(GLPI_LOCAL_I18N_DIR.'/core/en_GB.mo');\n }", " protected function mustChangePasswordProvider() {\n $tests = [];", " // test with no password expiration\n $tests[] = [\n 'last_update' => date('Y-m-d H:i:s', strtotime('-10 years')),\n 'expiration_delay' => -1,\n 'expected_result' => false,\n ];", " // tests with password expiration\n $cases = [\n '-5 days' => false,\n '-30 days' => true,\n ];\n foreach ($cases as $last_update => $expected_result) {\n $tests[] = [\n 'last_update' => date('Y-m-d H:i:s', strtotime($last_update)),\n 'expiration_delay' => 15,\n 'expected_result' => $expected_result,\n ];\n }", " return $tests;\n }", " /**\n * @dataProvider mustChangePasswordProvider\n */\n public function testMustChangePassword(string $last_update, int $expiration_delay, bool $expected_result) {\n global $CFG_GLPI;", " $this->login();\n $user = new \\User();\n $username = 'test_must_change_pass_' . mt_rand();\n $user_id = (int)$user->add([\n 'name' => $username,\n 'password' => 'test',\n 'password2' => 'test',\n '_profiles_id' => 1,\n ]);\n $this->integer($user_id)->isGreaterThan(0);\n $this->boolean($user->update(['id' => $user_id, 'password_last_update' => $last_update]))->isTrue();", " $cfg_backup = $CFG_GLPI;\n $CFG_GLPI['password_expiration_delay'] = $expiration_delay;\n $CFG_GLPI['password_expiration_lock_delay'] = -1;\n \\Session::destroy();\n \\Session::start();\n $auth = new \\Auth();\n $is_logged = $auth->login($username, 'test', true);\n $CFG_GLPI = $cfg_backup;", " $this->boolean($is_logged)->isEqualTo(true);\n $this->boolean(\\Session::mustChangePassword())->isEqualTo($expected_result);\n }", " protected function preferredLanguageProvider() {\n return [\n [\n 'header' => null,\n 'config' => null,\n 'legacy_config' => null,\n 'expected' => 'en_GB',\n ],\n [\n 'header' => null,\n 'config' => null,\n 'legacy_config' => 'it_IT',\n 'expected' => 'it_IT',\n ],\n [\n 'header' => null,\n 'config' => 'de_DE',\n 'legacy_config' => null,\n 'expected' => 'de_DE',\n ],\n [\n 'header' => 'en-US',\n 'config' => 'fr_FR',\n 'legacy_config' => null,\n 'expected' => 'en_US',\n ],\n [\n // latin as first choice (not available in GLPI), should fallback to italian\n 'header' => 'la, it-IT;q=0.9, it;q=0.8',\n 'config' => 'en_GB',\n 'legacy_config' => null,\n 'expected' => 'it_IT',\n ],\n ];\n }", " /**\n * @dataProvider preferredLanguageProvider\n */\n public function testGetPreferredLanguage(?string $header, ?string $config, ?string $legacy_config, string $expected) {\n global $CFG_GLPI;", " $header_backup = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null;\n $cfg_backup = $CFG_GLPI;", " if ($header !== null) {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $header;\n }\n $CFG_GLPI['language'] = $config;\n $CFG_GLPI['default_language'] = $legacy_config;\n $result = \\Session::getPreferredLanguage();", " if ($header_backup !== null) {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $header_backup;\n }\n $CFG_GLPI = $cfg_backup;", " $this->string($result)->isEqualTo($expected);\n }", "\n protected function idorProvider() {\n return [\n ['itemtype' => 'Computer'],\n ['itemtype' => 'Ticket'],\n ['itemtype' => 'Glpi\\\\Dashboard\\\\Item'],\n ['itemtype' => 'User', 'add_params' => ['right' => 'all']],", "", " ];\n }", " /**\n * @dataProvider idorProvider\n */\n function testIDORToken(string $itemtype = \"\", array $add_params = []) {\n // generate token\n $token = \\Session::getNewIDORToken($itemtype, $add_params);\n $this->string($token)->hasLength(64);", " // token exists in session and is valid\n $this->array($_SESSION['glpiidortokens'][$token])\n ->string['itemtype']->isEqualTo($itemtype)\n ->string['expires'];", " if (count($add_params) > 0) {\n $this->array($_SESSION['glpiidortokens'][$token])->size->isEqualTo(2 + count($add_params));\n }", " // validate token with dedicated method\n $result = \\Session::validateIDOR([\n '_idor_token' => $token,\n 'itemtype' => $itemtype,\n ] + $add_params);\n $this->boolean($result)->isTrue();\n }", "\n function testDORInvalid() {\n // random token\n $result = \\Session::validateIDOR([\n '_idor_token' => bin2hex(random_bytes(32)),\n 'itemtype' => 'Computer',\n ]);\n $this->boolean($result)->isFalse();", " // bad itemtype\n $token_bad_itt = \\Session::getNewIDORToken('Ticket');\n $result = \\Session::validateIDOR([\n '_idor_token' => $token_bad_itt,\n 'itemtype' => 'Computer',\n ]);\n $this->boolean($result)->isFalse();", " // missing add params\n $token_miss_param = \\Session::getNewIDORToken('User', ['right' => 'all']);\n $result = \\Session::validateIDOR([\n '_idor_token' => $token_miss_param,\n 'itemtype' => 'User',\n ]);\n $this->boolean($result)->isFalse();\n $result = \\Session::validateIDOR([\n '_idor_token' => $token_miss_param,\n 'itemtype' => 'User',\n 'right' => 'all'\n ]);\n $this->boolean($result)->isTrue();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ---------------------------------------------------------------------\n * GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2015-2021 Teclib' and contributors.\n *\n * http://glpi-project.org\n *\n * based on GLPI - Gestionnaire Libre de Parc Informatique\n * Copyright (C) 2003-2014 by the INDEPNET Development Team.\n *\n * ---------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of GLPI.\n *\n * GLPI is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * GLPI is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GLPI. If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n*/", "namespace tests\\units;", "/* Test for inc/session.class.php */", "class Session extends \\DbTestCase {", " public function testAddMessageAfterRedirect() {\n $err_msg = 'Something is broken. Weird.';\n $warn_msg = 'There was a warning. Be carefull.';\n $info_msg = 'All goes well. Or not... Who knows ;)';", " $this->array($_SESSION)->notHasKey('MESSAGE_AFTER_REDIRECT');", " //test add message in cron mode\n $_SESSION['glpicronuserrunning'] = 'cron_phpunit';\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n //adding a message in \"cron mode\" does not add anything in the session\n $this->array($_SESSION)->notHasKey('MESSAGE_AFTER_REDIRECT');", " //set not running from cron\n unset($_SESSION['glpicronuserrunning']);", " //test all messages types\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($warn_msg, false, WARNING);\n \\Session::addMessageAfterRedirect($info_msg, false, INFO);", " $expected = [\n ERROR => [$err_msg],\n WARNING => [$warn_msg],\n INFO => [$info_msg]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )\n ->matches('/' . str_replace('.', '\\.', $err_msg) . '/')\n ->matches('/' . str_replace('.', '\\.', $warn_msg) . '/')\n ->matches('/' . str_replace(['.', ')'], ['\\.', '\\)'], $info_msg) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();", " //test multiple messages of same type\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);", " $expected = [\n ERROR => [$err_msg, $err_msg, $err_msg]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )->matches('/' . str_replace('.', '\\.', $err_msg) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();", " //test message deduplication\n $err_msg_bis = $err_msg . ' not the same';\n \\Session::addMessageAfterRedirect($err_msg, true, ERROR);\n \\Session::addMessageAfterRedirect($err_msg_bis, true, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, true, ERROR);\n \\Session::addMessageAfterRedirect($err_msg, true, ERROR);", " $expected = [\n ERROR => [$err_msg, $err_msg_bis]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )\n ->matches('/' . str_replace('.', '\\.', $err_msg) . '/')\n ->matches('/' . str_replace('.', '\\.', $err_msg_bis) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();", " //test with reset\n \\Session::addMessageAfterRedirect($err_msg, false, ERROR);\n \\Session::addMessageAfterRedirect($warn_msg, false, WARNING);\n \\Session::addMessageAfterRedirect($info_msg, false, INFO, true);", " $expected = [\n INFO => [$info_msg]\n ];\n $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expected);", " $this->output(\n function () {\n \\Html::displayMessageAfterRedirect();\n }\n )->matches('/' . str_replace(['.', ')'], ['\\.', '\\)'], $info_msg) . '/');", " $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty();\n }", " public function testLoadGroups() {", " $entid_root = getItemByTypeName('Entity', '_test_root_entity', true);\n $entid_1 = getItemByTypeName('Entity', '_test_child_1', true);\n $entid_2 = getItemByTypeName('Entity', '_test_child_2', true);", " $entities_ids = [$entid_root, $entid_1, $entid_2];", " $uid = (int)getItemByTypeName('User', 'normal', true);", " $group = new \\Group();\n $group_user = new \\Group_User();", " $user_groups = [];", " foreach ($entities_ids as $entid) {\n $group_1 = [\n 'name' => \"Test group {$entid} recursive=no\",\n 'entities_id' => $entid,\n 'is_recursive' => 0,\n ];\n $gid_1 = (int)$group->add($group_1);\n $this->integer($gid_1)->isGreaterThan(0);\n $this->integer((int)$group_user->add(['groups_id' => $gid_1, 'users_id' => $uid]))->isGreaterThan(0);\n $group_1['id'] = $gid_1;\n $user_groups[] = $group_1;", " $group_2 = [\n 'name' => \"Test group {$entid} recursive=yes\",\n 'entities_id' => $entid,\n 'is_recursive' => 1,\n ];\n $gid_2 = (int)$group->add($group_2);\n $this->integer($gid_2)->isGreaterThan(0);\n $this->integer((int)$group_user->add(['groups_id' => $gid_2, 'users_id' => $uid]))->isGreaterThan(0);\n $group_2['id'] = $gid_2;\n $user_groups[] = $group_2;", " $group_3 = [\n 'name' => \"Test group {$entid} not attached to user\",\n 'entities_id' => $entid,\n 'is_recursive' => 1,\n ];\n $gid_3 = (int)$group->add($group_3);\n $this->integer($gid_3)->isGreaterThan(0);\n }", " $this->login('normal', 'normal');", " // Test groups from whole entity tree\n $session_backup = $_SESSION;\n $_SESSION['glpiactiveentities'] = $entities_ids;\n \\Session::loadGroups();\n $groups = $_SESSION['glpigroups'];\n $_SESSION = $session_backup;\n $expected_groups = array_map(\n function ($group) {\n return (string)$group['id'];\n },\n $user_groups\n );\n $this->array($groups)->isEqualTo($expected_groups);", " foreach ($entities_ids as $entid) {\n // Test groups from a given entity\n $expected_groups = [];\n foreach ($user_groups as $user_group) {\n if (($user_group['entities_id'] == $entid_root && $user_group['is_recursive'] == 1)\n || $user_group['entities_id'] == $entid) {\n $expected_groups[] = (string)$user_group['id'];\n }\n }", " $session_backup = $_SESSION;\n $_SESSION['glpiactiveentities'] = [$entid];\n \\Session::loadGroups();\n $groups = $_SESSION['glpigroups'];\n $_SESSION = $session_backup;\n $this->array($groups)->isEqualTo($expected_groups);\n }\n }", " public function testLocalI18n() {\n //load locales\n \\Session::loadLanguage('en_GB');\n $this->string(__('Login'))->isIdenticalTo('Login');", " //create directory for local i18n\n if (!file_exists(GLPI_LOCAL_I18N_DIR.'/core')) {\n mkdir(GLPI_LOCAL_I18N_DIR.'/core');\n }", " //write local MO file with i18n override\n copy(\n __DIR__ . '/../local_en_GB.mo',\n GLPI_LOCAL_I18N_DIR.'/core/en_GB.mo'\n );\n \\Session::loadLanguage('en_GB');", " $this->string(__('Login'))->isIdenticalTo('Login from local gettext');\n $this->string(__('Password'))->isIdenticalTo('Password');", " //write local PHP file with i18n override\n file_put_contents(\n GLPI_LOCAL_I18N_DIR.'/core/en_GB.php',\n \"<?php\\n\\$lang['Login'] = 'Login from local PHP';\\n\\$lang['Password'] = 'Password from local PHP';\\nreturn \\$lang;\"\n );\n \\Session::loadLanguage('en_GB');", " $this->string(__('Login'))->isIdenticalTo('Login from local gettext');\n $this->string(__('Password'))->isIdenticalTo('Password from local PHP');", " //cleanup -- keep at the end\n unlink(GLPI_LOCAL_I18N_DIR.'/core/en_GB.php');\n unlink(GLPI_LOCAL_I18N_DIR.'/core/en_GB.mo');\n }", " protected function mustChangePasswordProvider() {\n $tests = [];", " // test with no password expiration\n $tests[] = [\n 'last_update' => date('Y-m-d H:i:s', strtotime('-10 years')),\n 'expiration_delay' => -1,\n 'expected_result' => false,\n ];", " // tests with password expiration\n $cases = [\n '-5 days' => false,\n '-30 days' => true,\n ];\n foreach ($cases as $last_update => $expected_result) {\n $tests[] = [\n 'last_update' => date('Y-m-d H:i:s', strtotime($last_update)),\n 'expiration_delay' => 15,\n 'expected_result' => $expected_result,\n ];\n }", " return $tests;\n }", " /**\n * @dataProvider mustChangePasswordProvider\n */\n public function testMustChangePassword(string $last_update, int $expiration_delay, bool $expected_result) {\n global $CFG_GLPI;", " $this->login();\n $user = new \\User();\n $username = 'test_must_change_pass_' . mt_rand();\n $user_id = (int)$user->add([\n 'name' => $username,\n 'password' => 'test',\n 'password2' => 'test',\n '_profiles_id' => 1,\n ]);\n $this->integer($user_id)->isGreaterThan(0);\n $this->boolean($user->update(['id' => $user_id, 'password_last_update' => $last_update]))->isTrue();", " $cfg_backup = $CFG_GLPI;\n $CFG_GLPI['password_expiration_delay'] = $expiration_delay;\n $CFG_GLPI['password_expiration_lock_delay'] = -1;\n \\Session::destroy();\n \\Session::start();\n $auth = new \\Auth();\n $is_logged = $auth->login($username, 'test', true);\n $CFG_GLPI = $cfg_backup;", " $this->boolean($is_logged)->isEqualTo(true);\n $this->boolean(\\Session::mustChangePassword())->isEqualTo($expected_result);\n }", " protected function preferredLanguageProvider() {\n return [\n [\n 'header' => null,\n 'config' => null,\n 'legacy_config' => null,\n 'expected' => 'en_GB',\n ],\n [\n 'header' => null,\n 'config' => null,\n 'legacy_config' => 'it_IT',\n 'expected' => 'it_IT',\n ],\n [\n 'header' => null,\n 'config' => 'de_DE',\n 'legacy_config' => null,\n 'expected' => 'de_DE',\n ],\n [\n 'header' => 'en-US',\n 'config' => 'fr_FR',\n 'legacy_config' => null,\n 'expected' => 'en_US',\n ],\n [\n // latin as first choice (not available in GLPI), should fallback to italian\n 'header' => 'la, it-IT;q=0.9, it;q=0.8',\n 'config' => 'en_GB',\n 'legacy_config' => null,\n 'expected' => 'it_IT',\n ],\n ];\n }", " /**\n * @dataProvider preferredLanguageProvider\n */\n public function testGetPreferredLanguage(?string $header, ?string $config, ?string $legacy_config, string $expected) {\n global $CFG_GLPI;", " $header_backup = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null;\n $cfg_backup = $CFG_GLPI;", " if ($header !== null) {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $header;\n }\n $CFG_GLPI['language'] = $config;\n $CFG_GLPI['default_language'] = $legacy_config;\n $result = \\Session::getPreferredLanguage();", " if ($header_backup !== null) {\n $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $header_backup;\n }\n $CFG_GLPI = $cfg_backup;", " $this->string($result)->isEqualTo($expected);\n }", "\n protected function idorProvider() {\n return [\n ['itemtype' => 'Computer'],\n ['itemtype' => 'Ticket'],\n ['itemtype' => 'Glpi\\\\Dashboard\\\\Item'],\n ['itemtype' => 'User', 'add_params' => ['right' => 'all']],", " ['itemtype' => 'User', 'add_params' => ['entity_restrict' => 0]],", " ];\n }", " /**\n * @dataProvider idorProvider\n */\n function testIDORToken(string $itemtype = \"\", array $add_params = []) {\n // generate token\n $token = \\Session::getNewIDORToken($itemtype, $add_params);\n $this->string($token)->hasLength(64);", " // token exists in session and is valid\n $this->array($_SESSION['glpiidortokens'][$token])\n ->string['itemtype']->isEqualTo($itemtype)\n ->string['expires'];", " if (count($add_params) > 0) {\n $this->array($_SESSION['glpiidortokens'][$token])->size->isEqualTo(2 + count($add_params));\n }", " // validate token with dedicated method\n $result = \\Session::validateIDOR([\n '_idor_token' => $token,\n 'itemtype' => $itemtype,\n ] + $add_params);\n $this->boolean($result)->isTrue();\n }", "\n function testDORInvalid() {\n // random token\n $result = \\Session::validateIDOR([\n '_idor_token' => bin2hex(random_bytes(32)),\n 'itemtype' => 'Computer',\n ]);\n $this->boolean($result)->isFalse();", " // bad itemtype\n $token_bad_itt = \\Session::getNewIDORToken('Ticket');\n $result = \\Session::validateIDOR([\n '_idor_token' => $token_bad_itt,\n 'itemtype' => 'Computer',\n ]);\n $this->boolean($result)->isFalse();", " // missing add params\n $token_miss_param = \\Session::getNewIDORToken('User', ['right' => 'all']);\n $result = \\Session::validateIDOR([\n '_idor_token' => $token_miss_param,\n 'itemtype' => 'User',\n ]);\n $this->boolean($result)->isFalse();\n $result = \\Session::validateIDOR([\n '_idor_token' => $token_miss_param,\n 'itemtype' => 'User',\n 'right' => 'all'\n ]);\n $this->boolean($result)->isTrue();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [80, 686, 2205, 4032, 1333, 377], "buggy_code_start_loc": [79, 685, 176, 4029, 768, 377], "filenames": ["ajax/dropdownTrackingDeviceType.php", "inc/computer_item.class.php", "inc/dropdown.class.php", "inc/user.class.php", "tests/functionnal/Dropdown.php", "tests/functionnal/Session.php"], "fixing_code_end_loc": [82, 688, 2206, 4035, 1342, 379], "fixing_code_start_loc": [79, 685, 176, 4029, 768, 378], "message": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:9.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "3BAC9566-70F6-42A1-AED5-08499316477C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GLPI is an open-source asset and IT management software package that provides ITIL Service Desk features, licenses tracking and software auditing. In GLPI version 9.5.3, it was possible to switch entities with IDOR from a logged in user. This is fixed in version 9.5.4."}, {"lang": "es", "value": "GLPI es un paquete de software de gesti\u00f3n de activos y TI de c\u00f3digo abierto que proporciona funciones de ITIL Service Desk, seguimiento de licencias y auditor\u00eda de software.&#xa0;En GLPI versi\u00f3n 9.5.3, era posible cambiar entidades con IDOR desde un usuario que hab\u00eda iniciado sesi\u00f3n.&#xa0;Esto es corregido en la versi\u00f3n 9.5.4"}], "evaluatorComment": null, "id": "CVE-2021-21255", "lastModified": "2022-10-14T13:01:11.067", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:C/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-02T20:15:14.537", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/glpi-project/glpi/security/advisories/GHSA-v3m5-r3mx-ff9j"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-639"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-862"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/glpi-project/glpi/commit/aade65b7f67d46f23d276a8acb0df70651c3b1dc"}, "type": "CWE-639"}
288
Determine whether the {function_name} code is vulnerable or not.
[ "const _ = require('lodash')\nconst cheerio = require('cheerio')\nconst uslug = require('uslug')\nconst pageHelper = require('../../../helpers/page')\nconst URL = require('url').URL", "const mustacheRegExp = /(\\{|&#x7b;?){2}(.+?)(\\}|&#x7d;?){2}/i", "/* global WIKI */", "module.exports = {\n async render() {\n const $ = cheerio.load(this.input, {\n decodeEntities: true\n })", " if ($.root().children().length < 1) {\n return ''\n }", " // --------------------------------\n // STEP: PRE\n // --------------------------------", " for (let child of _.reject(this.children, ['step', 'post'])) {\n const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)\n await renderer.init($, child.config)\n }", " // --------------------------------\n // Detect internal / external links\n // --------------------------------", " let internalRefs = []\n const reservedPrefixes = /^\\/[a-z]\\//i\n const exactReservedPaths = /^\\/[a-z]$/i", " const isHostSet = WIKI.config.host.length > 7 && WIKI.config.host !== 'http://'\n if (!isHostSet) {\n WIKI.logger.warn('Host is not set. You must set the Site Host under General in the Administration Area!')\n }", " $('a').each((i, elm) => {\n let href = $(elm).attr('href')", " // -> Ignore empty / anchor links, e-mail addresses, and telephone numbers\n if (!href || href.length < 1 || href.indexOf('#') === 0 ||\n href.indexOf('mailto:') === 0 || href.indexOf('tel:') === 0) {\n return\n }", " // -> Strip host from local links\n if (isHostSet && href.indexOf(WIKI.config.host) === 0) {\n href = href.replace(WIKI.config.host, '')\n }", " // -> Assign local / external tag\n if (href.indexOf('://') < 0) {\n // -> Remove trailing slash\n if (_.endsWith('/')) {\n href = href.slice(0, -1)\n }", " // -> Check for system prefix\n if (reservedPrefixes.test(href) || exactReservedPaths.test(href)) {\n $(elm).addClass(`is-system-link`)\n } else if (href.indexOf('.') >= 0) {\n $(elm).addClass(`is-asset-link`)\n } else {\n let pagePath = null", " // -> Add locale prefix if using namespacing\n if (WIKI.config.lang.namespacing) {\n // -> Reformat paths\n if (href.indexOf('/') !== 0) {\n if (this.config.absoluteLinks) {\n href = `/${this.page.localeCode}/${href}`\n } else {\n href = (this.page.path === 'home') ? `/${this.page.localeCode}/${href}` : `/${this.page.localeCode}/${this.page.path}/${href}`\n }\n } else if (href.charAt(3) !== '/') {\n href = `/${this.page.localeCode}${href}`\n }", " try {\n const parsedUrl = new URL(`http://x${href}`)\n pagePath = pageHelper.parsePath(parsedUrl.pathname)\n } catch (err) {\n return\n }\n } else {\n // -> Reformat paths\n if (href.indexOf('/') !== 0) {\n if (this.config.absoluteLinks) {\n href = `/${href}`\n } else {\n href = (this.page.path === 'home') ? `/${href}` : `/${this.page.path}/${href}`\n }\n }", " try {\n const parsedUrl = new URL(`http://x${href}`)\n pagePath = pageHelper.parsePath(parsedUrl.pathname)\n } catch (err) {\n return\n }\n }\n // -> Save internal references\n internalRefs.push({\n localeCode: pagePath.locale,\n path: pagePath.path\n })", " $(elm).addClass(`is-internal-link`)\n }\n } else {\n $(elm).addClass(`is-external-link`)\n if (this.config.openExternalLinkNewTab) {\n $(elm).attr('target', '_blank')\n $(elm).attr('rel', this.config.relAttributeExternalLink)\n }\n }", " // -> Update element\n $(elm).attr('href', href)\n })", " // --------------------------------\n // Detect internal link states\n // --------------------------------", " const pastLinks = await this.page.$relatedQuery('links')", " if (internalRefs.length > 0) {\n // -> Find matching pages\n const results = await WIKI.models.pages.query().column('id', 'path', 'localeCode').where(builder => {\n internalRefs.forEach((ref, idx) => {\n if (idx < 1) {\n builder.where(ref)\n } else {\n builder.orWhere(ref)\n }\n })\n })", " // -> Apply tag to internal links for found pages\n $('a.is-internal-link').each((i, elm) => {\n const href = $(elm).attr('href')\n let hrefObj = {}\n try {\n const parsedUrl = new URL(`http://x${href}`)\n hrefObj = pageHelper.parsePath(parsedUrl.pathname)\n } catch (err) {\n return\n }\n if (_.some(results, r => {\n return r.localeCode === hrefObj.locale && r.path === hrefObj.path\n })) {\n $(elm).addClass(`is-valid-page`)\n } else {\n $(elm).addClass(`is-invalid-page`)\n }\n })", " // -> Add missing links\n const missingLinks = _.differenceWith(internalRefs, pastLinks, (nLink, pLink) => {\n return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path\n })\n if (missingLinks.length > 0) {\n if (WIKI.config.db.type === 'postgres') {\n await WIKI.models.pageLinks.query().insert(missingLinks.map(lnk => ({\n pageId: this.page.id,\n path: lnk.path,\n localeCode: lnk.localeCode\n })))\n } else {\n for (const lnk of missingLinks) {\n await WIKI.models.pageLinks.query().insert({\n pageId: this.page.id,\n path: lnk.path,\n localeCode: lnk.localeCode\n })\n }\n }\n }\n }", " // -> Remove outdated links\n if (pastLinks) {\n const outdatedLinks = _.differenceWith(pastLinks, internalRefs, (nLink, pLink) => {\n return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path\n })\n if (outdatedLinks.length > 0) {\n await WIKI.models.pageLinks.query().delete().whereIn('id', _.map(outdatedLinks, 'id'))\n }\n }", " // --------------------------------\n // Add header handles\n // --------------------------------", " let headers = []\n $('h1,h2,h3,h4,h5,h6').each((i, elm) => {\n if ($(elm).attr('id')) {\n return\n }\n let headerSlug = uslug($(elm).text())", " // -> Cannot start with a number (CSS selector limitation)\n if (headerSlug.match(/^\\d/)) {\n headerSlug = `h-${headerSlug}`\n }", " // -> Make sure header is unique\n if (headers.indexOf(headerSlug) >= 0) {\n let isUnique = false\n let hIdx = 1\n while (!isUnique) {\n const headerSlugTry = `${headerSlug}-${hIdx}`\n if (headers.indexOf(headerSlugTry) < 0) {\n isUnique = true\n headerSlug = headerSlugTry\n }\n hIdx++\n }\n }", " // -> Add anchor\n $(elm).attr('id', headerSlug).addClass('toc-header')\n $(elm).prepend(`<a class=\"toc-anchor\" href=\"#${headerSlug}\">&#xB6;</a> `)", " headers.push(headerSlug)\n })", " // --------------------------------\n // Wrap root text nodes\n // --------------------------------", " $('body').contents().toArray().forEach(item => {\n if (item.type === 'text' && item.parent.name === 'body') {\n $(item).wrap('<div></div>')\n }\n })", " // --------------------------------\n // Escape mustache expresions\n // --------------------------------", " function iterateMustacheNode (node) {\n const list = $(node).contents().toArray()\n list.forEach(item => {\n if (item.type === 'text') {\n const rawText = $(item).text()\n if (mustacheRegExp.test(rawText)) {\n $(item).parent().attr('v-pre', true)\n }\n } else {\n iterateMustacheNode(item)\n }\n })\n }\n iterateMustacheNode($.root())\n", "", " // --------------------------------\n // STEP: POST\n // --------------------------------", " let output = decodeEscape($.html('body').replace('<body>', '').replace('</body>', ''))", " for (let child of _.sortBy(_.filter(this.children, ['step', 'post']), ['order'])) {\n const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)\n output = await renderer.init(output, child.config)\n }", " return output\n }\n}", "function decodeEscape (string) {\n return string.replace(/&#x([0-9a-f]{1,6});/ig, (entity, code) => {\n code = parseInt(code, 16)", " // Don't unescape ASCII characters, assuming they're encoded for a good reason\n if (code < 0x80) return entity", " return String.fromCodePoint(code)\n })\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [263], "buggy_code_start_loc": [263], "filenames": ["server/modules/rendering/html-core/renderer.js"], "fixing_code_end_loc": [268], "fixing_code_start_loc": [264], "message": "Wiki.js an open-source wiki app built on Node.js. Wiki.js before version 2.5.191 is vulnerable to stored cross-site scripting through mustache expressions in code blocks. This vulnerability exists due to mustache expressions being parsed by Vue during content injection even though it is contained within a `<pre>` element. By creating a crafted wiki page, a malicious Wiki.js user may stage a stored cross-site scripting attack. This allows the attacker to execute malicious JavaScript when the page is viewed by other users. For an example see referenced GitHub Security Advisory. Commit 5ffa189383dd716f12b56b8cae2ba0d075996cf1 fixes this vulnerability by adding the v-pre directive to all `<pre>` tags during the render.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:requarks:wiki.js:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE1BA27C-823D-4E0A-A478-1E8CE5EC2EC8", "versionEndExcluding": "2.5.191", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Wiki.js an open-source wiki app built on Node.js. Wiki.js before version 2.5.191 is vulnerable to stored cross-site scripting through mustache expressions in code blocks. This vulnerability exists due to mustache expressions being parsed by Vue during content injection even though it is contained within a `<pre>` element. By creating a crafted wiki page, a malicious Wiki.js user may stage a stored cross-site scripting attack. This allows the attacker to execute malicious JavaScript when the page is viewed by other users. For an example see referenced GitHub Security Advisory. Commit 5ffa189383dd716f12b56b8cae2ba0d075996cf1 fixes this vulnerability by adding the v-pre directive to all `<pre>` tags during the render."}, {"lang": "es", "value": "Wiki.js una aplicaci\u00f3n wiki de c\u00f3digo abierto construida sobre Node.js.&#xa0;Wiki.js versiones anteriores a 2.5.191, es vulnerable a un ataque de tipo cross-site scripting almacenado por medio de expresiones mustache en bloques de c\u00f3digo.&#xa0;Esta vulnerabilidad se presenta debido a que las expresiones mustache eran analizadas por Vue durante la inyecci\u00f3n de contenido a pesar de que est\u00e1 contenida dentro de un elemento \"(pre)\".&#xa0;Al crear una p\u00e1gina wiki dise\u00f1ada, un usuario de Wiki.js malicioso puede organizar un ataque de tipo cross-site scripting almacenado.&#xa0;Esto permite al atacante ejecutar JavaScript malicioso cuando otros usuarios visualizan la p\u00e1gina.&#xa0;Para visualizar un ejemplo, consulte el Aviso de Seguridad de GitHub al que se hace referencia.&#xa0;Commit 5ffa189383dd716f12b56b8cae2ba0d075996cf1 corrige esta vulnerabilidad agregando la directiva v-pre a todas las etiquetas \"(pre)\" durante el renderizado"}], "evaluatorComment": null, "id": "CVE-2021-21383", "lastModified": "2021-03-24T14:00:10.747", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-18T17:15:13.947", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Requarks/wiki/commit/5ffa189383dd716f12b56b8cae2ba0d075996cf1"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/Requarks/wiki/releases/tag/2.5.191"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/Requarks/wiki/security/advisories/GHSA-6xx4-m8gx-826r"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/Requarks/wiki/commit/5ffa189383dd716f12b56b8cae2ba0d075996cf1"}, "type": "CWE-79"}
289
Determine whether the {function_name} code is vulnerable or not.
[ "const _ = require('lodash')\nconst cheerio = require('cheerio')\nconst uslug = require('uslug')\nconst pageHelper = require('../../../helpers/page')\nconst URL = require('url').URL", "const mustacheRegExp = /(\\{|&#x7b;?){2}(.+?)(\\}|&#x7d;?){2}/i", "/* global WIKI */", "module.exports = {\n async render() {\n const $ = cheerio.load(this.input, {\n decodeEntities: true\n })", " if ($.root().children().length < 1) {\n return ''\n }", " // --------------------------------\n // STEP: PRE\n // --------------------------------", " for (let child of _.reject(this.children, ['step', 'post'])) {\n const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)\n await renderer.init($, child.config)\n }", " // --------------------------------\n // Detect internal / external links\n // --------------------------------", " let internalRefs = []\n const reservedPrefixes = /^\\/[a-z]\\//i\n const exactReservedPaths = /^\\/[a-z]$/i", " const isHostSet = WIKI.config.host.length > 7 && WIKI.config.host !== 'http://'\n if (!isHostSet) {\n WIKI.logger.warn('Host is not set. You must set the Site Host under General in the Administration Area!')\n }", " $('a').each((i, elm) => {\n let href = $(elm).attr('href')", " // -> Ignore empty / anchor links, e-mail addresses, and telephone numbers\n if (!href || href.length < 1 || href.indexOf('#') === 0 ||\n href.indexOf('mailto:') === 0 || href.indexOf('tel:') === 0) {\n return\n }", " // -> Strip host from local links\n if (isHostSet && href.indexOf(WIKI.config.host) === 0) {\n href = href.replace(WIKI.config.host, '')\n }", " // -> Assign local / external tag\n if (href.indexOf('://') < 0) {\n // -> Remove trailing slash\n if (_.endsWith('/')) {\n href = href.slice(0, -1)\n }", " // -> Check for system prefix\n if (reservedPrefixes.test(href) || exactReservedPaths.test(href)) {\n $(elm).addClass(`is-system-link`)\n } else if (href.indexOf('.') >= 0) {\n $(elm).addClass(`is-asset-link`)\n } else {\n let pagePath = null", " // -> Add locale prefix if using namespacing\n if (WIKI.config.lang.namespacing) {\n // -> Reformat paths\n if (href.indexOf('/') !== 0) {\n if (this.config.absoluteLinks) {\n href = `/${this.page.localeCode}/${href}`\n } else {\n href = (this.page.path === 'home') ? `/${this.page.localeCode}/${href}` : `/${this.page.localeCode}/${this.page.path}/${href}`\n }\n } else if (href.charAt(3) !== '/') {\n href = `/${this.page.localeCode}${href}`\n }", " try {\n const parsedUrl = new URL(`http://x${href}`)\n pagePath = pageHelper.parsePath(parsedUrl.pathname)\n } catch (err) {\n return\n }\n } else {\n // -> Reformat paths\n if (href.indexOf('/') !== 0) {\n if (this.config.absoluteLinks) {\n href = `/${href}`\n } else {\n href = (this.page.path === 'home') ? `/${href}` : `/${this.page.path}/${href}`\n }\n }", " try {\n const parsedUrl = new URL(`http://x${href}`)\n pagePath = pageHelper.parsePath(parsedUrl.pathname)\n } catch (err) {\n return\n }\n }\n // -> Save internal references\n internalRefs.push({\n localeCode: pagePath.locale,\n path: pagePath.path\n })", " $(elm).addClass(`is-internal-link`)\n }\n } else {\n $(elm).addClass(`is-external-link`)\n if (this.config.openExternalLinkNewTab) {\n $(elm).attr('target', '_blank')\n $(elm).attr('rel', this.config.relAttributeExternalLink)\n }\n }", " // -> Update element\n $(elm).attr('href', href)\n })", " // --------------------------------\n // Detect internal link states\n // --------------------------------", " const pastLinks = await this.page.$relatedQuery('links')", " if (internalRefs.length > 0) {\n // -> Find matching pages\n const results = await WIKI.models.pages.query().column('id', 'path', 'localeCode').where(builder => {\n internalRefs.forEach((ref, idx) => {\n if (idx < 1) {\n builder.where(ref)\n } else {\n builder.orWhere(ref)\n }\n })\n })", " // -> Apply tag to internal links for found pages\n $('a.is-internal-link').each((i, elm) => {\n const href = $(elm).attr('href')\n let hrefObj = {}\n try {\n const parsedUrl = new URL(`http://x${href}`)\n hrefObj = pageHelper.parsePath(parsedUrl.pathname)\n } catch (err) {\n return\n }\n if (_.some(results, r => {\n return r.localeCode === hrefObj.locale && r.path === hrefObj.path\n })) {\n $(elm).addClass(`is-valid-page`)\n } else {\n $(elm).addClass(`is-invalid-page`)\n }\n })", " // -> Add missing links\n const missingLinks = _.differenceWith(internalRefs, pastLinks, (nLink, pLink) => {\n return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path\n })\n if (missingLinks.length > 0) {\n if (WIKI.config.db.type === 'postgres') {\n await WIKI.models.pageLinks.query().insert(missingLinks.map(lnk => ({\n pageId: this.page.id,\n path: lnk.path,\n localeCode: lnk.localeCode\n })))\n } else {\n for (const lnk of missingLinks) {\n await WIKI.models.pageLinks.query().insert({\n pageId: this.page.id,\n path: lnk.path,\n localeCode: lnk.localeCode\n })\n }\n }\n }\n }", " // -> Remove outdated links\n if (pastLinks) {\n const outdatedLinks = _.differenceWith(pastLinks, internalRefs, (nLink, pLink) => {\n return nLink.localeCode === pLink.localeCode && nLink.path === pLink.path\n })\n if (outdatedLinks.length > 0) {\n await WIKI.models.pageLinks.query().delete().whereIn('id', _.map(outdatedLinks, 'id'))\n }\n }", " // --------------------------------\n // Add header handles\n // --------------------------------", " let headers = []\n $('h1,h2,h3,h4,h5,h6').each((i, elm) => {\n if ($(elm).attr('id')) {\n return\n }\n let headerSlug = uslug($(elm).text())", " // -> Cannot start with a number (CSS selector limitation)\n if (headerSlug.match(/^\\d/)) {\n headerSlug = `h-${headerSlug}`\n }", " // -> Make sure header is unique\n if (headers.indexOf(headerSlug) >= 0) {\n let isUnique = false\n let hIdx = 1\n while (!isUnique) {\n const headerSlugTry = `${headerSlug}-${hIdx}`\n if (headers.indexOf(headerSlugTry) < 0) {\n isUnique = true\n headerSlug = headerSlugTry\n }\n hIdx++\n }\n }", " // -> Add anchor\n $(elm).attr('id', headerSlug).addClass('toc-header')\n $(elm).prepend(`<a class=\"toc-anchor\" href=\"#${headerSlug}\">&#xB6;</a> `)", " headers.push(headerSlug)\n })", " // --------------------------------\n // Wrap root text nodes\n // --------------------------------", " $('body').contents().toArray().forEach(item => {\n if (item.type === 'text' && item.parent.name === 'body') {\n $(item).wrap('<div></div>')\n }\n })", " // --------------------------------\n // Escape mustache expresions\n // --------------------------------", " function iterateMustacheNode (node) {\n const list = $(node).contents().toArray()\n list.forEach(item => {\n if (item.type === 'text') {\n const rawText = $(item).text()\n if (mustacheRegExp.test(rawText)) {\n $(item).parent().attr('v-pre', true)\n }\n } else {\n iterateMustacheNode(item)\n }\n })\n }\n iterateMustacheNode($.root())\n", " $('pre').each((idx, elm) => {\n $(elm).attr('v-pre', true)\n })\n", " // --------------------------------\n // STEP: POST\n // --------------------------------", " let output = decodeEscape($.html('body').replace('<body>', '').replace('</body>', ''))", " for (let child of _.sortBy(_.filter(this.children, ['step', 'post']), ['order'])) {\n const renderer = require(`../${_.kebabCase(child.key)}/renderer.js`)\n output = await renderer.init(output, child.config)\n }", " return output\n }\n}", "function decodeEscape (string) {\n return string.replace(/&#x([0-9a-f]{1,6});/ig, (entity, code) => {\n code = parseInt(code, 16)", " // Don't unescape ASCII characters, assuming they're encoded for a good reason\n if (code < 0x80) return entity", " return String.fromCodePoint(code)\n })\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [263], "buggy_code_start_loc": [263], "filenames": ["server/modules/rendering/html-core/renderer.js"], "fixing_code_end_loc": [268], "fixing_code_start_loc": [264], "message": "Wiki.js an open-source wiki app built on Node.js. Wiki.js before version 2.5.191 is vulnerable to stored cross-site scripting through mustache expressions in code blocks. This vulnerability exists due to mustache expressions being parsed by Vue during content injection even though it is contained within a `<pre>` element. By creating a crafted wiki page, a malicious Wiki.js user may stage a stored cross-site scripting attack. This allows the attacker to execute malicious JavaScript when the page is viewed by other users. For an example see referenced GitHub Security Advisory. Commit 5ffa189383dd716f12b56b8cae2ba0d075996cf1 fixes this vulnerability by adding the v-pre directive to all `<pre>` tags during the render.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:requarks:wiki.js:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE1BA27C-823D-4E0A-A478-1E8CE5EC2EC8", "versionEndExcluding": "2.5.191", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Wiki.js an open-source wiki app built on Node.js. Wiki.js before version 2.5.191 is vulnerable to stored cross-site scripting through mustache expressions in code blocks. This vulnerability exists due to mustache expressions being parsed by Vue during content injection even though it is contained within a `<pre>` element. By creating a crafted wiki page, a malicious Wiki.js user may stage a stored cross-site scripting attack. This allows the attacker to execute malicious JavaScript when the page is viewed by other users. For an example see referenced GitHub Security Advisory. Commit 5ffa189383dd716f12b56b8cae2ba0d075996cf1 fixes this vulnerability by adding the v-pre directive to all `<pre>` tags during the render."}, {"lang": "es", "value": "Wiki.js una aplicaci\u00f3n wiki de c\u00f3digo abierto construida sobre Node.js.&#xa0;Wiki.js versiones anteriores a 2.5.191, es vulnerable a un ataque de tipo cross-site scripting almacenado por medio de expresiones mustache en bloques de c\u00f3digo.&#xa0;Esta vulnerabilidad se presenta debido a que las expresiones mustache eran analizadas por Vue durante la inyecci\u00f3n de contenido a pesar de que est\u00e1 contenida dentro de un elemento \"(pre)\".&#xa0;Al crear una p\u00e1gina wiki dise\u00f1ada, un usuario de Wiki.js malicioso puede organizar un ataque de tipo cross-site scripting almacenado.&#xa0;Esto permite al atacante ejecutar JavaScript malicioso cuando otros usuarios visualizan la p\u00e1gina.&#xa0;Para visualizar un ejemplo, consulte el Aviso de Seguridad de GitHub al que se hace referencia.&#xa0;Commit 5ffa189383dd716f12b56b8cae2ba0d075996cf1 corrige esta vulnerabilidad agregando la directiva v-pre a todas las etiquetas \"(pre)\" durante el renderizado"}], "evaluatorComment": null, "id": "CVE-2021-21383", "lastModified": "2021-03-24T14:00:10.747", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-03-18T17:15:13.947", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Requarks/wiki/commit/5ffa189383dd716f12b56b8cae2ba0d075996cf1"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/Requarks/wiki/releases/tag/2.5.191"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/Requarks/wiki/security/advisories/GHSA-6xx4-m8gx-826r"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/Requarks/wiki/commit/5ffa189383dd716f12b56b8cae2ba0d075996cf1"}, "type": "CWE-79"}
289
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "##################################################\n#\n# Copyright (c) 2004-2017 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "/**\n * Implements elFinder as the 'connector' referenced by 'url' param in elfinder.tpl\n */", "require_once(\"../../../../exponent.php\");\nif (empty($user->id))\n exit();", "if (DEVELOPMENT) {\n set_time_limit(0);\n} // just in case it too long, not recommended for production", "ini_set('max_file_uploads', FM_SIMLIMIT); // allow uploading up to FM_SIMLIMIT files at once", "// needed for case insensitive search to work, due to broken UTF-8 support in PHP\n//ini_set('mbstring.internal_encoding', 'UTF-8');\n//ini_set('mbstring.func_overload', 2);", "include BASE . 'external/elFinder/php/elFinderConnector.class.php';\ninclude BASE . 'external/elFinder/php/elFinder.class.php';", "include BASE . 'external/elFinder/php/elFinderPlugin.php';\n//include BASE . 'external/elFinder/php/libs/GdBmp.php'; // will also autoload if needed\n//include BASE . 'external/elFinder/php/plugins/AutoResize/plugin.php'; // will also autoload if needed\n//include BASE . 'external/elFinder/php/plugins/AutoRotate/plugin.php';\n//include BASE . 'external/elFinder/php/plugins/Normalizer/plugin.php';\n//include BASE . 'external/elFinder/php/plugins/Sanitizer/plugin.php';\n//include BASE . 'external/elFinder/php/plugins/Watermark/plugin.php';\n//include BASE . 'external/elFinder/php/elFinderSessionInterface.php'; // will also autoload if needed\n//include BASE . 'external/elFinder/php/elFinderSession.php'; // will also autoload if needed", "include BASE . 'framework/modules/file/connector/elFinderExponent.class.php'; // our custom elFinder object", "include BASE . 'external/elFinder/php/elFinderVolumeDriver.class.php';\ninclude BASE . 'external/elFinder/php/elFinderVolumeLocalFileSystem.class.php';\n//include BASE . 'external/elFinder/php/elFinderVolumeMySQL.class.php';\n//include BASE . 'external/elFinder/php/elFinderVolumeFTP.class.php';\n//include BASE . 'external/elFinder/php/elFinderVolumeS3.class.php';\ninclude BASE . 'framework/modules/file/connector/elFinderVolumeExponent.class.php'; // our custom elFinder volume driver", "define('ELFINDER_IMG_PARENT_URL', PATH_RELATIVE . 'external/elFinder/');", "/**\n * # Dropbox volume driver need \"dropbox-php's Dropbox\" and \"PHP OAuth extension\" or \"PEAR's HTTP_OAUTH package\"\n * * dropbox-php: http://www.dropbox-php.com/\n * * PHP OAuth extension: http://pecl.php.net/package/oauth\n * * PEAR's HTTP_OAUTH package: http://pear.php.net/package/http_oauth\n * * HTTP_OAUTH package require HTTP_Request2 and Net_URL2\n */\n// Required for Dropbox.com connector support\n//include BASE . 'external/elFinder/php/elFinderVolumeDropbox.class.php';", "// Dropbox driver need next two settings. You can get at https://www.dropbox.com/developers\n// define('ELFINDER_DROPBOX_CONSUMERKEY', '');\n// define('ELFINDER_DROPBOX_CONSUMERSECRET', '');\n// define('ELFINDER_DROPBOX_META_CACHE_PATH',''); // optional for `options['metaCachePath']`", "function debug($o)\n{\n echo '<pre>';\n print_r($o);\n}", "/**\n * example logger function\n * Demonstrate how to work with elFinder event api\n *\n * @param string $cmd command name\n * @param array $result command result\n * @param array $args command arguments from client\n * @param elFinder $elfinder elFinder instance\n *\n * @return void|true\n * @author Troex Nevelin\n **/\nfunction logger($cmd, $result, $args, $elfinder)\n{\n if (DEVELOPMENT && LOGGER) {\n $log = sprintf(\"[%s] %s: %s \\n\", date('r'), strtoupper($cmd), var_export($result, true));\n $logfile = BASE . 'tmp/elfinder.log';\n $dir = dirname($logfile);\n if (!is_dir($dir) && !mkdir($dir, octdec(DIR_DEFAULT_MODE_STR + 0))) {\n return;\n }\n if (($fp = fopen($logfile, 'a'))) {\n fwrite($fp, $log);\n fclose($fp);\n }\n return;", "// // alternative logging method\n// foreach ($result as $key => $value) {\n// if (empty($value)) {\n// continue;\n// }\n// $data = array();\n// if (in_array($key, array('error', 'warning'))) {\n// array_push($data, implode(' ', $value));\n// } else {\n// if (is_array($value)) { // changes made to files\n// foreach ($value as $file) {\n// $filepath = (isset($file['realpath']) ? $file['realpath'] : $elfinder->realpath($file['hash']));\n// array_push($data, $filepath);\n// }\n// } else { // other value (ex. header)\n// array_push($data, $value);\n// }\n// }\n// $log .= sprintf(' %s(%s)', $key, implode(', ', $data));\n// }\n// $log .= \"\\n\";\n//\n// $logfile = BASE . 'tmp/elfinder.log';\n// $dir = dirname($logfile);\n// if (!is_dir($dir) && !mkdir($dir)) {\n// return;\n// }\n// if (($fp = fopen($logfile, 'a'))) {\n// fwrite($fp, $log);\n// fclose($fp);\n// }\n }\n}", "/**\n * example logger class\n * Demonstrate how to work with elFinder event api.\n *\n * @package elFinder\n * @author Dmitry (dio) Levashov\n **/\nclass elFinderSimpleLogger\n{", " /**\n * Log file path\n *\n * @var string\n **/\n protected $file = '';", " /**\n * constructor\n *\n * @param $path\n *\n * @return \\elFinderSimpleLogger\n * @author Dmitry (dio) Levashov\n */\n public function __construct($path)\n {\n $this->file = $path;\n $dir = dirname($path);\n if (!is_dir($dir)) {\n mkdir($dir, octdec(DIR_DEFAULT_MODE_STR + 0));\n }\n }", " /**\n * Create log record\n *\n * @param string $cmd command name\n * @param array $result command result\n * @param array $args command arguments from client\n * @param elFinder $elfinder elFinder instance\n *\n * @return void|true\n * @author Dmitry (dio) Levashov\n **/\n public function log($cmd, $result, $args, $elfinder)\n {\n if (DEVELOPMENT && LOGGER) {\n $log = $cmd . ' [' . date('d.m H:s') . \"]\\n\";", " if (!empty($result['error'])) {\n $log .= \"\\tERROR: \" . implode(' ', $result['error']) . \"\\n\";\n }", " if (!empty($result['warning'])) {\n $log .= \"\\tWARNING: \" . implode(' ', $result['warning']) . \"\\n\";\n }", " if (!empty($result['removed'])) {\n foreach ($result['removed'] as $file) {\n // removed file contain additional field \"realpath\"\n $log .= \"\\tREMOVED: \" . $file['realpath'] . \"\\n\";\n }\n }", " if (!empty($result['added'])) {\n foreach ($result['added'] as $file) {\n $log .= \"\\tADDED: \" . $elfinder->realpath($file['hash']) . \"\\n\";\n }\n }", " if (!empty($result['changed'])) {\n foreach ($result['changed'] as $file) {\n $log .= \"\\tCHANGED: \" . $elfinder->realpath($file['hash']) . \"\\n\";\n }\n }", " $this->write($log);\n $this->write(var_export($result, true), true);\n }\n }", " /**\n * Write log into file\n *\n * @param string $log log record\n *\n * @return void\n * @author Dmitry (dio) Levashov\n **/\n protected function write($log, $eol=false)\n {\n if ($eol)\n $eol = \"\\n\";\n if (($fp = @fopen($this->file, 'a'))) {\n fwrite($fp, $log . $eol);\n fclose($fp);\n }\n }", "} // END class\n//$logger = new elFinderSimpleLogger(BASE.'tmp/elfinder.log');", "/**\n * example accessControl function\n * to demonstrate how to control file access using \"accessControl\" callback.\n * This method will disable accessing files/folders starting from '.' (dot)\n *\n * @param string $attr attribute name (read|write|locked|hidden)\n * @param string $path file path relative to volume root directory started with directory separator\n * @param $data\n * @param object $volume elFinder volume driver object\n * @param bool|null $isDir path is directory (true: directory, false: file, null: unknown)\n *\n * @return bool|null\n */\nfunction access($attr, $path, $data, $volume, $isDir) {\n\treturn strpos(basename($path), '.') === 0 // if file/folder begins with '.' (dot)\n\t\t? !($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true\n\t\t: null; // else elFinder decide it itself\n}", "/**\n * example accessControl class\n *\n * @author Dmitry (dio) Levashov\n **/\nclass elFinderTestACL\n{", " /**\n * make dotfiles not readable, not writable, hidden and locked\n *\n * @param string $attr attribute name (read|write|locked|hidden)\n * @param string $path file path. Attention! This is path relative to volume root directory started with directory separator.\n * @param mixed $data data which seted in 'accessControlData' elFinder option\n * @param elFinderVolumeDriver $volume volume driver\n *\n * @return bool\n * @author Dmitry (dio) Levashov\n **/\n public function fsAccess($attr, $path, $data, $volume)\n {", " if ($volume->name() == 'localfilesystem') {\n return strpos(basename($path), '.') === 0\n ? !($attr == 'read' || $attr == 'write')\n : $attr == 'read' || $attr == 'write';\n }", " return true;\n }", "} // END class\n//$acl = new elFinderTestACL();", "/**\n * example acceptedName function\n */\nfunction validName($name)\n{\n return strpos($name, '.') !== 0;\n}", "$opts = array(\n 'locale' => LOCALE . '.' . LANG_CHARSET,\n 'bind' => array(\n // '*' => 'logger',\n 'mkdir mkfile rename duplicate upload rm paste' => 'logger', // use function style logger\n// 'mkdir mkfile rename duplicate upload rm paste' => array($logger, 'log'), // use class style logger\n// 'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(\n// 'Plugin.Normalizer.cmdPreprocess',\n// 'Plugin.Sanitizer.cmdPreprocess',\n// ),\n// 'ls' => array(\n// 'Plugin.Normalizer.cmdPostprocess',\n// 'Plugin.Sanitizer.cmdPostprocess',\n// ),\n 'upload.presave' => array(\n 'Plugin.AutoResize.onUpLoadPreSave',\n// 'Plugin.Watermark.onUpLoadPreSave',\n// 'Plugin.Normalizer.onUpLoadPreSave',\n// 'Plugin.Sanitizer.onUpLoadPreSave',\n// 'Plugin.AutoRotate.onUpLoadPreSave',\n ),\n ),\n // global plugin configure (optional)\n 'plugin' => array(\n 'AutoResize' => array(\n 'enable' => UPLOAD_WIDTH, // For control by volume driver\n 'maxWidth' => UPLOAD_WIDTH,\n 'maxHeight' => UPLOAD_WIDTH,\n 'quality' => THUMB_QUALITY, // JPEG image save quality\n 'targetType' => IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP, // Target image formats ( bit-field )\n// 'forceEffect' => false, // For change quality of small images\n// 'preserveExif' => false, // Preserve EXIF data (Imagick only)\n ),\n// 'Watermark' => array(\n// 'enable' => true, // For control by volume driver\n// 'source' => 'logo.png', // Path to Water mark image\n// 'marginRight' => 5, // Margin right pixel\n// 'marginBottom' => 5, // Margin bottom pixel\n// 'quality' => THUMB_QUALITY, // JPEG image save quality\n// 'transparency' => 70, // Water mark image transparency ( other than PNG )\n// 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )\n// 'targetMinPixel' => 200 // Target image minimum pixel size\n// ),\n// 'Normalizer' => array(\n// 'enable' => true,\n// 'nfc' => true,\n// 'nfkc' => true,\n// 'lowercase' => false,\n// 'convmap' => array()\n// ),\n// 'Sanitizer' => array(\n// 'enable' => true,\n// 'targets' => array('\\\\','/',':','*','?','\"','<','>','|'), // target chars\n// 'replace' => '_' // replace to this\n// ),\n// 'AutoRotate' => array(\n// 'enable' => true, // For control by volume driver\n// 'quality' => 95 // JPEG image save quality\n// )\n ),\n 'debug' => DEVELOPMENT,\n//\t'netVolumesSessionKey' => 'netVolumes',\n 'callbackWindowURL' => makeLink(array('controller'=>'file','action'=>'picker','ajax_action'=>1)),", " 'roots' => array(\n array(\n // 'id' => 'x5',\n 'driver' => 'Exponent',\n 'path' => BASE . 'files/',\n 'URL' => URL_FULL . 'files/',\n 'dirMode' => octdec(DIR_DEFAULT_MODE_STR + 0), // new dirs mode (default 0755)\n 'fileMode' => octdec(FILE_DEFAULT_MODE_STR + 0), // new files mode (default 0644)\n 'detectDirIcon' => '.foldericon.png', // File to be detected as a folder icon image (elFinder >= 2.1.10) e.g. '.favicon.png'\n 'keepTimestamp' => array('copy', 'move'), // Keep timestamp at inner filesystem (elFinder >= 2.1.12) It allowed 'copy', 'move' and 'upload'.\n // 'treeDeep' => 3,\n 'alias' => 'files',\n 'disabled' => array('netmount'),\n// 'maxArcFilesSize' => 100,\n 'accessControl' => 'access',\n // 'accessControl' => array($acl, 'fsAccess'),\n // 'accessControlData' => array('uid' => 1),\n 'uploadAllow' => array(\n 'application/arj',\n 'application/excel',\n 'application/gnutar',\n 'application/mspowerpoint',\n 'application/msword',\n 'application/octet-stream',\n 'application/onenote',\n 'application/pdf',\n 'application/plain',\n 'application/postscript',\n 'application/powerpoint',\n 'application/rar',\n 'application/rtf',\n 'application/vnd.ms-excel',\n 'application/vnd.ms-excel.addin.macroEnabled.12',\n 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',\n 'application/vnd.ms-excel.sheet.macroEnabled.12',\n 'application/vnd.ms-excel.template.macroEnabled.12',\n 'application/vnd.ms-office',\n 'application/vnd.ms-officetheme',\n 'application/vnd.ms-powerpoint',\n 'application/vnd.ms-powerpoint.addin.macroEnabled.12',\n 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',\n 'application/vnd.ms-powerpoint.slide.macroEnabled.12',\n 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',\n 'application/vnd.ms-powerpoint.template.macroEnabled.12',\n 'application/vnd.ms-word',\n 'application/vnd.ms-word.document.macroEnabled.12',\n 'application/vnd.ms-word.template.macroEnabled.12',\n 'application/vnd.oasis.opendocument.chart',\n 'application/vnd.oasis.opendocument.database',\n 'application/vnd.oasis.opendocument.formula',\n 'application/vnd.oasis.opendocument.graphics',\n 'application/vnd.oasis.opendocument.graphics-template',\n 'application/vnd.oasis.opendocument.image',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.presentation-template',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.spreadsheet-template',\n 'application/vnd.oasis.opendocument.text',\n 'application/vnd.oasis.opendocument.text-master',\n 'application/vnd.oasis.opendocument.text-template',\n 'application/vnd.oasis.opendocument.text-web',\n 'application/vnd.openofficeorg.extension',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'application/vnd.openxmlformats-officedocument.presentationml.slide',\n 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',\n 'application/vnd.openxmlformats-officedocument.presentationml.template',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',\n 'application/vocaltec-media-file',\n 'application/wordperfect',\n 'application/x-bittorrent',\n 'application/x-bzip',\n 'application/x-bzip2',\n 'application/x-compressed',\n 'application/x-excel',\n 'application/x-gzip',\n 'application/x-latex',\n 'application/x-midi',\n 'application/xml',\n 'application/x-msexcel',\n 'application/x-rar',\n 'application/x-rar-compressed',\n 'application/x-rtf',\n 'application/x-shockwave-flash',\n 'application/x-sit',\n 'application/x-stuffit',\n 'application/x-troff-msvideo',\n 'application/x-zip',\n 'application/x-zip-compressed',\n 'application/zip',\n 'audio',\n 'image',\n 'multipart/x-gzip',\n 'multipart/x-zip',\n 'text/plain',\n 'text/rtf',\n 'text/richtext',\n 'text/xml',\n 'video',\n 'text/csv'\n ),\n 'uploadDeny' => array(\n 'application/x-shockwave-flash'\n ),\n 'uploadOrder' => 'allow,deny',\n 'uploadOverwrite' => true,\n// 'uploadMaxSize' => '128m',\n // 'copyOverwrite' => false,\n 'copyJoin' => true,\n// 'mimeDetect' => 'internal',\n// 'tmpPath' => BASE . 'tmp',\n 'tmbCrop' => false,\n// 'imgLib' => 'gd', // 'auto' doesn't seem to work on some servers\n 'tmbPath' => BASE . 'tmp' . DIRECTORY_SEPARATOR . 'elfinder',\n 'tmbURL' => URL_FULL . 'tmp/elfinder/',\n 'tmbPathMode' => octdec(DIR_DEFAULT_MODE_STR + 0),\n 'tmbBgColor' => 'transparent',\n 'tmbSize' => FM_THUMB_SIZE,\n 'quarantine' => '..' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'elfinder' . DIRECTORY_SEPARATOR . '.quarantine',\n 'acceptedName' => '/^[^\\.].*$/',\n // 'acceptedName' => '/^[\\W]*$/',\n // 'acceptedName' => 'validName',\n 'utf8fix' => false,\n// 'statOwner' => true,\n 'attributes' => array(\n array(\n 'pattern' => '/^\\/\\./', // dot files are hidden\n 'read' => false,\n 'write' => false,\n 'hidden' => true,\n 'locked' => true\n )\n )\n )\n )\n);", "//header('Access-Control-Allow-Origin: *');", "$connector = new elFinderConnector(new elFinderExponent($opts), true);", "$connector->run();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [513], "buggy_code_start_loc": [512], "filenames": ["framework/modules/file/connector/elfinder.php"], "fixing_code_end_loc": [513], "fixing_code_start_loc": [512], "message": "In Exponent CMS before 2.4.1 Patch #5, XSS in elFinder is possible in framework/modules/file/connector/elfinder.php.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:*:p4:*:*:*:*:*:*", "matchCriteriaId": "BFC75474-A888-413E-B7EF-E76FE79504B9", "versionEndExcluding": null, "versionEndIncluding": "2.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Exponent CMS before 2.4.1 Patch #5, XSS in elFinder is possible in framework/modules/file/connector/elfinder.php."}, {"lang": "es", "value": "En Exponent CMS en versiones anteriores a 2.4.1 Patch #5, XSS en elFinder es posible en framework/modules/file/connector/elfinder.php."}], "evaluatorComment": null, "id": "CVE-2017-8085", "lastModified": "2017-04-29T01:59:02.130", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-04-24T14:59:00.183", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://www.exponentcms.org/news/patch-5-released-for-v2-4-1-to-fix-a-few-critical-issues"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/98043"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/exponentcms/exponent-cms/commit/0b2241ff1c7d86376fa260c5d4c1714f6cef9c0f"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/exponentcms/exponent-cms/releases/tag/v2.4.1patch5"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/0b2241ff1c7d86376fa260c5d4c1714f6cef9c0f"}, "type": "CWE-79"}
290
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "##################################################\n#\n# Copyright (c) 2004-2017 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "/**\n * Implements elFinder as the 'connector' referenced by 'url' param in elfinder.tpl\n */", "require_once(\"../../../../exponent.php\");\nif (empty($user->id))\n exit();", "if (DEVELOPMENT) {\n set_time_limit(0);\n} // just in case it too long, not recommended for production", "ini_set('max_file_uploads', FM_SIMLIMIT); // allow uploading up to FM_SIMLIMIT files at once", "// needed for case insensitive search to work, due to broken UTF-8 support in PHP\n//ini_set('mbstring.internal_encoding', 'UTF-8');\n//ini_set('mbstring.func_overload', 2);", "include BASE . 'external/elFinder/php/elFinderConnector.class.php';\ninclude BASE . 'external/elFinder/php/elFinder.class.php';", "include BASE . 'external/elFinder/php/elFinderPlugin.php';\n//include BASE . 'external/elFinder/php/libs/GdBmp.php'; // will also autoload if needed\n//include BASE . 'external/elFinder/php/plugins/AutoResize/plugin.php'; // will also autoload if needed\n//include BASE . 'external/elFinder/php/plugins/AutoRotate/plugin.php';\n//include BASE . 'external/elFinder/php/plugins/Normalizer/plugin.php';\n//include BASE . 'external/elFinder/php/plugins/Sanitizer/plugin.php';\n//include BASE . 'external/elFinder/php/plugins/Watermark/plugin.php';\n//include BASE . 'external/elFinder/php/elFinderSessionInterface.php'; // will also autoload if needed\n//include BASE . 'external/elFinder/php/elFinderSession.php'; // will also autoload if needed", "include BASE . 'framework/modules/file/connector/elFinderExponent.class.php'; // our custom elFinder object", "include BASE . 'external/elFinder/php/elFinderVolumeDriver.class.php';\ninclude BASE . 'external/elFinder/php/elFinderVolumeLocalFileSystem.class.php';\n//include BASE . 'external/elFinder/php/elFinderVolumeMySQL.class.php';\n//include BASE . 'external/elFinder/php/elFinderVolumeFTP.class.php';\n//include BASE . 'external/elFinder/php/elFinderVolumeS3.class.php';\ninclude BASE . 'framework/modules/file/connector/elFinderVolumeExponent.class.php'; // our custom elFinder volume driver", "define('ELFINDER_IMG_PARENT_URL', PATH_RELATIVE . 'external/elFinder/');", "/**\n * # Dropbox volume driver need \"dropbox-php's Dropbox\" and \"PHP OAuth extension\" or \"PEAR's HTTP_OAUTH package\"\n * * dropbox-php: http://www.dropbox-php.com/\n * * PHP OAuth extension: http://pecl.php.net/package/oauth\n * * PEAR's HTTP_OAUTH package: http://pear.php.net/package/http_oauth\n * * HTTP_OAUTH package require HTTP_Request2 and Net_URL2\n */\n// Required for Dropbox.com connector support\n//include BASE . 'external/elFinder/php/elFinderVolumeDropbox.class.php';", "// Dropbox driver need next two settings. You can get at https://www.dropbox.com/developers\n// define('ELFINDER_DROPBOX_CONSUMERKEY', '');\n// define('ELFINDER_DROPBOX_CONSUMERSECRET', '');\n// define('ELFINDER_DROPBOX_META_CACHE_PATH',''); // optional for `options['metaCachePath']`", "function debug($o)\n{\n echo '<pre>';\n print_r($o);\n}", "/**\n * example logger function\n * Demonstrate how to work with elFinder event api\n *\n * @param string $cmd command name\n * @param array $result command result\n * @param array $args command arguments from client\n * @param elFinder $elfinder elFinder instance\n *\n * @return void|true\n * @author Troex Nevelin\n **/\nfunction logger($cmd, $result, $args, $elfinder)\n{\n if (DEVELOPMENT && LOGGER) {\n $log = sprintf(\"[%s] %s: %s \\n\", date('r'), strtoupper($cmd), var_export($result, true));\n $logfile = BASE . 'tmp/elfinder.log';\n $dir = dirname($logfile);\n if (!is_dir($dir) && !mkdir($dir, octdec(DIR_DEFAULT_MODE_STR + 0))) {\n return;\n }\n if (($fp = fopen($logfile, 'a'))) {\n fwrite($fp, $log);\n fclose($fp);\n }\n return;", "// // alternative logging method\n// foreach ($result as $key => $value) {\n// if (empty($value)) {\n// continue;\n// }\n// $data = array();\n// if (in_array($key, array('error', 'warning'))) {\n// array_push($data, implode(' ', $value));\n// } else {\n// if (is_array($value)) { // changes made to files\n// foreach ($value as $file) {\n// $filepath = (isset($file['realpath']) ? $file['realpath'] : $elfinder->realpath($file['hash']));\n// array_push($data, $filepath);\n// }\n// } else { // other value (ex. header)\n// array_push($data, $value);\n// }\n// }\n// $log .= sprintf(' %s(%s)', $key, implode(', ', $data));\n// }\n// $log .= \"\\n\";\n//\n// $logfile = BASE . 'tmp/elfinder.log';\n// $dir = dirname($logfile);\n// if (!is_dir($dir) && !mkdir($dir)) {\n// return;\n// }\n// if (($fp = fopen($logfile, 'a'))) {\n// fwrite($fp, $log);\n// fclose($fp);\n// }\n }\n}", "/**\n * example logger class\n * Demonstrate how to work with elFinder event api.\n *\n * @package elFinder\n * @author Dmitry (dio) Levashov\n **/\nclass elFinderSimpleLogger\n{", " /**\n * Log file path\n *\n * @var string\n **/\n protected $file = '';", " /**\n * constructor\n *\n * @param $path\n *\n * @return \\elFinderSimpleLogger\n * @author Dmitry (dio) Levashov\n */\n public function __construct($path)\n {\n $this->file = $path;\n $dir = dirname($path);\n if (!is_dir($dir)) {\n mkdir($dir, octdec(DIR_DEFAULT_MODE_STR + 0));\n }\n }", " /**\n * Create log record\n *\n * @param string $cmd command name\n * @param array $result command result\n * @param array $args command arguments from client\n * @param elFinder $elfinder elFinder instance\n *\n * @return void|true\n * @author Dmitry (dio) Levashov\n **/\n public function log($cmd, $result, $args, $elfinder)\n {\n if (DEVELOPMENT && LOGGER) {\n $log = $cmd . ' [' . date('d.m H:s') . \"]\\n\";", " if (!empty($result['error'])) {\n $log .= \"\\tERROR: \" . implode(' ', $result['error']) . \"\\n\";\n }", " if (!empty($result['warning'])) {\n $log .= \"\\tWARNING: \" . implode(' ', $result['warning']) . \"\\n\";\n }", " if (!empty($result['removed'])) {\n foreach ($result['removed'] as $file) {\n // removed file contain additional field \"realpath\"\n $log .= \"\\tREMOVED: \" . $file['realpath'] . \"\\n\";\n }\n }", " if (!empty($result['added'])) {\n foreach ($result['added'] as $file) {\n $log .= \"\\tADDED: \" . $elfinder->realpath($file['hash']) . \"\\n\";\n }\n }", " if (!empty($result['changed'])) {\n foreach ($result['changed'] as $file) {\n $log .= \"\\tCHANGED: \" . $elfinder->realpath($file['hash']) . \"\\n\";\n }\n }", " $this->write($log);\n $this->write(var_export($result, true), true);\n }\n }", " /**\n * Write log into file\n *\n * @param string $log log record\n *\n * @return void\n * @author Dmitry (dio) Levashov\n **/\n protected function write($log, $eol=false)\n {\n if ($eol)\n $eol = \"\\n\";\n if (($fp = @fopen($this->file, 'a'))) {\n fwrite($fp, $log . $eol);\n fclose($fp);\n }\n }", "} // END class\n//$logger = new elFinderSimpleLogger(BASE.'tmp/elfinder.log');", "/**\n * example accessControl function\n * to demonstrate how to control file access using \"accessControl\" callback.\n * This method will disable accessing files/folders starting from '.' (dot)\n *\n * @param string $attr attribute name (read|write|locked|hidden)\n * @param string $path file path relative to volume root directory started with directory separator\n * @param $data\n * @param object $volume elFinder volume driver object\n * @param bool|null $isDir path is directory (true: directory, false: file, null: unknown)\n *\n * @return bool|null\n */\nfunction access($attr, $path, $data, $volume, $isDir) {\n\treturn strpos(basename($path), '.') === 0 // if file/folder begins with '.' (dot)\n\t\t? !($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true\n\t\t: null; // else elFinder decide it itself\n}", "/**\n * example accessControl class\n *\n * @author Dmitry (dio) Levashov\n **/\nclass elFinderTestACL\n{", " /**\n * make dotfiles not readable, not writable, hidden and locked\n *\n * @param string $attr attribute name (read|write|locked|hidden)\n * @param string $path file path. Attention! This is path relative to volume root directory started with directory separator.\n * @param mixed $data data which seted in 'accessControlData' elFinder option\n * @param elFinderVolumeDriver $volume volume driver\n *\n * @return bool\n * @author Dmitry (dio) Levashov\n **/\n public function fsAccess($attr, $path, $data, $volume)\n {", " if ($volume->name() == 'localfilesystem') {\n return strpos(basename($path), '.') === 0\n ? !($attr == 'read' || $attr == 'write')\n : $attr == 'read' || $attr == 'write';\n }", " return true;\n }", "} // END class\n//$acl = new elFinderTestACL();", "/**\n * example acceptedName function\n */\nfunction validName($name)\n{\n return strpos($name, '.') !== 0;\n}", "$opts = array(\n 'locale' => LOCALE . '.' . LANG_CHARSET,\n 'bind' => array(\n // '*' => 'logger',\n 'mkdir mkfile rename duplicate upload rm paste' => 'logger', // use function style logger\n// 'mkdir mkfile rename duplicate upload rm paste' => array($logger, 'log'), // use class style logger\n// 'upload.pre mkdir.pre mkfile.pre rename.pre archive.pre ls.pre' => array(\n// 'Plugin.Normalizer.cmdPreprocess',\n// 'Plugin.Sanitizer.cmdPreprocess',\n// ),\n// 'ls' => array(\n// 'Plugin.Normalizer.cmdPostprocess',\n// 'Plugin.Sanitizer.cmdPostprocess',\n// ),\n 'upload.presave' => array(\n 'Plugin.AutoResize.onUpLoadPreSave',\n// 'Plugin.Watermark.onUpLoadPreSave',\n// 'Plugin.Normalizer.onUpLoadPreSave',\n// 'Plugin.Sanitizer.onUpLoadPreSave',\n// 'Plugin.AutoRotate.onUpLoadPreSave',\n ),\n ),\n // global plugin configure (optional)\n 'plugin' => array(\n 'AutoResize' => array(\n 'enable' => UPLOAD_WIDTH, // For control by volume driver\n 'maxWidth' => UPLOAD_WIDTH,\n 'maxHeight' => UPLOAD_WIDTH,\n 'quality' => THUMB_QUALITY, // JPEG image save quality\n 'targetType' => IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP, // Target image formats ( bit-field )\n// 'forceEffect' => false, // For change quality of small images\n// 'preserveExif' => false, // Preserve EXIF data (Imagick only)\n ),\n// 'Watermark' => array(\n// 'enable' => true, // For control by volume driver\n// 'source' => 'logo.png', // Path to Water mark image\n// 'marginRight' => 5, // Margin right pixel\n// 'marginBottom' => 5, // Margin bottom pixel\n// 'quality' => THUMB_QUALITY, // JPEG image save quality\n// 'transparency' => 70, // Water mark image transparency ( other than PNG )\n// 'targetType' => IMG_GIF|IMG_JPG|IMG_PNG|IMG_WBMP, // Target image formats ( bit-field )\n// 'targetMinPixel' => 200 // Target image minimum pixel size\n// ),\n// 'Normalizer' => array(\n// 'enable' => true,\n// 'nfc' => true,\n// 'nfkc' => true,\n// 'lowercase' => false,\n// 'convmap' => array()\n// ),\n// 'Sanitizer' => array(\n// 'enable' => true,\n// 'targets' => array('\\\\','/',':','*','?','\"','<','>','|'), // target chars\n// 'replace' => '_' // replace to this\n// ),\n// 'AutoRotate' => array(\n// 'enable' => true, // For control by volume driver\n// 'quality' => 95 // JPEG image save quality\n// )\n ),\n 'debug' => DEVELOPMENT,\n//\t'netVolumesSessionKey' => 'netVolumes',\n 'callbackWindowURL' => makeLink(array('controller'=>'file','action'=>'picker','ajax_action'=>1)),", " 'roots' => array(\n array(\n // 'id' => 'x5',\n 'driver' => 'Exponent',\n 'path' => BASE . 'files/',\n 'URL' => URL_FULL . 'files/',\n 'dirMode' => octdec(DIR_DEFAULT_MODE_STR + 0), // new dirs mode (default 0755)\n 'fileMode' => octdec(FILE_DEFAULT_MODE_STR + 0), // new files mode (default 0644)\n 'detectDirIcon' => '.foldericon.png', // File to be detected as a folder icon image (elFinder >= 2.1.10) e.g. '.favicon.png'\n 'keepTimestamp' => array('copy', 'move'), // Keep timestamp at inner filesystem (elFinder >= 2.1.12) It allowed 'copy', 'move' and 'upload'.\n // 'treeDeep' => 3,\n 'alias' => 'files',\n 'disabled' => array('netmount'),\n// 'maxArcFilesSize' => 100,\n 'accessControl' => 'access',\n // 'accessControl' => array($acl, 'fsAccess'),\n // 'accessControlData' => array('uid' => 1),\n 'uploadAllow' => array(\n 'application/arj',\n 'application/excel',\n 'application/gnutar',\n 'application/mspowerpoint',\n 'application/msword',\n 'application/octet-stream',\n 'application/onenote',\n 'application/pdf',\n 'application/plain',\n 'application/postscript',\n 'application/powerpoint',\n 'application/rar',\n 'application/rtf',\n 'application/vnd.ms-excel',\n 'application/vnd.ms-excel.addin.macroEnabled.12',\n 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',\n 'application/vnd.ms-excel.sheet.macroEnabled.12',\n 'application/vnd.ms-excel.template.macroEnabled.12',\n 'application/vnd.ms-office',\n 'application/vnd.ms-officetheme',\n 'application/vnd.ms-powerpoint',\n 'application/vnd.ms-powerpoint.addin.macroEnabled.12',\n 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',\n 'application/vnd.ms-powerpoint.slide.macroEnabled.12',\n 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',\n 'application/vnd.ms-powerpoint.template.macroEnabled.12',\n 'application/vnd.ms-word',\n 'application/vnd.ms-word.document.macroEnabled.12',\n 'application/vnd.ms-word.template.macroEnabled.12',\n 'application/vnd.oasis.opendocument.chart',\n 'application/vnd.oasis.opendocument.database',\n 'application/vnd.oasis.opendocument.formula',\n 'application/vnd.oasis.opendocument.graphics',\n 'application/vnd.oasis.opendocument.graphics-template',\n 'application/vnd.oasis.opendocument.image',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.presentation-template',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.spreadsheet-template',\n 'application/vnd.oasis.opendocument.text',\n 'application/vnd.oasis.opendocument.text-master',\n 'application/vnd.oasis.opendocument.text-template',\n 'application/vnd.oasis.opendocument.text-web',\n 'application/vnd.openofficeorg.extension',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'application/vnd.openxmlformats-officedocument.presentationml.slide',\n 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',\n 'application/vnd.openxmlformats-officedocument.presentationml.template',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',\n 'application/vocaltec-media-file',\n 'application/wordperfect',\n 'application/x-bittorrent',\n 'application/x-bzip',\n 'application/x-bzip2',\n 'application/x-compressed',\n 'application/x-excel',\n 'application/x-gzip',\n 'application/x-latex',\n 'application/x-midi',\n 'application/xml',\n 'application/x-msexcel',\n 'application/x-rar',\n 'application/x-rar-compressed',\n 'application/x-rtf',\n 'application/x-shockwave-flash',\n 'application/x-sit',\n 'application/x-stuffit',\n 'application/x-troff-msvideo',\n 'application/x-zip',\n 'application/x-zip-compressed',\n 'application/zip',\n 'audio',\n 'image',\n 'multipart/x-gzip',\n 'multipart/x-zip',\n 'text/plain',\n 'text/rtf',\n 'text/richtext',\n 'text/xml',\n 'video',\n 'text/csv'\n ),\n 'uploadDeny' => array(\n 'application/x-shockwave-flash'\n ),\n 'uploadOrder' => 'allow,deny',\n 'uploadOverwrite' => true,\n// 'uploadMaxSize' => '128m',\n // 'copyOverwrite' => false,\n 'copyJoin' => true,\n// 'mimeDetect' => 'internal',\n// 'tmpPath' => BASE . 'tmp',\n 'tmbCrop' => false,\n// 'imgLib' => 'gd', // 'auto' doesn't seem to work on some servers\n 'tmbPath' => BASE . 'tmp' . DIRECTORY_SEPARATOR . 'elfinder',\n 'tmbURL' => URL_FULL . 'tmp/elfinder/',\n 'tmbPathMode' => octdec(DIR_DEFAULT_MODE_STR + 0),\n 'tmbBgColor' => 'transparent',\n 'tmbSize' => FM_THUMB_SIZE,\n 'quarantine' => '..' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'elfinder' . DIRECTORY_SEPARATOR . '.quarantine',\n 'acceptedName' => '/^[^\\.].*$/',\n // 'acceptedName' => '/^[\\W]*$/',\n // 'acceptedName' => 'validName',\n 'utf8fix' => false,\n// 'statOwner' => true,\n 'attributes' => array(\n array(\n 'pattern' => '/^\\/\\./', // dot files are hidden\n 'read' => false,\n 'write' => false,\n 'hidden' => true,\n 'locked' => true\n )\n )\n )\n )\n);", "//header('Access-Control-Allow-Origin: *');", "$connector = new elFinderConnector(new elFinderExponent($opts));", "$connector->run();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [513], "buggy_code_start_loc": [512], "filenames": ["framework/modules/file/connector/elfinder.php"], "fixing_code_end_loc": [513], "fixing_code_start_loc": [512], "message": "In Exponent CMS before 2.4.1 Patch #5, XSS in elFinder is possible in framework/modules/file/connector/elfinder.php.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:*:p4:*:*:*:*:*:*", "matchCriteriaId": "BFC75474-A888-413E-B7EF-E76FE79504B9", "versionEndExcluding": null, "versionEndIncluding": "2.4.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Exponent CMS before 2.4.1 Patch #5, XSS in elFinder is possible in framework/modules/file/connector/elfinder.php."}, {"lang": "es", "value": "En Exponent CMS en versiones anteriores a 2.4.1 Patch #5, XSS en elFinder es posible en framework/modules/file/connector/elfinder.php."}], "evaluatorComment": null, "id": "CVE-2017-8085", "lastModified": "2017-04-29T01:59:02.130", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-04-24T14:59:00.183", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://www.exponentcms.org/news/patch-5-released-for-v2-4-1-to-fix-a-few-critical-issues"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/98043"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/exponentcms/exponent-cms/commit/0b2241ff1c7d86376fa260c5d4c1714f6cef9c0f"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/exponentcms/exponent-cms/releases/tag/v2.4.1patch5"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/0b2241ff1c7d86376fa260c5d4c1714f6cef9c0f"}, "type": "CWE-79"}
290
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (C) 2015 Cisco Systems, Inc. and/or its affiliates. All rights reserved.\n * Copyright (C) 2013 Sourcefire, Inc.\n *\n * Authors: Steven Morgan <smorgan@sourcefire.com>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n */", "#if HAVE_CONFIG_H\n#include \"clamav-config.h\"\n#endif", "#include <errno.h>\n#include \"xar.h\"\n#include \"fmap.h\"\n#if HAVE_LIBXML2\n#ifdef _WIN32\n#ifndef LIBXML_WRITER_ENABLED\n#define LIBXML_WRITER_ENABLED 1\n#endif\n#endif\n#include <libxml/xmlreader.h>\n#include \"clamav.h\"\n#include \"str.h\"\n#include \"scanners.h\"\n#include \"inflate64.h\"\n#include \"lzma_iface.h\"", "/*\n xar_cleanup_temp_file - cleanup after cli_gentempfd\n parameters:\n ctx - cli_ctx context pointer\n fd - fd to close\n tmpname - name of file to unlink, address of storage to free\n returns - CL_SUCCESS or CL_EUNLINK\n */\nstatic int xar_cleanup_temp_file(cli_ctx *ctx, int fd, char * tmpname)\n{\n int rc = CL_SUCCESS;\n if (fd > -1)\n close(fd);\n if (tmpname != NULL) {\n if (!ctx->engine->keeptmp) {\n if (cli_unlink(tmpname)) {\n cli_dbgmsg(\"cli_scanxar: error unlinking tmpfile %s\\n\", tmpname); \n rc = CL_EUNLINK;\n }\n }\n free(tmpname);\n }\n return rc;\n}", "/*\n xar_get_numeric_from_xml_element - extract xml element value as numeric\n parameters:\n reader - xmlTextReaderPtr\n value - pointer to long to contain the returned value\n returns - CL_SUCCESS or CL_EFORMAT\n */", "static int xar_get_numeric_from_xml_element(xmlTextReaderPtr reader, long * value)", "{\n const xmlChar * numstr;", "", " if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {\n numstr = xmlTextReaderConstValue(reader);\n if (numstr) {", " *value = atol((const char *)numstr);\n if (*value < 0) {", " cli_dbgmsg(\"cli_scanxar: XML element value %li\\n\", *value);\n return CL_EFORMAT;\n }", "", " return CL_SUCCESS;\n }\n }\n cli_dbgmsg(\"cli_scanxar: No text for XML element\\n\");\n return CL_EFORMAT;\n}", "/*\n xar_get_checksum_values - extract checksum and hash algorithm from xml element\n parameters:\n reader - xmlTextReaderPtr\n cksum - pointer to char* for returning checksum value.\n hash - pointer to int for returning checksum algorithm.\n returns - void\n */\nstatic void xar_get_checksum_values(xmlTextReaderPtr reader, unsigned char ** cksum, int * hash)\n{\n xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)\"style\");\n const xmlChar * xmlval;", " *hash = XAR_CKSUM_NONE;\n if (style == NULL) {\n cli_dbgmsg(\"cli_scaxar: xmlTextReaderGetAttribute no style attribute \"\n \"for checksum element\\n\");\n } else {\n cli_dbgmsg(\"cli_scanxar: checksum algorithm is %s.\\n\", style); \n if (0 == xmlStrcasecmp(style, (const xmlChar *)\"sha1\")) {\n *hash = XAR_CKSUM_SHA1;\n } else if (0 == xmlStrcasecmp(style, (const xmlChar *)\"md5\")) {\n *hash = XAR_CKSUM_MD5;\n } else {\n cli_dbgmsg(\"cli_scanxar: checksum algorithm %s is unsupported.\\n\", style);\n *hash = XAR_CKSUM_OTHER;\n }\n }\n if (style != NULL)\n xmlFree(style);", " if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {\n xmlval = xmlTextReaderConstValue(reader);\n if (xmlval) {", " *cksum = xmlStrdup(xmlval); \n cli_dbgmsg(\"cli_scanxar: checksum value is %s.\\n\", *cksum);", " } else {\n *cksum = NULL;\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderConstValue() returns NULL for checksum value.\\n\"); \n }\n }\n else\n cli_dbgmsg(\"cli_scanxar: No text for XML checksum element.\\n\");\n}", "/*\n xar_get_toc_data_values - return the values of a <data> or <ea> xml element that represent \n an extent of data on the heap.\n parameters:\n reader - xmlTextReaderPtr\n length - pointer to long for returning value of the <length> element.\n offset - pointer to long for returning value of the <offset> element.\n size - pointer to long for returning value of the <size> element.\n encoding - pointer to int for returning indication of the <encoding> style attribute.\n a_cksum - pointer to char* for return archived checksum value.\n a_hash - pointer to int for returning archived checksum algorithm.\n e_cksum - pointer to char* for return extracted checksum value.\n e_hash - pointer to int for returning extracted checksum algorithm.\n returns - CL_FORMAT, CL_SUCCESS, CL_BREAK. CL_BREAK indicates no more <data>/<ea> element.\n */", "static int xar_get_toc_data_values(xmlTextReaderPtr reader, long *length, long *offset, long *size, int *encoding,", " unsigned char ** a_cksum, int * a_hash, unsigned char ** e_cksum, int * e_hash)\n{\n const xmlChar *name;\n int indata = 0, inea = 0;\n int rc, gotoffset=0, gotlength=0, gotsize=0;", " *a_cksum = NULL;\n *a_hash = XAR_CKSUM_NONE;\n *e_cksum = NULL;\n *e_hash = XAR_CKSUM_NONE;\n *encoding = CL_TYPE_ANY;", " rc = xmlTextReaderRead(reader);\n while (rc == 1) {\n name = xmlTextReaderConstLocalName(reader);\n if (indata || inea) {\n /* cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read %s\\n\", name); */\n if (xmlStrEqual(name, (const xmlChar *)\"offset\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset))\n gotoffset=1;", " } else if (xmlStrEqual(name, (const xmlChar *)\"length\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length))\n gotlength=1;", " } else if (xmlStrEqual(name, (const xmlChar *)\"size\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size))\n gotsize=1;", " } else if (xmlStrEqual(name, (const xmlChar *)\"archived-checksum\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n cli_dbgmsg(\"cli_scanxar: <archived-checksum>:\\n\");\n xar_get_checksum_values(reader, a_cksum, a_hash);\n \n } else if ((xmlStrEqual(name, (const xmlChar *)\"extracted-checksum\") ||\n xmlStrEqual(name, (const xmlChar *)\"unarchived-checksum\")) &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n cli_dbgmsg(\"cli_scanxar: <extracted-checksum>:\\n\");\n xar_get_checksum_values(reader, e_cksum, e_hash);", " } else if (xmlStrEqual(name, (const xmlChar *)\"encoding\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)\"style\");\n if (style == NULL) {\n cli_dbgmsg(\"cli_scaxar: xmlTextReaderGetAttribute no style attribute \"\n \"for encoding element\\n\");\n *encoding = CL_TYPE_ANY;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-gzip\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-gzip.\\n\");\n *encoding = CL_TYPE_GZ; \n } else if (xmlStrEqual(style, (const xmlChar *)\"application/octet-stream\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/octet-stream.\\n\");\n *encoding = CL_TYPE_ANY; \n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-bzip2\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-bzip2.\\n\");\n *encoding = CL_TYPE_BZ;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-lzma\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-lzma.\\n\");\n *encoding = CL_TYPE_7Z;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-xz\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-xz.\\n\");\n *encoding = CL_TYPE_XZ;\n } else {\n cli_dbgmsg(\"cli_scaxar: unknown style value=%s for encoding element\\n\", style);\n *encoding = CL_TYPE_ANY;\n }\n if (style != NULL)\n xmlFree(style);", " } else if (indata && xmlStrEqual(name, (const xmlChar *)\"data\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {\n break;", " } else if (inea && xmlStrEqual(name, (const xmlChar *)\"ea\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {\n break;\n }\n \n } else {\n if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (xmlStrEqual(name, (const xmlChar *)\"data\")) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read <data>\\n\");\n indata = 1;\n } else if (xmlStrEqual(name, (const xmlChar *)\"ea\")) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read <ea>\\n\");\n inea = 1;\n }\n } else if ((xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) &&\n xmlStrEqual(name, (const xmlChar *)\"xar\")) {\n cli_dbgmsg(\"cli_scanxar: finished parsing xar TOC.\\n\"); \n break;\n }\n }\n rc = xmlTextReaderRead(reader);\n }\n \n if (gotoffset && gotlength && gotsize) {\n rc = CL_SUCCESS;\n }\n else if (0 == gotoffset + gotlength + gotsize)\n rc = CL_BREAK;\n else\n rc = CL_EFORMAT;", " return rc;\n}", "/*\n xar_process_subdocument - check TOC for xml subdocument. If found, extract and\n scan in memory.\n Parameters:\n reader - xmlTextReaderPtr\n ctx - pointer to cli_ctx\n Returns:\n CL_SUCCESS - subdoc found and clean scan (or virus found and SCAN_ALL), or no subdocument\n other - error return code from cli_mem_scandesc()\n*/ \nstatic int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx)\n{\n int rc = CL_SUCCESS, subdoc_len, fd;\n xmlChar * subdoc;\n const xmlChar *name;\n char * tmpname;", " while (xmlTextReaderRead(reader) == 1) {\n name = xmlTextReaderConstLocalName(reader);\n if (name == NULL) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderConstLocalName() no name.\\n\");\n rc = CL_EFORMAT;\n break;\n }\n if (xmlStrEqual(name, (const xmlChar *)\"toc\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT)\n return CL_SUCCESS;\n if (xmlStrEqual(name, (const xmlChar *)\"subdoc\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n subdoc = xmlTextReaderReadInnerXml(reader);\n if (subdoc == NULL) {\n cli_dbgmsg(\"cli_scanxar: no content in subdoc element.\\n\");\n xmlTextReaderNext(reader);\n continue;\n }\n subdoc_len = xmlStrlen(subdoc);\n cli_dbgmsg(\"cli_scanxar: in-memory scan of xml subdocument, len %i.\\n\", subdoc_len);\n rc = cli_mem_scandesc(subdoc, subdoc_len, ctx);\n if (rc == CL_VIRUS && SCAN_ALL)\n rc = CL_SUCCESS;\n \n /* make a file to leave if --leave-temps in effect */\n if(ctx->engine->keeptmp) {\n if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {\n cli_dbgmsg(\"cli_scanxar: Can't create temporary file for subdocument.\\n\");\n } else {\n cli_dbgmsg(\"cli_scanxar: Writing subdoc to temp file %s.\\n\", tmpname);\n if (cli_writen(fd, subdoc, subdoc_len) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error writing subdoc temporary file.\\n\");\n rc = CL_EWRITE;\n }\n rc = xar_cleanup_temp_file(ctx, fd, tmpname);\n }\n }", " xmlFree(subdoc);\n if (rc != CL_SUCCESS)\n return rc;\n xmlTextReaderNext(reader);\n } \n }\n return rc;\n}", "static void * xar_hash_init(int hash, void **sc, void **mc)\n{\n if (!sc && !mc)\n return NULL;\n switch (hash) {\n case XAR_CKSUM_SHA1:\n *sc = cl_hash_init(\"sha1\");\n if (!(*sc)) {\n return NULL;\n }", " return *sc;\n case XAR_CKSUM_MD5:\n *mc = cl_hash_init(\"md5\");\n if (!(*mc)) {\n return NULL;\n }", " return *mc;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return NULL;\n }\n}", "static void xar_hash_update(void * hash_ctx, void * data, unsigned long size, int hash)\n{\n if (!hash_ctx || !data || !size)\n return;", " switch (hash) {\n case XAR_CKSUM_NONE:\n case XAR_CKSUM_OTHER:\n return;\n }", " cl_update_hash(hash_ctx, data, size);\n}", "static void xar_hash_final(void * hash_ctx, void * result, int hash)\n{\n if (!hash_ctx || !result)\n return;", " switch (hash) {\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n return;\n }", " cl_finish_hash(hash_ctx, result);\n}", "static int xar_hash_check(int hash, const void * result, const void * expected)\n{\n int len;", " if (!result || !expected)\n return 1;\n switch (hash) {\n case XAR_CKSUM_SHA1:", " len = SHA1_HASH_SIZE;", " break;\n case XAR_CKSUM_MD5:", " len = CLI_HASH_MD5;", " break;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return 1;\n }\n return memcmp(result, expected, len);\n}", "#endif", "/*\n cli_scanxar - scan an xar archive.\n Parameters:\n ctx - pointer to cli_ctx.\n returns - CL_SUCCESS or CL_ error code.\n*/", "int cli_scanxar(cli_ctx *ctx)\n{\n int rc = CL_SUCCESS;\n unsigned int cksum_fails = 0;\n unsigned int extract_errors = 0;\n#if HAVE_LIBXML2\n int fd = -1;\n struct xar_header hdr;\n fmap_t *map = *ctx->fmap;", " long length, offset, size, at;", " int encoding;\n z_stream strm;\n char *toc, *tmpname;\n xmlTextReaderPtr reader = NULL;\n int a_hash, e_hash;\n unsigned char *a_cksum = NULL, *e_cksum = NULL;\n void *a_hash_ctx = NULL, *e_hash_ctx = NULL;\n char result[SHA1_HASH_SIZE];", " memset(&strm, 0x00, sizeof(z_stream));", " /* retrieve xar header */\n if (fmap_readn(*ctx->fmap, &hdr, 0, sizeof(hdr)) != sizeof(hdr)) {\n cli_dbgmsg(\"cli_scanxar: Invalid header, too short.\\n\");\n return CL_EFORMAT;\n }\n hdr.magic = be32_to_host(hdr.magic);", " if (hdr.magic == XAR_HEADER_MAGIC) {\n cli_dbgmsg(\"cli_scanxar: Matched magic\\n\");\n }\n else {\n cli_dbgmsg(\"cli_scanxar: Invalid magic\\n\");\n return CL_EFORMAT;\n }\n hdr.size = be16_to_host(hdr.size);\n hdr.version = be16_to_host(hdr.version);\n hdr.toc_length_compressed = be64_to_host(hdr.toc_length_compressed);\n hdr.toc_length_decompressed = be64_to_host(hdr.toc_length_decompressed);\n hdr.chksum_alg = be32_to_host(hdr.chksum_alg);", " /* cli_dbgmsg(\"hdr.magic %x\\n\", hdr.magic); */\n /* cli_dbgmsg(\"hdr.size %i\\n\", hdr.size); */\n /* cli_dbgmsg(\"hdr.version %i\\n\", hdr.version); */\n /* cli_dbgmsg(\"hdr.toc_length_compressed %lu\\n\", hdr.toc_length_compressed); */\n /* cli_dbgmsg(\"hdr.toc_length_decompressed %lu\\n\", hdr.toc_length_decompressed); */\n /* cli_dbgmsg(\"hdr.chksum_alg %i\\n\", hdr.chksum_alg); */\n \n /* Uncompress TOC */\n strm.next_in = (unsigned char *)fmap_need_off_once(*ctx->fmap, hdr.size, hdr.toc_length_compressed);\n if (strm.next_in == NULL) {\n cli_dbgmsg(\"cli_scanxar: fmap_need_off_once fails on TOC.\\n\");\n return CL_EREAD;\n }\n strm.avail_in = hdr.toc_length_compressed; \n toc = cli_malloc(hdr.toc_length_decompressed+1);\n if (toc == NULL) {\n cli_dbgmsg(\"cli_scanxar: cli_malloc fails on TOC decompress buffer.\\n\");\n return CL_EMEM;\n }\n toc[hdr.toc_length_decompressed] = '\\0';\n strm.avail_out = hdr.toc_length_decompressed;\n strm.next_out = (unsigned char *)toc;\n rc = inflateInit(&strm);\n if (rc != Z_OK) {\n cli_dbgmsg(\"cli_scanxar:inflateInit error %i \\n\", rc);\n rc = CL_EFORMAT;\n goto exit_toc;\n } \n rc = inflate(&strm, Z_SYNC_FLUSH);\n if (rc != Z_OK && rc != Z_STREAM_END) {\n cli_dbgmsg(\"cli_scanxar:inflate error %i \\n\", rc);\n rc = CL_EFORMAT;\n goto exit_toc;\n }\n rc = inflateEnd(&strm);\n if (rc != Z_OK) {\n cli_dbgmsg(\"cli_scanxar:inflateEnd error %i \\n\", rc);\n rc = CL_EFORMAT;\n goto exit_toc;\n }\n", "", " /* cli_dbgmsg(\"cli_scanxar: TOC xml:\\n%s\\n\", toc); */\n /* printf(\"cli_scanxar: TOC xml:\\n%s\\n\", toc); */\n /* cli_dbgmsg(\"cli_scanxar: TOC end:\\n\"); */\n /* printf(\"cli_scanxar: TOC end:\\n\"); */", " /* scan the xml */\n cli_dbgmsg(\"cli_scanxar: scanning xar TOC xml in memory.\\n\"); \n rc = cli_mem_scandesc(toc, hdr.toc_length_decompressed, ctx);\n if (rc != CL_SUCCESS) {\n if (rc != CL_VIRUS || !SCAN_ALL)\n goto exit_toc; \n }", " /* make a file to leave if --leave-temps in effect */\n if(ctx->engine->keeptmp) {\n if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {\n cli_dbgmsg(\"cli_scanxar: Can't create temporary file for TOC.\\n\");\n goto exit_toc;\n }\n if (cli_writen(fd, toc, hdr.toc_length_decompressed) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error writing TOC.\\n\");\n rc = CL_EWRITE;\n xar_cleanup_temp_file(ctx, fd, tmpname);\n goto exit_toc;\n }\n rc = xar_cleanup_temp_file(ctx, fd, tmpname);\n if (rc != CL_SUCCESS)\n goto exit_toc;\n }", " reader = xmlReaderForMemory(toc, hdr.toc_length_decompressed, \"noname.xml\", NULL, CLAMAV_MIN_XMLREADER_FLAGS);\n if (reader == NULL) {\n cli_dbgmsg(\"cli_scanxar: xmlReaderForMemory error for TOC\\n\");\n goto exit_toc;\n }", " rc = xar_scan_subdocuments(reader, ctx);\n if (rc != CL_SUCCESS) {\n cli_dbgmsg(\"xar_scan_subdocuments returns %i.\\n\", rc);\n goto exit_reader;\n }", " /* Walk the TOC XML and extract files */\n fd = -1;\n tmpname = NULL;\n while (CL_SUCCESS == (rc = xar_get_toc_data_values(reader, &length, &offset, &size, &encoding,\n &a_cksum, &a_hash, &e_cksum, &e_hash))) {\n int do_extract_cksum = 1;\n unsigned char * blockp;\n void *a_sc, *e_sc;\n void *a_mc, *e_mc;\n char * expected;", " /* clean up temp file from previous loop iteration */\n if (fd > -1 && tmpname) {\n rc = xar_cleanup_temp_file(ctx, fd, tmpname);\n if (rc != CL_SUCCESS)\n goto exit_reader;\n }", " at = offset + hdr.toc_length_compressed + hdr.size;", " if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {\n cli_dbgmsg(\"cli_scanxar: Can't generate temporary file.\\n\");\n goto exit_reader;\n }\n", " cli_dbgmsg(\"cli_scanxar: decompress into temp file:\\n%s, size %li,\\n\"\n \"from xar heap offset %li length %li\\n\",", " tmpname, size, offset, length);", "\n a_hash_ctx = xar_hash_init(a_hash, &a_sc, &a_mc);\n e_hash_ctx = xar_hash_init(e_hash, &e_sc, &e_mc);", " switch (encoding) {\n case CL_TYPE_GZ:\n /* inflate gzip directly because file segments do not contain magic */\n memset(&strm, 0, sizeof(strm));\n if ((rc = inflateInit(&strm)) != Z_OK) {\n cli_dbgmsg(\"cli_scanxar: InflateInit failed: %d\\n\", rc);\n rc = CL_EFORMAT;\n extract_errors++;\n break;\n }\n \n while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {\n unsigned long avail_in;\n void * next_in;\n unsigned int bytes = MIN(map->len - at, map->pgsz);\n bytes = MIN(length, bytes);\n if(!(strm.next_in = next_in = (void*)fmap_need_off_once(map, at, bytes))) {\n cli_dbgmsg(\"cli_scanxar: Can't read %u bytes @ %lu.\\n\", bytes, (long unsigned)at);\n inflateEnd(&strm);\n rc = CL_EREAD;\n goto exit_tmpfile;\n }\n at += bytes;\n strm.avail_in = avail_in = bytes;\n do {\n int inf, outsize = 0;\n unsigned char buff[FILEBUFF];\n strm.avail_out = sizeof(buff);\n strm.next_out = buff;\n inf = inflate(&strm, Z_SYNC_FLUSH);\n if (inf != Z_OK && inf != Z_STREAM_END && inf != Z_BUF_ERROR) {\n cli_dbgmsg(\"cli_scanxar: inflate error %i %s.\\n\", inf, strm.msg?strm.msg:\"\");\n rc = CL_EFORMAT;\n extract_errors++;\n break;\n }", " bytes = sizeof(buff) - strm.avail_out;", " if (e_hash_ctx != NULL)\n xar_hash_update(e_hash_ctx, buff, bytes, e_hash);\n \n if (cli_writen(fd, buff, bytes) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error file %s.\\n\", tmpname);\n inflateEnd(&strm);\n rc = CL_EWRITE;\n goto exit_tmpfile;\n }\n outsize += sizeof(buff) - strm.avail_out;\n if (cli_checklimits(\"cli_scanxar\", ctx, outsize, 0, 0) != CL_CLEAN) {\n break;\n }\n if (inf == Z_STREAM_END) {\n break;\n }\n } while (strm.avail_out == 0);", " if (rc != CL_SUCCESS)\n break;", " avail_in -= strm.avail_in;\n if (a_hash_ctx != NULL)\n xar_hash_update(a_hash_ctx, next_in, avail_in, a_hash);\n }", " inflateEnd(&strm);\n break;\n case CL_TYPE_7Z:\n#define CLI_LZMA_OBUF_SIZE 1024*1024\n#define CLI_LZMA_HDR_SIZE LZMA_PROPS_SIZE+8\n#define CLI_LZMA_IBUF_SIZE CLI_LZMA_OBUF_SIZE>>2 /* estimated compression ratio 25% */\n {\n struct CLI_LZMA lz;", " unsigned long in_remaining = length;", " unsigned long out_size = 0;\n unsigned char * buff = __lzma_wrap_alloc(NULL, CLI_LZMA_OBUF_SIZE);\n int lret;", " ", " memset(&lz, 0, sizeof(lz));\n if (buff == NULL) {\n cli_dbgmsg(\"cli_scanxar: memory request for lzma decompression buffer fails.\\n\");\n rc = CL_EMEM;\n goto exit_tmpfile;\n \n }", " blockp = (void*)fmap_need_off_once(map, at, CLI_LZMA_HDR_SIZE);\n if (blockp == NULL) {\n char errbuff[128];\n cli_strerror(errno, errbuff, sizeof(errbuff));", " cli_dbgmsg(\"cli_scanxar: Can't read %li bytes @ %li, errno:%s.\\n\",\n length, at, errbuff);", " rc = CL_EREAD;\n __lzma_wrap_free(NULL, buff);\n goto exit_tmpfile;\n }", " lz.next_in = blockp;\n lz.avail_in = CLI_LZMA_HDR_SIZE;", " if (a_hash_ctx != NULL)\n xar_hash_update(a_hash_ctx, blockp, CLI_LZMA_HDR_SIZE, a_hash);", " lret = cli_LzmaInit(&lz, 0);\n if (lret != LZMA_RESULT_OK) {\n cli_dbgmsg(\"cli_scanxar: cli_LzmaInit() fails: %i.\\n\", lret);\n rc = CL_EFORMAT;\n __lzma_wrap_free(NULL, buff);\n extract_errors++;\n break;\n }", " at += CLI_LZMA_HDR_SIZE;\n in_remaining -= CLI_LZMA_HDR_SIZE;\n while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {\n SizeT avail_in;\n SizeT avail_out;\n void * next_in;\n unsigned long in_consumed;", " lz.next_out = buff;\n lz.avail_out = CLI_LZMA_OBUF_SIZE;\n lz.avail_in = avail_in = MIN(CLI_LZMA_IBUF_SIZE, in_remaining);\n lz.next_in = next_in = (void*)fmap_need_off_once(map, at, lz.avail_in);\n if (lz.next_in == NULL) {\n char errbuff[128];\n cli_strerror(errno, errbuff, sizeof(errbuff));\n cli_dbgmsg(\"cli_scanxar: Can't read %li bytes @ %li, errno: %s.\\n\",", " length, at, errbuff);", " rc = CL_EREAD;\n __lzma_wrap_free(NULL, buff);\n cli_LzmaShutdown(&lz);\n goto exit_tmpfile;\n }", " lret = cli_LzmaDecode(&lz);\n if (lret != LZMA_RESULT_OK && lret != LZMA_STREAM_END) {\n cli_dbgmsg(\"cli_scanxar: cli_LzmaDecode() fails: %i.\\n\", lret);\n rc = CL_EFORMAT;\n extract_errors++;\n break;\n }", " in_consumed = avail_in - lz.avail_in;\n in_remaining -= in_consumed;\n at += in_consumed;\n avail_out = CLI_LZMA_OBUF_SIZE - lz.avail_out;\n \n if (avail_out == 0)\n cli_dbgmsg(\"cli_scanxar: cli_LzmaDecode() produces no output for \"\n \"avail_in %llu, avail_out %llu.\\n\",\n (long long unsigned)avail_in, (long long unsigned)avail_out);", " if (a_hash_ctx != NULL)\n xar_hash_update(a_hash_ctx, next_in, in_consumed, a_hash); \n if (e_hash_ctx != NULL)\n xar_hash_update(e_hash_ctx, buff, avail_out, e_hash);", " /* Write a decompressed block. */\n /* cli_dbgmsg(\"Writing %li bytes to LZMA decompress temp file, \" */\n /* \"consumed %li of %li available compressed bytes.\\n\", */\n /* avail_out, in_consumed, avail_in); */", " if (cli_writen(fd, buff, avail_out) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error writing lzma temp file for %llu bytes.\\n\",\n (long long unsigned)avail_out);\n __lzma_wrap_free(NULL, buff);\n cli_LzmaShutdown(&lz);\n rc = CL_EWRITE;\n goto exit_tmpfile;\n }", " /* Check file size limitation. */\n out_size += avail_out;\n if (cli_checklimits(\"cli_scanxar\", ctx, out_size, 0, 0) != CL_CLEAN) {\n break;\n }", " if (lret == LZMA_STREAM_END)\n break;\n }", " cli_LzmaShutdown(&lz);\n __lzma_wrap_free(NULL, buff);\n }\n break; \n case CL_TYPE_ANY:\n default:\n case CL_TYPE_BZ:\n case CL_TYPE_XZ:\n /* for uncompressed, bzip2, xz, and unknown, just pull the file, cli_magic_scandesc does the rest */\n do_extract_cksum = 0;\n {", " unsigned long write_len;\n ", " if (ctx->engine->maxfilesize)", " write_len = MIN((size_t)(ctx->engine->maxfilesize), (size_t)length);\n else\n write_len = length;", " ", " if (!(blockp = (void*)fmap_need_off_once(map, at, length))) {", " char errbuff[128];\n cli_strerror(errno, errbuff, sizeof(errbuff));", " cli_dbgmsg(\"cli_scanxar: Can't read %li bytes @ %li, errno:%s.\\n\",\n length, at, errbuff);", " rc = CL_EREAD;\n goto exit_tmpfile;\n }\n \n if (a_hash_ctx != NULL)", " xar_hash_update(a_hash_ctx, blockp, length, a_hash);", " ", " if (cli_writen(fd, blockp, write_len) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error %li bytes @ %li.\\n\", length, at);", " rc = CL_EWRITE;\n goto exit_tmpfile;\n }\n /*break;*/\n } ", " }", "\n if (rc == CL_SUCCESS) {\n if (a_hash_ctx != NULL) {\n xar_hash_final(a_hash_ctx, result, a_hash);\n a_hash_ctx = NULL;\n } else {\n cli_dbgmsg(\"cli_scanxar: archived-checksum missing.\\n\");\n cksum_fails++;\n }\n if (a_cksum != NULL) {\n expected = cli_hex2str((char *)a_cksum);\n if (xar_hash_check(a_hash, result, expected) != 0) {\n cli_dbgmsg(\"cli_scanxar: archived-checksum mismatch.\\n\");\n cksum_fails++;\n } else {\n cli_dbgmsg(\"cli_scanxar: archived-checksum matched.\\n\"); \n }\n free(expected);\n }", " if (e_hash_ctx != NULL) {\n xar_hash_final(e_hash_ctx, result, e_hash);\n e_hash_ctx = NULL;\n } else {\n cli_dbgmsg(\"cli_scanxar: extracted-checksum(unarchived-checksum) missing.\\n\");\n cksum_fails++;\n }\n if (e_cksum != NULL) {\n if (do_extract_cksum) {\n expected = cli_hex2str((char *)e_cksum);\n if (xar_hash_check(e_hash, result, expected) != 0) {\n cli_dbgmsg(\"cli_scanxar: extracted-checksum mismatch.\\n\");\n cksum_fails++;\n } else {\n cli_dbgmsg(\"cli_scanxar: extracted-checksum matched.\\n\"); \n }\n free(expected);\n }\n }\n \n rc = cli_magic_scandesc(fd, ctx);\n if (rc != CL_SUCCESS) {\n if (rc == CL_VIRUS) {\n cli_dbgmsg(\"cli_scanxar: Infected with %s\\n\", cli_get_last_virus(ctx));\n if (!SCAN_ALL)\n goto exit_tmpfile;\n } else if (rc != CL_BREAK) {\n cli_dbgmsg(\"cli_scanxar: cli_magic_scandesc error %i\\n\", rc);\n goto exit_tmpfile;\n }\n }\n }\n \n if (a_cksum != NULL) {\n xmlFree(a_cksum);\n a_cksum = NULL;\n }\n if (e_cksum != NULL) {\n xmlFree(e_cksum);\n e_cksum = NULL;\n }\n }", " exit_tmpfile:\n xar_cleanup_temp_file(ctx, fd, tmpname);\n if (a_hash_ctx != NULL)\n xar_hash_final(a_hash_ctx, result, a_hash);\n if (e_hash_ctx != NULL)\n xar_hash_final(e_hash_ctx, result, e_hash);\n \n exit_reader:\n if (a_cksum != NULL)\n xmlFree(a_cksum); \n if (e_cksum != NULL)\n xmlFree(e_cksum);\n xmlTextReaderClose(reader);\n xmlFreeTextReader(reader);", " exit_toc:\n free(toc);\n if (rc == CL_BREAK)\n rc = CL_SUCCESS;\n#else\n cli_dbgmsg(\"cli_scanxar: can't scan xar files, need libxml2.\\n\");\n#endif\n if (cksum_fails + extract_errors != 0) {", " cli_warnmsg(\"cli_scanxar: %u checksum errors and %u extraction errors, use --debug for more info.\\n\",", " cksum_fails, extract_errors);\n }", " return rc;\n}" ]
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [875], "buggy_code_start_loc": [74], "filenames": ["libclamav/xar.c"], "fixing_code_end_loc": [896], "fixing_code_start_loc": [74], "message": "ClamAV version version 0.99.3 contains a Out of bounds heap memory read vulnerability in XAR parser, function xar_hash_check() that can result in Leaking of memory, may help in developing exploit chains.. This attack appear to be exploitable via The victim must scan a crafted XAR file. This vulnerability appears to have been fixed in after commit d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:clamav:clamav:0.99.3:*:*:*:*:*:*:*", "matchCriteriaId": "AE14FC74-CDE8-4D9B-BAF5-0BE844C9B950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "ClamAV version version 0.99.3 contains a Out of bounds heap memory read vulnerability in XAR parser, function xar_hash_check() that can result in Leaking of memory, may help in developing exploit chains.. This attack appear to be exploitable via The victim must scan a crafted XAR file. This vulnerability appears to have been fixed in after commit d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6."}, {"lang": "es", "value": "ClamAV, versi\u00f3n 0.99.3, contiene una vulnerabilidad de lectura de memoria din\u00e1mica (heap) fuera de l\u00edmites en el analizador XAR, en la funci\u00f3n xar_hash_check() que puede resultar en un filtrado de memoria y ayudar a desarrollar cadenas de exploits. El ataque parece ser explotable si una v\u00edctima escanea un archivo XAR malicioso. La vulnerabilidad parece haber sido solucionada tras el commit con ID d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6."}], "evaluatorComment": null, "id": "CVE-2018-1000085", "lastModified": "2019-03-20T18:30:29.427", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-03-13T15:29:01.113", "references": [{"source": "cve@mitre.org", "tags": ["Issue Tracking", "Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/09/29/4"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/Cisco-Talos/clamav-devel/commit/d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/03/msg00011.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201804-16"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3592-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3592-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Cisco-Talos/clamav-devel/commit/d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6"}, "type": "CWE-125"}
291
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (C) 2015 Cisco Systems, Inc. and/or its affiliates. All rights reserved.\n * Copyright (C) 2013 Sourcefire, Inc.\n *\n * Authors: Steven Morgan <smorgan@sourcefire.com>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n */", "#if HAVE_CONFIG_H\n#include \"clamav-config.h\"\n#endif", "#include <errno.h>\n#include \"xar.h\"\n#include \"fmap.h\"\n#if HAVE_LIBXML2\n#ifdef _WIN32\n#ifndef LIBXML_WRITER_ENABLED\n#define LIBXML_WRITER_ENABLED 1\n#endif\n#endif\n#include <libxml/xmlreader.h>\n#include \"clamav.h\"\n#include \"str.h\"\n#include \"scanners.h\"\n#include \"inflate64.h\"\n#include \"lzma_iface.h\"", "/*\n xar_cleanup_temp_file - cleanup after cli_gentempfd\n parameters:\n ctx - cli_ctx context pointer\n fd - fd to close\n tmpname - name of file to unlink, address of storage to free\n returns - CL_SUCCESS or CL_EUNLINK\n */\nstatic int xar_cleanup_temp_file(cli_ctx *ctx, int fd, char * tmpname)\n{\n int rc = CL_SUCCESS;\n if (fd > -1)\n close(fd);\n if (tmpname != NULL) {\n if (!ctx->engine->keeptmp) {\n if (cli_unlink(tmpname)) {\n cli_dbgmsg(\"cli_scanxar: error unlinking tmpfile %s\\n\", tmpname); \n rc = CL_EUNLINK;\n }\n }\n free(tmpname);\n }\n return rc;\n}", "/*\n xar_get_numeric_from_xml_element - extract xml element value as numeric\n parameters:\n reader - xmlTextReaderPtr\n value - pointer to long to contain the returned value\n returns - CL_SUCCESS or CL_EFORMAT\n */", "static int xar_get_numeric_from_xml_element(xmlTextReaderPtr reader, size_t * value)", "{\n const xmlChar * numstr;", " ssize_t numval;\n", " if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {\n numstr = xmlTextReaderConstValue(reader);\n if (numstr) {", " numval = atol((const char *)numstr);\n if (numval < 0) {", " cli_dbgmsg(\"cli_scanxar: XML element value %li\\n\", *value);\n return CL_EFORMAT;\n }", " *value = numval;", " return CL_SUCCESS;\n }\n }\n cli_dbgmsg(\"cli_scanxar: No text for XML element\\n\");\n return CL_EFORMAT;\n}", "/*\n xar_get_checksum_values - extract checksum and hash algorithm from xml element\n parameters:\n reader - xmlTextReaderPtr\n cksum - pointer to char* for returning checksum value.\n hash - pointer to int for returning checksum algorithm.\n returns - void\n */\nstatic void xar_get_checksum_values(xmlTextReaderPtr reader, unsigned char ** cksum, int * hash)\n{\n xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)\"style\");\n const xmlChar * xmlval;", " *hash = XAR_CKSUM_NONE;\n if (style == NULL) {\n cli_dbgmsg(\"cli_scaxar: xmlTextReaderGetAttribute no style attribute \"\n \"for checksum element\\n\");\n } else {\n cli_dbgmsg(\"cli_scanxar: checksum algorithm is %s.\\n\", style); \n if (0 == xmlStrcasecmp(style, (const xmlChar *)\"sha1\")) {\n *hash = XAR_CKSUM_SHA1;\n } else if (0 == xmlStrcasecmp(style, (const xmlChar *)\"md5\")) {\n *hash = XAR_CKSUM_MD5;\n } else {\n cli_dbgmsg(\"cli_scanxar: checksum algorithm %s is unsupported.\\n\", style);\n *hash = XAR_CKSUM_OTHER;\n }\n }\n if (style != NULL)\n xmlFree(style);", " if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {\n xmlval = xmlTextReaderConstValue(reader);\n if (xmlval) {", " cli_dbgmsg(\"cli_scanxar: checksum value is %s.\\n\", xmlval);\n if (*hash == XAR_CKSUM_SHA1 && xmlStrlen(xmlval) == 2 * CLI_HASHLEN_SHA1 ||\n *hash == XAR_CKSUM_MD5 && xmlStrlen(xmlval) == 2 * CLI_HASHLEN_MD5)\n {\n *cksum = xmlStrdup(xmlval); \n } \n else\n {\n cli_dbgmsg(\"cli_scanxar: checksum type is unknown or length is invalid.\\n\");\n *hash = XAR_CKSUM_OTHER;\n *cksum = NULL;\n }", " } else {\n *cksum = NULL;\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderConstValue() returns NULL for checksum value.\\n\"); \n }\n }\n else\n cli_dbgmsg(\"cli_scanxar: No text for XML checksum element.\\n\");\n}", "/*\n xar_get_toc_data_values - return the values of a <data> or <ea> xml element that represent \n an extent of data on the heap.\n parameters:\n reader - xmlTextReaderPtr\n length - pointer to long for returning value of the <length> element.\n offset - pointer to long for returning value of the <offset> element.\n size - pointer to long for returning value of the <size> element.\n encoding - pointer to int for returning indication of the <encoding> style attribute.\n a_cksum - pointer to char* for return archived checksum value.\n a_hash - pointer to int for returning archived checksum algorithm.\n e_cksum - pointer to char* for return extracted checksum value.\n e_hash - pointer to int for returning extracted checksum algorithm.\n returns - CL_FORMAT, CL_SUCCESS, CL_BREAK. CL_BREAK indicates no more <data>/<ea> element.\n */", "static int xar_get_toc_data_values(xmlTextReaderPtr reader, size_t *length, size_t *offset, size_t *size, int *encoding,", " unsigned char ** a_cksum, int * a_hash, unsigned char ** e_cksum, int * e_hash)\n{\n const xmlChar *name;\n int indata = 0, inea = 0;\n int rc, gotoffset=0, gotlength=0, gotsize=0;", " *a_cksum = NULL;\n *a_hash = XAR_CKSUM_NONE;\n *e_cksum = NULL;\n *e_hash = XAR_CKSUM_NONE;\n *encoding = CL_TYPE_ANY;", " rc = xmlTextReaderRead(reader);\n while (rc == 1) {\n name = xmlTextReaderConstLocalName(reader);\n if (indata || inea) {\n /* cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read %s\\n\", name); */\n if (xmlStrEqual(name, (const xmlChar *)\"offset\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset))\n gotoffset=1;", " } else if (xmlStrEqual(name, (const xmlChar *)\"length\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length))\n gotlength=1;", " } else if (xmlStrEqual(name, (const xmlChar *)\"size\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size))\n gotsize=1;", " } else if (xmlStrEqual(name, (const xmlChar *)\"archived-checksum\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n cli_dbgmsg(\"cli_scanxar: <archived-checksum>:\\n\");\n xar_get_checksum_values(reader, a_cksum, a_hash);\n \n } else if ((xmlStrEqual(name, (const xmlChar *)\"extracted-checksum\") ||\n xmlStrEqual(name, (const xmlChar *)\"unarchived-checksum\")) &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n cli_dbgmsg(\"cli_scanxar: <extracted-checksum>:\\n\");\n xar_get_checksum_values(reader, e_cksum, e_hash);", " } else if (xmlStrEqual(name, (const xmlChar *)\"encoding\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)\"style\");\n if (style == NULL) {\n cli_dbgmsg(\"cli_scaxar: xmlTextReaderGetAttribute no style attribute \"\n \"for encoding element\\n\");\n *encoding = CL_TYPE_ANY;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-gzip\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-gzip.\\n\");\n *encoding = CL_TYPE_GZ; \n } else if (xmlStrEqual(style, (const xmlChar *)\"application/octet-stream\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/octet-stream.\\n\");\n *encoding = CL_TYPE_ANY; \n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-bzip2\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-bzip2.\\n\");\n *encoding = CL_TYPE_BZ;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-lzma\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-lzma.\\n\");\n *encoding = CL_TYPE_7Z;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application/x-xz\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application/x-xz.\\n\");\n *encoding = CL_TYPE_XZ;\n } else {\n cli_dbgmsg(\"cli_scaxar: unknown style value=%s for encoding element\\n\", style);\n *encoding = CL_TYPE_ANY;\n }\n if (style != NULL)\n xmlFree(style);", " } else if (indata && xmlStrEqual(name, (const xmlChar *)\"data\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {\n break;", " } else if (inea && xmlStrEqual(name, (const xmlChar *)\"ea\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {\n break;\n }\n \n } else {\n if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (xmlStrEqual(name, (const xmlChar *)\"data\")) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read <data>\\n\");\n indata = 1;\n } else if (xmlStrEqual(name, (const xmlChar *)\"ea\")) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read <ea>\\n\");\n inea = 1;\n }\n } else if ((xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) &&\n xmlStrEqual(name, (const xmlChar *)\"xar\")) {\n cli_dbgmsg(\"cli_scanxar: finished parsing xar TOC.\\n\"); \n break;\n }\n }\n rc = xmlTextReaderRead(reader);\n }\n \n if (gotoffset && gotlength && gotsize) {\n rc = CL_SUCCESS;\n }\n else if (0 == gotoffset + gotlength + gotsize)\n rc = CL_BREAK;\n else\n rc = CL_EFORMAT;", " return rc;\n}", "/*\n xar_process_subdocument - check TOC for xml subdocument. If found, extract and\n scan in memory.\n Parameters:\n reader - xmlTextReaderPtr\n ctx - pointer to cli_ctx\n Returns:\n CL_SUCCESS - subdoc found and clean scan (or virus found and SCAN_ALL), or no subdocument\n other - error return code from cli_mem_scandesc()\n*/ \nstatic int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx)\n{\n int rc = CL_SUCCESS, subdoc_len, fd;\n xmlChar * subdoc;\n const xmlChar *name;\n char * tmpname;", " while (xmlTextReaderRead(reader) == 1) {\n name = xmlTextReaderConstLocalName(reader);\n if (name == NULL) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderConstLocalName() no name.\\n\");\n rc = CL_EFORMAT;\n break;\n }\n if (xmlStrEqual(name, (const xmlChar *)\"toc\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT)\n return CL_SUCCESS;\n if (xmlStrEqual(name, (const xmlChar *)\"subdoc\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n subdoc = xmlTextReaderReadInnerXml(reader);\n if (subdoc == NULL) {\n cli_dbgmsg(\"cli_scanxar: no content in subdoc element.\\n\");\n xmlTextReaderNext(reader);\n continue;\n }\n subdoc_len = xmlStrlen(subdoc);\n cli_dbgmsg(\"cli_scanxar: in-memory scan of xml subdocument, len %i.\\n\", subdoc_len);\n rc = cli_mem_scandesc(subdoc, subdoc_len, ctx);\n if (rc == CL_VIRUS && SCAN_ALL)\n rc = CL_SUCCESS;\n \n /* make a file to leave if --leave-temps in effect */\n if(ctx->engine->keeptmp) {\n if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {\n cli_dbgmsg(\"cli_scanxar: Can't create temporary file for subdocument.\\n\");\n } else {\n cli_dbgmsg(\"cli_scanxar: Writing subdoc to temp file %s.\\n\", tmpname);\n if (cli_writen(fd, subdoc, subdoc_len) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error writing subdoc temporary file.\\n\");\n rc = CL_EWRITE;\n }\n rc = xar_cleanup_temp_file(ctx, fd, tmpname);\n }\n }", " xmlFree(subdoc);\n if (rc != CL_SUCCESS)\n return rc;\n xmlTextReaderNext(reader);\n } \n }\n return rc;\n}", "static void * xar_hash_init(int hash, void **sc, void **mc)\n{\n if (!sc && !mc)\n return NULL;\n switch (hash) {\n case XAR_CKSUM_SHA1:\n *sc = cl_hash_init(\"sha1\");\n if (!(*sc)) {\n return NULL;\n }", " return *sc;\n case XAR_CKSUM_MD5:\n *mc = cl_hash_init(\"md5\");\n if (!(*mc)) {\n return NULL;\n }", " return *mc;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return NULL;\n }\n}", "static void xar_hash_update(void * hash_ctx, void * data, unsigned long size, int hash)\n{\n if (!hash_ctx || !data || !size)\n return;", " switch (hash) {\n case XAR_CKSUM_NONE:\n case XAR_CKSUM_OTHER:\n return;\n }", " cl_update_hash(hash_ctx, data, size);\n}", "static void xar_hash_final(void * hash_ctx, void * result, int hash)\n{\n if (!hash_ctx || !result)\n return;", " switch (hash) {\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n return;\n }", " cl_finish_hash(hash_ctx, result);\n}", "static int xar_hash_check(int hash, const void * result, const void * expected)\n{\n int len;", " if (!result || !expected)\n return 1;\n switch (hash) {\n case XAR_CKSUM_SHA1:", " len = CLI_HASHLEN_SHA1;", " break;\n case XAR_CKSUM_MD5:", " len = CLI_HASHLEN_MD5;", " break;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return 1;\n }\n return memcmp(result, expected, len);\n}", "#endif", "/*\n cli_scanxar - scan an xar archive.\n Parameters:\n ctx - pointer to cli_ctx.\n returns - CL_SUCCESS or CL_ error code.\n*/", "int cli_scanxar(cli_ctx *ctx)\n{\n int rc = CL_SUCCESS;\n unsigned int cksum_fails = 0;\n unsigned int extract_errors = 0;\n#if HAVE_LIBXML2\n int fd = -1;\n struct xar_header hdr;\n fmap_t *map = *ctx->fmap;", " size_t length, offset, size, at;", " int encoding;\n z_stream strm;\n char *toc, *tmpname;\n xmlTextReaderPtr reader = NULL;\n int a_hash, e_hash;\n unsigned char *a_cksum = NULL, *e_cksum = NULL;\n void *a_hash_ctx = NULL, *e_hash_ctx = NULL;\n char result[SHA1_HASH_SIZE];", " memset(&strm, 0x00, sizeof(z_stream));", " /* retrieve xar header */\n if (fmap_readn(*ctx->fmap, &hdr, 0, sizeof(hdr)) != sizeof(hdr)) {\n cli_dbgmsg(\"cli_scanxar: Invalid header, too short.\\n\");\n return CL_EFORMAT;\n }\n hdr.magic = be32_to_host(hdr.magic);", " if (hdr.magic == XAR_HEADER_MAGIC) {\n cli_dbgmsg(\"cli_scanxar: Matched magic\\n\");\n }\n else {\n cli_dbgmsg(\"cli_scanxar: Invalid magic\\n\");\n return CL_EFORMAT;\n }\n hdr.size = be16_to_host(hdr.size);\n hdr.version = be16_to_host(hdr.version);\n hdr.toc_length_compressed = be64_to_host(hdr.toc_length_compressed);\n hdr.toc_length_decompressed = be64_to_host(hdr.toc_length_decompressed);\n hdr.chksum_alg = be32_to_host(hdr.chksum_alg);", " /* cli_dbgmsg(\"hdr.magic %x\\n\", hdr.magic); */\n /* cli_dbgmsg(\"hdr.size %i\\n\", hdr.size); */\n /* cli_dbgmsg(\"hdr.version %i\\n\", hdr.version); */\n /* cli_dbgmsg(\"hdr.toc_length_compressed %lu\\n\", hdr.toc_length_compressed); */\n /* cli_dbgmsg(\"hdr.toc_length_decompressed %lu\\n\", hdr.toc_length_decompressed); */\n /* cli_dbgmsg(\"hdr.chksum_alg %i\\n\", hdr.chksum_alg); */\n \n /* Uncompress TOC */\n strm.next_in = (unsigned char *)fmap_need_off_once(*ctx->fmap, hdr.size, hdr.toc_length_compressed);\n if (strm.next_in == NULL) {\n cli_dbgmsg(\"cli_scanxar: fmap_need_off_once fails on TOC.\\n\");\n return CL_EREAD;\n }\n strm.avail_in = hdr.toc_length_compressed; \n toc = cli_malloc(hdr.toc_length_decompressed+1);\n if (toc == NULL) {\n cli_dbgmsg(\"cli_scanxar: cli_malloc fails on TOC decompress buffer.\\n\");\n return CL_EMEM;\n }\n toc[hdr.toc_length_decompressed] = '\\0';\n strm.avail_out = hdr.toc_length_decompressed;\n strm.next_out = (unsigned char *)toc;\n rc = inflateInit(&strm);\n if (rc != Z_OK) {\n cli_dbgmsg(\"cli_scanxar:inflateInit error %i \\n\", rc);\n rc = CL_EFORMAT;\n goto exit_toc;\n } \n rc = inflate(&strm, Z_SYNC_FLUSH);\n if (rc != Z_OK && rc != Z_STREAM_END) {\n cli_dbgmsg(\"cli_scanxar:inflate error %i \\n\", rc);\n rc = CL_EFORMAT;\n goto exit_toc;\n }\n rc = inflateEnd(&strm);\n if (rc != Z_OK) {\n cli_dbgmsg(\"cli_scanxar:inflateEnd error %i \\n\", rc);\n rc = CL_EFORMAT;\n goto exit_toc;\n }\n", " if (hdr.toc_length_decompressed != strm.total_out) {\n cli_dbgmsg(\"TOC decompress length %\" PRIu64 \" does not match amount decompressed %lu\\n\",\n hdr.toc_length_decompressed, strm.total_out);\n toc[strm.total_out] = '\\0';\n hdr.toc_length_decompressed = strm.total_out;\n }\n", " /* cli_dbgmsg(\"cli_scanxar: TOC xml:\\n%s\\n\", toc); */\n /* printf(\"cli_scanxar: TOC xml:\\n%s\\n\", toc); */\n /* cli_dbgmsg(\"cli_scanxar: TOC end:\\n\"); */\n /* printf(\"cli_scanxar: TOC end:\\n\"); */", " /* scan the xml */\n cli_dbgmsg(\"cli_scanxar: scanning xar TOC xml in memory.\\n\"); \n rc = cli_mem_scandesc(toc, hdr.toc_length_decompressed, ctx);\n if (rc != CL_SUCCESS) {\n if (rc != CL_VIRUS || !SCAN_ALL)\n goto exit_toc; \n }", " /* make a file to leave if --leave-temps in effect */\n if(ctx->engine->keeptmp) {\n if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {\n cli_dbgmsg(\"cli_scanxar: Can't create temporary file for TOC.\\n\");\n goto exit_toc;\n }\n if (cli_writen(fd, toc, hdr.toc_length_decompressed) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error writing TOC.\\n\");\n rc = CL_EWRITE;\n xar_cleanup_temp_file(ctx, fd, tmpname);\n goto exit_toc;\n }\n rc = xar_cleanup_temp_file(ctx, fd, tmpname);\n if (rc != CL_SUCCESS)\n goto exit_toc;\n }", " reader = xmlReaderForMemory(toc, hdr.toc_length_decompressed, \"noname.xml\", NULL, CLAMAV_MIN_XMLREADER_FLAGS);\n if (reader == NULL) {\n cli_dbgmsg(\"cli_scanxar: xmlReaderForMemory error for TOC\\n\");\n goto exit_toc;\n }", " rc = xar_scan_subdocuments(reader, ctx);\n if (rc != CL_SUCCESS) {\n cli_dbgmsg(\"xar_scan_subdocuments returns %i.\\n\", rc);\n goto exit_reader;\n }", " /* Walk the TOC XML and extract files */\n fd = -1;\n tmpname = NULL;\n while (CL_SUCCESS == (rc = xar_get_toc_data_values(reader, &length, &offset, &size, &encoding,\n &a_cksum, &a_hash, &e_cksum, &e_hash))) {\n int do_extract_cksum = 1;\n unsigned char * blockp;\n void *a_sc, *e_sc;\n void *a_mc, *e_mc;\n char * expected;", " /* clean up temp file from previous loop iteration */\n if (fd > -1 && tmpname) {\n rc = xar_cleanup_temp_file(ctx, fd, tmpname);\n if (rc != CL_SUCCESS)\n goto exit_reader;\n }", " at = offset + hdr.toc_length_compressed + hdr.size;", " if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {\n cli_dbgmsg(\"cli_scanxar: Can't generate temporary file.\\n\");\n goto exit_reader;\n }\n", " cli_dbgmsg(\"cli_scanxar: decompress into temp file:\\n%s, size %zu,\\n\"\n \"from xar heap offset %zu length %zu\\n\",", " tmpname, size, offset, length);", "\n a_hash_ctx = xar_hash_init(a_hash, &a_sc, &a_mc);\n e_hash_ctx = xar_hash_init(e_hash, &e_sc, &e_mc);", " switch (encoding) {\n case CL_TYPE_GZ:\n /* inflate gzip directly because file segments do not contain magic */\n memset(&strm, 0, sizeof(strm));\n if ((rc = inflateInit(&strm)) != Z_OK) {\n cli_dbgmsg(\"cli_scanxar: InflateInit failed: %d\\n\", rc);\n rc = CL_EFORMAT;\n extract_errors++;\n break;\n }\n \n while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {\n unsigned long avail_in;\n void * next_in;\n unsigned int bytes = MIN(map->len - at, map->pgsz);\n bytes = MIN(length, bytes);\n if(!(strm.next_in = next_in = (void*)fmap_need_off_once(map, at, bytes))) {\n cli_dbgmsg(\"cli_scanxar: Can't read %u bytes @ %lu.\\n\", bytes, (long unsigned)at);\n inflateEnd(&strm);\n rc = CL_EREAD;\n goto exit_tmpfile;\n }\n at += bytes;\n strm.avail_in = avail_in = bytes;\n do {\n int inf, outsize = 0;\n unsigned char buff[FILEBUFF];\n strm.avail_out = sizeof(buff);\n strm.next_out = buff;\n inf = inflate(&strm, Z_SYNC_FLUSH);\n if (inf != Z_OK && inf != Z_STREAM_END && inf != Z_BUF_ERROR) {\n cli_dbgmsg(\"cli_scanxar: inflate error %i %s.\\n\", inf, strm.msg?strm.msg:\"\");\n rc = CL_EFORMAT;\n extract_errors++;\n break;\n }", " bytes = sizeof(buff) - strm.avail_out;", " if (e_hash_ctx != NULL)\n xar_hash_update(e_hash_ctx, buff, bytes, e_hash);\n \n if (cli_writen(fd, buff, bytes) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error file %s.\\n\", tmpname);\n inflateEnd(&strm);\n rc = CL_EWRITE;\n goto exit_tmpfile;\n }\n outsize += sizeof(buff) - strm.avail_out;\n if (cli_checklimits(\"cli_scanxar\", ctx, outsize, 0, 0) != CL_CLEAN) {\n break;\n }\n if (inf == Z_STREAM_END) {\n break;\n }\n } while (strm.avail_out == 0);", " if (rc != CL_SUCCESS)\n break;", " avail_in -= strm.avail_in;\n if (a_hash_ctx != NULL)\n xar_hash_update(a_hash_ctx, next_in, avail_in, a_hash);\n }", " inflateEnd(&strm);\n break;\n case CL_TYPE_7Z:\n#define CLI_LZMA_OBUF_SIZE 1024*1024\n#define CLI_LZMA_HDR_SIZE LZMA_PROPS_SIZE+8\n#define CLI_LZMA_IBUF_SIZE CLI_LZMA_OBUF_SIZE>>2 /* estimated compression ratio 25% */\n {\n struct CLI_LZMA lz;", " unsigned long in_remaining = MIN(length, map->len - at);", " unsigned long out_size = 0;\n unsigned char * buff = __lzma_wrap_alloc(NULL, CLI_LZMA_OBUF_SIZE);\n int lret;", "\n if (length > in_remaining)\n length = in_remaining;\n", " memset(&lz, 0, sizeof(lz));\n if (buff == NULL) {\n cli_dbgmsg(\"cli_scanxar: memory request for lzma decompression buffer fails.\\n\");\n rc = CL_EMEM;\n goto exit_tmpfile;\n \n }", " blockp = (void*)fmap_need_off_once(map, at, CLI_LZMA_HDR_SIZE);\n if (blockp == NULL) {\n char errbuff[128];\n cli_strerror(errno, errbuff, sizeof(errbuff));", " cli_dbgmsg(\"cli_scanxar: Can't read %i bytes @ %li, errno:%s.\\n\",\n CLI_LZMA_HDR_SIZE, at, errbuff);", " rc = CL_EREAD;\n __lzma_wrap_free(NULL, buff);\n goto exit_tmpfile;\n }", " lz.next_in = blockp;\n lz.avail_in = CLI_LZMA_HDR_SIZE;", " if (a_hash_ctx != NULL)\n xar_hash_update(a_hash_ctx, blockp, CLI_LZMA_HDR_SIZE, a_hash);", " lret = cli_LzmaInit(&lz, 0);\n if (lret != LZMA_RESULT_OK) {\n cli_dbgmsg(\"cli_scanxar: cli_LzmaInit() fails: %i.\\n\", lret);\n rc = CL_EFORMAT;\n __lzma_wrap_free(NULL, buff);\n extract_errors++;\n break;\n }", " at += CLI_LZMA_HDR_SIZE;\n in_remaining -= CLI_LZMA_HDR_SIZE;\n while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {\n SizeT avail_in;\n SizeT avail_out;\n void * next_in;\n unsigned long in_consumed;", " lz.next_out = buff;\n lz.avail_out = CLI_LZMA_OBUF_SIZE;\n lz.avail_in = avail_in = MIN(CLI_LZMA_IBUF_SIZE, in_remaining);\n lz.next_in = next_in = (void*)fmap_need_off_once(map, at, lz.avail_in);\n if (lz.next_in == NULL) {\n char errbuff[128];\n cli_strerror(errno, errbuff, sizeof(errbuff));\n cli_dbgmsg(\"cli_scanxar: Can't read %li bytes @ %li, errno: %s.\\n\",", " lz.avail_in, at, errbuff);", " rc = CL_EREAD;\n __lzma_wrap_free(NULL, buff);\n cli_LzmaShutdown(&lz);\n goto exit_tmpfile;\n }", " lret = cli_LzmaDecode(&lz);\n if (lret != LZMA_RESULT_OK && lret != LZMA_STREAM_END) {\n cli_dbgmsg(\"cli_scanxar: cli_LzmaDecode() fails: %i.\\n\", lret);\n rc = CL_EFORMAT;\n extract_errors++;\n break;\n }", " in_consumed = avail_in - lz.avail_in;\n in_remaining -= in_consumed;\n at += in_consumed;\n avail_out = CLI_LZMA_OBUF_SIZE - lz.avail_out;\n \n if (avail_out == 0)\n cli_dbgmsg(\"cli_scanxar: cli_LzmaDecode() produces no output for \"\n \"avail_in %llu, avail_out %llu.\\n\",\n (long long unsigned)avail_in, (long long unsigned)avail_out);", " if (a_hash_ctx != NULL)\n xar_hash_update(a_hash_ctx, next_in, in_consumed, a_hash); \n if (e_hash_ctx != NULL)\n xar_hash_update(e_hash_ctx, buff, avail_out, e_hash);", " /* Write a decompressed block. */\n /* cli_dbgmsg(\"Writing %li bytes to LZMA decompress temp file, \" */\n /* \"consumed %li of %li available compressed bytes.\\n\", */\n /* avail_out, in_consumed, avail_in); */", " if (cli_writen(fd, buff, avail_out) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error writing lzma temp file for %llu bytes.\\n\",\n (long long unsigned)avail_out);\n __lzma_wrap_free(NULL, buff);\n cli_LzmaShutdown(&lz);\n rc = CL_EWRITE;\n goto exit_tmpfile;\n }", " /* Check file size limitation. */\n out_size += avail_out;\n if (cli_checklimits(\"cli_scanxar\", ctx, out_size, 0, 0) != CL_CLEAN) {\n break;\n }", " if (lret == LZMA_STREAM_END)\n break;\n }", " cli_LzmaShutdown(&lz);\n __lzma_wrap_free(NULL, buff);\n }\n break; \n case CL_TYPE_ANY:\n default:\n case CL_TYPE_BZ:\n case CL_TYPE_XZ:\n /* for uncompressed, bzip2, xz, and unknown, just pull the file, cli_magic_scandesc does the rest */\n do_extract_cksum = 0;\n {", " size_t writelen = MIN(map->len - at, length);\n", " if (ctx->engine->maxfilesize)", " writelen = MIN((size_t)(ctx->engine->maxfilesize), writelen);", " ", " if (!(blockp = (void*)fmap_need_off_once(map, at, writelen))) {", " char errbuff[128];\n cli_strerror(errno, errbuff, sizeof(errbuff));", " cli_dbgmsg(\"cli_scanxar: Can't read %zu bytes @ %zu, errno:%s.\\n\",\n writelen, at, errbuff);", " rc = CL_EREAD;\n goto exit_tmpfile;\n }\n \n if (a_hash_ctx != NULL)", " xar_hash_update(a_hash_ctx, blockp, writelen, a_hash);", " ", " if (cli_writen(fd, blockp, writelen) < 0) {\n cli_dbgmsg(\"cli_scanxar: cli_writen error %zu bytes @ %li.\\n\", writelen, at);", " rc = CL_EWRITE;\n goto exit_tmpfile;\n }\n /*break;*/\n } ", " } /* end of switch */", "\n if (rc == CL_SUCCESS) {\n if (a_hash_ctx != NULL) {\n xar_hash_final(a_hash_ctx, result, a_hash);\n a_hash_ctx = NULL;\n } else {\n cli_dbgmsg(\"cli_scanxar: archived-checksum missing.\\n\");\n cksum_fails++;\n }\n if (a_cksum != NULL) {\n expected = cli_hex2str((char *)a_cksum);\n if (xar_hash_check(a_hash, result, expected) != 0) {\n cli_dbgmsg(\"cli_scanxar: archived-checksum mismatch.\\n\");\n cksum_fails++;\n } else {\n cli_dbgmsg(\"cli_scanxar: archived-checksum matched.\\n\"); \n }\n free(expected);\n }", " if (e_hash_ctx != NULL) {\n xar_hash_final(e_hash_ctx, result, e_hash);\n e_hash_ctx = NULL;\n } else {\n cli_dbgmsg(\"cli_scanxar: extracted-checksum(unarchived-checksum) missing.\\n\");\n cksum_fails++;\n }\n if (e_cksum != NULL) {\n if (do_extract_cksum) {\n expected = cli_hex2str((char *)e_cksum);\n if (xar_hash_check(e_hash, result, expected) != 0) {\n cli_dbgmsg(\"cli_scanxar: extracted-checksum mismatch.\\n\");\n cksum_fails++;\n } else {\n cli_dbgmsg(\"cli_scanxar: extracted-checksum matched.\\n\"); \n }\n free(expected);\n }\n }\n \n rc = cli_magic_scandesc(fd, ctx);\n if (rc != CL_SUCCESS) {\n if (rc == CL_VIRUS) {\n cli_dbgmsg(\"cli_scanxar: Infected with %s\\n\", cli_get_last_virus(ctx));\n if (!SCAN_ALL)\n goto exit_tmpfile;\n } else if (rc != CL_BREAK) {\n cli_dbgmsg(\"cli_scanxar: cli_magic_scandesc error %i\\n\", rc);\n goto exit_tmpfile;\n }\n }\n }\n \n if (a_cksum != NULL) {\n xmlFree(a_cksum);\n a_cksum = NULL;\n }\n if (e_cksum != NULL) {\n xmlFree(e_cksum);\n e_cksum = NULL;\n }\n }", " exit_tmpfile:\n xar_cleanup_temp_file(ctx, fd, tmpname);\n if (a_hash_ctx != NULL)\n xar_hash_final(a_hash_ctx, result, a_hash);\n if (e_hash_ctx != NULL)\n xar_hash_final(e_hash_ctx, result, e_hash);\n \n exit_reader:\n if (a_cksum != NULL)\n xmlFree(a_cksum); \n if (e_cksum != NULL)\n xmlFree(e_cksum);\n xmlTextReaderClose(reader);\n xmlFreeTextReader(reader);", " exit_toc:\n free(toc);\n if (rc == CL_BREAK)\n rc = CL_SUCCESS;\n#else\n cli_dbgmsg(\"cli_scanxar: can't scan xar files, need libxml2.\\n\");\n#endif\n if (cksum_fails + extract_errors != 0) {", " cli_dbgmsg(\"cli_scanxar: %u checksum errors and %u extraction errors.\\n\",", " cksum_fails, extract_errors);\n }", " return rc;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [875], "buggy_code_start_loc": [74], "filenames": ["libclamav/xar.c"], "fixing_code_end_loc": [896], "fixing_code_start_loc": [74], "message": "ClamAV version version 0.99.3 contains a Out of bounds heap memory read vulnerability in XAR parser, function xar_hash_check() that can result in Leaking of memory, may help in developing exploit chains.. This attack appear to be exploitable via The victim must scan a crafted XAR file. This vulnerability appears to have been fixed in after commit d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:clamav:clamav:0.99.3:*:*:*:*:*:*:*", "matchCriteriaId": "AE14FC74-CDE8-4D9B-BAF5-0BE844C9B950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "ClamAV version version 0.99.3 contains a Out of bounds heap memory read vulnerability in XAR parser, function xar_hash_check() that can result in Leaking of memory, may help in developing exploit chains.. This attack appear to be exploitable via The victim must scan a crafted XAR file. This vulnerability appears to have been fixed in after commit d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6."}, {"lang": "es", "value": "ClamAV, versi\u00f3n 0.99.3, contiene una vulnerabilidad de lectura de memoria din\u00e1mica (heap) fuera de l\u00edmites en el analizador XAR, en la funci\u00f3n xar_hash_check() que puede resultar en un filtrado de memoria y ayudar a desarrollar cadenas de exploits. El ataque parece ser explotable si una v\u00edctima escanea un archivo XAR malicioso. La vulnerabilidad parece haber sido solucionada tras el commit con ID d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6."}], "evaluatorComment": null, "id": "CVE-2018-1000085", "lastModified": "2019-03-20T18:30:29.427", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-03-13T15:29:01.113", "references": [{"source": "cve@mitre.org", "tags": ["Issue Tracking", "Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/09/29/4"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/Cisco-Talos/clamav-devel/commit/d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/03/msg00011.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201804-16"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3592-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3592-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Cisco-Talos/clamav-devel/commit/d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6"}, "type": "CWE-125"}
291
Determine whether the {function_name} code is vulnerable or not.
[ "const middlewares = require('../lib/middlewares');\nconst AppCache = require('../lib/cache').AppCache;", "describe('middlewares', () => {\n let fakeReq, fakeRes;", " beforeEach(() => {\n fakeReq = {\n originalUrl: 'http://example.com/parse/',\n url: 'http://example.com/',\n body: {\n _ApplicationId: 'FakeAppId',\n },\n headers: {},\n get: key => {\n return fakeReq.headers[key.toLowerCase()];\n },\n };\n fakeRes = jasmine.createSpyObj('fakeRes', ['end', 'status']);\n AppCache.put(fakeReq.body._ApplicationId, {});\n });", " afterEach(() => {\n AppCache.del(fakeReq.body._ApplicationId);\n });", " it('should use _ContentType if provided', done => {\n expect(fakeReq.headers['content-type']).toEqual(undefined);\n const contentType = 'image/jpeg';\n fakeReq.body._ContentType = contentType;\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeReq.headers['content-type']).toEqual(contentType);\n expect(fakeReq.body._ContentType).toEqual(undefined);\n done();\n });\n });", " it('should give invalid response when keys are configured but no key supplied', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should give invalid response when keys are configured but supplied key is incorrect', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-rest-api-key'] = 'wrongKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should give invalid response when keys are configured but different key is supplied', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-client-key'] = 'clientKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed when any one of the configured keys supplied', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n clientKey: 'clientKey',\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-rest-api-key'] = 'restAPIKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should succeed when client key supplied but empty', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n clientKey: '',\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-client-key'] = '';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should succeed when no keys are configured and none supplied', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n });\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " const BodyParams = {\n clientVersion: '_ClientVersion',\n installationId: '_InstallationId',\n sessionToken: '_SessionToken',\n masterKey: '_MasterKey',\n javascriptKey: '_JavaScriptKey',\n };", " const BodyKeys = Object.keys(BodyParams);", " BodyKeys.forEach(infoKey => {\n const bodyKey = BodyParams[infoKey];\n const keyValue = 'Fake' + bodyKey;\n // javascriptKey is the only one that gets defaulted,\n const otherKeys = BodyKeys.filter(\n otherKey => otherKey !== infoKey && otherKey !== 'javascriptKey'\n );", " it(`it should pull ${bodyKey} into req.info`, done => {\n fakeReq.body[bodyKey] = keyValue;", " middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeReq.body[bodyKey]).toEqual(undefined);\n expect(fakeReq.info[infoKey]).toEqual(keyValue);", " otherKeys.forEach(otherKey => {\n expect(fakeReq.info[otherKey]).toEqual(undefined);\n });", " done();\n });\n });\n });", " it('should not succeed if the ip does not belong to masterKeyIps list', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.ip = 'ip3';\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed if the ip does belong to masterKeyIps list', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.ip = 'ip1';\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });\n", " it('should not succeed if the connection.remoteAddress does not belong to masterKeyIps list', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.connection = { remoteAddress: 'ip3' };\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed if the connection.remoteAddress does belong to masterKeyIps list', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.connection = { remoteAddress: 'ip1' };\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should not succeed if the socket.remoteAddress does not belong to masterKeyIps list', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.socket = { remoteAddress: 'ip3' };\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed if the socket.remoteAddress does belong to masterKeyIps list', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.socket = { remoteAddress: 'ip1' };\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should not succeed if the connection.socket.remoteAddress does not belong to masterKeyIps list', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.connection = { socket: { remoteAddress: 'ip3' } };\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed if the connection.socket.remoteAddress does belong to masterKeyIps list', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.connection = { socket: { remoteAddress: 'ip1' } };\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });\n", " it('should allow any ip to use masterKey if masterKeyIps is empty', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: [],\n });\n fakeReq.ip = 'ip1';\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });\n", " it('should succeed if xff header does belong to masterKeyIps', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1'],\n });\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n fakeReq.headers['x-forwarded-for'] = 'ip1, ip2, ip3';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should succeed if xff header with one ip does belong to masterKeyIps', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1'],\n });\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n fakeReq.headers['x-forwarded-for'] = 'ip1';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should not succeed if xff header does not belong to masterKeyIps', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip4'],\n });\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n fakeReq.headers['x-forwarded-for'] = 'ip1, ip2, ip3';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should not succeed if xff header is empty and masterKeyIps is set', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1'],\n });\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n fakeReq.headers['x-forwarded-for'] = '';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);", " });", " it('should properly expose the headers', () => {\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(Object.keys(headers).length).toBe(4);\n expect(headers['Access-Control-Expose-Headers']).toBe(\n 'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id'\n );\n });", " it('should set default Access-Control-Allow-Headers if allowHeaders are empty', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowHeaders: undefined,\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);", " AppCache.put(fakeReq.body._ApplicationId, {\n allowHeaders: [],\n });\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);\n });", " it('should append custom headers to Access-Control-Allow-Headers if allowHeaders provided', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowHeaders: ['Header-1', 'Header-2'],\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Headers']).toContain('Header-1, Header-2');\n expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);\n });", " it('should set default Access-Control-Allow-Origin if allowOrigin is empty', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowOrigin: undefined,\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Origin']).toEqual('*');\n });", " it('should set custom origin to Access-Control-Allow-Origin if allowOrigin is provided', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowOrigin: 'https://parseplatform.org/',\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Origin']).toEqual('https://parseplatform.org/');\n });", " it('should use user provided on field userFromJWT', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n });\n fakeReq.userFromJWT = 'fake-user';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeReq.auth.user).toEqual('fake-user');\n done();\n });\n });", " it('should give invalid response when upload file without x-parse-application-id in header', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n });\n fakeReq.body = Buffer.from('fake-file');\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "const middlewares = require('../lib/middlewares');\nconst AppCache = require('../lib/cache').AppCache;", "describe('middlewares', () => {\n let fakeReq, fakeRes;", " beforeEach(() => {\n fakeReq = {\n originalUrl: 'http://example.com/parse/',\n url: 'http://example.com/',\n body: {\n _ApplicationId: 'FakeAppId',\n },\n headers: {},\n get: key => {\n return fakeReq.headers[key.toLowerCase()];\n },\n };\n fakeRes = jasmine.createSpyObj('fakeRes', ['end', 'status']);\n AppCache.put(fakeReq.body._ApplicationId, {});\n });", " afterEach(() => {\n AppCache.del(fakeReq.body._ApplicationId);\n });", " it('should use _ContentType if provided', done => {\n expect(fakeReq.headers['content-type']).toEqual(undefined);\n const contentType = 'image/jpeg';\n fakeReq.body._ContentType = contentType;\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeReq.headers['content-type']).toEqual(contentType);\n expect(fakeReq.body._ContentType).toEqual(undefined);\n done();\n });\n });", " it('should give invalid response when keys are configured but no key supplied', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should give invalid response when keys are configured but supplied key is incorrect', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-rest-api-key'] = 'wrongKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should give invalid response when keys are configured but different key is supplied', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-client-key'] = 'clientKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed when any one of the configured keys supplied', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n clientKey: 'clientKey',\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-rest-api-key'] = 'restAPIKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should succeed when client key supplied but empty', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n clientKey: '',\n masterKey: 'masterKey',\n restAPIKey: 'restAPIKey',\n });\n fakeReq.headers['x-parse-client-key'] = '';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " it('should succeed when no keys are configured and none supplied', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n });\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });", " const BodyParams = {\n clientVersion: '_ClientVersion',\n installationId: '_InstallationId',\n sessionToken: '_SessionToken',\n masterKey: '_MasterKey',\n javascriptKey: '_JavaScriptKey',\n };", " const BodyKeys = Object.keys(BodyParams);", " BodyKeys.forEach(infoKey => {\n const bodyKey = BodyParams[infoKey];\n const keyValue = 'Fake' + bodyKey;\n // javascriptKey is the only one that gets defaulted,\n const otherKeys = BodyKeys.filter(\n otherKey => otherKey !== infoKey && otherKey !== 'javascriptKey'\n );", " it(`it should pull ${bodyKey} into req.info`, done => {\n fakeReq.body[bodyKey] = keyValue;", " middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeReq.body[bodyKey]).toEqual(undefined);\n expect(fakeReq.info[infoKey]).toEqual(keyValue);", " otherKeys.forEach(otherKey => {\n expect(fakeReq.info[otherKey]).toEqual(undefined);\n });", " done();\n });\n });\n });", " it('should not succeed if the ip does not belong to masterKeyIps list', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.ip = 'ip3';\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });", " it('should succeed if the ip does belong to masterKeyIps list', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: ['ip1', 'ip2'],\n });\n fakeReq.ip = 'ip1';\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });\n", "", " it('should allow any ip to use masterKey if masterKeyIps is empty', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n masterKeyIps: [],\n });\n fakeReq.ip = 'ip1';\n fakeReq.headers['x-parse-master-key'] = 'masterKey';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeRes.status).not.toHaveBeenCalled();\n done();\n });\n });\n", " it('can set trust proxy', async () => {\n const server = await reconfigureServer({ trustProxy: 1 });\n expect(server.app.parent.settings['trust proxy']).toBe(1);", " });", " it('should properly expose the headers', () => {\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(Object.keys(headers).length).toBe(4);\n expect(headers['Access-Control-Expose-Headers']).toBe(\n 'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id'\n );\n });", " it('should set default Access-Control-Allow-Headers if allowHeaders are empty', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowHeaders: undefined,\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);", " AppCache.put(fakeReq.body._ApplicationId, {\n allowHeaders: [],\n });\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);\n });", " it('should append custom headers to Access-Control-Allow-Headers if allowHeaders provided', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowHeaders: ['Header-1', 'Header-2'],\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Headers']).toContain('Header-1, Header-2');\n expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);\n });", " it('should set default Access-Control-Allow-Origin if allowOrigin is empty', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowOrigin: undefined,\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Origin']).toEqual('*');\n });", " it('should set custom origin to Access-Control-Allow-Origin if allowOrigin is provided', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n allowOrigin: 'https://parseplatform.org/',\n });\n const headers = {};\n const res = {\n header: (key, value) => {\n headers[key] = value;\n },\n };\n const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);\n allowCrossDomain(fakeReq, res, () => {});\n expect(headers['Access-Control-Allow-Origin']).toEqual('https://parseplatform.org/');\n });", " it('should use user provided on field userFromJWT', done => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n });\n fakeReq.userFromJWT = 'fake-user';\n middlewares.handleParseHeaders(fakeReq, fakeRes, () => {\n expect(fakeReq.auth.user).toEqual('fake-user');\n done();\n });\n });", " it('should give invalid response when upload file without x-parse-application-id in header', () => {\n AppCache.put(fakeReq.body._ApplicationId, {\n masterKey: 'masterKey',\n });\n fakeReq.body = Buffer.from('fake-file');\n middlewares.handleParseHeaders(fakeReq, fakeRes);\n expect(fakeRes.status).toHaveBeenCalledWith(403);\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n**** GENERATED CODE ****\nThis code has been generated by resources/buildConfigDefinitions.js\nDo not edit manually, but update Options/index.js\n*/\nvar parsers = require('./parsers');", "module.exports.SchemaOptions = {\n afterMigration: {\n env: 'PARSE_SERVER_SCHEMA_AFTER_MIGRATION',\n help: 'Execute a callback after running schema migrations.',\n },\n beforeMigration: {\n env: 'PARSE_SERVER_SCHEMA_BEFORE_MIGRATION',\n help: 'Execute a callback before running schema migrations.',\n },\n definitions: {\n env: 'PARSE_SERVER_SCHEMA_DEFINITIONS',\n help:\n 'Rest representation on Parse.Schema https://docs.parseplatform.org/rest/guide/#adding-a-schema',\n required: true,\n action: parsers.objectParser,\n default: [],\n },\n deleteExtraFields: {\n env: 'PARSE_SERVER_SCHEMA_DELETE_EXTRA_FIELDS',\n help:\n 'Is true if Parse Server should delete any fields not defined in a schema definition. This should only be used during development.',\n action: parsers.booleanParser,\n default: false,\n },\n lockSchemas: {\n env: 'PARSE_SERVER_SCHEMA_LOCK_SCHEMAS',\n help:\n 'Is true if Parse Server will reject any attempts to modify the schema while the server is running.',\n action: parsers.booleanParser,\n default: false,\n },\n recreateModifiedFields: {\n env: 'PARSE_SERVER_SCHEMA_RECREATE_MODIFIED_FIELDS',\n help:\n 'Is true if Parse Server should recreate any fields that are different between the current database schema and theschema definition. This should only be used during development.',\n action: parsers.booleanParser,\n default: false,\n },\n strict: {\n env: 'PARSE_SERVER_SCHEMA_STRICT',\n help: 'Is true if Parse Server should exit if schema update fail.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.ParseServerOptions = {\n accountLockout: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT',\n help: 'The account lockout policy for failed login attempts.',\n action: parsers.objectParser,\n },\n allowClientClassCreation: {\n env: 'PARSE_SERVER_ALLOW_CLIENT_CLASS_CREATION',\n help: 'Enable (or disable) client class creation, defaults to true',\n action: parsers.booleanParser,\n default: true,\n },\n allowCustomObjectId: {\n env: 'PARSE_SERVER_ALLOW_CUSTOM_OBJECT_ID',\n help: 'Enable (or disable) custom objectId',\n action: parsers.booleanParser,\n default: false,\n },\n allowHeaders: {\n env: 'PARSE_SERVER_ALLOW_HEADERS',\n help: 'Add headers to Access-Control-Allow-Headers',\n action: parsers.arrayParser,\n },\n allowOrigin: {\n env: 'PARSE_SERVER_ALLOW_ORIGIN',\n help: 'Sets the origin to Access-Control-Allow-Origin',\n },\n analyticsAdapter: {\n env: 'PARSE_SERVER_ANALYTICS_ADAPTER',\n help: 'Adapter module for the analytics',\n action: parsers.moduleOrObjectParser,\n },\n appId: {\n env: 'PARSE_SERVER_APPLICATION_ID',\n help: 'Your Parse Application ID',\n required: true,\n },\n appName: {\n env: 'PARSE_SERVER_APP_NAME',\n help: 'Sets the app name',\n },\n auth: {\n env: 'PARSE_SERVER_AUTH_PROVIDERS',\n help:\n 'Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication',\n action: parsers.arrayParser,\n },\n cacheAdapter: {\n env: 'PARSE_SERVER_CACHE_ADAPTER',\n help: 'Adapter module for the cache',\n action: parsers.moduleOrObjectParser,\n },\n cacheMaxSize: {\n env: 'PARSE_SERVER_CACHE_MAX_SIZE',\n help: 'Sets the maximum size for the in memory cache, defaults to 10000',\n action: parsers.numberParser('cacheMaxSize'),\n default: 10000,\n },\n cacheTTL: {\n env: 'PARSE_SERVER_CACHE_TTL',\n help: 'Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)',\n action: parsers.numberParser('cacheTTL'),\n default: 5000,\n },\n clientKey: {\n env: 'PARSE_SERVER_CLIENT_KEY',\n help: 'Key for iOS, MacOS, tvOS clients',\n },\n cloud: {\n env: 'PARSE_SERVER_CLOUD',\n help: 'Full path to your cloud code main.js',\n },\n cluster: {\n env: 'PARSE_SERVER_CLUSTER',\n help: 'Run with cluster, optionally set the number of processes default to os.cpus().length',\n action: parsers.numberOrBooleanParser,\n },\n collectionPrefix: {\n env: 'PARSE_SERVER_COLLECTION_PREFIX',\n help: 'A collection prefix for the classes',\n default: '',\n },\n customPages: {\n env: 'PARSE_SERVER_CUSTOM_PAGES',\n help: 'custom pages for password validation and reset',\n action: parsers.objectParser,\n default: {},\n },\n databaseAdapter: {\n env: 'PARSE_SERVER_DATABASE_ADAPTER',\n help:\n 'Adapter module for the database; any options that are not explicitly described here are passed directly to the database client.',\n action: parsers.moduleOrObjectParser,\n },\n databaseOptions: {\n env: 'PARSE_SERVER_DATABASE_OPTIONS',\n help: 'Options to pass to the database client',\n action: parsers.objectParser,\n },\n databaseURI: {\n env: 'PARSE_SERVER_DATABASE_URI',\n help: 'The full URI to your database. Supported databases are mongodb or postgres.',\n required: true,\n default: 'mongodb://localhost:27017/parse',\n },\n defaultLimit: {\n env: 'PARSE_SERVER_DEFAULT_LIMIT',\n help: 'Default value for limit option on queries, defaults to `100`.',\n action: parsers.numberParser('defaultLimit'),\n default: 100,\n },\n directAccess: {\n env: 'PARSE_SERVER_DIRECT_ACCESS',\n help:\n 'Set to `true` if Parse requests within the same Node.js environment as Parse Server should be routed to Parse Server directly instead of via the HTTP interface. Default is `false`.<br><br>If set to `false` then Parse requests within the same Node.js environment as Parse Server are executed as HTTP requests sent to Parse Server via the `serverURL`. For example, a `Parse.Query` in Cloud Code is calling Parse Server via a HTTP request. The server is essentially making a HTTP request to itself, unnecessarily using network resources such as network ports.<br><br>\\u26A0\\uFE0F In environments where multiple Parse Server instances run behind a load balancer and Parse requests within the current Node.js environment should be routed via the load balancer and distributed as HTTP requests among all instances via the `serverURL`, this should be set to `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n dotNetKey: {\n env: 'PARSE_SERVER_DOT_NET_KEY',\n help: 'Key for Unity and .Net SDK',\n },\n emailAdapter: {\n env: 'PARSE_SERVER_EMAIL_ADAPTER',\n help: 'Adapter module for email sending',\n action: parsers.moduleOrObjectParser,\n },\n emailVerifyTokenReuseIfValid: {\n env: 'PARSE_SERVER_EMAIL_VERIFY_TOKEN_REUSE_IF_VALID',\n help:\n 'Set to `true` if a email verification token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.',\n action: parsers.booleanParser,\n default: false,\n },\n emailVerifyTokenValidityDuration: {\n env: 'PARSE_SERVER_EMAIL_VERIFY_TOKEN_VALIDITY_DURATION',\n help:\n 'Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.<br>Requires option `verifyUserEmails: true`.',\n action: parsers.numberParser('emailVerifyTokenValidityDuration'),\n },\n enableAnonymousUsers: {\n env: 'PARSE_SERVER_ENABLE_ANON_USERS',\n help: 'Enable (or disable) anonymous users, defaults to true',\n action: parsers.booleanParser,\n default: true,\n },\n enableExpressErrorHandler: {\n env: 'PARSE_SERVER_ENABLE_EXPRESS_ERROR_HANDLER',\n help: 'Enables the default express error handler for all errors',\n action: parsers.booleanParser,\n default: false,\n },\n encryptionKey: {\n env: 'PARSE_SERVER_ENCRYPTION_KEY',\n help: 'Key for encrypting your files',\n },\n enforcePrivateUsers: {\n env: 'PARSE_SERVER_ENFORCE_PRIVATE_USERS',\n help: 'Set to true if new users should be created without public read and write access.',\n action: parsers.booleanParser,\n default: false,\n },\n expireInactiveSessions: {\n env: 'PARSE_SERVER_EXPIRE_INACTIVE_SESSIONS',\n help:\n 'Sets whether we should expire the inactive sessions, defaults to true. If false, all new sessions are created with no expiration date.',\n action: parsers.booleanParser,\n default: true,\n },\n fileKey: {\n env: 'PARSE_SERVER_FILE_KEY',\n help: 'Key for your files',\n },\n filesAdapter: {\n env: 'PARSE_SERVER_FILES_ADAPTER',\n help: 'Adapter module for the files sub-system',\n action: parsers.moduleOrObjectParser,\n },\n fileUpload: {\n env: 'PARSE_SERVER_FILE_UPLOAD_OPTIONS',\n help: 'Options for file uploads',\n action: parsers.objectParser,\n default: {},\n },\n graphQLPath: {\n env: 'PARSE_SERVER_GRAPHQL_PATH',\n help: 'Mount path for the GraphQL endpoint, defaults to /graphql',\n default: '/graphql',\n },\n graphQLSchema: {\n env: 'PARSE_SERVER_GRAPH_QLSCHEMA',\n help: 'Full path to your GraphQL custom schema.graphql file',\n },\n host: {\n env: 'PARSE_SERVER_HOST',\n help: 'The host to serve ParseServer on, defaults to 0.0.0.0',\n default: '0.0.0.0',\n },\n idempotencyOptions: {\n env: 'PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_OPTIONS',\n help:\n 'Options for request idempotency to deduplicate identical requests that may be caused by network issues. Caution, this is an experimental feature that may not be appropriate for production.',\n action: parsers.objectParser,\n default: {},\n },\n javascriptKey: {\n env: 'PARSE_SERVER_JAVASCRIPT_KEY',\n help: 'Key for the Javascript SDK',\n },\n jsonLogs: {\n env: 'JSON_LOGS',\n help: 'Log as structured JSON objects',\n action: parsers.booleanParser,\n },\n liveQuery: {\n env: 'PARSE_SERVER_LIVE_QUERY',\n help: \"parse-server's LiveQuery configuration object\",\n action: parsers.objectParser,\n },\n liveQueryServerOptions: {\n env: 'PARSE_SERVER_LIVE_QUERY_SERVER_OPTIONS',\n help: 'Live query server configuration options (will start the liveQuery server)',\n action: parsers.objectParser,\n },\n loggerAdapter: {\n env: 'PARSE_SERVER_LOGGER_ADAPTER',\n help: 'Adapter module for the logging sub-system',\n action: parsers.moduleOrObjectParser,\n },\n logLevel: {\n env: 'PARSE_SERVER_LOG_LEVEL',\n help: 'Sets the level for logs',\n },\n logsFolder: {\n env: 'PARSE_SERVER_LOGS_FOLDER',\n help: \"Folder for the logs (defaults to './logs'); set to null to disable file based logging\",\n default: './logs',\n },\n masterKey: {\n env: 'PARSE_SERVER_MASTER_KEY',\n help: 'Your Parse Master Key',\n required: true,\n },\n masterKeyIps: {\n env: 'PARSE_SERVER_MASTER_KEY_IPS',\n help: 'Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)',\n action: parsers.arrayParser,\n default: [],\n },\n maxLimit: {\n env: 'PARSE_SERVER_MAX_LIMIT',\n help: 'Max value for limit option on queries, defaults to unlimited',\n action: parsers.numberParser('maxLimit'),\n },\n maxLogFiles: {\n env: 'PARSE_SERVER_MAX_LOG_FILES',\n help:\n \"Maximum number of logs to keep. If not set, no logs will be removed. This can be a number of files or number of days. If using days, add 'd' as the suffix. (default: null)\",\n action: parsers.objectParser,\n },\n maxUploadSize: {\n env: 'PARSE_SERVER_MAX_UPLOAD_SIZE',\n help: 'Max file size for uploads, defaults to 20mb',\n default: '20mb',\n },\n middleware: {\n env: 'PARSE_SERVER_MIDDLEWARE',\n help: 'middleware for express server, can be string or function',\n },\n mountGraphQL: {\n env: 'PARSE_SERVER_MOUNT_GRAPHQL',\n help: 'Mounts the GraphQL endpoint',\n action: parsers.booleanParser,\n default: false,\n },\n mountPath: {\n env: 'PARSE_SERVER_MOUNT_PATH',\n help: 'Mount path for the server, defaults to /parse',\n default: '/parse',\n },\n mountPlayground: {\n env: 'PARSE_SERVER_MOUNT_PLAYGROUND',\n help: 'Mounts the GraphQL Playground - never use this option in production',\n action: parsers.booleanParser,\n default: false,\n },\n objectIdSize: {\n env: 'PARSE_SERVER_OBJECT_ID_SIZE',\n help: \"Sets the number of characters in generated object id's, default 10\",\n action: parsers.numberParser('objectIdSize'),\n default: 10,\n },\n pages: {\n env: 'PARSE_SERVER_PAGES',\n help:\n 'The options for pages such as password reset and email verification. Caution, this is an experimental feature that may not be appropriate for production.',\n action: parsers.objectParser,\n default: {},\n },\n passwordPolicy: {\n env: 'PARSE_SERVER_PASSWORD_POLICY',\n help: 'The password policy for enforcing password related rules.',\n action: parsers.objectParser,\n },\n playgroundPath: {\n env: 'PARSE_SERVER_PLAYGROUND_PATH',\n help: 'Mount path for the GraphQL Playground, defaults to /playground',\n default: '/playground',\n },\n port: {\n env: 'PORT',\n help: 'The port to run the ParseServer, defaults to 1337.',\n action: parsers.numberParser('port'),\n default: 1337,\n },\n preserveFileName: {\n env: 'PARSE_SERVER_PRESERVE_FILE_NAME',\n help: 'Enable (or disable) the addition of a unique hash to the file names',\n action: parsers.booleanParser,\n default: false,\n },\n preventLoginWithUnverifiedEmail: {\n env: 'PARSE_SERVER_PREVENT_LOGIN_WITH_UNVERIFIED_EMAIL',\n help:\n 'Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.',\n action: parsers.booleanParser,\n default: false,\n },\n protectedFields: {\n env: 'PARSE_SERVER_PROTECTED_FIELDS',\n help: 'Protected fields that should be treated with extra security when fetching details.',\n action: parsers.objectParser,\n default: {\n _User: {\n '*': ['email'],\n },\n },\n },\n publicServerURL: {\n env: 'PARSE_PUBLIC_SERVER_URL',\n help: 'Public URL to your parse server with http:// or https://.',\n },\n push: {\n env: 'PARSE_SERVER_PUSH',\n help:\n 'Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications',\n action: parsers.objectParser,\n },\n readOnlyMasterKey: {\n env: 'PARSE_SERVER_READ_ONLY_MASTER_KEY',\n help: 'Read-only key, which has the same capabilities as MasterKey without writes',\n },\n requestKeywordDenylist: {\n env: 'PARSE_SERVER_REQUEST_KEYWORD_DENYLIST',\n help:\n 'An array of keys and values that are prohibited in database read and write requests to prevent potential security vulnerabilities. It is possible to specify only a key (`{\"key\":\"...\"}`), only a value (`{\"value\":\"...\"}`) or a key-value pair (`{\"key\":\"...\",\"value\":\"...\"}`). The specification can use the following types: `boolean`, `numeric` or `string`, where `string` will be interpreted as a regex notation. Request data is deep-scanned for matching definitions to detect also any nested occurrences. Defaults are patterns that are likely to be used in malicious requests. Setting this option will override the default patterns.',\n action: parsers.arrayParser,\n default: [\n {\n key: '_bsontype',\n value: 'Code',\n },\n {\n key: 'constructor',\n },\n {\n key: '__proto__',\n },\n ],\n },\n restAPIKey: {\n env: 'PARSE_SERVER_REST_API_KEY',\n help: 'Key for REST calls',\n },\n revokeSessionOnPasswordReset: {\n env: 'PARSE_SERVER_REVOKE_SESSION_ON_PASSWORD_RESET',\n help:\n \"When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.\",\n action: parsers.booleanParser,\n default: true,\n },\n scheduledPush: {\n env: 'PARSE_SERVER_SCHEDULED_PUSH',\n help: 'Configuration for push scheduling, defaults to false.',\n action: parsers.booleanParser,\n default: false,\n },\n schema: {\n env: 'PARSE_SERVER_SCHEMA',\n help: 'Defined schema',\n action: parsers.objectParser,\n },\n security: {\n env: 'PARSE_SERVER_SECURITY',\n help: 'The security options to identify and report weak security settings.',\n action: parsers.objectParser,\n default: {},\n },\n serverCloseComplete: {\n env: 'PARSE_SERVER_SERVER_CLOSE_COMPLETE',\n help: 'Callback when server has closed',\n },\n serverStartComplete: {\n env: 'PARSE_SERVER_SERVER_START_COMPLETE',\n help: 'Callback when server has started',\n },\n serverURL: {\n env: 'PARSE_SERVER_URL',\n help: 'URL to your parse server with http:// or https://.',\n required: true,\n },\n sessionLength: {\n env: 'PARSE_SERVER_SESSION_LENGTH',\n help: 'Session duration, in seconds, defaults to 1 year',\n action: parsers.numberParser('sessionLength'),\n default: 31536000,\n },\n silent: {\n env: 'SILENT',\n help: 'Disables console output',\n action: parsers.booleanParser,\n },\n startLiveQueryServer: {\n env: 'PARSE_SERVER_START_LIVE_QUERY_SERVER',\n help: 'Starts the liveQuery server',\n action: parsers.booleanParser,\n },", "", " userSensitiveFields: {\n env: 'PARSE_SERVER_USER_SENSITIVE_FIELDS',\n help:\n 'Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields',\n action: parsers.arrayParser,\n },\n verbose: {\n env: 'VERBOSE',\n help: 'Set the logging to verbose',\n action: parsers.booleanParser,\n },\n verifyUserEmails: {\n env: 'PARSE_SERVER_VERIFY_USER_EMAILS',\n help:\n 'Set to `true` to require users to verify their email address to complete the sign-up process.<br><br>Default is `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n webhookKey: {\n env: 'PARSE_SERVER_WEBHOOK_KEY',\n help: 'Key sent with outgoing webhook calls',\n },\n};\nmodule.exports.SecurityOptions = {\n checkGroups: {\n env: 'PARSE_SERVER_SECURITY_CHECK_GROUPS',\n help:\n 'The security check groups to run. This allows to add custom security checks or override existing ones. Default are the groups defined in `CheckGroups.js`.',\n action: parsers.arrayParser,\n },\n enableCheck: {\n env: 'PARSE_SERVER_SECURITY_ENABLE_CHECK',\n help: 'Is true if Parse Server should check for weak security settings.',\n action: parsers.booleanParser,\n default: false,\n },\n enableCheckLog: {\n env: 'PARSE_SERVER_SECURITY_ENABLE_CHECK_LOG',\n help:\n 'Is true if the security check report should be written to logs. This should only be enabled temporarily to not expose weak security settings in logs.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.PagesOptions = {\n customRoutes: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_ROUTES',\n help: 'The custom routes.',\n action: parsers.arrayParser,\n default: [],\n },\n customUrls: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URLS',\n help: 'The URLs to the custom pages.',\n action: parsers.objectParser,\n default: {},\n },\n enableLocalization: {\n env: 'PARSE_SERVER_PAGES_ENABLE_LOCALIZATION',\n help: 'Is true if pages should be localized; this has no effect on custom page redirects.',\n action: parsers.booleanParser,\n default: false,\n },\n enableRouter: {\n env: 'PARSE_SERVER_PAGES_ENABLE_ROUTER',\n help:\n 'Is true if the pages router should be enabled; this is required for any of the pages options to take effect. Caution, this is an experimental feature that may not be appropriate for production.',\n action: parsers.booleanParser,\n default: false,\n },\n forceRedirect: {\n env: 'PARSE_SERVER_PAGES_FORCE_REDIRECT',\n help:\n 'Is true if responses should always be redirects and never content, false if the response type should depend on the request type (GET request -> content response; POST request -> redirect response).',\n action: parsers.booleanParser,\n default: false,\n },\n localizationFallbackLocale: {\n env: 'PARSE_SERVER_PAGES_LOCALIZATION_FALLBACK_LOCALE',\n help:\n 'The fallback locale for localization if no matching translation is provided for the given locale. This is only relevant when providing translation resources via JSON file.',\n default: 'en',\n },\n localizationJsonPath: {\n env: 'PARSE_SERVER_PAGES_LOCALIZATION_JSON_PATH',\n help:\n 'The path to the JSON file for localization; the translations will be used to fill template placeholders according to the locale.',\n },\n pagesEndpoint: {\n env: 'PARSE_SERVER_PAGES_PAGES_ENDPOINT',\n help: \"The API endpoint for the pages. Default is 'apps'.\",\n default: 'apps',\n },\n pagesPath: {\n env: 'PARSE_SERVER_PAGES_PAGES_PATH',\n help:\n \"The path to the pages directory; this also defines where the static endpoint '/apps' points to. Default is the './public/' directory.\",\n default: './public',\n },\n placeholders: {\n env: 'PARSE_SERVER_PAGES_PLACEHOLDERS',\n help:\n 'The placeholder keys and values which will be filled in pages; this can be a simple object or a callback function.',\n action: parsers.objectParser,\n default: {},\n },\n};\nmodule.exports.PagesRoute = {\n handler: {\n env: 'PARSE_SERVER_PAGES_ROUTE_HANDLER',\n help: 'The route handler that is an async function.',\n required: true,\n },\n method: {\n env: 'PARSE_SERVER_PAGES_ROUTE_METHOD',\n help: \"The route method, e.g. 'GET' or 'POST'.\",\n required: true,\n },\n path: {\n env: 'PARSE_SERVER_PAGES_ROUTE_PATH',\n help: 'The route path.',\n required: true,\n },\n};\nmodule.exports.PagesCustomUrlsOptions = {\n emailVerificationLinkExpired: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_LINK_EXPIRED',\n help: 'The URL to the custom page for email verification -> link expired.',\n },\n emailVerificationLinkInvalid: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_LINK_INVALID',\n help: 'The URL to the custom page for email verification -> link invalid.',\n },\n emailVerificationSendFail: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_SEND_FAIL',\n help: 'The URL to the custom page for email verification -> link send fail.',\n },\n emailVerificationSendSuccess: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_SEND_SUCCESS',\n help: 'The URL to the custom page for email verification -> resend link -> success.',\n },\n emailVerificationSuccess: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_SUCCESS',\n help: 'The URL to the custom page for email verification -> success.',\n },\n passwordReset: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_PASSWORD_RESET',\n help: 'The URL to the custom page for password reset.',\n },\n passwordResetLinkInvalid: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_PASSWORD_RESET_LINK_INVALID',\n help: 'The URL to the custom page for password reset -> link invalid.',\n },\n passwordResetSuccess: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_PASSWORD_RESET_SUCCESS',\n help: 'The URL to the custom page for password reset -> success.',\n },\n};\nmodule.exports.CustomPagesOptions = {\n choosePassword: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_CHOOSE_PASSWORD',\n help: 'choose password page path',\n },\n expiredVerificationLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_EXPIRED_VERIFICATION_LINK',\n help: 'expired verification link page path',\n },\n invalidLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_LINK',\n help: 'invalid link page path',\n },\n invalidPasswordResetLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_PASSWORD_RESET_LINK',\n help: 'invalid password reset link page path',\n },\n invalidVerificationLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_VERIFICATION_LINK',\n help: 'invalid verification link page path',\n },\n linkSendFail: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_FAIL',\n help: 'verification link send fail page path',\n },\n linkSendSuccess: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_SUCCESS',\n help: 'verification link send success page path',\n },\n parseFrameURL: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_PARSE_FRAME_URL',\n help: 'for masking user-facing pages',\n },\n passwordResetSuccess: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_PASSWORD_RESET_SUCCESS',\n help: 'password reset success page path',\n },\n verifyEmailSuccess: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_VERIFY_EMAIL_SUCCESS',\n help: 'verify email success page path',\n },\n};\nmodule.exports.LiveQueryOptions = {\n classNames: {\n env: 'PARSE_SERVER_LIVEQUERY_CLASSNAMES',\n help: \"parse-server's LiveQuery classNames\",\n action: parsers.arrayParser,\n },\n pubSubAdapter: {\n env: 'PARSE_SERVER_LIVEQUERY_PUB_SUB_ADAPTER',\n help: 'LiveQuery pubsub adapter',\n action: parsers.moduleOrObjectParser,\n },\n redisOptions: {\n env: 'PARSE_SERVER_LIVEQUERY_REDIS_OPTIONS',\n help: \"parse-server's LiveQuery redisOptions\",\n action: parsers.objectParser,\n },\n redisURL: {\n env: 'PARSE_SERVER_LIVEQUERY_REDIS_URL',\n help: \"parse-server's LiveQuery redisURL\",\n },\n wssAdapter: {\n env: 'PARSE_SERVER_LIVEQUERY_WSS_ADAPTER',\n help: 'Adapter module for the WebSocketServer',\n action: parsers.moduleOrObjectParser,\n },\n};\nmodule.exports.LiveQueryServerOptions = {\n appId: {\n env: 'PARSE_LIVE_QUERY_SERVER_APP_ID',\n help:\n 'This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.',\n },\n cacheTimeout: {\n env: 'PARSE_LIVE_QUERY_SERVER_CACHE_TIMEOUT',\n help:\n \"Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 5 * 1000 ms (5 seconds).\",\n action: parsers.numberParser('cacheTimeout'),\n },\n keyPairs: {\n env: 'PARSE_LIVE_QUERY_SERVER_KEY_PAIRS',\n help:\n 'A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.',\n action: parsers.objectParser,\n },\n logLevel: {\n env: 'PARSE_LIVE_QUERY_SERVER_LOG_LEVEL',\n help:\n 'This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.',\n },\n masterKey: {\n env: 'PARSE_LIVE_QUERY_SERVER_MASTER_KEY',\n help:\n 'This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.',\n },\n port: {\n env: 'PARSE_LIVE_QUERY_SERVER_PORT',\n help: 'The port to run the LiveQuery server, defaults to 1337.',\n action: parsers.numberParser('port'),\n default: 1337,\n },\n pubSubAdapter: {\n env: 'PARSE_LIVE_QUERY_SERVER_PUB_SUB_ADAPTER',\n help: 'LiveQuery pubsub adapter',\n action: parsers.moduleOrObjectParser,\n },\n redisOptions: {\n env: 'PARSE_LIVE_QUERY_SERVER_REDIS_OPTIONS',\n help: \"parse-server's LiveQuery redisOptions\",\n action: parsers.objectParser,\n },\n redisURL: {\n env: 'PARSE_LIVE_QUERY_SERVER_REDIS_URL',\n help: \"parse-server's LiveQuery redisURL\",\n },\n serverURL: {\n env: 'PARSE_LIVE_QUERY_SERVER_SERVER_URL',\n help:\n 'This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.',\n },\n websocketTimeout: {\n env: 'PARSE_LIVE_QUERY_SERVER_WEBSOCKET_TIMEOUT',\n help:\n 'Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).',\n action: parsers.numberParser('websocketTimeout'),\n },\n wssAdapter: {\n env: 'PARSE_LIVE_QUERY_SERVER_WSS_ADAPTER',\n help: 'Adapter module for the WebSocketServer',\n action: parsers.moduleOrObjectParser,\n },\n};\nmodule.exports.IdempotencyOptions = {\n paths: {\n env: 'PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_PATHS',\n help:\n 'An array of paths for which the feature should be enabled. The mount path must not be included, for example instead of `/parse/functions/myFunction` specifiy `functions/myFunction`. The entries are interpreted as regular expression, for example `functions/.*` matches all functions, `jobs/.*` matches all jobs, `classes/.*` matches all classes, `.*` matches all paths.',\n action: parsers.arrayParser,\n default: [],\n },\n ttl: {\n env: 'PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_TTL',\n help:\n 'The duration in seconds after which a request record is discarded from the database, defaults to 300s.',\n action: parsers.numberParser('ttl'),\n default: 300,\n },\n};\nmodule.exports.AccountLockoutOptions = {\n duration: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT_DURATION',\n help:\n 'Set the duration in minutes that a locked-out account remains locked out before automatically becoming unlocked.<br><br>Valid values are greater than `0` and less than `100000`.',\n action: parsers.numberParser('duration'),\n },\n threshold: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT_THRESHOLD',\n help:\n 'Set the number of failed sign-in attempts that will cause a user account to be locked. If the account is locked. The account will unlock after the duration set in the `duration` option has passed and no further login attempts have been made.<br><br>Valid values are greater than `0` and less than `1000`.',\n action: parsers.numberParser('threshold'),\n },\n unlockOnPasswordReset: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT_UNLOCK_ON_PASSWORD_RESET',\n help:\n 'Set to `true` if the account should be unlocked after a successful password reset.<br><br>Default is `false`.<br>Requires options `duration` and `threshold` to be set.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.PasswordPolicyOptions = {\n doNotAllowUsername: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_DO_NOT_ALLOW_USERNAME',\n help:\n 'Set to `true` to disallow the username as part of the password.<br><br>Default is `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n maxPasswordAge: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_MAX_PASSWORD_AGE',\n help:\n 'Set the number of days after which a password expires. Login attempts fail if the user does not reset the password before expiration.',\n action: parsers.numberParser('maxPasswordAge'),\n },\n maxPasswordHistory: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_MAX_PASSWORD_HISTORY',\n help:\n 'Set the number of previous password that will not be allowed to be set as new password. If the option is not set or set to `0`, no previous passwords will be considered.<br><br>Valid values are >= `0` and <= `20`.<br>Default is `0`.',\n action: parsers.numberParser('maxPasswordHistory'),\n },\n resetTokenReuseIfValid: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_RESET_TOKEN_REUSE_IF_VALID',\n help:\n 'Set to `true` if a password reset token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n resetTokenValidityDuration: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_RESET_TOKEN_VALIDITY_DURATION',\n help:\n 'Set the validity duration of the password reset token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.',\n action: parsers.numberParser('resetTokenValidityDuration'),\n },\n validationError: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_VALIDATION_ERROR',\n help:\n 'Set the error message to be sent.<br><br>Default is `Password does not meet the Password Policy requirements.`',\n },\n validatorCallback: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_VALIDATOR_CALLBACK',\n help:\n 'Set a callback function to validate a password to be accepted.<br><br>If used in combination with `validatorPattern`, the password must pass both to be accepted.',\n },\n validatorPattern: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_VALIDATOR_PATTERN',\n help:\n 'Set the regular expression validation pattern a password must match to be accepted.<br><br>If used in combination with `validatorCallback`, the password must pass both to be accepted.',\n },\n};\nmodule.exports.FileUploadOptions = {\n enableForAnonymousUser: {\n env: 'PARSE_SERVER_FILE_UPLOAD_ENABLE_FOR_ANONYMOUS_USER',\n help: 'Is true if file upload should be allowed for anonymous users.',\n action: parsers.booleanParser,\n default: false,\n },\n enableForAuthenticatedUser: {\n env: 'PARSE_SERVER_FILE_UPLOAD_ENABLE_FOR_AUTHENTICATED_USER',\n help: 'Is true if file upload should be allowed for authenticated users.',\n action: parsers.booleanParser,\n default: true,\n },\n enableForPublic: {\n env: 'PARSE_SERVER_FILE_UPLOAD_ENABLE_FOR_PUBLIC',\n help: 'Is true if file upload should be allowed for anyone, regardless of user authentication.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.DatabaseOptions = {\n enableSchemaHooks: {\n env: 'PARSE_SERVER_DATABASE_ENABLE_SCHEMA_HOOKS',\n help:\n 'Enables database real-time hooks to update single schema cache. Set to `true` if using multiple Parse Servers instances connected to the same database. Failing to do so will cause a schema change to not propagate to all instances and re-syncing will only happen when the instances restart. To use this feature with MongoDB, a replica set cluster with [change stream](https://docs.mongodb.com/manual/changeStreams/#availability) support is required.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.AuthAdapter = {\n enabled: {\n help: 'Is `true` if the auth adapter is enabled, `false` otherwise.',\n action: parsers.booleanParser,\n default: true,\n },\n};" ]
[ 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n**** GENERATED CODE ****\nThis code has been generated by resources/buildConfigDefinitions.js\nDo not edit manually, but update Options/index.js\n*/\nvar parsers = require('./parsers');", "module.exports.SchemaOptions = {\n afterMigration: {\n env: 'PARSE_SERVER_SCHEMA_AFTER_MIGRATION',\n help: 'Execute a callback after running schema migrations.',\n },\n beforeMigration: {\n env: 'PARSE_SERVER_SCHEMA_BEFORE_MIGRATION',\n help: 'Execute a callback before running schema migrations.',\n },\n definitions: {\n env: 'PARSE_SERVER_SCHEMA_DEFINITIONS',\n help:\n 'Rest representation on Parse.Schema https://docs.parseplatform.org/rest/guide/#adding-a-schema',\n required: true,\n action: parsers.objectParser,\n default: [],\n },\n deleteExtraFields: {\n env: 'PARSE_SERVER_SCHEMA_DELETE_EXTRA_FIELDS',\n help:\n 'Is true if Parse Server should delete any fields not defined in a schema definition. This should only be used during development.',\n action: parsers.booleanParser,\n default: false,\n },\n lockSchemas: {\n env: 'PARSE_SERVER_SCHEMA_LOCK_SCHEMAS',\n help:\n 'Is true if Parse Server will reject any attempts to modify the schema while the server is running.',\n action: parsers.booleanParser,\n default: false,\n },\n recreateModifiedFields: {\n env: 'PARSE_SERVER_SCHEMA_RECREATE_MODIFIED_FIELDS',\n help:\n 'Is true if Parse Server should recreate any fields that are different between the current database schema and theschema definition. This should only be used during development.',\n action: parsers.booleanParser,\n default: false,\n },\n strict: {\n env: 'PARSE_SERVER_SCHEMA_STRICT',\n help: 'Is true if Parse Server should exit if schema update fail.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.ParseServerOptions = {\n accountLockout: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT',\n help: 'The account lockout policy for failed login attempts.',\n action: parsers.objectParser,\n },\n allowClientClassCreation: {\n env: 'PARSE_SERVER_ALLOW_CLIENT_CLASS_CREATION',\n help: 'Enable (or disable) client class creation, defaults to true',\n action: parsers.booleanParser,\n default: true,\n },\n allowCustomObjectId: {\n env: 'PARSE_SERVER_ALLOW_CUSTOM_OBJECT_ID',\n help: 'Enable (or disable) custom objectId',\n action: parsers.booleanParser,\n default: false,\n },\n allowHeaders: {\n env: 'PARSE_SERVER_ALLOW_HEADERS',\n help: 'Add headers to Access-Control-Allow-Headers',\n action: parsers.arrayParser,\n },\n allowOrigin: {\n env: 'PARSE_SERVER_ALLOW_ORIGIN',\n help: 'Sets the origin to Access-Control-Allow-Origin',\n },\n analyticsAdapter: {\n env: 'PARSE_SERVER_ANALYTICS_ADAPTER',\n help: 'Adapter module for the analytics',\n action: parsers.moduleOrObjectParser,\n },\n appId: {\n env: 'PARSE_SERVER_APPLICATION_ID',\n help: 'Your Parse Application ID',\n required: true,\n },\n appName: {\n env: 'PARSE_SERVER_APP_NAME',\n help: 'Sets the app name',\n },\n auth: {\n env: 'PARSE_SERVER_AUTH_PROVIDERS',\n help:\n 'Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication',\n action: parsers.arrayParser,\n },\n cacheAdapter: {\n env: 'PARSE_SERVER_CACHE_ADAPTER',\n help: 'Adapter module for the cache',\n action: parsers.moduleOrObjectParser,\n },\n cacheMaxSize: {\n env: 'PARSE_SERVER_CACHE_MAX_SIZE',\n help: 'Sets the maximum size for the in memory cache, defaults to 10000',\n action: parsers.numberParser('cacheMaxSize'),\n default: 10000,\n },\n cacheTTL: {\n env: 'PARSE_SERVER_CACHE_TTL',\n help: 'Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)',\n action: parsers.numberParser('cacheTTL'),\n default: 5000,\n },\n clientKey: {\n env: 'PARSE_SERVER_CLIENT_KEY',\n help: 'Key for iOS, MacOS, tvOS clients',\n },\n cloud: {\n env: 'PARSE_SERVER_CLOUD',\n help: 'Full path to your cloud code main.js',\n },\n cluster: {\n env: 'PARSE_SERVER_CLUSTER',\n help: 'Run with cluster, optionally set the number of processes default to os.cpus().length',\n action: parsers.numberOrBooleanParser,\n },\n collectionPrefix: {\n env: 'PARSE_SERVER_COLLECTION_PREFIX',\n help: 'A collection prefix for the classes',\n default: '',\n },\n customPages: {\n env: 'PARSE_SERVER_CUSTOM_PAGES',\n help: 'custom pages for password validation and reset',\n action: parsers.objectParser,\n default: {},\n },\n databaseAdapter: {\n env: 'PARSE_SERVER_DATABASE_ADAPTER',\n help:\n 'Adapter module for the database; any options that are not explicitly described here are passed directly to the database client.',\n action: parsers.moduleOrObjectParser,\n },\n databaseOptions: {\n env: 'PARSE_SERVER_DATABASE_OPTIONS',\n help: 'Options to pass to the database client',\n action: parsers.objectParser,\n },\n databaseURI: {\n env: 'PARSE_SERVER_DATABASE_URI',\n help: 'The full URI to your database. Supported databases are mongodb or postgres.',\n required: true,\n default: 'mongodb://localhost:27017/parse',\n },\n defaultLimit: {\n env: 'PARSE_SERVER_DEFAULT_LIMIT',\n help: 'Default value for limit option on queries, defaults to `100`.',\n action: parsers.numberParser('defaultLimit'),\n default: 100,\n },\n directAccess: {\n env: 'PARSE_SERVER_DIRECT_ACCESS',\n help:\n 'Set to `true` if Parse requests within the same Node.js environment as Parse Server should be routed to Parse Server directly instead of via the HTTP interface. Default is `false`.<br><br>If set to `false` then Parse requests within the same Node.js environment as Parse Server are executed as HTTP requests sent to Parse Server via the `serverURL`. For example, a `Parse.Query` in Cloud Code is calling Parse Server via a HTTP request. The server is essentially making a HTTP request to itself, unnecessarily using network resources such as network ports.<br><br>\\u26A0\\uFE0F In environments where multiple Parse Server instances run behind a load balancer and Parse requests within the current Node.js environment should be routed via the load balancer and distributed as HTTP requests among all instances via the `serverURL`, this should be set to `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n dotNetKey: {\n env: 'PARSE_SERVER_DOT_NET_KEY',\n help: 'Key for Unity and .Net SDK',\n },\n emailAdapter: {\n env: 'PARSE_SERVER_EMAIL_ADAPTER',\n help: 'Adapter module for email sending',\n action: parsers.moduleOrObjectParser,\n },\n emailVerifyTokenReuseIfValid: {\n env: 'PARSE_SERVER_EMAIL_VERIFY_TOKEN_REUSE_IF_VALID',\n help:\n 'Set to `true` if a email verification token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.',\n action: parsers.booleanParser,\n default: false,\n },\n emailVerifyTokenValidityDuration: {\n env: 'PARSE_SERVER_EMAIL_VERIFY_TOKEN_VALIDITY_DURATION',\n help:\n 'Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.<br>Requires option `verifyUserEmails: true`.',\n action: parsers.numberParser('emailVerifyTokenValidityDuration'),\n },\n enableAnonymousUsers: {\n env: 'PARSE_SERVER_ENABLE_ANON_USERS',\n help: 'Enable (or disable) anonymous users, defaults to true',\n action: parsers.booleanParser,\n default: true,\n },\n enableExpressErrorHandler: {\n env: 'PARSE_SERVER_ENABLE_EXPRESS_ERROR_HANDLER',\n help: 'Enables the default express error handler for all errors',\n action: parsers.booleanParser,\n default: false,\n },\n encryptionKey: {\n env: 'PARSE_SERVER_ENCRYPTION_KEY',\n help: 'Key for encrypting your files',\n },\n enforcePrivateUsers: {\n env: 'PARSE_SERVER_ENFORCE_PRIVATE_USERS',\n help: 'Set to true if new users should be created without public read and write access.',\n action: parsers.booleanParser,\n default: false,\n },\n expireInactiveSessions: {\n env: 'PARSE_SERVER_EXPIRE_INACTIVE_SESSIONS',\n help:\n 'Sets whether we should expire the inactive sessions, defaults to true. If false, all new sessions are created with no expiration date.',\n action: parsers.booleanParser,\n default: true,\n },\n fileKey: {\n env: 'PARSE_SERVER_FILE_KEY',\n help: 'Key for your files',\n },\n filesAdapter: {\n env: 'PARSE_SERVER_FILES_ADAPTER',\n help: 'Adapter module for the files sub-system',\n action: parsers.moduleOrObjectParser,\n },\n fileUpload: {\n env: 'PARSE_SERVER_FILE_UPLOAD_OPTIONS',\n help: 'Options for file uploads',\n action: parsers.objectParser,\n default: {},\n },\n graphQLPath: {\n env: 'PARSE_SERVER_GRAPHQL_PATH',\n help: 'Mount path for the GraphQL endpoint, defaults to /graphql',\n default: '/graphql',\n },\n graphQLSchema: {\n env: 'PARSE_SERVER_GRAPH_QLSCHEMA',\n help: 'Full path to your GraphQL custom schema.graphql file',\n },\n host: {\n env: 'PARSE_SERVER_HOST',\n help: 'The host to serve ParseServer on, defaults to 0.0.0.0',\n default: '0.0.0.0',\n },\n idempotencyOptions: {\n env: 'PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_OPTIONS',\n help:\n 'Options for request idempotency to deduplicate identical requests that may be caused by network issues. Caution, this is an experimental feature that may not be appropriate for production.',\n action: parsers.objectParser,\n default: {},\n },\n javascriptKey: {\n env: 'PARSE_SERVER_JAVASCRIPT_KEY',\n help: 'Key for the Javascript SDK',\n },\n jsonLogs: {\n env: 'JSON_LOGS',\n help: 'Log as structured JSON objects',\n action: parsers.booleanParser,\n },\n liveQuery: {\n env: 'PARSE_SERVER_LIVE_QUERY',\n help: \"parse-server's LiveQuery configuration object\",\n action: parsers.objectParser,\n },\n liveQueryServerOptions: {\n env: 'PARSE_SERVER_LIVE_QUERY_SERVER_OPTIONS',\n help: 'Live query server configuration options (will start the liveQuery server)',\n action: parsers.objectParser,\n },\n loggerAdapter: {\n env: 'PARSE_SERVER_LOGGER_ADAPTER',\n help: 'Adapter module for the logging sub-system',\n action: parsers.moduleOrObjectParser,\n },\n logLevel: {\n env: 'PARSE_SERVER_LOG_LEVEL',\n help: 'Sets the level for logs',\n },\n logsFolder: {\n env: 'PARSE_SERVER_LOGS_FOLDER',\n help: \"Folder for the logs (defaults to './logs'); set to null to disable file based logging\",\n default: './logs',\n },\n masterKey: {\n env: 'PARSE_SERVER_MASTER_KEY',\n help: 'Your Parse Master Key',\n required: true,\n },\n masterKeyIps: {\n env: 'PARSE_SERVER_MASTER_KEY_IPS',\n help: 'Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)',\n action: parsers.arrayParser,\n default: [],\n },\n maxLimit: {\n env: 'PARSE_SERVER_MAX_LIMIT',\n help: 'Max value for limit option on queries, defaults to unlimited',\n action: parsers.numberParser('maxLimit'),\n },\n maxLogFiles: {\n env: 'PARSE_SERVER_MAX_LOG_FILES',\n help:\n \"Maximum number of logs to keep. If not set, no logs will be removed. This can be a number of files or number of days. If using days, add 'd' as the suffix. (default: null)\",\n action: parsers.objectParser,\n },\n maxUploadSize: {\n env: 'PARSE_SERVER_MAX_UPLOAD_SIZE',\n help: 'Max file size for uploads, defaults to 20mb',\n default: '20mb',\n },\n middleware: {\n env: 'PARSE_SERVER_MIDDLEWARE',\n help: 'middleware for express server, can be string or function',\n },\n mountGraphQL: {\n env: 'PARSE_SERVER_MOUNT_GRAPHQL',\n help: 'Mounts the GraphQL endpoint',\n action: parsers.booleanParser,\n default: false,\n },\n mountPath: {\n env: 'PARSE_SERVER_MOUNT_PATH',\n help: 'Mount path for the server, defaults to /parse',\n default: '/parse',\n },\n mountPlayground: {\n env: 'PARSE_SERVER_MOUNT_PLAYGROUND',\n help: 'Mounts the GraphQL Playground - never use this option in production',\n action: parsers.booleanParser,\n default: false,\n },\n objectIdSize: {\n env: 'PARSE_SERVER_OBJECT_ID_SIZE',\n help: \"Sets the number of characters in generated object id's, default 10\",\n action: parsers.numberParser('objectIdSize'),\n default: 10,\n },\n pages: {\n env: 'PARSE_SERVER_PAGES',\n help:\n 'The options for pages such as password reset and email verification. Caution, this is an experimental feature that may not be appropriate for production.',\n action: parsers.objectParser,\n default: {},\n },\n passwordPolicy: {\n env: 'PARSE_SERVER_PASSWORD_POLICY',\n help: 'The password policy for enforcing password related rules.',\n action: parsers.objectParser,\n },\n playgroundPath: {\n env: 'PARSE_SERVER_PLAYGROUND_PATH',\n help: 'Mount path for the GraphQL Playground, defaults to /playground',\n default: '/playground',\n },\n port: {\n env: 'PORT',\n help: 'The port to run the ParseServer, defaults to 1337.',\n action: parsers.numberParser('port'),\n default: 1337,\n },\n preserveFileName: {\n env: 'PARSE_SERVER_PRESERVE_FILE_NAME',\n help: 'Enable (or disable) the addition of a unique hash to the file names',\n action: parsers.booleanParser,\n default: false,\n },\n preventLoginWithUnverifiedEmail: {\n env: 'PARSE_SERVER_PREVENT_LOGIN_WITH_UNVERIFIED_EMAIL',\n help:\n 'Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.',\n action: parsers.booleanParser,\n default: false,\n },\n protectedFields: {\n env: 'PARSE_SERVER_PROTECTED_FIELDS',\n help: 'Protected fields that should be treated with extra security when fetching details.',\n action: parsers.objectParser,\n default: {\n _User: {\n '*': ['email'],\n },\n },\n },\n publicServerURL: {\n env: 'PARSE_PUBLIC_SERVER_URL',\n help: 'Public URL to your parse server with http:// or https://.',\n },\n push: {\n env: 'PARSE_SERVER_PUSH',\n help:\n 'Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications',\n action: parsers.objectParser,\n },\n readOnlyMasterKey: {\n env: 'PARSE_SERVER_READ_ONLY_MASTER_KEY',\n help: 'Read-only key, which has the same capabilities as MasterKey without writes',\n },\n requestKeywordDenylist: {\n env: 'PARSE_SERVER_REQUEST_KEYWORD_DENYLIST',\n help:\n 'An array of keys and values that are prohibited in database read and write requests to prevent potential security vulnerabilities. It is possible to specify only a key (`{\"key\":\"...\"}`), only a value (`{\"value\":\"...\"}`) or a key-value pair (`{\"key\":\"...\",\"value\":\"...\"}`). The specification can use the following types: `boolean`, `numeric` or `string`, where `string` will be interpreted as a regex notation. Request data is deep-scanned for matching definitions to detect also any nested occurrences. Defaults are patterns that are likely to be used in malicious requests. Setting this option will override the default patterns.',\n action: parsers.arrayParser,\n default: [\n {\n key: '_bsontype',\n value: 'Code',\n },\n {\n key: 'constructor',\n },\n {\n key: '__proto__',\n },\n ],\n },\n restAPIKey: {\n env: 'PARSE_SERVER_REST_API_KEY',\n help: 'Key for REST calls',\n },\n revokeSessionOnPasswordReset: {\n env: 'PARSE_SERVER_REVOKE_SESSION_ON_PASSWORD_RESET',\n help:\n \"When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.\",\n action: parsers.booleanParser,\n default: true,\n },\n scheduledPush: {\n env: 'PARSE_SERVER_SCHEDULED_PUSH',\n help: 'Configuration for push scheduling, defaults to false.',\n action: parsers.booleanParser,\n default: false,\n },\n schema: {\n env: 'PARSE_SERVER_SCHEMA',\n help: 'Defined schema',\n action: parsers.objectParser,\n },\n security: {\n env: 'PARSE_SERVER_SECURITY',\n help: 'The security options to identify and report weak security settings.',\n action: parsers.objectParser,\n default: {},\n },\n serverCloseComplete: {\n env: 'PARSE_SERVER_SERVER_CLOSE_COMPLETE',\n help: 'Callback when server has closed',\n },\n serverStartComplete: {\n env: 'PARSE_SERVER_SERVER_START_COMPLETE',\n help: 'Callback when server has started',\n },\n serverURL: {\n env: 'PARSE_SERVER_URL',\n help: 'URL to your parse server with http:// or https://.',\n required: true,\n },\n sessionLength: {\n env: 'PARSE_SERVER_SESSION_LENGTH',\n help: 'Session duration, in seconds, defaults to 1 year',\n action: parsers.numberParser('sessionLength'),\n default: 31536000,\n },\n silent: {\n env: 'SILENT',\n help: 'Disables console output',\n action: parsers.booleanParser,\n },\n startLiveQueryServer: {\n env: 'PARSE_SERVER_START_LIVE_QUERY_SERVER',\n help: 'Starts the liveQuery server',\n action: parsers.booleanParser,\n },", " trustProxy: {\n env: 'PARSE_SERVER_TRUST_PROXY',\n help:\n 'The trust proxy settings. It is important to understand the exact setup of the reverse proxy, since this setting will trust values provided in the Parse Server API request. See the <a href=\"https://expressjs.com/en/guide/behind-proxies.html\">express trust proxy settings</a> documentation. Defaults to `false`.',\n action: parsers.objectParser,\n default: [],\n },", " userSensitiveFields: {\n env: 'PARSE_SERVER_USER_SENSITIVE_FIELDS',\n help:\n 'Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields',\n action: parsers.arrayParser,\n },\n verbose: {\n env: 'VERBOSE',\n help: 'Set the logging to verbose',\n action: parsers.booleanParser,\n },\n verifyUserEmails: {\n env: 'PARSE_SERVER_VERIFY_USER_EMAILS',\n help:\n 'Set to `true` to require users to verify their email address to complete the sign-up process.<br><br>Default is `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n webhookKey: {\n env: 'PARSE_SERVER_WEBHOOK_KEY',\n help: 'Key sent with outgoing webhook calls',\n },\n};\nmodule.exports.SecurityOptions = {\n checkGroups: {\n env: 'PARSE_SERVER_SECURITY_CHECK_GROUPS',\n help:\n 'The security check groups to run. This allows to add custom security checks or override existing ones. Default are the groups defined in `CheckGroups.js`.',\n action: parsers.arrayParser,\n },\n enableCheck: {\n env: 'PARSE_SERVER_SECURITY_ENABLE_CHECK',\n help: 'Is true if Parse Server should check for weak security settings.',\n action: parsers.booleanParser,\n default: false,\n },\n enableCheckLog: {\n env: 'PARSE_SERVER_SECURITY_ENABLE_CHECK_LOG',\n help:\n 'Is true if the security check report should be written to logs. This should only be enabled temporarily to not expose weak security settings in logs.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.PagesOptions = {\n customRoutes: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_ROUTES',\n help: 'The custom routes.',\n action: parsers.arrayParser,\n default: [],\n },\n customUrls: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URLS',\n help: 'The URLs to the custom pages.',\n action: parsers.objectParser,\n default: {},\n },\n enableLocalization: {\n env: 'PARSE_SERVER_PAGES_ENABLE_LOCALIZATION',\n help: 'Is true if pages should be localized; this has no effect on custom page redirects.',\n action: parsers.booleanParser,\n default: false,\n },\n enableRouter: {\n env: 'PARSE_SERVER_PAGES_ENABLE_ROUTER',\n help:\n 'Is true if the pages router should be enabled; this is required for any of the pages options to take effect. Caution, this is an experimental feature that may not be appropriate for production.',\n action: parsers.booleanParser,\n default: false,\n },\n forceRedirect: {\n env: 'PARSE_SERVER_PAGES_FORCE_REDIRECT',\n help:\n 'Is true if responses should always be redirects and never content, false if the response type should depend on the request type (GET request -> content response; POST request -> redirect response).',\n action: parsers.booleanParser,\n default: false,\n },\n localizationFallbackLocale: {\n env: 'PARSE_SERVER_PAGES_LOCALIZATION_FALLBACK_LOCALE',\n help:\n 'The fallback locale for localization if no matching translation is provided for the given locale. This is only relevant when providing translation resources via JSON file.',\n default: 'en',\n },\n localizationJsonPath: {\n env: 'PARSE_SERVER_PAGES_LOCALIZATION_JSON_PATH',\n help:\n 'The path to the JSON file for localization; the translations will be used to fill template placeholders according to the locale.',\n },\n pagesEndpoint: {\n env: 'PARSE_SERVER_PAGES_PAGES_ENDPOINT',\n help: \"The API endpoint for the pages. Default is 'apps'.\",\n default: 'apps',\n },\n pagesPath: {\n env: 'PARSE_SERVER_PAGES_PAGES_PATH',\n help:\n \"The path to the pages directory; this also defines where the static endpoint '/apps' points to. Default is the './public/' directory.\",\n default: './public',\n },\n placeholders: {\n env: 'PARSE_SERVER_PAGES_PLACEHOLDERS',\n help:\n 'The placeholder keys and values which will be filled in pages; this can be a simple object or a callback function.',\n action: parsers.objectParser,\n default: {},\n },\n};\nmodule.exports.PagesRoute = {\n handler: {\n env: 'PARSE_SERVER_PAGES_ROUTE_HANDLER',\n help: 'The route handler that is an async function.',\n required: true,\n },\n method: {\n env: 'PARSE_SERVER_PAGES_ROUTE_METHOD',\n help: \"The route method, e.g. 'GET' or 'POST'.\",\n required: true,\n },\n path: {\n env: 'PARSE_SERVER_PAGES_ROUTE_PATH',\n help: 'The route path.',\n required: true,\n },\n};\nmodule.exports.PagesCustomUrlsOptions = {\n emailVerificationLinkExpired: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_LINK_EXPIRED',\n help: 'The URL to the custom page for email verification -> link expired.',\n },\n emailVerificationLinkInvalid: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_LINK_INVALID',\n help: 'The URL to the custom page for email verification -> link invalid.',\n },\n emailVerificationSendFail: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_SEND_FAIL',\n help: 'The URL to the custom page for email verification -> link send fail.',\n },\n emailVerificationSendSuccess: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_SEND_SUCCESS',\n help: 'The URL to the custom page for email verification -> resend link -> success.',\n },\n emailVerificationSuccess: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_EMAIL_VERIFICATION_SUCCESS',\n help: 'The URL to the custom page for email verification -> success.',\n },\n passwordReset: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_PASSWORD_RESET',\n help: 'The URL to the custom page for password reset.',\n },\n passwordResetLinkInvalid: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_PASSWORD_RESET_LINK_INVALID',\n help: 'The URL to the custom page for password reset -> link invalid.',\n },\n passwordResetSuccess: {\n env: 'PARSE_SERVER_PAGES_CUSTOM_URL_PASSWORD_RESET_SUCCESS',\n help: 'The URL to the custom page for password reset -> success.',\n },\n};\nmodule.exports.CustomPagesOptions = {\n choosePassword: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_CHOOSE_PASSWORD',\n help: 'choose password page path',\n },\n expiredVerificationLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_EXPIRED_VERIFICATION_LINK',\n help: 'expired verification link page path',\n },\n invalidLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_LINK',\n help: 'invalid link page path',\n },\n invalidPasswordResetLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_PASSWORD_RESET_LINK',\n help: 'invalid password reset link page path',\n },\n invalidVerificationLink: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_INVALID_VERIFICATION_LINK',\n help: 'invalid verification link page path',\n },\n linkSendFail: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_FAIL',\n help: 'verification link send fail page path',\n },\n linkSendSuccess: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_LINK_SEND_SUCCESS',\n help: 'verification link send success page path',\n },\n parseFrameURL: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_PARSE_FRAME_URL',\n help: 'for masking user-facing pages',\n },\n passwordResetSuccess: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_PASSWORD_RESET_SUCCESS',\n help: 'password reset success page path',\n },\n verifyEmailSuccess: {\n env: 'PARSE_SERVER_CUSTOM_PAGES_VERIFY_EMAIL_SUCCESS',\n help: 'verify email success page path',\n },\n};\nmodule.exports.LiveQueryOptions = {\n classNames: {\n env: 'PARSE_SERVER_LIVEQUERY_CLASSNAMES',\n help: \"parse-server's LiveQuery classNames\",\n action: parsers.arrayParser,\n },\n pubSubAdapter: {\n env: 'PARSE_SERVER_LIVEQUERY_PUB_SUB_ADAPTER',\n help: 'LiveQuery pubsub adapter',\n action: parsers.moduleOrObjectParser,\n },\n redisOptions: {\n env: 'PARSE_SERVER_LIVEQUERY_REDIS_OPTIONS',\n help: \"parse-server's LiveQuery redisOptions\",\n action: parsers.objectParser,\n },\n redisURL: {\n env: 'PARSE_SERVER_LIVEQUERY_REDIS_URL',\n help: \"parse-server's LiveQuery redisURL\",\n },\n wssAdapter: {\n env: 'PARSE_SERVER_LIVEQUERY_WSS_ADAPTER',\n help: 'Adapter module for the WebSocketServer',\n action: parsers.moduleOrObjectParser,\n },\n};\nmodule.exports.LiveQueryServerOptions = {\n appId: {\n env: 'PARSE_LIVE_QUERY_SERVER_APP_ID',\n help:\n 'This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.',\n },\n cacheTimeout: {\n env: 'PARSE_LIVE_QUERY_SERVER_CACHE_TIMEOUT',\n help:\n \"Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 5 * 1000 ms (5 seconds).\",\n action: parsers.numberParser('cacheTimeout'),\n },\n keyPairs: {\n env: 'PARSE_LIVE_QUERY_SERVER_KEY_PAIRS',\n help:\n 'A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.',\n action: parsers.objectParser,\n },\n logLevel: {\n env: 'PARSE_LIVE_QUERY_SERVER_LOG_LEVEL',\n help:\n 'This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.',\n },\n masterKey: {\n env: 'PARSE_LIVE_QUERY_SERVER_MASTER_KEY',\n help:\n 'This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.',\n },\n port: {\n env: 'PARSE_LIVE_QUERY_SERVER_PORT',\n help: 'The port to run the LiveQuery server, defaults to 1337.',\n action: parsers.numberParser('port'),\n default: 1337,\n },\n pubSubAdapter: {\n env: 'PARSE_LIVE_QUERY_SERVER_PUB_SUB_ADAPTER',\n help: 'LiveQuery pubsub adapter',\n action: parsers.moduleOrObjectParser,\n },\n redisOptions: {\n env: 'PARSE_LIVE_QUERY_SERVER_REDIS_OPTIONS',\n help: \"parse-server's LiveQuery redisOptions\",\n action: parsers.objectParser,\n },\n redisURL: {\n env: 'PARSE_LIVE_QUERY_SERVER_REDIS_URL',\n help: \"parse-server's LiveQuery redisURL\",\n },\n serverURL: {\n env: 'PARSE_LIVE_QUERY_SERVER_SERVER_URL',\n help:\n 'This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.',\n },\n websocketTimeout: {\n env: 'PARSE_LIVE_QUERY_SERVER_WEBSOCKET_TIMEOUT',\n help:\n 'Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).',\n action: parsers.numberParser('websocketTimeout'),\n },\n wssAdapter: {\n env: 'PARSE_LIVE_QUERY_SERVER_WSS_ADAPTER',\n help: 'Adapter module for the WebSocketServer',\n action: parsers.moduleOrObjectParser,\n },\n};\nmodule.exports.IdempotencyOptions = {\n paths: {\n env: 'PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_PATHS',\n help:\n 'An array of paths for which the feature should be enabled. The mount path must not be included, for example instead of `/parse/functions/myFunction` specifiy `functions/myFunction`. The entries are interpreted as regular expression, for example `functions/.*` matches all functions, `jobs/.*` matches all jobs, `classes/.*` matches all classes, `.*` matches all paths.',\n action: parsers.arrayParser,\n default: [],\n },\n ttl: {\n env: 'PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_TTL',\n help:\n 'The duration in seconds after which a request record is discarded from the database, defaults to 300s.',\n action: parsers.numberParser('ttl'),\n default: 300,\n },\n};\nmodule.exports.AccountLockoutOptions = {\n duration: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT_DURATION',\n help:\n 'Set the duration in minutes that a locked-out account remains locked out before automatically becoming unlocked.<br><br>Valid values are greater than `0` and less than `100000`.',\n action: parsers.numberParser('duration'),\n },\n threshold: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT_THRESHOLD',\n help:\n 'Set the number of failed sign-in attempts that will cause a user account to be locked. If the account is locked. The account will unlock after the duration set in the `duration` option has passed and no further login attempts have been made.<br><br>Valid values are greater than `0` and less than `1000`.',\n action: parsers.numberParser('threshold'),\n },\n unlockOnPasswordReset: {\n env: 'PARSE_SERVER_ACCOUNT_LOCKOUT_UNLOCK_ON_PASSWORD_RESET',\n help:\n 'Set to `true` if the account should be unlocked after a successful password reset.<br><br>Default is `false`.<br>Requires options `duration` and `threshold` to be set.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.PasswordPolicyOptions = {\n doNotAllowUsername: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_DO_NOT_ALLOW_USERNAME',\n help:\n 'Set to `true` to disallow the username as part of the password.<br><br>Default is `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n maxPasswordAge: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_MAX_PASSWORD_AGE',\n help:\n 'Set the number of days after which a password expires. Login attempts fail if the user does not reset the password before expiration.',\n action: parsers.numberParser('maxPasswordAge'),\n },\n maxPasswordHistory: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_MAX_PASSWORD_HISTORY',\n help:\n 'Set the number of previous password that will not be allowed to be set as new password. If the option is not set or set to `0`, no previous passwords will be considered.<br><br>Valid values are >= `0` and <= `20`.<br>Default is `0`.',\n action: parsers.numberParser('maxPasswordHistory'),\n },\n resetTokenReuseIfValid: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_RESET_TOKEN_REUSE_IF_VALID',\n help:\n 'Set to `true` if a password reset token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.',\n action: parsers.booleanParser,\n default: false,\n },\n resetTokenValidityDuration: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_RESET_TOKEN_VALIDITY_DURATION',\n help:\n 'Set the validity duration of the password reset token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.',\n action: parsers.numberParser('resetTokenValidityDuration'),\n },\n validationError: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_VALIDATION_ERROR',\n help:\n 'Set the error message to be sent.<br><br>Default is `Password does not meet the Password Policy requirements.`',\n },\n validatorCallback: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_VALIDATOR_CALLBACK',\n help:\n 'Set a callback function to validate a password to be accepted.<br><br>If used in combination with `validatorPattern`, the password must pass both to be accepted.',\n },\n validatorPattern: {\n env: 'PARSE_SERVER_PASSWORD_POLICY_VALIDATOR_PATTERN',\n help:\n 'Set the regular expression validation pattern a password must match to be accepted.<br><br>If used in combination with `validatorCallback`, the password must pass both to be accepted.',\n },\n};\nmodule.exports.FileUploadOptions = {\n enableForAnonymousUser: {\n env: 'PARSE_SERVER_FILE_UPLOAD_ENABLE_FOR_ANONYMOUS_USER',\n help: 'Is true if file upload should be allowed for anonymous users.',\n action: parsers.booleanParser,\n default: false,\n },\n enableForAuthenticatedUser: {\n env: 'PARSE_SERVER_FILE_UPLOAD_ENABLE_FOR_AUTHENTICATED_USER',\n help: 'Is true if file upload should be allowed for authenticated users.',\n action: parsers.booleanParser,\n default: true,\n },\n enableForPublic: {\n env: 'PARSE_SERVER_FILE_UPLOAD_ENABLE_FOR_PUBLIC',\n help: 'Is true if file upload should be allowed for anyone, regardless of user authentication.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.DatabaseOptions = {\n enableSchemaHooks: {\n env: 'PARSE_SERVER_DATABASE_ENABLE_SCHEMA_HOOKS',\n help:\n 'Enables database real-time hooks to update single schema cache. Set to `true` if using multiple Parse Servers instances connected to the same database. Failing to do so will cause a schema change to not propagate to all instances and re-syncing will only happen when the instances restart. To use this feature with MongoDB, a replica set cluster with [change stream](https://docs.mongodb.com/manual/changeStreams/#availability) support is required.',\n action: parsers.booleanParser,\n default: false,\n },\n};\nmodule.exports.AuthAdapter = {\n enabled: {\n help: 'Is `true` if the auth adapter is enabled, `false` otherwise.',\n action: parsers.booleanParser,\n default: true,\n },\n};" ]
[ 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * @interface SchemaOptions\n * @property {Function} afterMigration Execute a callback after running schema migrations.\n * @property {Function} beforeMigration Execute a callback before running schema migrations.\n * @property {Any} definitions Rest representation on Parse.Schema https://docs.parseplatform.org/rest/guide/#adding-a-schema\n * @property {Boolean} deleteExtraFields Is true if Parse Server should delete any fields not defined in a schema definition. This should only be used during development.\n * @property {Boolean} lockSchemas Is true if Parse Server will reject any attempts to modify the schema while the server is running.\n * @property {Boolean} recreateModifiedFields Is true if Parse Server should recreate any fields that are different between the current database schema and theschema definition. This should only be used during development.\n * @property {Boolean} strict Is true if Parse Server should exit if schema update fail.\n */", "/**\n * @interface ParseServerOptions\n * @property {AccountLockoutOptions} accountLockout The account lockout policy for failed login attempts.\n * @property {Boolean} allowClientClassCreation Enable (or disable) client class creation, defaults to true\n * @property {Boolean} allowCustomObjectId Enable (or disable) custom objectId\n * @property {String[]} allowHeaders Add headers to Access-Control-Allow-Headers\n * @property {String} allowOrigin Sets the origin to Access-Control-Allow-Origin\n * @property {Adapter<AnalyticsAdapter>} analyticsAdapter Adapter module for the analytics\n * @property {String} appId Your Parse Application ID\n * @property {String} appName Sets the app name\n * @property {AuthAdapter[]} auth Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication\n * @property {Adapter<CacheAdapter>} cacheAdapter Adapter module for the cache\n * @property {Number} cacheMaxSize Sets the maximum size for the in memory cache, defaults to 10000\n * @property {Number} cacheTTL Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)\n * @property {String} clientKey Key for iOS, MacOS, tvOS clients\n * @property {String} cloud Full path to your cloud code main.js\n * @property {Number|Boolean} cluster Run with cluster, optionally set the number of processes default to os.cpus().length\n * @property {String} collectionPrefix A collection prefix for the classes\n * @property {CustomPagesOptions} customPages custom pages for password validation and reset\n * @property {Adapter<StorageAdapter>} databaseAdapter Adapter module for the database; any options that are not explicitly described here are passed directly to the database client.\n * @property {DatabaseOptions} databaseOptions Options to pass to the database client\n * @property {String} databaseURI The full URI to your database. Supported databases are mongodb or postgres.\n * @property {Number} defaultLimit Default value for limit option on queries, defaults to `100`.\n * @property {Boolean} directAccess Set to `true` if Parse requests within the same Node.js environment as Parse Server should be routed to Parse Server directly instead of via the HTTP interface. Default is `false`.<br><br>If set to `false` then Parse requests within the same Node.js environment as Parse Server are executed as HTTP requests sent to Parse Server via the `serverURL`. For example, a `Parse.Query` in Cloud Code is calling Parse Server via a HTTP request. The server is essentially making a HTTP request to itself, unnecessarily using network resources such as network ports.<br><br>⚠️ In environments where multiple Parse Server instances run behind a load balancer and Parse requests within the current Node.js environment should be routed via the load balancer and distributed as HTTP requests among all instances via the `serverURL`, this should be set to `false`.\n * @property {String} dotNetKey Key for Unity and .Net SDK\n * @property {Adapter<MailAdapter>} emailAdapter Adapter module for email sending\n * @property {Boolean} emailVerifyTokenReuseIfValid Set to `true` if a email verification token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.\n * @property {Number} emailVerifyTokenValidityDuration Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.<br>Requires option `verifyUserEmails: true`.\n * @property {Boolean} enableAnonymousUsers Enable (or disable) anonymous users, defaults to true\n * @property {Boolean} enableExpressErrorHandler Enables the default express error handler for all errors\n * @property {String} encryptionKey Key for encrypting your files\n * @property {Boolean} enforcePrivateUsers Set to true if new users should be created without public read and write access.\n * @property {Boolean} expireInactiveSessions Sets whether we should expire the inactive sessions, defaults to true. If false, all new sessions are created with no expiration date.\n * @property {String} fileKey Key for your files\n * @property {Adapter<FilesAdapter>} filesAdapter Adapter module for the files sub-system\n * @property {FileUploadOptions} fileUpload Options for file uploads\n * @property {String} graphQLPath Mount path for the GraphQL endpoint, defaults to /graphql\n * @property {String} graphQLSchema Full path to your GraphQL custom schema.graphql file\n * @property {String} host The host to serve ParseServer on, defaults to 0.0.0.0\n * @property {IdempotencyOptions} idempotencyOptions Options for request idempotency to deduplicate identical requests that may be caused by network issues. Caution, this is an experimental feature that may not be appropriate for production.\n * @property {String} javascriptKey Key for the Javascript SDK\n * @property {Boolean} jsonLogs Log as structured JSON objects\n * @property {LiveQueryOptions} liveQuery parse-server's LiveQuery configuration object\n * @property {LiveQueryServerOptions} liveQueryServerOptions Live query server configuration options (will start the liveQuery server)\n * @property {Adapter<LoggerAdapter>} loggerAdapter Adapter module for the logging sub-system\n * @property {String} logLevel Sets the level for logs\n * @property {String} logsFolder Folder for the logs (defaults to './logs'); set to null to disable file based logging\n * @property {String} masterKey Your Parse Master Key\n * @property {String[]} masterKeyIps Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)\n * @property {Number} maxLimit Max value for limit option on queries, defaults to unlimited\n * @property {Number|String} maxLogFiles Maximum number of logs to keep. If not set, no logs will be removed. This can be a number of files or number of days. If using days, add 'd' as the suffix. (default: null)\n * @property {String} maxUploadSize Max file size for uploads, defaults to 20mb\n * @property {Union} middleware middleware for express server, can be string or function\n * @property {Boolean} mountGraphQL Mounts the GraphQL endpoint\n * @property {String} mountPath Mount path for the server, defaults to /parse\n * @property {Boolean} mountPlayground Mounts the GraphQL Playground - never use this option in production\n * @property {Number} objectIdSize Sets the number of characters in generated object id's, default 10\n * @property {PagesOptions} pages The options for pages such as password reset and email verification. Caution, this is an experimental feature that may not be appropriate for production.\n * @property {PasswordPolicyOptions} passwordPolicy The password policy for enforcing password related rules.\n * @property {String} playgroundPath Mount path for the GraphQL Playground, defaults to /playground\n * @property {Number} port The port to run the ParseServer, defaults to 1337.\n * @property {Boolean} preserveFileName Enable (or disable) the addition of a unique hash to the file names\n * @property {Boolean} preventLoginWithUnverifiedEmail Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.\n * @property {ProtectedFields} protectedFields Protected fields that should be treated with extra security when fetching details.\n * @property {String} publicServerURL Public URL to your parse server with http:// or https://.\n * @property {Any} push Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications\n * @property {String} readOnlyMasterKey Read-only key, which has the same capabilities as MasterKey without writes\n * @property {RequestKeywordDenylist[]} requestKeywordDenylist An array of keys and values that are prohibited in database read and write requests to prevent potential security vulnerabilities. It is possible to specify only a key (`{\"key\":\"...\"}`), only a value (`{\"value\":\"...\"}`) or a key-value pair (`{\"key\":\"...\",\"value\":\"...\"}`). The specification can use the following types: `boolean`, `numeric` or `string`, where `string` will be interpreted as a regex notation. Request data is deep-scanned for matching definitions to detect also any nested occurrences. Defaults are patterns that are likely to be used in malicious requests. Setting this option will override the default patterns.\n * @property {String} restAPIKey Key for REST calls\n * @property {Boolean} revokeSessionOnPasswordReset When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.\n * @property {Boolean} scheduledPush Configuration for push scheduling, defaults to false.\n * @property {SchemaOptions} schema Defined schema\n * @property {SecurityOptions} security The security options to identify and report weak security settings.\n * @property {Function} serverCloseComplete Callback when server has closed\n * @property {Function} serverStartComplete Callback when server has started\n * @property {String} serverURL URL to your parse server with http:// or https://.\n * @property {Number} sessionLength Session duration, in seconds, defaults to 1 year\n * @property {Boolean} silent Disables console output\n * @property {Boolean} startLiveQueryServer Starts the liveQuery server", "", " * @property {String[]} userSensitiveFields Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields\n * @property {Boolean} verbose Set the logging to verbose\n * @property {Boolean} verifyUserEmails Set to `true` to require users to verify their email address to complete the sign-up process.<br><br>Default is `false`.\n * @property {String} webhookKey Key sent with outgoing webhook calls\n */", "/**\n * @interface SecurityOptions\n * @property {CheckGroup[]} checkGroups The security check groups to run. This allows to add custom security checks or override existing ones. Default are the groups defined in `CheckGroups.js`.\n * @property {Boolean} enableCheck Is true if Parse Server should check for weak security settings.\n * @property {Boolean} enableCheckLog Is true if the security check report should be written to logs. This should only be enabled temporarily to not expose weak security settings in logs.\n */", "/**\n * @interface PagesOptions\n * @property {PagesRoute[]} customRoutes The custom routes.\n * @property {PagesCustomUrlsOptions} customUrls The URLs to the custom pages.\n * @property {Boolean} enableLocalization Is true if pages should be localized; this has no effect on custom page redirects.\n * @property {Boolean} enableRouter Is true if the pages router should be enabled; this is required for any of the pages options to take effect. Caution, this is an experimental feature that may not be appropriate for production.\n * @property {Boolean} forceRedirect Is true if responses should always be redirects and never content, false if the response type should depend on the request type (GET request -> content response; POST request -> redirect response).\n * @property {String} localizationFallbackLocale The fallback locale for localization if no matching translation is provided for the given locale. This is only relevant when providing translation resources via JSON file.\n * @property {String} localizationJsonPath The path to the JSON file for localization; the translations will be used to fill template placeholders according to the locale.\n * @property {String} pagesEndpoint The API endpoint for the pages. Default is 'apps'.\n * @property {String} pagesPath The path to the pages directory; this also defines where the static endpoint '/apps' points to. Default is the './public/' directory.\n * @property {Object} placeholders The placeholder keys and values which will be filled in pages; this can be a simple object or a callback function.\n */", "/**\n * @interface PagesRoute\n * @property {Function} handler The route handler that is an async function.\n * @property {String} method The route method, e.g. 'GET' or 'POST'.\n * @property {String} path The route path.\n */", "/**\n * @interface PagesCustomUrlsOptions\n * @property {String} emailVerificationLinkExpired The URL to the custom page for email verification -> link expired.\n * @property {String} emailVerificationLinkInvalid The URL to the custom page for email verification -> link invalid.\n * @property {String} emailVerificationSendFail The URL to the custom page for email verification -> link send fail.\n * @property {String} emailVerificationSendSuccess The URL to the custom page for email verification -> resend link -> success.\n * @property {String} emailVerificationSuccess The URL to the custom page for email verification -> success.\n * @property {String} passwordReset The URL to the custom page for password reset.\n * @property {String} passwordResetLinkInvalid The URL to the custom page for password reset -> link invalid.\n * @property {String} passwordResetSuccess The URL to the custom page for password reset -> success.\n */", "/**\n * @interface CustomPagesOptions\n * @property {String} choosePassword choose password page path\n * @property {String} expiredVerificationLink expired verification link page path\n * @property {String} invalidLink invalid link page path\n * @property {String} invalidPasswordResetLink invalid password reset link page path\n * @property {String} invalidVerificationLink invalid verification link page path\n * @property {String} linkSendFail verification link send fail page path\n * @property {String} linkSendSuccess verification link send success page path\n * @property {String} parseFrameURL for masking user-facing pages\n * @property {String} passwordResetSuccess password reset success page path\n * @property {String} verifyEmailSuccess verify email success page path\n */", "/**\n * @interface LiveQueryOptions\n * @property {String[]} classNames parse-server's LiveQuery classNames\n * @property {Adapter<PubSubAdapter>} pubSubAdapter LiveQuery pubsub adapter\n * @property {Any} redisOptions parse-server's LiveQuery redisOptions\n * @property {String} redisURL parse-server's LiveQuery redisURL\n * @property {Adapter<WSSAdapter>} wssAdapter Adapter module for the WebSocketServer\n */", "/**\n * @interface LiveQueryServerOptions\n * @property {String} appId This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.\n * @property {Number} cacheTimeout Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 5 * 1000 ms (5 seconds).\n * @property {Any} keyPairs A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.\n * @property {String} logLevel This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.\n * @property {String} masterKey This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.\n * @property {Number} port The port to run the LiveQuery server, defaults to 1337.\n * @property {Adapter<PubSubAdapter>} pubSubAdapter LiveQuery pubsub adapter\n * @property {Any} redisOptions parse-server's LiveQuery redisOptions\n * @property {String} redisURL parse-server's LiveQuery redisURL\n * @property {String} serverURL This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.\n * @property {Number} websocketTimeout Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).\n * @property {Adapter<WSSAdapter>} wssAdapter Adapter module for the WebSocketServer\n */", "/**\n * @interface IdempotencyOptions\n * @property {String[]} paths An array of paths for which the feature should be enabled. The mount path must not be included, for example instead of `/parse/functions/myFunction` specifiy `functions/myFunction`. The entries are interpreted as regular expression, for example `functions/.*` matches all functions, `jobs/.*` matches all jobs, `classes/.*` matches all classes, `.*` matches all paths.\n * @property {Number} ttl The duration in seconds after which a request record is discarded from the database, defaults to 300s.\n */", "/**\n * @interface AccountLockoutOptions\n * @property {Number} duration Set the duration in minutes that a locked-out account remains locked out before automatically becoming unlocked.<br><br>Valid values are greater than `0` and less than `100000`.\n * @property {Number} threshold Set the number of failed sign-in attempts that will cause a user account to be locked. If the account is locked. The account will unlock after the duration set in the `duration` option has passed and no further login attempts have been made.<br><br>Valid values are greater than `0` and less than `1000`.\n * @property {Boolean} unlockOnPasswordReset Set to `true` if the account should be unlocked after a successful password reset.<br><br>Default is `false`.<br>Requires options `duration` and `threshold` to be set.\n */", "/**\n * @interface PasswordPolicyOptions\n * @property {Boolean} doNotAllowUsername Set to `true` to disallow the username as part of the password.<br><br>Default is `false`.\n * @property {Number} maxPasswordAge Set the number of days after which a password expires. Login attempts fail if the user does not reset the password before expiration.\n * @property {Number} maxPasswordHistory Set the number of previous password that will not be allowed to be set as new password. If the option is not set or set to `0`, no previous passwords will be considered.<br><br>Valid values are >= `0` and <= `20`.<br>Default is `0`.\n * @property {Boolean} resetTokenReuseIfValid Set to `true` if a password reset token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.\n * @property {Number} resetTokenValidityDuration Set the validity duration of the password reset token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.\n * @property {String} validationError Set the error message to be sent.<br><br>Default is `Password does not meet the Password Policy requirements.`\n * @property {Function} validatorCallback Set a callback function to validate a password to be accepted.<br><br>If used in combination with `validatorPattern`, the password must pass both to be accepted.\n * @property {String} validatorPattern Set the regular expression validation pattern a password must match to be accepted.<br><br>If used in combination with `validatorCallback`, the password must pass both to be accepted.\n */", "/**\n * @interface FileUploadOptions\n * @property {Boolean} enableForAnonymousUser Is true if file upload should be allowed for anonymous users.\n * @property {Boolean} enableForAuthenticatedUser Is true if file upload should be allowed for authenticated users.\n * @property {Boolean} enableForPublic Is true if file upload should be allowed for anyone, regardless of user authentication.\n */", "/**\n * @interface DatabaseOptions\n * @property {Boolean} enableSchemaHooks Enables database real-time hooks to update single schema cache. Set to `true` if using multiple Parse Servers instances connected to the same database. Failing to do so will cause a schema change to not propagate to all instances and re-syncing will only happen when the instances restart. To use this feature with MongoDB, a replica set cluster with [change stream](https://docs.mongodb.com/manual/changeStreams/#availability) support is required.\n */", "/**\n * @interface AuthAdapter\n * @property {Boolean} enabled Is `true` if the auth adapter is enabled, `false` otherwise.\n */" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * @interface SchemaOptions\n * @property {Function} afterMigration Execute a callback after running schema migrations.\n * @property {Function} beforeMigration Execute a callback before running schema migrations.\n * @property {Any} definitions Rest representation on Parse.Schema https://docs.parseplatform.org/rest/guide/#adding-a-schema\n * @property {Boolean} deleteExtraFields Is true if Parse Server should delete any fields not defined in a schema definition. This should only be used during development.\n * @property {Boolean} lockSchemas Is true if Parse Server will reject any attempts to modify the schema while the server is running.\n * @property {Boolean} recreateModifiedFields Is true if Parse Server should recreate any fields that are different between the current database schema and theschema definition. This should only be used during development.\n * @property {Boolean} strict Is true if Parse Server should exit if schema update fail.\n */", "/**\n * @interface ParseServerOptions\n * @property {AccountLockoutOptions} accountLockout The account lockout policy for failed login attempts.\n * @property {Boolean} allowClientClassCreation Enable (or disable) client class creation, defaults to true\n * @property {Boolean} allowCustomObjectId Enable (or disable) custom objectId\n * @property {String[]} allowHeaders Add headers to Access-Control-Allow-Headers\n * @property {String} allowOrigin Sets the origin to Access-Control-Allow-Origin\n * @property {Adapter<AnalyticsAdapter>} analyticsAdapter Adapter module for the analytics\n * @property {String} appId Your Parse Application ID\n * @property {String} appName Sets the app name\n * @property {AuthAdapter[]} auth Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication\n * @property {Adapter<CacheAdapter>} cacheAdapter Adapter module for the cache\n * @property {Number} cacheMaxSize Sets the maximum size for the in memory cache, defaults to 10000\n * @property {Number} cacheTTL Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)\n * @property {String} clientKey Key for iOS, MacOS, tvOS clients\n * @property {String} cloud Full path to your cloud code main.js\n * @property {Number|Boolean} cluster Run with cluster, optionally set the number of processes default to os.cpus().length\n * @property {String} collectionPrefix A collection prefix for the classes\n * @property {CustomPagesOptions} customPages custom pages for password validation and reset\n * @property {Adapter<StorageAdapter>} databaseAdapter Adapter module for the database; any options that are not explicitly described here are passed directly to the database client.\n * @property {DatabaseOptions} databaseOptions Options to pass to the database client\n * @property {String} databaseURI The full URI to your database. Supported databases are mongodb or postgres.\n * @property {Number} defaultLimit Default value for limit option on queries, defaults to `100`.\n * @property {Boolean} directAccess Set to `true` if Parse requests within the same Node.js environment as Parse Server should be routed to Parse Server directly instead of via the HTTP interface. Default is `false`.<br><br>If set to `false` then Parse requests within the same Node.js environment as Parse Server are executed as HTTP requests sent to Parse Server via the `serverURL`. For example, a `Parse.Query` in Cloud Code is calling Parse Server via a HTTP request. The server is essentially making a HTTP request to itself, unnecessarily using network resources such as network ports.<br><br>⚠️ In environments where multiple Parse Server instances run behind a load balancer and Parse requests within the current Node.js environment should be routed via the load balancer and distributed as HTTP requests among all instances via the `serverURL`, this should be set to `false`.\n * @property {String} dotNetKey Key for Unity and .Net SDK\n * @property {Adapter<MailAdapter>} emailAdapter Adapter module for email sending\n * @property {Boolean} emailVerifyTokenReuseIfValid Set to `true` if a email verification token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.\n * @property {Number} emailVerifyTokenValidityDuration Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.<br>Requires option `verifyUserEmails: true`.\n * @property {Boolean} enableAnonymousUsers Enable (or disable) anonymous users, defaults to true\n * @property {Boolean} enableExpressErrorHandler Enables the default express error handler for all errors\n * @property {String} encryptionKey Key for encrypting your files\n * @property {Boolean} enforcePrivateUsers Set to true if new users should be created without public read and write access.\n * @property {Boolean} expireInactiveSessions Sets whether we should expire the inactive sessions, defaults to true. If false, all new sessions are created with no expiration date.\n * @property {String} fileKey Key for your files\n * @property {Adapter<FilesAdapter>} filesAdapter Adapter module for the files sub-system\n * @property {FileUploadOptions} fileUpload Options for file uploads\n * @property {String} graphQLPath Mount path for the GraphQL endpoint, defaults to /graphql\n * @property {String} graphQLSchema Full path to your GraphQL custom schema.graphql file\n * @property {String} host The host to serve ParseServer on, defaults to 0.0.0.0\n * @property {IdempotencyOptions} idempotencyOptions Options for request idempotency to deduplicate identical requests that may be caused by network issues. Caution, this is an experimental feature that may not be appropriate for production.\n * @property {String} javascriptKey Key for the Javascript SDK\n * @property {Boolean} jsonLogs Log as structured JSON objects\n * @property {LiveQueryOptions} liveQuery parse-server's LiveQuery configuration object\n * @property {LiveQueryServerOptions} liveQueryServerOptions Live query server configuration options (will start the liveQuery server)\n * @property {Adapter<LoggerAdapter>} loggerAdapter Adapter module for the logging sub-system\n * @property {String} logLevel Sets the level for logs\n * @property {String} logsFolder Folder for the logs (defaults to './logs'); set to null to disable file based logging\n * @property {String} masterKey Your Parse Master Key\n * @property {String[]} masterKeyIps Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)\n * @property {Number} maxLimit Max value for limit option on queries, defaults to unlimited\n * @property {Number|String} maxLogFiles Maximum number of logs to keep. If not set, no logs will be removed. This can be a number of files or number of days. If using days, add 'd' as the suffix. (default: null)\n * @property {String} maxUploadSize Max file size for uploads, defaults to 20mb\n * @property {Union} middleware middleware for express server, can be string or function\n * @property {Boolean} mountGraphQL Mounts the GraphQL endpoint\n * @property {String} mountPath Mount path for the server, defaults to /parse\n * @property {Boolean} mountPlayground Mounts the GraphQL Playground - never use this option in production\n * @property {Number} objectIdSize Sets the number of characters in generated object id's, default 10\n * @property {PagesOptions} pages The options for pages such as password reset and email verification. Caution, this is an experimental feature that may not be appropriate for production.\n * @property {PasswordPolicyOptions} passwordPolicy The password policy for enforcing password related rules.\n * @property {String} playgroundPath Mount path for the GraphQL Playground, defaults to /playground\n * @property {Number} port The port to run the ParseServer, defaults to 1337.\n * @property {Boolean} preserveFileName Enable (or disable) the addition of a unique hash to the file names\n * @property {Boolean} preventLoginWithUnverifiedEmail Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.<br><br>Default is `false`.<br>Requires option `verifyUserEmails: true`.\n * @property {ProtectedFields} protectedFields Protected fields that should be treated with extra security when fetching details.\n * @property {String} publicServerURL Public URL to your parse server with http:// or https://.\n * @property {Any} push Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications\n * @property {String} readOnlyMasterKey Read-only key, which has the same capabilities as MasterKey without writes\n * @property {RequestKeywordDenylist[]} requestKeywordDenylist An array of keys and values that are prohibited in database read and write requests to prevent potential security vulnerabilities. It is possible to specify only a key (`{\"key\":\"...\"}`), only a value (`{\"value\":\"...\"}`) or a key-value pair (`{\"key\":\"...\",\"value\":\"...\"}`). The specification can use the following types: `boolean`, `numeric` or `string`, where `string` will be interpreted as a regex notation. Request data is deep-scanned for matching definitions to detect also any nested occurrences. Defaults are patterns that are likely to be used in malicious requests. Setting this option will override the default patterns.\n * @property {String} restAPIKey Key for REST calls\n * @property {Boolean} revokeSessionOnPasswordReset When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.\n * @property {Boolean} scheduledPush Configuration for push scheduling, defaults to false.\n * @property {SchemaOptions} schema Defined schema\n * @property {SecurityOptions} security The security options to identify and report weak security settings.\n * @property {Function} serverCloseComplete Callback when server has closed\n * @property {Function} serverStartComplete Callback when server has started\n * @property {String} serverURL URL to your parse server with http:// or https://.\n * @property {Number} sessionLength Session duration, in seconds, defaults to 1 year\n * @property {Boolean} silent Disables console output\n * @property {Boolean} startLiveQueryServer Starts the liveQuery server", " * @property {Any} trustProxy The trust proxy settings. It is important to understand the exact setup of the reverse proxy, since this setting will trust values provided in the Parse Server API request. See the <a href=\"https://expressjs.com/en/guide/behind-proxies.html\">express trust proxy settings</a> documentation. Defaults to `false`.", " * @property {String[]} userSensitiveFields Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields\n * @property {Boolean} verbose Set the logging to verbose\n * @property {Boolean} verifyUserEmails Set to `true` to require users to verify their email address to complete the sign-up process.<br><br>Default is `false`.\n * @property {String} webhookKey Key sent with outgoing webhook calls\n */", "/**\n * @interface SecurityOptions\n * @property {CheckGroup[]} checkGroups The security check groups to run. This allows to add custom security checks or override existing ones. Default are the groups defined in `CheckGroups.js`.\n * @property {Boolean} enableCheck Is true if Parse Server should check for weak security settings.\n * @property {Boolean} enableCheckLog Is true if the security check report should be written to logs. This should only be enabled temporarily to not expose weak security settings in logs.\n */", "/**\n * @interface PagesOptions\n * @property {PagesRoute[]} customRoutes The custom routes.\n * @property {PagesCustomUrlsOptions} customUrls The URLs to the custom pages.\n * @property {Boolean} enableLocalization Is true if pages should be localized; this has no effect on custom page redirects.\n * @property {Boolean} enableRouter Is true if the pages router should be enabled; this is required for any of the pages options to take effect. Caution, this is an experimental feature that may not be appropriate for production.\n * @property {Boolean} forceRedirect Is true if responses should always be redirects and never content, false if the response type should depend on the request type (GET request -> content response; POST request -> redirect response).\n * @property {String} localizationFallbackLocale The fallback locale for localization if no matching translation is provided for the given locale. This is only relevant when providing translation resources via JSON file.\n * @property {String} localizationJsonPath The path to the JSON file for localization; the translations will be used to fill template placeholders according to the locale.\n * @property {String} pagesEndpoint The API endpoint for the pages. Default is 'apps'.\n * @property {String} pagesPath The path to the pages directory; this also defines where the static endpoint '/apps' points to. Default is the './public/' directory.\n * @property {Object} placeholders The placeholder keys and values which will be filled in pages; this can be a simple object or a callback function.\n */", "/**\n * @interface PagesRoute\n * @property {Function} handler The route handler that is an async function.\n * @property {String} method The route method, e.g. 'GET' or 'POST'.\n * @property {String} path The route path.\n */", "/**\n * @interface PagesCustomUrlsOptions\n * @property {String} emailVerificationLinkExpired The URL to the custom page for email verification -> link expired.\n * @property {String} emailVerificationLinkInvalid The URL to the custom page for email verification -> link invalid.\n * @property {String} emailVerificationSendFail The URL to the custom page for email verification -> link send fail.\n * @property {String} emailVerificationSendSuccess The URL to the custom page for email verification -> resend link -> success.\n * @property {String} emailVerificationSuccess The URL to the custom page for email verification -> success.\n * @property {String} passwordReset The URL to the custom page for password reset.\n * @property {String} passwordResetLinkInvalid The URL to the custom page for password reset -> link invalid.\n * @property {String} passwordResetSuccess The URL to the custom page for password reset -> success.\n */", "/**\n * @interface CustomPagesOptions\n * @property {String} choosePassword choose password page path\n * @property {String} expiredVerificationLink expired verification link page path\n * @property {String} invalidLink invalid link page path\n * @property {String} invalidPasswordResetLink invalid password reset link page path\n * @property {String} invalidVerificationLink invalid verification link page path\n * @property {String} linkSendFail verification link send fail page path\n * @property {String} linkSendSuccess verification link send success page path\n * @property {String} parseFrameURL for masking user-facing pages\n * @property {String} passwordResetSuccess password reset success page path\n * @property {String} verifyEmailSuccess verify email success page path\n */", "/**\n * @interface LiveQueryOptions\n * @property {String[]} classNames parse-server's LiveQuery classNames\n * @property {Adapter<PubSubAdapter>} pubSubAdapter LiveQuery pubsub adapter\n * @property {Any} redisOptions parse-server's LiveQuery redisOptions\n * @property {String} redisURL parse-server's LiveQuery redisURL\n * @property {Adapter<WSSAdapter>} wssAdapter Adapter module for the WebSocketServer\n */", "/**\n * @interface LiveQueryServerOptions\n * @property {String} appId This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.\n * @property {Number} cacheTimeout Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 5 * 1000 ms (5 seconds).\n * @property {Any} keyPairs A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.\n * @property {String} logLevel This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.\n * @property {String} masterKey This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.\n * @property {Number} port The port to run the LiveQuery server, defaults to 1337.\n * @property {Adapter<PubSubAdapter>} pubSubAdapter LiveQuery pubsub adapter\n * @property {Any} redisOptions parse-server's LiveQuery redisOptions\n * @property {String} redisURL parse-server's LiveQuery redisURL\n * @property {String} serverURL This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.\n * @property {Number} websocketTimeout Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).\n * @property {Adapter<WSSAdapter>} wssAdapter Adapter module for the WebSocketServer\n */", "/**\n * @interface IdempotencyOptions\n * @property {String[]} paths An array of paths for which the feature should be enabled. The mount path must not be included, for example instead of `/parse/functions/myFunction` specifiy `functions/myFunction`. The entries are interpreted as regular expression, for example `functions/.*` matches all functions, `jobs/.*` matches all jobs, `classes/.*` matches all classes, `.*` matches all paths.\n * @property {Number} ttl The duration in seconds after which a request record is discarded from the database, defaults to 300s.\n */", "/**\n * @interface AccountLockoutOptions\n * @property {Number} duration Set the duration in minutes that a locked-out account remains locked out before automatically becoming unlocked.<br><br>Valid values are greater than `0` and less than `100000`.\n * @property {Number} threshold Set the number of failed sign-in attempts that will cause a user account to be locked. If the account is locked. The account will unlock after the duration set in the `duration` option has passed and no further login attempts have been made.<br><br>Valid values are greater than `0` and less than `1000`.\n * @property {Boolean} unlockOnPasswordReset Set to `true` if the account should be unlocked after a successful password reset.<br><br>Default is `false`.<br>Requires options `duration` and `threshold` to be set.\n */", "/**\n * @interface PasswordPolicyOptions\n * @property {Boolean} doNotAllowUsername Set to `true` to disallow the username as part of the password.<br><br>Default is `false`.\n * @property {Number} maxPasswordAge Set the number of days after which a password expires. Login attempts fail if the user does not reset the password before expiration.\n * @property {Number} maxPasswordHistory Set the number of previous password that will not be allowed to be set as new password. If the option is not set or set to `0`, no previous passwords will be considered.<br><br>Valid values are >= `0` and <= `20`.<br>Default is `0`.\n * @property {Boolean} resetTokenReuseIfValid Set to `true` if a password reset token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.<br><br>Default is `false`.\n * @property {Number} resetTokenValidityDuration Set the validity duration of the password reset token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.<br><br>For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).<br><br>Default is `undefined`.\n * @property {String} validationError Set the error message to be sent.<br><br>Default is `Password does not meet the Password Policy requirements.`\n * @property {Function} validatorCallback Set a callback function to validate a password to be accepted.<br><br>If used in combination with `validatorPattern`, the password must pass both to be accepted.\n * @property {String} validatorPattern Set the regular expression validation pattern a password must match to be accepted.<br><br>If used in combination with `validatorCallback`, the password must pass both to be accepted.\n */", "/**\n * @interface FileUploadOptions\n * @property {Boolean} enableForAnonymousUser Is true if file upload should be allowed for anonymous users.\n * @property {Boolean} enableForAuthenticatedUser Is true if file upload should be allowed for authenticated users.\n * @property {Boolean} enableForPublic Is true if file upload should be allowed for anyone, regardless of user authentication.\n */", "/**\n * @interface DatabaseOptions\n * @property {Boolean} enableSchemaHooks Enables database real-time hooks to update single schema cache. Set to `true` if using multiple Parse Servers instances connected to the same database. Failing to do so will cause a schema change to not propagate to all instances and re-syncing will only happen when the instances restart. To use this feature with MongoDB, a replica set cluster with [change stream](https://docs.mongodb.com/manual/changeStreams/#availability) support is required.\n */", "/**\n * @interface AuthAdapter\n * @property {Boolean} enabled Is `true` if the auth adapter is enabled, `false` otherwise.\n */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "// @flow\nimport { AnalyticsAdapter } from '../Adapters/Analytics/AnalyticsAdapter';\nimport { FilesAdapter } from '../Adapters/Files/FilesAdapter';\nimport { LoggerAdapter } from '../Adapters/Logger/LoggerAdapter';\nimport { StorageAdapter } from '../Adapters/Storage/StorageAdapter';\nimport { CacheAdapter } from '../Adapters/Cache/CacheAdapter';\nimport { MailAdapter } from '../Adapters/Email/MailAdapter';\nimport { PubSubAdapter } from '../Adapters/PubSub/PubSubAdapter';\nimport { WSSAdapter } from '../Adapters/WebSocketServer/WSSAdapter';\nimport { CheckGroup } from '../Security/CheckGroup';", "export interface SchemaOptions {\n /* Rest representation on Parse.Schema https://docs.parseplatform.org/rest/guide/#adding-a-schema\n :DEFAULT: [] */\n definitions: any;\n /* Is true if Parse Server should exit if schema update fail.\n :DEFAULT: false */\n strict: ?boolean;\n /* Is true if Parse Server should delete any fields not defined in a schema definition. This should only be used during development.\n :DEFAULT: false */\n deleteExtraFields: ?boolean;\n /* Is true if Parse Server should recreate any fields that are different between the current database schema and theschema definition. This should only be used during development.\n :DEFAULT: false */\n recreateModifiedFields: ?boolean;\n /* Is true if Parse Server will reject any attempts to modify the schema while the server is running.\n :DEFAULT: false */\n lockSchemas: ?boolean;\n /* Execute a callback before running schema migrations. */\n beforeMigration: ?() => void | Promise<void>;\n /* Execute a callback after running schema migrations. */\n afterMigration: ?() => void | Promise<void>;\n}", "type Adapter<T> = string | any | T;\ntype NumberOrBoolean = number | boolean;\ntype NumberOrString = number | string;\ntype ProtectedFields = any;\ntype RequestKeywordDenylist = {\n key: string | any,\n value: any,\n};", "export interface ParseServerOptions {\n /* Your Parse Application ID\n :ENV: PARSE_SERVER_APPLICATION_ID */\n appId: string;\n /* Your Parse Master Key */\n masterKey: string;\n /* URL to your parse server with http:// or https://.\n :ENV: PARSE_SERVER_URL */\n serverURL: string;\n /* Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)\n :DEFAULT: [] */\n masterKeyIps: ?(string[]);\n /* Sets the app name */\n appName: ?string;\n /* Add headers to Access-Control-Allow-Headers */\n allowHeaders: ?(string[]);\n /* Sets the origin to Access-Control-Allow-Origin */\n allowOrigin: ?string;\n /* Adapter module for the analytics */\n analyticsAdapter: ?Adapter<AnalyticsAdapter>;\n /* Adapter module for the files sub-system */\n filesAdapter: ?Adapter<FilesAdapter>;\n /* Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications */\n push: ?any;\n /* Configuration for push scheduling, defaults to false.\n :DEFAULT: false */\n scheduledPush: ?boolean;\n /* Adapter module for the logging sub-system */\n loggerAdapter: ?Adapter<LoggerAdapter>;\n /* Log as structured JSON objects\n :ENV: JSON_LOGS */\n jsonLogs: ?boolean;\n /* Folder for the logs (defaults to './logs'); set to null to disable file based logging\n :ENV: PARSE_SERVER_LOGS_FOLDER\n :DEFAULT: ./logs */\n logsFolder: ?string;\n /* Set the logging to verbose\n :ENV: VERBOSE */\n verbose: ?boolean;\n /* Sets the level for logs */\n logLevel: ?string;\n /* Maximum number of logs to keep. If not set, no logs will be removed. This can be a number of files or number of days. If using days, add 'd' as the suffix. (default: null) */\n maxLogFiles: ?NumberOrString;\n /* Disables console output\n :ENV: SILENT */\n silent: ?boolean;\n /* The full URI to your database. Supported databases are mongodb or postgres.\n :DEFAULT: mongodb://localhost:27017/parse */\n databaseURI: string;\n /* Options to pass to the database client\n :ENV: PARSE_SERVER_DATABASE_OPTIONS */\n databaseOptions: ?DatabaseOptions;\n /* Adapter module for the database; any options that are not explicitly described here are passed directly to the database client. */\n databaseAdapter: ?Adapter<StorageAdapter>;\n /* Full path to your cloud code main.js */\n cloud: ?string;\n /* A collection prefix for the classes\n :DEFAULT: '' */\n collectionPrefix: ?string;\n /* Key for iOS, MacOS, tvOS clients */\n clientKey: ?string;\n /* Key for the Javascript SDK */\n javascriptKey: ?string;\n /* Key for Unity and .Net SDK */\n dotNetKey: ?string;\n /* Key for encrypting your files\n :ENV: PARSE_SERVER_ENCRYPTION_KEY */\n encryptionKey: ?string;\n /* Key for REST calls\n :ENV: PARSE_SERVER_REST_API_KEY */\n restAPIKey: ?string;\n /* Read-only key, which has the same capabilities as MasterKey without writes */\n readOnlyMasterKey: ?string;\n /* Key sent with outgoing webhook calls */\n webhookKey: ?string;\n /* Key for your files */\n fileKey: ?string;\n /* Enable (or disable) the addition of a unique hash to the file names\n :ENV: PARSE_SERVER_PRESERVE_FILE_NAME\n :DEFAULT: false */\n preserveFileName: ?boolean;\n /* Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields */\n userSensitiveFields: ?(string[]);\n /* Protected fields that should be treated with extra security when fetching details.\n :DEFAULT: {\"_User\": {\"*\": [\"email\"]}} */\n protectedFields: ?ProtectedFields;\n /* Enable (or disable) anonymous users, defaults to true\n :ENV: PARSE_SERVER_ENABLE_ANON_USERS\n :DEFAULT: true */\n enableAnonymousUsers: ?boolean;\n /* Enable (or disable) client class creation, defaults to true\n :ENV: PARSE_SERVER_ALLOW_CLIENT_CLASS_CREATION\n :DEFAULT: true */\n allowClientClassCreation: ?boolean;\n /* Enable (or disable) custom objectId\n :ENV: PARSE_SERVER_ALLOW_CUSTOM_OBJECT_ID\n :DEFAULT: false */\n allowCustomObjectId: ?boolean;\n /* Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication\n :ENV: PARSE_SERVER_AUTH_PROVIDERS */\n auth: ?(AuthAdapter[]);\n /* Max file size for uploads, defaults to 20mb\n :DEFAULT: 20mb */\n maxUploadSize: ?string;\n /* Set to `true` to require users to verify their email address to complete the sign-up process.\n <br><br>\n Default is `false`.\n :DEFAULT: false */\n verifyUserEmails: ?boolean;\n /* Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.\n <br><br>\n Default is `false`.\n <br>\n Requires option `verifyUserEmails: true`.\n :DEFAULT: false */\n preventLoginWithUnverifiedEmail: ?boolean;\n /* Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.\n <br><br>\n For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).\n <br><br>\n Default is `undefined`.\n <br>\n Requires option `verifyUserEmails: true`.\n */\n emailVerifyTokenValidityDuration: ?number;\n /* Set to `true` if a email verification token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.\n <br><br>\n Default is `false`.\n <br>\n Requires option `verifyUserEmails: true`.\n :DEFAULT: false */\n emailVerifyTokenReuseIfValid: ?boolean;\n /* The account lockout policy for failed login attempts. */\n accountLockout: ?AccountLockoutOptions;\n /* The password policy for enforcing password related rules. */\n passwordPolicy: ?PasswordPolicyOptions;\n /* Adapter module for the cache */\n cacheAdapter: ?Adapter<CacheAdapter>;\n /* Adapter module for email sending */\n emailAdapter: ?Adapter<MailAdapter>;\n /* Public URL to your parse server with http:// or https://.\n :ENV: PARSE_PUBLIC_SERVER_URL */\n publicServerURL: ?string;\n /* The options for pages such as password reset and email verification. Caution, this is an experimental feature that may not be appropriate for production.\n :DEFAULT: {} */\n pages: ?PagesOptions;\n /* custom pages for password validation and reset\n :DEFAULT: {} */\n customPages: ?CustomPagesOptions;\n /* parse-server's LiveQuery configuration object */\n liveQuery: ?LiveQueryOptions;\n /* Session duration, in seconds, defaults to 1 year\n :DEFAULT: 31536000 */\n sessionLength: ?number;\n /* Default value for limit option on queries, defaults to `100`.\n :DEFAULT: 100 */\n defaultLimit: ?number;\n /* Max value for limit option on queries, defaults to unlimited */\n maxLimit: ?number;\n /* Sets whether we should expire the inactive sessions, defaults to true. If false, all new sessions are created with no expiration date.\n :DEFAULT: true */\n expireInactiveSessions: ?boolean;\n /* When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.\n :DEFAULT: true */\n revokeSessionOnPasswordReset: ?boolean;\n /* Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)\n :DEFAULT: 5000 */\n cacheTTL: ?number;\n /* Sets the maximum size for the in memory cache, defaults to 10000\n :DEFAULT: 10000 */\n cacheMaxSize: ?number;\n /* Set to `true` if Parse requests within the same Node.js environment as Parse Server should be routed to Parse Server directly instead of via the HTTP interface. Default is `false`.\n <br><br>\n If set to `false` then Parse requests within the same Node.js environment as Parse Server are executed as HTTP requests sent to Parse Server via the `serverURL`. For example, a `Parse.Query` in Cloud Code is calling Parse Server via a HTTP request. The server is essentially making a HTTP request to itself, unnecessarily using network resources such as network ports.\n <br><br>\n ⚠️ In environments where multiple Parse Server instances run behind a load balancer and Parse requests within the current Node.js environment should be routed via the load balancer and distributed as HTTP requests among all instances via the `serverURL`, this should be set to `false`.\n :DEFAULT: false */\n directAccess: ?boolean;\n /* Enables the default express error handler for all errors\n :DEFAULT: false */\n enableExpressErrorHandler: ?boolean;\n /* Sets the number of characters in generated object id's, default 10\n :DEFAULT: 10 */\n objectIdSize: ?number;\n /* The port to run the ParseServer, defaults to 1337.\n :ENV: PORT\n :DEFAULT: 1337 */\n port: ?number;\n /* The host to serve ParseServer on, defaults to 0.0.0.0\n :DEFAULT: 0.0.0.0 */\n host: ?string;\n /* Mount path for the server, defaults to /parse\n :DEFAULT: /parse */\n mountPath: ?string;\n /* Run with cluster, optionally set the number of processes default to os.cpus().length */\n cluster: ?NumberOrBoolean;\n /* middleware for express server, can be string or function */\n middleware: ?((() => void) | string);", "", " /* Starts the liveQuery server */\n startLiveQueryServer: ?boolean;\n /* Live query server configuration options (will start the liveQuery server) */\n liveQueryServerOptions: ?LiveQueryServerOptions;\n /* Options for request idempotency to deduplicate identical requests that may be caused by network issues. Caution, this is an experimental feature that may not be appropriate for production.\n :ENV: PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_OPTIONS\n :DEFAULT: false */\n idempotencyOptions: ?IdempotencyOptions;\n /* Options for file uploads\n :ENV: PARSE_SERVER_FILE_UPLOAD_OPTIONS\n :DEFAULT: {} */\n fileUpload: ?FileUploadOptions;\n /* Full path to your GraphQL custom schema.graphql file */\n graphQLSchema: ?string;\n /* Mounts the GraphQL endpoint\n :ENV: PARSE_SERVER_MOUNT_GRAPHQL\n :DEFAULT: false */\n mountGraphQL: ?boolean;\n /* Mount path for the GraphQL endpoint, defaults to /graphql\n :ENV: PARSE_SERVER_GRAPHQL_PATH\n :DEFAULT: /graphql */\n graphQLPath: ?string;\n /* Mounts the GraphQL Playground - never use this option in production\n :ENV: PARSE_SERVER_MOUNT_PLAYGROUND\n :DEFAULT: false */\n mountPlayground: ?boolean;\n /* Mount path for the GraphQL Playground, defaults to /playground\n :ENV: PARSE_SERVER_PLAYGROUND_PATH\n :DEFAULT: /playground */\n playgroundPath: ?string;\n /* Callback when server has started */\n serverStartComplete: ?(error: ?Error) => void;\n /* Defined schema\n :ENV: PARSE_SERVER_SCHEMA\n */\n schema: ?SchemaOptions;\n /* Callback when server has closed */\n serverCloseComplete: ?() => void;\n /* The security options to identify and report weak security settings.\n :DEFAULT: {} */\n security: ?SecurityOptions;\n /* Set to true if new users should be created without public read and write access.\n :DEFAULT: false */\n enforcePrivateUsers: ?boolean;\n /* An array of keys and values that are prohibited in database read and write requests to prevent potential security vulnerabilities. It is possible to specify only a key (`{\"key\":\"...\"}`), only a value (`{\"value\":\"...\"}`) or a key-value pair (`{\"key\":\"...\",\"value\":\"...\"}`). The specification can use the following types: `boolean`, `numeric` or `string`, where `string` will be interpreted as a regex notation. Request data is deep-scanned for matching definitions to detect also any nested occurrences. Defaults are patterns that are likely to be used in malicious requests. Setting this option will override the default patterns.\n :DEFAULT: [{\"key\":\"_bsontype\",\"value\":\"Code\"},{\"key\":\"constructor\"},{\"key\":\"__proto__\"}] */\n requestKeywordDenylist: ?(RequestKeywordDenylist[]);\n}", "export interface SecurityOptions {\n /* Is true if Parse Server should check for weak security settings.\n :DEFAULT: false */\n enableCheck: ?boolean;\n /* Is true if the security check report should be written to logs. This should only be enabled temporarily to not expose weak security settings in logs.\n :DEFAULT: false */\n enableCheckLog: ?boolean;\n /* The security check groups to run. This allows to add custom security checks or override existing ones. Default are the groups defined in `CheckGroups.js`. */\n checkGroups: ?(CheckGroup[]);\n}", "export interface PagesOptions {\n /* Is true if the pages router should be enabled; this is required for any of the pages options to take effect. Caution, this is an experimental feature that may not be appropriate for production.\n :DEFAULT: false */\n enableRouter: ?boolean;\n /* Is true if pages should be localized; this has no effect on custom page redirects.\n :DEFAULT: false */\n enableLocalization: ?boolean;\n /* The path to the JSON file for localization; the translations will be used to fill template placeholders according to the locale. */\n localizationJsonPath: ?string;\n /* The fallback locale for localization if no matching translation is provided for the given locale. This is only relevant when providing translation resources via JSON file.\n :DEFAULT: en */\n localizationFallbackLocale: ?string;\n /* The placeholder keys and values which will be filled in pages; this can be a simple object or a callback function.\n :DEFAULT: {} */\n placeholders: ?Object;\n /* Is true if responses should always be redirects and never content, false if the response type should depend on the request type (GET request -> content response; POST request -> redirect response).\n :DEFAULT: false */\n forceRedirect: ?boolean;\n /* The path to the pages directory; this also defines where the static endpoint '/apps' points to. Default is the './public/' directory.\n :DEFAULT: ./public */\n pagesPath: ?string;\n /* The API endpoint for the pages. Default is 'apps'.\n :DEFAULT: apps */\n pagesEndpoint: ?string;\n /* The URLs to the custom pages.\n :DEFAULT: {} */\n customUrls: ?PagesCustomUrlsOptions;\n /* The custom routes.\n :DEFAULT: [] */\n customRoutes: ?(PagesRoute[]);\n}", "export interface PagesRoute {\n /* The route path. */\n path: string;\n /* The route method, e.g. 'GET' or 'POST'. */\n method: string;\n /* The route handler that is an async function. */\n handler: () => void;\n}", "export interface PagesCustomUrlsOptions {\n /* The URL to the custom page for password reset. */\n passwordReset: ?string;\n /* The URL to the custom page for password reset -> link invalid. */\n passwordResetLinkInvalid: ?string;\n /* The URL to the custom page for password reset -> success. */\n passwordResetSuccess: ?string;\n /* The URL to the custom page for email verification -> success. */\n emailVerificationSuccess: ?string;\n /* The URL to the custom page for email verification -> link send fail. */\n emailVerificationSendFail: ?string;\n /* The URL to the custom page for email verification -> resend link -> success. */\n emailVerificationSendSuccess: ?string;\n /* The URL to the custom page for email verification -> link invalid. */\n emailVerificationLinkInvalid: ?string;\n /* The URL to the custom page for email verification -> link expired. */\n emailVerificationLinkExpired: ?string;\n}", "export interface CustomPagesOptions {\n /* invalid link page path */\n invalidLink: ?string;\n /* verification link send fail page path */\n linkSendFail: ?string;\n /* choose password page path */\n choosePassword: ?string;\n /* verification link send success page path */\n linkSendSuccess: ?string;\n /* verify email success page path */\n verifyEmailSuccess: ?string;\n /* password reset success page path */\n passwordResetSuccess: ?string;\n /* invalid verification link page path */\n invalidVerificationLink: ?string;\n /* expired verification link page path */\n expiredVerificationLink: ?string;\n /* invalid password reset link page path */\n invalidPasswordResetLink: ?string;\n /* for masking user-facing pages */\n parseFrameURL: ?string;\n}", "export interface LiveQueryOptions {\n /* parse-server's LiveQuery classNames\n :ENV: PARSE_SERVER_LIVEQUERY_CLASSNAMES */\n classNames: ?(string[]);\n /* parse-server's LiveQuery redisOptions */\n redisOptions: ?any;\n /* parse-server's LiveQuery redisURL */\n redisURL: ?string;\n /* LiveQuery pubsub adapter */\n pubSubAdapter: ?Adapter<PubSubAdapter>;\n /* Adapter module for the WebSocketServer */\n wssAdapter: ?Adapter<WSSAdapter>;\n}", "export interface LiveQueryServerOptions {\n /* This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.*/\n appId: ?string;\n /* This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.*/\n masterKey: ?string;\n /* This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.*/\n serverURL: ?string;\n /* A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.*/\n keyPairs: ?any;\n /* Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).*/\n websocketTimeout: ?number;\n /* Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 5 * 1000 ms (5 seconds).*/\n cacheTimeout: ?number;\n /* This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.*/\n logLevel: ?string;\n /* The port to run the LiveQuery server, defaults to 1337.\n :DEFAULT: 1337 */\n port: ?number;\n /* parse-server's LiveQuery redisOptions */\n redisOptions: ?any;\n /* parse-server's LiveQuery redisURL */\n redisURL: ?string;\n /* LiveQuery pubsub adapter */\n pubSubAdapter: ?Adapter<PubSubAdapter>;\n /* Adapter module for the WebSocketServer */\n wssAdapter: ?Adapter<WSSAdapter>;\n}", "export interface IdempotencyOptions {\n /* An array of paths for which the feature should be enabled. The mount path must not be included, for example instead of `/parse/functions/myFunction` specifiy `functions/myFunction`. The entries are interpreted as regular expression, for example `functions/.*` matches all functions, `jobs/.*` matches all jobs, `classes/.*` matches all classes, `.*` matches all paths.\n :DEFAULT: [] */\n paths: ?(string[]);\n /* The duration in seconds after which a request record is discarded from the database, defaults to 300s.\n :DEFAULT: 300 */\n ttl: ?number;\n}", "export interface AccountLockoutOptions {\n /* Set the duration in minutes that a locked-out account remains locked out before automatically becoming unlocked.\n <br><br>\n Valid values are greater than `0` and less than `100000`. */\n duration: ?number;\n /* Set the number of failed sign-in attempts that will cause a user account to be locked. If the account is locked. The account will unlock after the duration set in the `duration` option has passed and no further login attempts have been made.\n <br><br>\n Valid values are greater than `0` and less than `1000`. */\n threshold: ?number;\n /* Set to `true` if the account should be unlocked after a successful password reset.\n <br><br>\n Default is `false`.\n <br>\n Requires options `duration` and `threshold` to be set.\n :DEFAULT: false */\n unlockOnPasswordReset: ?boolean;\n}", "export interface PasswordPolicyOptions {\n /* Set the regular expression validation pattern a password must match to be accepted.\n <br><br>\n If used in combination with `validatorCallback`, the password must pass both to be accepted. */\n validatorPattern: ?string;\n /* */\n /* Set a callback function to validate a password to be accepted.\n <br><br>\n If used in combination with `validatorPattern`, the password must pass both to be accepted. */\n validatorCallback: ?() => void;\n /* Set the error message to be sent.\n <br><br>\n Default is `Password does not meet the Password Policy requirements.` */\n validationError: ?string;\n /* Set to `true` to disallow the username as part of the password.\n <br><br>\n Default is `false`.\n :DEFAULT: false */\n doNotAllowUsername: ?boolean;\n /* Set the number of days after which a password expires. Login attempts fail if the user does not reset the password before expiration. */\n maxPasswordAge: ?number;\n /* Set the number of previous password that will not be allowed to be set as new password. If the option is not set or set to `0`, no previous passwords will be considered.\n <br><br>\n Valid values are >= `0` and <= `20`.\n <br>\n Default is `0`.\n */\n maxPasswordHistory: ?number;\n /* Set the validity duration of the password reset token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.\n <br><br>\n For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).\n <br><br>\n Default is `undefined`.\n */\n resetTokenValidityDuration: ?number;\n /* Set to `true` if a password reset token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.\n <br><br>\n Default is `false`.\n :DEFAULT: false */\n resetTokenReuseIfValid: ?boolean;\n}", "export interface FileUploadOptions {\n /* Is true if file upload should be allowed for anonymous users.\n :DEFAULT: false */\n enableForAnonymousUser: ?boolean;\n /* Is true if file upload should be allowed for authenticated users.\n :DEFAULT: true */\n enableForAuthenticatedUser: ?boolean;\n /* Is true if file upload should be allowed for anyone, regardless of user authentication.\n :DEFAULT: false */\n enableForPublic: ?boolean;\n}", "export interface DatabaseOptions {\n /* Enables database real-time hooks to update single schema cache. Set to `true` if using multiple Parse Servers instances connected to the same database. Failing to do so will cause a schema change to not propagate to all instances and re-syncing will only happen when the instances restart. To use this feature with MongoDB, a replica set cluster with [change stream](https://docs.mongodb.com/manual/changeStreams/#availability) support is required.\n :DEFAULT: false */\n enableSchemaHooks: ?boolean;\n}", "export interface AuthAdapter {\n /* Is `true` if the auth adapter is enabled, `false` otherwise.\n :DEFAULT: true\n :ENV:\n */\n enabled: ?boolean;\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "// @flow\nimport { AnalyticsAdapter } from '../Adapters/Analytics/AnalyticsAdapter';\nimport { FilesAdapter } from '../Adapters/Files/FilesAdapter';\nimport { LoggerAdapter } from '../Adapters/Logger/LoggerAdapter';\nimport { StorageAdapter } from '../Adapters/Storage/StorageAdapter';\nimport { CacheAdapter } from '../Adapters/Cache/CacheAdapter';\nimport { MailAdapter } from '../Adapters/Email/MailAdapter';\nimport { PubSubAdapter } from '../Adapters/PubSub/PubSubAdapter';\nimport { WSSAdapter } from '../Adapters/WebSocketServer/WSSAdapter';\nimport { CheckGroup } from '../Security/CheckGroup';", "export interface SchemaOptions {\n /* Rest representation on Parse.Schema https://docs.parseplatform.org/rest/guide/#adding-a-schema\n :DEFAULT: [] */\n definitions: any;\n /* Is true if Parse Server should exit if schema update fail.\n :DEFAULT: false */\n strict: ?boolean;\n /* Is true if Parse Server should delete any fields not defined in a schema definition. This should only be used during development.\n :DEFAULT: false */\n deleteExtraFields: ?boolean;\n /* Is true if Parse Server should recreate any fields that are different between the current database schema and theschema definition. This should only be used during development.\n :DEFAULT: false */\n recreateModifiedFields: ?boolean;\n /* Is true if Parse Server will reject any attempts to modify the schema while the server is running.\n :DEFAULT: false */\n lockSchemas: ?boolean;\n /* Execute a callback before running schema migrations. */\n beforeMigration: ?() => void | Promise<void>;\n /* Execute a callback after running schema migrations. */\n afterMigration: ?() => void | Promise<void>;\n}", "type Adapter<T> = string | any | T;\ntype NumberOrBoolean = number | boolean;\ntype NumberOrString = number | string;\ntype ProtectedFields = any;\ntype RequestKeywordDenylist = {\n key: string | any,\n value: any,\n};", "export interface ParseServerOptions {\n /* Your Parse Application ID\n :ENV: PARSE_SERVER_APPLICATION_ID */\n appId: string;\n /* Your Parse Master Key */\n masterKey: string;\n /* URL to your parse server with http:// or https://.\n :ENV: PARSE_SERVER_URL */\n serverURL: string;\n /* Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)\n :DEFAULT: [] */\n masterKeyIps: ?(string[]);\n /* Sets the app name */\n appName: ?string;\n /* Add headers to Access-Control-Allow-Headers */\n allowHeaders: ?(string[]);\n /* Sets the origin to Access-Control-Allow-Origin */\n allowOrigin: ?string;\n /* Adapter module for the analytics */\n analyticsAdapter: ?Adapter<AnalyticsAdapter>;\n /* Adapter module for the files sub-system */\n filesAdapter: ?Adapter<FilesAdapter>;\n /* Configuration for push, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#push-notifications */\n push: ?any;\n /* Configuration for push scheduling, defaults to false.\n :DEFAULT: false */\n scheduledPush: ?boolean;\n /* Adapter module for the logging sub-system */\n loggerAdapter: ?Adapter<LoggerAdapter>;\n /* Log as structured JSON objects\n :ENV: JSON_LOGS */\n jsonLogs: ?boolean;\n /* Folder for the logs (defaults to './logs'); set to null to disable file based logging\n :ENV: PARSE_SERVER_LOGS_FOLDER\n :DEFAULT: ./logs */\n logsFolder: ?string;\n /* Set the logging to verbose\n :ENV: VERBOSE */\n verbose: ?boolean;\n /* Sets the level for logs */\n logLevel: ?string;\n /* Maximum number of logs to keep. If not set, no logs will be removed. This can be a number of files or number of days. If using days, add 'd' as the suffix. (default: null) */\n maxLogFiles: ?NumberOrString;\n /* Disables console output\n :ENV: SILENT */\n silent: ?boolean;\n /* The full URI to your database. Supported databases are mongodb or postgres.\n :DEFAULT: mongodb://localhost:27017/parse */\n databaseURI: string;\n /* Options to pass to the database client\n :ENV: PARSE_SERVER_DATABASE_OPTIONS */\n databaseOptions: ?DatabaseOptions;\n /* Adapter module for the database; any options that are not explicitly described here are passed directly to the database client. */\n databaseAdapter: ?Adapter<StorageAdapter>;\n /* Full path to your cloud code main.js */\n cloud: ?string;\n /* A collection prefix for the classes\n :DEFAULT: '' */\n collectionPrefix: ?string;\n /* Key for iOS, MacOS, tvOS clients */\n clientKey: ?string;\n /* Key for the Javascript SDK */\n javascriptKey: ?string;\n /* Key for Unity and .Net SDK */\n dotNetKey: ?string;\n /* Key for encrypting your files\n :ENV: PARSE_SERVER_ENCRYPTION_KEY */\n encryptionKey: ?string;\n /* Key for REST calls\n :ENV: PARSE_SERVER_REST_API_KEY */\n restAPIKey: ?string;\n /* Read-only key, which has the same capabilities as MasterKey without writes */\n readOnlyMasterKey: ?string;\n /* Key sent with outgoing webhook calls */\n webhookKey: ?string;\n /* Key for your files */\n fileKey: ?string;\n /* Enable (or disable) the addition of a unique hash to the file names\n :ENV: PARSE_SERVER_PRESERVE_FILE_NAME\n :DEFAULT: false */\n preserveFileName: ?boolean;\n /* Personally identifiable information fields in the user table the should be removed for non-authorized users. Deprecated @see protectedFields */\n userSensitiveFields: ?(string[]);\n /* Protected fields that should be treated with extra security when fetching details.\n :DEFAULT: {\"_User\": {\"*\": [\"email\"]}} */\n protectedFields: ?ProtectedFields;\n /* Enable (or disable) anonymous users, defaults to true\n :ENV: PARSE_SERVER_ENABLE_ANON_USERS\n :DEFAULT: true */\n enableAnonymousUsers: ?boolean;\n /* Enable (or disable) client class creation, defaults to true\n :ENV: PARSE_SERVER_ALLOW_CLIENT_CLASS_CREATION\n :DEFAULT: true */\n allowClientClassCreation: ?boolean;\n /* Enable (or disable) custom objectId\n :ENV: PARSE_SERVER_ALLOW_CUSTOM_OBJECT_ID\n :DEFAULT: false */\n allowCustomObjectId: ?boolean;\n /* Configuration for your authentication providers, as stringified JSON. See http://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication\n :ENV: PARSE_SERVER_AUTH_PROVIDERS */\n auth: ?(AuthAdapter[]);\n /* Max file size for uploads, defaults to 20mb\n :DEFAULT: 20mb */\n maxUploadSize: ?string;\n /* Set to `true` to require users to verify their email address to complete the sign-up process.\n <br><br>\n Default is `false`.\n :DEFAULT: false */\n verifyUserEmails: ?boolean;\n /* Set to `true` to prevent a user from logging in if the email has not yet been verified and email verification is required.\n <br><br>\n Default is `false`.\n <br>\n Requires option `verifyUserEmails: true`.\n :DEFAULT: false */\n preventLoginWithUnverifiedEmail: ?boolean;\n /* Set the validity duration of the email verification token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.\n <br><br>\n For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).\n <br><br>\n Default is `undefined`.\n <br>\n Requires option `verifyUserEmails: true`.\n */\n emailVerifyTokenValidityDuration: ?number;\n /* Set to `true` if a email verification token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.\n <br><br>\n Default is `false`.\n <br>\n Requires option `verifyUserEmails: true`.\n :DEFAULT: false */\n emailVerifyTokenReuseIfValid: ?boolean;\n /* The account lockout policy for failed login attempts. */\n accountLockout: ?AccountLockoutOptions;\n /* The password policy for enforcing password related rules. */\n passwordPolicy: ?PasswordPolicyOptions;\n /* Adapter module for the cache */\n cacheAdapter: ?Adapter<CacheAdapter>;\n /* Adapter module for email sending */\n emailAdapter: ?Adapter<MailAdapter>;\n /* Public URL to your parse server with http:// or https://.\n :ENV: PARSE_PUBLIC_SERVER_URL */\n publicServerURL: ?string;\n /* The options for pages such as password reset and email verification. Caution, this is an experimental feature that may not be appropriate for production.\n :DEFAULT: {} */\n pages: ?PagesOptions;\n /* custom pages for password validation and reset\n :DEFAULT: {} */\n customPages: ?CustomPagesOptions;\n /* parse-server's LiveQuery configuration object */\n liveQuery: ?LiveQueryOptions;\n /* Session duration, in seconds, defaults to 1 year\n :DEFAULT: 31536000 */\n sessionLength: ?number;\n /* Default value for limit option on queries, defaults to `100`.\n :DEFAULT: 100 */\n defaultLimit: ?number;\n /* Max value for limit option on queries, defaults to unlimited */\n maxLimit: ?number;\n /* Sets whether we should expire the inactive sessions, defaults to true. If false, all new sessions are created with no expiration date.\n :DEFAULT: true */\n expireInactiveSessions: ?boolean;\n /* When a user changes their password, either through the reset password email or while logged in, all sessions are revoked if this is true. Set to false if you don't want to revoke sessions.\n :DEFAULT: true */\n revokeSessionOnPasswordReset: ?boolean;\n /* Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)\n :DEFAULT: 5000 */\n cacheTTL: ?number;\n /* Sets the maximum size for the in memory cache, defaults to 10000\n :DEFAULT: 10000 */\n cacheMaxSize: ?number;\n /* Set to `true` if Parse requests within the same Node.js environment as Parse Server should be routed to Parse Server directly instead of via the HTTP interface. Default is `false`.\n <br><br>\n If set to `false` then Parse requests within the same Node.js environment as Parse Server are executed as HTTP requests sent to Parse Server via the `serverURL`. For example, a `Parse.Query` in Cloud Code is calling Parse Server via a HTTP request. The server is essentially making a HTTP request to itself, unnecessarily using network resources such as network ports.\n <br><br>\n ⚠️ In environments where multiple Parse Server instances run behind a load balancer and Parse requests within the current Node.js environment should be routed via the load balancer and distributed as HTTP requests among all instances via the `serverURL`, this should be set to `false`.\n :DEFAULT: false */\n directAccess: ?boolean;\n /* Enables the default express error handler for all errors\n :DEFAULT: false */\n enableExpressErrorHandler: ?boolean;\n /* Sets the number of characters in generated object id's, default 10\n :DEFAULT: 10 */\n objectIdSize: ?number;\n /* The port to run the ParseServer, defaults to 1337.\n :ENV: PORT\n :DEFAULT: 1337 */\n port: ?number;\n /* The host to serve ParseServer on, defaults to 0.0.0.0\n :DEFAULT: 0.0.0.0 */\n host: ?string;\n /* Mount path for the server, defaults to /parse\n :DEFAULT: /parse */\n mountPath: ?string;\n /* Run with cluster, optionally set the number of processes default to os.cpus().length */\n cluster: ?NumberOrBoolean;\n /* middleware for express server, can be string or function */\n middleware: ?((() => void) | string);", " /* The trust proxy settings. It is important to understand the exact setup of the reverse proxy, since this setting will trust values provided in the Parse Server API request. See the <a href=\"https://expressjs.com/en/guide/behind-proxies.html\">express trust proxy settings</a> documentation. Defaults to `false`.\n :DEFAULT: false */\n trustProxy: ?any;", " /* Starts the liveQuery server */\n startLiveQueryServer: ?boolean;\n /* Live query server configuration options (will start the liveQuery server) */\n liveQueryServerOptions: ?LiveQueryServerOptions;\n /* Options for request idempotency to deduplicate identical requests that may be caused by network issues. Caution, this is an experimental feature that may not be appropriate for production.\n :ENV: PARSE_SERVER_EXPERIMENTAL_IDEMPOTENCY_OPTIONS\n :DEFAULT: false */\n idempotencyOptions: ?IdempotencyOptions;\n /* Options for file uploads\n :ENV: PARSE_SERVER_FILE_UPLOAD_OPTIONS\n :DEFAULT: {} */\n fileUpload: ?FileUploadOptions;\n /* Full path to your GraphQL custom schema.graphql file */\n graphQLSchema: ?string;\n /* Mounts the GraphQL endpoint\n :ENV: PARSE_SERVER_MOUNT_GRAPHQL\n :DEFAULT: false */\n mountGraphQL: ?boolean;\n /* Mount path for the GraphQL endpoint, defaults to /graphql\n :ENV: PARSE_SERVER_GRAPHQL_PATH\n :DEFAULT: /graphql */\n graphQLPath: ?string;\n /* Mounts the GraphQL Playground - never use this option in production\n :ENV: PARSE_SERVER_MOUNT_PLAYGROUND\n :DEFAULT: false */\n mountPlayground: ?boolean;\n /* Mount path for the GraphQL Playground, defaults to /playground\n :ENV: PARSE_SERVER_PLAYGROUND_PATH\n :DEFAULT: /playground */\n playgroundPath: ?string;\n /* Callback when server has started */\n serverStartComplete: ?(error: ?Error) => void;\n /* Defined schema\n :ENV: PARSE_SERVER_SCHEMA\n */\n schema: ?SchemaOptions;\n /* Callback when server has closed */\n serverCloseComplete: ?() => void;\n /* The security options to identify and report weak security settings.\n :DEFAULT: {} */\n security: ?SecurityOptions;\n /* Set to true if new users should be created without public read and write access.\n :DEFAULT: false */\n enforcePrivateUsers: ?boolean;\n /* An array of keys and values that are prohibited in database read and write requests to prevent potential security vulnerabilities. It is possible to specify only a key (`{\"key\":\"...\"}`), only a value (`{\"value\":\"...\"}`) or a key-value pair (`{\"key\":\"...\",\"value\":\"...\"}`). The specification can use the following types: `boolean`, `numeric` or `string`, where `string` will be interpreted as a regex notation. Request data is deep-scanned for matching definitions to detect also any nested occurrences. Defaults are patterns that are likely to be used in malicious requests. Setting this option will override the default patterns.\n :DEFAULT: [{\"key\":\"_bsontype\",\"value\":\"Code\"},{\"key\":\"constructor\"},{\"key\":\"__proto__\"}] */\n requestKeywordDenylist: ?(RequestKeywordDenylist[]);\n}", "export interface SecurityOptions {\n /* Is true if Parse Server should check for weak security settings.\n :DEFAULT: false */\n enableCheck: ?boolean;\n /* Is true if the security check report should be written to logs. This should only be enabled temporarily to not expose weak security settings in logs.\n :DEFAULT: false */\n enableCheckLog: ?boolean;\n /* The security check groups to run. This allows to add custom security checks or override existing ones. Default are the groups defined in `CheckGroups.js`. */\n checkGroups: ?(CheckGroup[]);\n}", "export interface PagesOptions {\n /* Is true if the pages router should be enabled; this is required for any of the pages options to take effect. Caution, this is an experimental feature that may not be appropriate for production.\n :DEFAULT: false */\n enableRouter: ?boolean;\n /* Is true if pages should be localized; this has no effect on custom page redirects.\n :DEFAULT: false */\n enableLocalization: ?boolean;\n /* The path to the JSON file for localization; the translations will be used to fill template placeholders according to the locale. */\n localizationJsonPath: ?string;\n /* The fallback locale for localization if no matching translation is provided for the given locale. This is only relevant when providing translation resources via JSON file.\n :DEFAULT: en */\n localizationFallbackLocale: ?string;\n /* The placeholder keys and values which will be filled in pages; this can be a simple object or a callback function.\n :DEFAULT: {} */\n placeholders: ?Object;\n /* Is true if responses should always be redirects and never content, false if the response type should depend on the request type (GET request -> content response; POST request -> redirect response).\n :DEFAULT: false */\n forceRedirect: ?boolean;\n /* The path to the pages directory; this also defines where the static endpoint '/apps' points to. Default is the './public/' directory.\n :DEFAULT: ./public */\n pagesPath: ?string;\n /* The API endpoint for the pages. Default is 'apps'.\n :DEFAULT: apps */\n pagesEndpoint: ?string;\n /* The URLs to the custom pages.\n :DEFAULT: {} */\n customUrls: ?PagesCustomUrlsOptions;\n /* The custom routes.\n :DEFAULT: [] */\n customRoutes: ?(PagesRoute[]);\n}", "export interface PagesRoute {\n /* The route path. */\n path: string;\n /* The route method, e.g. 'GET' or 'POST'. */\n method: string;\n /* The route handler that is an async function. */\n handler: () => void;\n}", "export interface PagesCustomUrlsOptions {\n /* The URL to the custom page for password reset. */\n passwordReset: ?string;\n /* The URL to the custom page for password reset -> link invalid. */\n passwordResetLinkInvalid: ?string;\n /* The URL to the custom page for password reset -> success. */\n passwordResetSuccess: ?string;\n /* The URL to the custom page for email verification -> success. */\n emailVerificationSuccess: ?string;\n /* The URL to the custom page for email verification -> link send fail. */\n emailVerificationSendFail: ?string;\n /* The URL to the custom page for email verification -> resend link -> success. */\n emailVerificationSendSuccess: ?string;\n /* The URL to the custom page for email verification -> link invalid. */\n emailVerificationLinkInvalid: ?string;\n /* The URL to the custom page for email verification -> link expired. */\n emailVerificationLinkExpired: ?string;\n}", "export interface CustomPagesOptions {\n /* invalid link page path */\n invalidLink: ?string;\n /* verification link send fail page path */\n linkSendFail: ?string;\n /* choose password page path */\n choosePassword: ?string;\n /* verification link send success page path */\n linkSendSuccess: ?string;\n /* verify email success page path */\n verifyEmailSuccess: ?string;\n /* password reset success page path */\n passwordResetSuccess: ?string;\n /* invalid verification link page path */\n invalidVerificationLink: ?string;\n /* expired verification link page path */\n expiredVerificationLink: ?string;\n /* invalid password reset link page path */\n invalidPasswordResetLink: ?string;\n /* for masking user-facing pages */\n parseFrameURL: ?string;\n}", "export interface LiveQueryOptions {\n /* parse-server's LiveQuery classNames\n :ENV: PARSE_SERVER_LIVEQUERY_CLASSNAMES */\n classNames: ?(string[]);\n /* parse-server's LiveQuery redisOptions */\n redisOptions: ?any;\n /* parse-server's LiveQuery redisURL */\n redisURL: ?string;\n /* LiveQuery pubsub adapter */\n pubSubAdapter: ?Adapter<PubSubAdapter>;\n /* Adapter module for the WebSocketServer */\n wssAdapter: ?Adapter<WSSAdapter>;\n}", "export interface LiveQueryServerOptions {\n /* This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId.*/\n appId: ?string;\n /* This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey.*/\n masterKey: ?string;\n /* This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL.*/\n serverURL: ?string;\n /* A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details.*/\n keyPairs: ?any;\n /* Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients, defaults to 10 * 1000 ms (10 s).*/\n websocketTimeout: ?number;\n /* Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details, defaults to 5 * 1000 ms (5 seconds).*/\n cacheTimeout: ?number;\n /* This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE, defaults to INFO.*/\n logLevel: ?string;\n /* The port to run the LiveQuery server, defaults to 1337.\n :DEFAULT: 1337 */\n port: ?number;\n /* parse-server's LiveQuery redisOptions */\n redisOptions: ?any;\n /* parse-server's LiveQuery redisURL */\n redisURL: ?string;\n /* LiveQuery pubsub adapter */\n pubSubAdapter: ?Adapter<PubSubAdapter>;\n /* Adapter module for the WebSocketServer */\n wssAdapter: ?Adapter<WSSAdapter>;\n}", "export interface IdempotencyOptions {\n /* An array of paths for which the feature should be enabled. The mount path must not be included, for example instead of `/parse/functions/myFunction` specifiy `functions/myFunction`. The entries are interpreted as regular expression, for example `functions/.*` matches all functions, `jobs/.*` matches all jobs, `classes/.*` matches all classes, `.*` matches all paths.\n :DEFAULT: [] */\n paths: ?(string[]);\n /* The duration in seconds after which a request record is discarded from the database, defaults to 300s.\n :DEFAULT: 300 */\n ttl: ?number;\n}", "export interface AccountLockoutOptions {\n /* Set the duration in minutes that a locked-out account remains locked out before automatically becoming unlocked.\n <br><br>\n Valid values are greater than `0` and less than `100000`. */\n duration: ?number;\n /* Set the number of failed sign-in attempts that will cause a user account to be locked. If the account is locked. The account will unlock after the duration set in the `duration` option has passed and no further login attempts have been made.\n <br><br>\n Valid values are greater than `0` and less than `1000`. */\n threshold: ?number;\n /* Set to `true` if the account should be unlocked after a successful password reset.\n <br><br>\n Default is `false`.\n <br>\n Requires options `duration` and `threshold` to be set.\n :DEFAULT: false */\n unlockOnPasswordReset: ?boolean;\n}", "export interface PasswordPolicyOptions {\n /* Set the regular expression validation pattern a password must match to be accepted.\n <br><br>\n If used in combination with `validatorCallback`, the password must pass both to be accepted. */\n validatorPattern: ?string;\n /* */\n /* Set a callback function to validate a password to be accepted.\n <br><br>\n If used in combination with `validatorPattern`, the password must pass both to be accepted. */\n validatorCallback: ?() => void;\n /* Set the error message to be sent.\n <br><br>\n Default is `Password does not meet the Password Policy requirements.` */\n validationError: ?string;\n /* Set to `true` to disallow the username as part of the password.\n <br><br>\n Default is `false`.\n :DEFAULT: false */\n doNotAllowUsername: ?boolean;\n /* Set the number of days after which a password expires. Login attempts fail if the user does not reset the password before expiration. */\n maxPasswordAge: ?number;\n /* Set the number of previous password that will not be allowed to be set as new password. If the option is not set or set to `0`, no previous passwords will be considered.\n <br><br>\n Valid values are >= `0` and <= `20`.\n <br>\n Default is `0`.\n */\n maxPasswordHistory: ?number;\n /* Set the validity duration of the password reset token in seconds after which the token expires. The token is used in the link that is set in the email. After the token expires, the link becomes invalid and a new link has to be sent. If the option is not set or set to `undefined`, then the token never expires.\n <br><br>\n For example, to expire the token after 2 hours, set a value of 7200 seconds (= 60 seconds * 60 minutes * 2 hours).\n <br><br>\n Default is `undefined`.\n */\n resetTokenValidityDuration: ?number;\n /* Set to `true` if a password reset token should be reused in case another token is requested but there is a token that is still valid, i.e. has not expired. This avoids the often observed issue that a user requests multiple emails and does not know which link contains a valid token because each newly generated token would invalidate the previous token.\n <br><br>\n Default is `false`.\n :DEFAULT: false */\n resetTokenReuseIfValid: ?boolean;\n}", "export interface FileUploadOptions {\n /* Is true if file upload should be allowed for anonymous users.\n :DEFAULT: false */\n enableForAnonymousUser: ?boolean;\n /* Is true if file upload should be allowed for authenticated users.\n :DEFAULT: true */\n enableForAuthenticatedUser: ?boolean;\n /* Is true if file upload should be allowed for anyone, regardless of user authentication.\n :DEFAULT: false */\n enableForPublic: ?boolean;\n}", "export interface DatabaseOptions {\n /* Enables database real-time hooks to update single schema cache. Set to `true` if using multiple Parse Servers instances connected to the same database. Failing to do so will cause a schema change to not propagate to all instances and re-syncing will only happen when the instances restart. To use this feature with MongoDB, a replica set cluster with [change stream](https://docs.mongodb.com/manual/changeStreams/#availability) support is required.\n :DEFAULT: false */\n enableSchemaHooks: ?boolean;\n}", "export interface AuthAdapter {\n /* Is `true` if the auth adapter is enabled, `false` otherwise.\n :DEFAULT: true\n :ENV:\n */\n enabled: ?boolean;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "// ParseServer - open-source compatible API Server for Parse apps", "var batch = require('./batch'),\n bodyParser = require('body-parser'),\n express = require('express'),\n middlewares = require('./middlewares'),\n Parse = require('parse/node').Parse,\n { parse } = require('graphql'),\n path = require('path'),\n fs = require('fs');", "import { ParseServerOptions, LiveQueryServerOptions } from './Options';\nimport defaults from './defaults';\nimport * as logging from './logger';\nimport Config from './Config';\nimport PromiseRouter from './PromiseRouter';\nimport requiredParameter from './requiredParameter';\nimport { AnalyticsRouter } from './Routers/AnalyticsRouter';\nimport { ClassesRouter } from './Routers/ClassesRouter';\nimport { FeaturesRouter } from './Routers/FeaturesRouter';\nimport { FilesRouter } from './Routers/FilesRouter';\nimport { FunctionsRouter } from './Routers/FunctionsRouter';\nimport { GlobalConfigRouter } from './Routers/GlobalConfigRouter';\nimport { GraphQLRouter } from './Routers/GraphQLRouter';\nimport { HooksRouter } from './Routers/HooksRouter';\nimport { IAPValidationRouter } from './Routers/IAPValidationRouter';\nimport { InstallationsRouter } from './Routers/InstallationsRouter';\nimport { LogsRouter } from './Routers/LogsRouter';\nimport { ParseLiveQueryServer } from './LiveQuery/ParseLiveQueryServer';\nimport { PagesRouter } from './Routers/PagesRouter';\nimport { PublicAPIRouter } from './Routers/PublicAPIRouter';\nimport { PushRouter } from './Routers/PushRouter';\nimport { CloudCodeRouter } from './Routers/CloudCodeRouter';\nimport { RolesRouter } from './Routers/RolesRouter';\nimport { SchemasRouter } from './Routers/SchemasRouter';\nimport { SessionsRouter } from './Routers/SessionsRouter';\nimport { UsersRouter } from './Routers/UsersRouter';\nimport { PurgeRouter } from './Routers/PurgeRouter';\nimport { AudiencesRouter } from './Routers/AudiencesRouter';\nimport { AggregateRouter } from './Routers/AggregateRouter';\nimport { ParseServerRESTController } from './ParseServerRESTController';\nimport * as controllers from './Controllers';\nimport { ParseGraphQLServer } from './GraphQL/ParseGraphQLServer';\nimport { SecurityRouter } from './Routers/SecurityRouter';\nimport CheckRunner from './Security/CheckRunner';\nimport Deprecator from './Deprecator/Deprecator';\nimport { DefinedSchemas } from './SchemaMigrations/DefinedSchemas';", "// Mutate the Parse object to add the Cloud Code handlers\naddParseCloud();", "// ParseServer works like a constructor of an express app.\n// https://parseplatform.org/parse-server/api/master/ParseServerOptions.html\nclass ParseServer {\n /**\n * @constructor\n * @param {ParseServerOptions} options the parse server initialization options\n */\n constructor(options: ParseServerOptions) {\n // Scan for deprecated Parse Server options\n Deprecator.scanParseServerOptions(options);\n // Set option defaults\n injectDefaults(options);\n const {\n appId = requiredParameter('You must provide an appId!'),\n masterKey = requiredParameter('You must provide a masterKey!'),\n cloud,\n security,\n javascriptKey,\n serverURL = requiredParameter('You must provide a serverURL!'),\n serverStartComplete,\n schema,\n } = options;\n // Initialize the node client SDK automatically\n Parse.initialize(appId, javascriptKey || 'unused', masterKey);\n Parse.serverURL = serverURL;", " const allControllers = controllers.getControllers(options);", " const { loggerController, databaseController, hooksController } = allControllers;\n this.config = Config.put(Object.assign({}, options, allControllers));", " logging.setLogger(loggerController);", " // Note: Tests will start to fail if any validation happens after this is called.\n databaseController\n .performInitialization()\n .then(() => hooksController.load())\n .then(async () => {\n if (schema) {\n await new DefinedSchemas(schema, this.config).execute();\n }\n if (serverStartComplete) {\n serverStartComplete();\n }\n })\n .catch(error => {\n if (serverStartComplete) {\n serverStartComplete(error);\n } else {\n console.error(error);\n process.exit(1);\n }\n });", " if (cloud) {\n addParseCloud();\n if (typeof cloud === 'function') {\n cloud(Parse);\n } else if (typeof cloud === 'string') {\n require(path.resolve(process.cwd(), cloud));\n } else {\n throw \"argument 'cloud' must either be a string or a function\";\n }\n }", " if (security && security.enableCheck && security.enableCheckLog) {\n new CheckRunner(options.security).run();\n }\n }", " get app() {\n if (!this._app) {\n this._app = ParseServer.app(this.config);\n }\n return this._app;\n }", " handleShutdown() {\n const promises = [];\n const { adapter: databaseAdapter } = this.config.databaseController;\n if (databaseAdapter && typeof databaseAdapter.handleShutdown === 'function') {\n promises.push(databaseAdapter.handleShutdown());\n }\n const { adapter: fileAdapter } = this.config.filesController;\n if (fileAdapter && typeof fileAdapter.handleShutdown === 'function') {\n promises.push(fileAdapter.handleShutdown());\n }\n const { adapter: cacheAdapter } = this.config.cacheController;\n if (cacheAdapter && typeof cacheAdapter.handleShutdown === 'function') {\n promises.push(cacheAdapter.handleShutdown());\n }\n return (promises.length > 0 ? Promise.all(promises) : Promise.resolve()).then(() => {\n if (this.config.serverCloseComplete) {\n this.config.serverCloseComplete();\n }\n });\n }", " /**\n * @static\n * Create an express app for the parse server\n * @param {Object} options let you specify the maxUploadSize when creating the express app */\n static app(options) {\n const { maxUploadSize = '20mb', appId, directAccess, pages } = options;\n // This app serves the Parse API directly.\n // It's the equivalent of https://api.parse.com/1 in the hosted Parse API.\n var api = express();\n //api.use(\"/apps\", express.static(__dirname + \"/public\"));\n api.use(middlewares.allowCrossDomain(appId));\n // File handling needs to be before default middlewares are applied\n api.use(\n '/',\n new FilesRouter().expressRouter({\n maxUploadSize: maxUploadSize,\n })\n );", " api.use('/health', function (req, res) {\n res.json({\n status: 'ok',\n });\n });", " api.use(\n '/',\n bodyParser.urlencoded({ extended: false }),\n pages.enableRouter\n ? new PagesRouter(pages).expressRouter()\n : new PublicAPIRouter().expressRouter()\n );", " api.use(bodyParser.json({ type: '*/*', limit: maxUploadSize }));\n api.use(middlewares.allowMethodOverride);\n api.use(middlewares.handleParseHeaders);", " const appRouter = ParseServer.promiseRouter({ appId });\n api.use(appRouter.expressRouter());", " api.use(middlewares.handleParseErrors);", " // run the following when not testing\n if (!process.env.TESTING) {\n //This causes tests to spew some useless warnings, so disable in test\n /* istanbul ignore next */\n process.on('uncaughtException', err => {\n if (err.code === 'EADDRINUSE') {\n // user-friendly message for this common error\n process.stderr.write(`Unable to listen on port ${err.port}. The port is already in use.`);\n process.exit(0);\n } else {\n throw err;\n }\n });\n // verify the server url after a 'mount' event is received\n /* istanbul ignore next */\n api.on('mount', function () {\n ParseServer.verifyServerUrl();\n });\n }\n if (process.env.PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS === '1' || directAccess) {\n Parse.CoreManager.setRESTController(ParseServerRESTController(appId, appRouter));\n }\n return api;\n }", " static promiseRouter({ appId }) {\n const routers = [\n new ClassesRouter(),\n new UsersRouter(),\n new SessionsRouter(),\n new RolesRouter(),\n new AnalyticsRouter(),\n new InstallationsRouter(),\n new FunctionsRouter(),\n new SchemasRouter(),\n new PushRouter(),\n new LogsRouter(),\n new IAPValidationRouter(),\n new FeaturesRouter(),\n new GlobalConfigRouter(),\n new GraphQLRouter(),\n new PurgeRouter(),\n new HooksRouter(),\n new CloudCodeRouter(),\n new AudiencesRouter(),\n new AggregateRouter(),\n new SecurityRouter(),\n ];", " const routes = routers.reduce((memo, router) => {\n return memo.concat(router.routes);\n }, []);", " const appRouter = new PromiseRouter(routes, appId);", " batch.mountOnto(appRouter);\n return appRouter;\n }", " /**\n * starts the parse server's express app\n * @param {ParseServerOptions} options to use to start the server\n * @param {Function} callback called when the server has started\n * @returns {ParseServer} the parse server instance\n */\n start(options: ParseServerOptions, callback: ?() => void) {\n const app = express();\n if (options.middleware) {\n let middleware;\n if (typeof options.middleware == 'string') {\n middleware = require(path.resolve(process.cwd(), options.middleware));\n } else {\n middleware = options.middleware; // use as-is let express fail\n }\n app.use(middleware);\n }", " app.use(options.mountPath, this.app);", " if (options.mountGraphQL === true || options.mountPlayground === true) {\n let graphQLCustomTypeDefs = undefined;\n if (typeof options.graphQLSchema === 'string') {\n graphQLCustomTypeDefs = parse(fs.readFileSync(options.graphQLSchema, 'utf8'));\n } else if (\n typeof options.graphQLSchema === 'object' ||\n typeof options.graphQLSchema === 'function'\n ) {\n graphQLCustomTypeDefs = options.graphQLSchema;\n }", " const parseGraphQLServer = new ParseGraphQLServer(this, {\n graphQLPath: options.graphQLPath,\n playgroundPath: options.playgroundPath,\n graphQLCustomTypeDefs,\n });", " if (options.mountGraphQL) {\n parseGraphQLServer.applyGraphQL(app);\n }", " if (options.mountPlayground) {\n parseGraphQLServer.applyPlayground(app);\n }\n }", " const server = app.listen(options.port, options.host, callback);\n this.server = server;", " if (options.startLiveQueryServer || options.liveQueryServerOptions) {\n this.liveQueryServer = ParseServer.createLiveQueryServer(\n server,\n options.liveQueryServerOptions,\n options\n );\n }", "", " /* istanbul ignore next */\n if (!process.env.TESTING) {\n configureListeners(this);\n }\n this.expressApp = app;\n return this;\n }", " /**\n * Creates a new ParseServer and starts it.\n * @param {ParseServerOptions} options used to start the server\n * @param {Function} callback called when the server has started\n * @returns {ParseServer} the parse server instance\n */\n static start(options: ParseServerOptions, callback: ?() => void) {\n const parseServer = new ParseServer(options);\n return parseServer.start(options, callback);\n }", " /**\n * Helper method to create a liveQuery server\n * @static\n * @param {Server} httpServer an optional http server to pass\n * @param {LiveQueryServerOptions} config options for the liveQueryServer\n * @param {ParseServerOptions} options options for the ParseServer\n * @returns {ParseLiveQueryServer} the live query server instance\n */\n static createLiveQueryServer(\n httpServer,\n config: LiveQueryServerOptions,\n options: ParseServerOptions\n ) {\n if (!httpServer || (config && config.port)) {\n var app = express();\n httpServer = require('http').createServer(app);\n httpServer.listen(config.port);\n }\n return new ParseLiveQueryServer(httpServer, config, options);\n }", " static verifyServerUrl(callback) {\n // perform a health check on the serverURL value\n if (Parse.serverURL) {\n const request = require('./request');\n request({ url: Parse.serverURL.replace(/\\/$/, '') + '/health' })\n .catch(response => response)\n .then(response => {\n const json = response.data || null;\n if (response.status !== 200 || !json || (json && json.status !== 'ok')) {\n /* eslint-disable no-console */\n console.warn(\n `\\nWARNING, Unable to connect to '${Parse.serverURL}'.` +\n ` Cloud code and push notifications may be unavailable!\\n`\n );\n /* eslint-enable no-console */\n if (callback) {\n callback(false);\n }\n } else {\n if (callback) {\n callback(true);\n }\n }\n });\n }\n }\n}", "function addParseCloud() {\n const ParseCloud = require('./cloud-code/Parse.Cloud');\n Object.defineProperty(Parse, 'Server', {\n get() {\n return Config.get(Parse.applicationId);\n },\n set(newVal) {\n newVal.appId = Parse.applicationId;\n Config.put(newVal);\n },\n configurable: true,\n });\n Object.assign(Parse.Cloud, ParseCloud);\n global.Parse = Parse;\n}", "function injectDefaults(options: ParseServerOptions) {\n Object.keys(defaults).forEach(key => {\n if (!Object.prototype.hasOwnProperty.call(options, key)) {\n options[key] = defaults[key];\n }\n });", " if (!Object.prototype.hasOwnProperty.call(options, 'serverURL')) {\n options.serverURL = `http://localhost:${options.port}${options.mountPath}`;\n }", " // Reserved Characters\n if (options.appId) {\n const regex = /[!#$%'()*+&/:;=?@[\\]{}^,|<>]/g;\n if (options.appId.match(regex)) {\n console.warn(\n `\\nWARNING, appId that contains special characters can cause issues while using with urls.\\n`\n );\n }\n }", " // Backwards compatibility\n if (options.userSensitiveFields) {\n /* eslint-disable no-console */\n !process.env.TESTING &&\n console.warn(\n `\\nDEPRECATED: userSensitiveFields has been replaced by protectedFields allowing the ability to protect fields in all classes with CLP. \\n`\n );\n /* eslint-enable no-console */", " const userSensitiveFields = Array.from(\n new Set([...(defaults.userSensitiveFields || []), ...(options.userSensitiveFields || [])])\n );", " // If the options.protectedFields is unset,\n // it'll be assigned the default above.\n // Here, protect against the case where protectedFields\n // is set, but doesn't have _User.\n if (!('_User' in options.protectedFields)) {\n options.protectedFields = Object.assign({ _User: [] }, options.protectedFields);\n }", " options.protectedFields['_User']['*'] = Array.from(\n new Set([...(options.protectedFields['_User']['*'] || []), ...userSensitiveFields])\n );\n }", " // Merge protectedFields options with defaults.\n Object.keys(defaults.protectedFields).forEach(c => {\n const cur = options.protectedFields[c];\n if (!cur) {\n options.protectedFields[c] = defaults.protectedFields[c];\n } else {\n Object.keys(defaults.protectedFields[c]).forEach(r => {\n const unq = new Set([\n ...(options.protectedFields[c][r] || []),\n ...defaults.protectedFields[c][r],\n ]);\n options.protectedFields[c][r] = Array.from(unq);\n });\n }\n });", " options.masterKeyIps = Array.from(\n new Set(options.masterKeyIps.concat(defaults.masterKeyIps, options.masterKeyIps))\n );\n}", "// Those can't be tested as it requires a subprocess\n/* istanbul ignore next */\nfunction configureListeners(parseServer) {\n const server = parseServer.server;\n const sockets = {};\n /* Currently, express doesn't shut down immediately after receiving SIGINT/SIGTERM if it has client connections that haven't timed out. (This is a known issue with node - https://github.com/nodejs/node/issues/2642)\n This function, along with `destroyAliveConnections()`, intend to fix this behavior such that parse server will close all open connections and initiate the shutdown process as soon as it receives a SIGINT/SIGTERM signal. */\n server.on('connection', socket => {\n const socketId = socket.remoteAddress + ':' + socket.remotePort;\n sockets[socketId] = socket;\n socket.on('close', () => {\n delete sockets[socketId];\n });\n });", " const destroyAliveConnections = function () {\n for (const socketId in sockets) {\n try {\n sockets[socketId].destroy();\n } catch (e) {\n /* */\n }\n }\n };", " const handleShutdown = function () {\n process.stdout.write('Termination signal received. Shutting down.');\n destroyAliveConnections();\n server.close();\n parseServer.handleShutdown();\n };\n process.on('SIGTERM', handleShutdown);\n process.on('SIGINT', handleShutdown);\n}", "export default ParseServer;" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "// ParseServer - open-source compatible API Server for Parse apps", "var batch = require('./batch'),\n bodyParser = require('body-parser'),\n express = require('express'),\n middlewares = require('./middlewares'),\n Parse = require('parse/node').Parse,\n { parse } = require('graphql'),\n path = require('path'),\n fs = require('fs');", "import { ParseServerOptions, LiveQueryServerOptions } from './Options';\nimport defaults from './defaults';\nimport * as logging from './logger';\nimport Config from './Config';\nimport PromiseRouter from './PromiseRouter';\nimport requiredParameter from './requiredParameter';\nimport { AnalyticsRouter } from './Routers/AnalyticsRouter';\nimport { ClassesRouter } from './Routers/ClassesRouter';\nimport { FeaturesRouter } from './Routers/FeaturesRouter';\nimport { FilesRouter } from './Routers/FilesRouter';\nimport { FunctionsRouter } from './Routers/FunctionsRouter';\nimport { GlobalConfigRouter } from './Routers/GlobalConfigRouter';\nimport { GraphQLRouter } from './Routers/GraphQLRouter';\nimport { HooksRouter } from './Routers/HooksRouter';\nimport { IAPValidationRouter } from './Routers/IAPValidationRouter';\nimport { InstallationsRouter } from './Routers/InstallationsRouter';\nimport { LogsRouter } from './Routers/LogsRouter';\nimport { ParseLiveQueryServer } from './LiveQuery/ParseLiveQueryServer';\nimport { PagesRouter } from './Routers/PagesRouter';\nimport { PublicAPIRouter } from './Routers/PublicAPIRouter';\nimport { PushRouter } from './Routers/PushRouter';\nimport { CloudCodeRouter } from './Routers/CloudCodeRouter';\nimport { RolesRouter } from './Routers/RolesRouter';\nimport { SchemasRouter } from './Routers/SchemasRouter';\nimport { SessionsRouter } from './Routers/SessionsRouter';\nimport { UsersRouter } from './Routers/UsersRouter';\nimport { PurgeRouter } from './Routers/PurgeRouter';\nimport { AudiencesRouter } from './Routers/AudiencesRouter';\nimport { AggregateRouter } from './Routers/AggregateRouter';\nimport { ParseServerRESTController } from './ParseServerRESTController';\nimport * as controllers from './Controllers';\nimport { ParseGraphQLServer } from './GraphQL/ParseGraphQLServer';\nimport { SecurityRouter } from './Routers/SecurityRouter';\nimport CheckRunner from './Security/CheckRunner';\nimport Deprecator from './Deprecator/Deprecator';\nimport { DefinedSchemas } from './SchemaMigrations/DefinedSchemas';", "// Mutate the Parse object to add the Cloud Code handlers\naddParseCloud();", "// ParseServer works like a constructor of an express app.\n// https://parseplatform.org/parse-server/api/master/ParseServerOptions.html\nclass ParseServer {\n /**\n * @constructor\n * @param {ParseServerOptions} options the parse server initialization options\n */\n constructor(options: ParseServerOptions) {\n // Scan for deprecated Parse Server options\n Deprecator.scanParseServerOptions(options);\n // Set option defaults\n injectDefaults(options);\n const {\n appId = requiredParameter('You must provide an appId!'),\n masterKey = requiredParameter('You must provide a masterKey!'),\n cloud,\n security,\n javascriptKey,\n serverURL = requiredParameter('You must provide a serverURL!'),\n serverStartComplete,\n schema,\n } = options;\n // Initialize the node client SDK automatically\n Parse.initialize(appId, javascriptKey || 'unused', masterKey);\n Parse.serverURL = serverURL;", " const allControllers = controllers.getControllers(options);", " const { loggerController, databaseController, hooksController } = allControllers;\n this.config = Config.put(Object.assign({}, options, allControllers));", " logging.setLogger(loggerController);", " // Note: Tests will start to fail if any validation happens after this is called.\n databaseController\n .performInitialization()\n .then(() => hooksController.load())\n .then(async () => {\n if (schema) {\n await new DefinedSchemas(schema, this.config).execute();\n }\n if (serverStartComplete) {\n serverStartComplete();\n }\n })\n .catch(error => {\n if (serverStartComplete) {\n serverStartComplete(error);\n } else {\n console.error(error);\n process.exit(1);\n }\n });", " if (cloud) {\n addParseCloud();\n if (typeof cloud === 'function') {\n cloud(Parse);\n } else if (typeof cloud === 'string') {\n require(path.resolve(process.cwd(), cloud));\n } else {\n throw \"argument 'cloud' must either be a string or a function\";\n }\n }", " if (security && security.enableCheck && security.enableCheckLog) {\n new CheckRunner(options.security).run();\n }\n }", " get app() {\n if (!this._app) {\n this._app = ParseServer.app(this.config);\n }\n return this._app;\n }", " handleShutdown() {\n const promises = [];\n const { adapter: databaseAdapter } = this.config.databaseController;\n if (databaseAdapter && typeof databaseAdapter.handleShutdown === 'function') {\n promises.push(databaseAdapter.handleShutdown());\n }\n const { adapter: fileAdapter } = this.config.filesController;\n if (fileAdapter && typeof fileAdapter.handleShutdown === 'function') {\n promises.push(fileAdapter.handleShutdown());\n }\n const { adapter: cacheAdapter } = this.config.cacheController;\n if (cacheAdapter && typeof cacheAdapter.handleShutdown === 'function') {\n promises.push(cacheAdapter.handleShutdown());\n }\n return (promises.length > 0 ? Promise.all(promises) : Promise.resolve()).then(() => {\n if (this.config.serverCloseComplete) {\n this.config.serverCloseComplete();\n }\n });\n }", " /**\n * @static\n * Create an express app for the parse server\n * @param {Object} options let you specify the maxUploadSize when creating the express app */\n static app(options) {\n const { maxUploadSize = '20mb', appId, directAccess, pages } = options;\n // This app serves the Parse API directly.\n // It's the equivalent of https://api.parse.com/1 in the hosted Parse API.\n var api = express();\n //api.use(\"/apps\", express.static(__dirname + \"/public\"));\n api.use(middlewares.allowCrossDomain(appId));\n // File handling needs to be before default middlewares are applied\n api.use(\n '/',\n new FilesRouter().expressRouter({\n maxUploadSize: maxUploadSize,\n })\n );", " api.use('/health', function (req, res) {\n res.json({\n status: 'ok',\n });\n });", " api.use(\n '/',\n bodyParser.urlencoded({ extended: false }),\n pages.enableRouter\n ? new PagesRouter(pages).expressRouter()\n : new PublicAPIRouter().expressRouter()\n );", " api.use(bodyParser.json({ type: '*/*', limit: maxUploadSize }));\n api.use(middlewares.allowMethodOverride);\n api.use(middlewares.handleParseHeaders);", " const appRouter = ParseServer.promiseRouter({ appId });\n api.use(appRouter.expressRouter());", " api.use(middlewares.handleParseErrors);", " // run the following when not testing\n if (!process.env.TESTING) {\n //This causes tests to spew some useless warnings, so disable in test\n /* istanbul ignore next */\n process.on('uncaughtException', err => {\n if (err.code === 'EADDRINUSE') {\n // user-friendly message for this common error\n process.stderr.write(`Unable to listen on port ${err.port}. The port is already in use.`);\n process.exit(0);\n } else {\n throw err;\n }\n });\n // verify the server url after a 'mount' event is received\n /* istanbul ignore next */\n api.on('mount', function () {\n ParseServer.verifyServerUrl();\n });\n }\n if (process.env.PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS === '1' || directAccess) {\n Parse.CoreManager.setRESTController(ParseServerRESTController(appId, appRouter));\n }\n return api;\n }", " static promiseRouter({ appId }) {\n const routers = [\n new ClassesRouter(),\n new UsersRouter(),\n new SessionsRouter(),\n new RolesRouter(),\n new AnalyticsRouter(),\n new InstallationsRouter(),\n new FunctionsRouter(),\n new SchemasRouter(),\n new PushRouter(),\n new LogsRouter(),\n new IAPValidationRouter(),\n new FeaturesRouter(),\n new GlobalConfigRouter(),\n new GraphQLRouter(),\n new PurgeRouter(),\n new HooksRouter(),\n new CloudCodeRouter(),\n new AudiencesRouter(),\n new AggregateRouter(),\n new SecurityRouter(),\n ];", " const routes = routers.reduce((memo, router) => {\n return memo.concat(router.routes);\n }, []);", " const appRouter = new PromiseRouter(routes, appId);", " batch.mountOnto(appRouter);\n return appRouter;\n }", " /**\n * starts the parse server's express app\n * @param {ParseServerOptions} options to use to start the server\n * @param {Function} callback called when the server has started\n * @returns {ParseServer} the parse server instance\n */\n start(options: ParseServerOptions, callback: ?() => void) {\n const app = express();\n if (options.middleware) {\n let middleware;\n if (typeof options.middleware == 'string') {\n middleware = require(path.resolve(process.cwd(), options.middleware));\n } else {\n middleware = options.middleware; // use as-is let express fail\n }\n app.use(middleware);\n }", " app.use(options.mountPath, this.app);", " if (options.mountGraphQL === true || options.mountPlayground === true) {\n let graphQLCustomTypeDefs = undefined;\n if (typeof options.graphQLSchema === 'string') {\n graphQLCustomTypeDefs = parse(fs.readFileSync(options.graphQLSchema, 'utf8'));\n } else if (\n typeof options.graphQLSchema === 'object' ||\n typeof options.graphQLSchema === 'function'\n ) {\n graphQLCustomTypeDefs = options.graphQLSchema;\n }", " const parseGraphQLServer = new ParseGraphQLServer(this, {\n graphQLPath: options.graphQLPath,\n playgroundPath: options.playgroundPath,\n graphQLCustomTypeDefs,\n });", " if (options.mountGraphQL) {\n parseGraphQLServer.applyGraphQL(app);\n }", " if (options.mountPlayground) {\n parseGraphQLServer.applyPlayground(app);\n }\n }", " const server = app.listen(options.port, options.host, callback);\n this.server = server;", " if (options.startLiveQueryServer || options.liveQueryServerOptions) {\n this.liveQueryServer = ParseServer.createLiveQueryServer(\n server,\n options.liveQueryServerOptions,\n options\n );\n }", " if (options.trustProxy) {\n app.set('trust proxy', options.trustProxy);\n }", " /* istanbul ignore next */\n if (!process.env.TESTING) {\n configureListeners(this);\n }\n this.expressApp = app;\n return this;\n }", " /**\n * Creates a new ParseServer and starts it.\n * @param {ParseServerOptions} options used to start the server\n * @param {Function} callback called when the server has started\n * @returns {ParseServer} the parse server instance\n */\n static start(options: ParseServerOptions, callback: ?() => void) {\n const parseServer = new ParseServer(options);\n return parseServer.start(options, callback);\n }", " /**\n * Helper method to create a liveQuery server\n * @static\n * @param {Server} httpServer an optional http server to pass\n * @param {LiveQueryServerOptions} config options for the liveQueryServer\n * @param {ParseServerOptions} options options for the ParseServer\n * @returns {ParseLiveQueryServer} the live query server instance\n */\n static createLiveQueryServer(\n httpServer,\n config: LiveQueryServerOptions,\n options: ParseServerOptions\n ) {\n if (!httpServer || (config && config.port)) {\n var app = express();\n httpServer = require('http').createServer(app);\n httpServer.listen(config.port);\n }\n return new ParseLiveQueryServer(httpServer, config, options);\n }", " static verifyServerUrl(callback) {\n // perform a health check on the serverURL value\n if (Parse.serverURL) {\n const request = require('./request');\n request({ url: Parse.serverURL.replace(/\\/$/, '') + '/health' })\n .catch(response => response)\n .then(response => {\n const json = response.data || null;\n if (response.status !== 200 || !json || (json && json.status !== 'ok')) {\n /* eslint-disable no-console */\n console.warn(\n `\\nWARNING, Unable to connect to '${Parse.serverURL}'.` +\n ` Cloud code and push notifications may be unavailable!\\n`\n );\n /* eslint-enable no-console */\n if (callback) {\n callback(false);\n }\n } else {\n if (callback) {\n callback(true);\n }\n }\n });\n }\n }\n}", "function addParseCloud() {\n const ParseCloud = require('./cloud-code/Parse.Cloud');\n Object.defineProperty(Parse, 'Server', {\n get() {\n return Config.get(Parse.applicationId);\n },\n set(newVal) {\n newVal.appId = Parse.applicationId;\n Config.put(newVal);\n },\n configurable: true,\n });\n Object.assign(Parse.Cloud, ParseCloud);\n global.Parse = Parse;\n}", "function injectDefaults(options: ParseServerOptions) {\n Object.keys(defaults).forEach(key => {\n if (!Object.prototype.hasOwnProperty.call(options, key)) {\n options[key] = defaults[key];\n }\n });", " if (!Object.prototype.hasOwnProperty.call(options, 'serverURL')) {\n options.serverURL = `http://localhost:${options.port}${options.mountPath}`;\n }", " // Reserved Characters\n if (options.appId) {\n const regex = /[!#$%'()*+&/:;=?@[\\]{}^,|<>]/g;\n if (options.appId.match(regex)) {\n console.warn(\n `\\nWARNING, appId that contains special characters can cause issues while using with urls.\\n`\n );\n }\n }", " // Backwards compatibility\n if (options.userSensitiveFields) {\n /* eslint-disable no-console */\n !process.env.TESTING &&\n console.warn(\n `\\nDEPRECATED: userSensitiveFields has been replaced by protectedFields allowing the ability to protect fields in all classes with CLP. \\n`\n );\n /* eslint-enable no-console */", " const userSensitiveFields = Array.from(\n new Set([...(defaults.userSensitiveFields || []), ...(options.userSensitiveFields || [])])\n );", " // If the options.protectedFields is unset,\n // it'll be assigned the default above.\n // Here, protect against the case where protectedFields\n // is set, but doesn't have _User.\n if (!('_User' in options.protectedFields)) {\n options.protectedFields = Object.assign({ _User: [] }, options.protectedFields);\n }", " options.protectedFields['_User']['*'] = Array.from(\n new Set([...(options.protectedFields['_User']['*'] || []), ...userSensitiveFields])\n );\n }", " // Merge protectedFields options with defaults.\n Object.keys(defaults.protectedFields).forEach(c => {\n const cur = options.protectedFields[c];\n if (!cur) {\n options.protectedFields[c] = defaults.protectedFields[c];\n } else {\n Object.keys(defaults.protectedFields[c]).forEach(r => {\n const unq = new Set([\n ...(options.protectedFields[c][r] || []),\n ...defaults.protectedFields[c][r],\n ]);\n options.protectedFields[c][r] = Array.from(unq);\n });\n }\n });", " options.masterKeyIps = Array.from(\n new Set(options.masterKeyIps.concat(defaults.masterKeyIps, options.masterKeyIps))\n );\n}", "// Those can't be tested as it requires a subprocess\n/* istanbul ignore next */\nfunction configureListeners(parseServer) {\n const server = parseServer.server;\n const sockets = {};\n /* Currently, express doesn't shut down immediately after receiving SIGINT/SIGTERM if it has client connections that haven't timed out. (This is a known issue with node - https://github.com/nodejs/node/issues/2642)\n This function, along with `destroyAliveConnections()`, intend to fix this behavior such that parse server will close all open connections and initiate the shutdown process as soon as it receives a SIGINT/SIGTERM signal. */\n server.on('connection', socket => {\n const socketId = socket.remoteAddress + ':' + socket.remotePort;\n sockets[socketId] = socket;\n socket.on('close', () => {\n delete sockets[socketId];\n });\n });", " const destroyAliveConnections = function () {\n for (const socketId in sockets) {\n try {\n sockets[socketId].destroy();\n } catch (e) {\n /* */\n }\n }\n };", " const handleShutdown = function () {\n process.stdout.write('Termination signal received. Shutting down.');\n destroyAliveConnections();\n server.close();\n parseServer.handleShutdown();\n };\n process.on('SIGTERM', handleShutdown);\n process.on('SIGINT', handleShutdown);\n}", "export default ParseServer;" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "import AppCache from './cache';\nimport Parse from 'parse/node';\nimport auth from './Auth';\nimport Config from './Config';\nimport ClientSDK from './ClientSDK';\nimport defaultLogger from './logger';\nimport rest from './rest';\nimport MongoStorageAdapter from './Adapters/Storage/Mongo/MongoStorageAdapter';\nimport PostgresStorageAdapter from './Adapters/Storage/Postgres/PostgresStorageAdapter';", "export const DEFAULT_ALLOWED_HEADERS =\n 'X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, X-Parse-Request-Id, Content-Type, Pragma, Cache-Control';", "const getMountForRequest = function (req) {\n const mountPathLength = req.originalUrl.length - req.url.length;\n const mountPath = req.originalUrl.slice(0, mountPathLength);\n return req.protocol + '://' + req.get('host') + mountPath;\n};", "// Checks that the request is authorized for this app and checks user\n// auth too.\n// The bodyparser should run before this middleware.\n// Adds info to the request:\n// req.config - the Config for this app\n// req.auth - the Auth for this request\nexport function handleParseHeaders(req, res, next) {\n var mount = getMountForRequest(req);", " let context = {};\n if (req.get('X-Parse-Cloud-Context') != null) {\n try {\n context = JSON.parse(req.get('X-Parse-Cloud-Context'));\n if (Object.prototype.toString.call(context) !== '[object Object]') {\n throw 'Context is not an object';\n }\n } catch (e) {\n return malformedContext(req, res);\n }\n }\n var info = {\n appId: req.get('X-Parse-Application-Id'),\n sessionToken: req.get('X-Parse-Session-Token'),\n masterKey: req.get('X-Parse-Master-Key'),\n installationId: req.get('X-Parse-Installation-Id'),\n clientKey: req.get('X-Parse-Client-Key'),\n javascriptKey: req.get('X-Parse-Javascript-Key'),\n dotNetKey: req.get('X-Parse-Windows-Key'),\n restAPIKey: req.get('X-Parse-REST-API-Key'),\n clientVersion: req.get('X-Parse-Client-Version'),\n context: context,\n };", " var basicAuth = httpAuth(req);", " if (basicAuth) {\n var basicAuthAppId = basicAuth.appId;\n if (AppCache.get(basicAuthAppId)) {\n info.appId = basicAuthAppId;\n info.masterKey = basicAuth.masterKey || info.masterKey;\n info.javascriptKey = basicAuth.javascriptKey || info.javascriptKey;\n }\n }", " if (req.body) {\n // Unity SDK sends a _noBody key which needs to be removed.\n // Unclear at this point if action needs to be taken.\n delete req.body._noBody;\n }", " var fileViaJSON = false;", " if (!info.appId || !AppCache.get(info.appId)) {\n // See if we can find the app id on the body.\n if (req.body instanceof Buffer) {\n // The only chance to find the app id is if this is a file\n // upload that actually is a JSON body. So try to parse it.\n // https://github.com/parse-community/parse-server/issues/6589\n // It is also possible that the client is trying to upload a file but forgot\n // to provide x-parse-app-id in header and parse a binary file will fail\n try {\n req.body = JSON.parse(req.body);\n } catch (e) {\n return invalidRequest(req, res);\n }\n fileViaJSON = true;\n }", " if (req.body) {\n delete req.body._RevocableSession;\n }", " if (\n req.body &&\n req.body._ApplicationId &&\n AppCache.get(req.body._ApplicationId) &&\n (!info.masterKey || AppCache.get(req.body._ApplicationId).masterKey === info.masterKey)\n ) {\n info.appId = req.body._ApplicationId;\n info.javascriptKey = req.body._JavaScriptKey || '';\n delete req.body._ApplicationId;\n delete req.body._JavaScriptKey;\n // TODO: test that the REST API formats generated by the other\n // SDKs are handled ok\n if (req.body._ClientVersion) {\n info.clientVersion = req.body._ClientVersion;\n delete req.body._ClientVersion;\n }\n if (req.body._InstallationId) {\n info.installationId = req.body._InstallationId;\n delete req.body._InstallationId;\n }\n if (req.body._SessionToken) {\n info.sessionToken = req.body._SessionToken;\n delete req.body._SessionToken;\n }\n if (req.body._MasterKey) {\n info.masterKey = req.body._MasterKey;\n delete req.body._MasterKey;\n }\n if (req.body._context) {\n if (req.body._context instanceof Object) {\n info.context = req.body._context;\n } else {\n try {\n info.context = JSON.parse(req.body._context);\n if (Object.prototype.toString.call(info.context) !== '[object Object]') {\n throw 'Context is not an object';\n }\n } catch (e) {\n return malformedContext(req, res);\n }\n }\n delete req.body._context;\n }\n if (req.body._ContentType) {\n req.headers['content-type'] = req.body._ContentType;\n delete req.body._ContentType;\n }\n } else {\n return invalidRequest(req, res);\n }\n }", " if (info.sessionToken && typeof info.sessionToken !== 'string') {\n info.sessionToken = info.sessionToken.toString();\n }", " if (info.clientVersion) {\n info.clientSDK = ClientSDK.fromString(info.clientVersion);\n }", " if (fileViaJSON) {\n req.fileData = req.body.fileData;\n // We need to repopulate req.body with a buffer\n var base64 = req.body.base64;\n req.body = Buffer.from(base64, 'base64');\n }", " const clientIp = getClientIp(req);", " info.app = AppCache.get(info.appId);\n req.config = Config.get(info.appId, mount);\n req.config.headers = req.headers || {};\n req.config.ip = clientIp;\n req.info = info;", " if (\n info.masterKey &&\n req.config.masterKeyIps &&\n req.config.masterKeyIps.length !== 0 &&\n req.config.masterKeyIps.indexOf(clientIp) === -1\n ) {\n return invalidRequest(req, res);\n }", " var isMaster = info.masterKey === req.config.masterKey;", " if (isMaster) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: true,\n });\n next();\n return;\n }", " var isReadOnlyMaster = info.masterKey === req.config.readOnlyMasterKey;\n if (\n typeof req.config.readOnlyMasterKey != 'undefined' &&\n req.config.readOnlyMasterKey &&\n isReadOnlyMaster\n ) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: true,\n isReadOnly: true,\n });\n next();\n return;\n }", " // Client keys are not required in parse-server, but if any have been configured in the server, validate them\n // to preserve original behavior.\n const keys = ['clientKey', 'javascriptKey', 'dotNetKey', 'restAPIKey'];\n const oneKeyConfigured = keys.some(function (key) {\n return req.config[key] !== undefined;\n });\n const oneKeyMatches = keys.some(function (key) {\n return req.config[key] !== undefined && info[key] === req.config[key];\n });", " if (oneKeyConfigured && !oneKeyMatches) {\n return invalidRequest(req, res);\n }", " if (req.url == '/login') {\n delete info.sessionToken;\n }", " if (req.userFromJWT) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: false,\n user: req.userFromJWT,\n });\n next();\n return;\n }", " if (!info.sessionToken) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: false,\n });\n next();\n return;\n }", " return Promise.resolve()\n .then(() => {\n // handle the upgradeToRevocableSession path on it's own\n if (\n info.sessionToken &&\n req.url === '/upgradeToRevocableSession' &&\n info.sessionToken.indexOf('r:') != 0\n ) {\n return auth.getAuthForLegacySessionToken({\n config: req.config,\n installationId: info.installationId,\n sessionToken: info.sessionToken,\n });\n } else {\n return auth.getAuthForSessionToken({\n config: req.config,\n installationId: info.installationId,\n sessionToken: info.sessionToken,\n });\n }\n })\n .then(auth => {\n if (auth) {\n req.auth = auth;\n next();\n }\n })\n .catch(error => {\n if (error instanceof Parse.Error) {\n next(error);\n return;\n } else {\n // TODO: Determine the correct error scenario.\n req.config.loggerController.error('error getting auth for sessionToken', error);\n throw new Parse.Error(Parse.Error.UNKNOWN_ERROR, error);\n }\n });\n}", "function getClientIp(req) {", " if (req.headers['x-forwarded-for']) {\n // try to get from x-forwared-for if it set (behind reverse proxy)\n return req.headers['x-forwarded-for'].split(',')[0];\n } else if (req.connection && req.connection.remoteAddress) {\n // no proxy, try getting from connection.remoteAddress\n return req.connection.remoteAddress;\n } else if (req.socket) {\n // try to get it from req.socket\n return req.socket.remoteAddress;\n } else if (req.connection && req.connection.socket) {\n // try to get it form the connection.socket\n return req.connection.socket.remoteAddress;\n } else {\n // if non above, fallback.\n return req.ip;\n }", "}", "function httpAuth(req) {\n if (!(req.req || req).headers.authorization) return;", " var header = (req.req || req).headers.authorization;\n var appId, masterKey, javascriptKey;", " // parse header\n var authPrefix = 'basic ';", " var match = header.toLowerCase().indexOf(authPrefix);", " if (match == 0) {\n var encodedAuth = header.substring(authPrefix.length, header.length);\n var credentials = decodeBase64(encodedAuth).split(':');", " if (credentials.length == 2) {\n appId = credentials[0];\n var key = credentials[1];", " var jsKeyPrefix = 'javascript-key=';", " var matchKey = key.indexOf(jsKeyPrefix);\n if (matchKey == 0) {\n javascriptKey = key.substring(jsKeyPrefix.length, key.length);\n } else {\n masterKey = key;\n }\n }\n }", " return { appId: appId, masterKey: masterKey, javascriptKey: javascriptKey };\n}", "function decodeBase64(str) {\n return Buffer.from(str, 'base64').toString();\n}", "export function allowCrossDomain(appId) {\n return (req, res, next) => {\n const config = Config.get(appId, getMountForRequest(req));\n let allowHeaders = DEFAULT_ALLOWED_HEADERS;\n if (config && config.allowHeaders) {\n allowHeaders += `, ${config.allowHeaders.join(', ')}`;\n }\n const allowOrigin = (config && config.allowOrigin) || '*';\n res.header('Access-Control-Allow-Origin', allowOrigin);\n res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');\n res.header('Access-Control-Allow-Headers', allowHeaders);\n res.header('Access-Control-Expose-Headers', 'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id');\n // intercept OPTIONS method\n if ('OPTIONS' == req.method) {\n res.sendStatus(200);\n } else {\n next();\n }\n };\n}", "export function allowMethodOverride(req, res, next) {\n if (req.method === 'POST' && req.body._method) {\n req.originalMethod = req.method;\n req.method = req.body._method;\n delete req.body._method;\n }\n next();\n}", "export function handleParseErrors(err, req, res, next) {\n const log = (req.config && req.config.loggerController) || defaultLogger;\n if (err instanceof Parse.Error) {\n if (req.config && req.config.enableExpressErrorHandler) {\n return next(err);\n }\n let httpStatus;\n // TODO: fill out this mapping\n switch (err.code) {\n case Parse.Error.INTERNAL_SERVER_ERROR:\n httpStatus = 500;\n break;\n case Parse.Error.OBJECT_NOT_FOUND:\n httpStatus = 404;\n break;\n default:\n httpStatus = 400;\n }\n res.status(httpStatus);\n res.json({ code: err.code, error: err.message });\n log.error('Parse error: ', err);\n } else if (err.status && err.message) {\n res.status(err.status);\n res.json({ error: err.message });\n if (!(process && process.env.TESTING)) {\n next(err);\n }\n } else {\n log.error('Uncaught internal server error.', err, err.stack);\n res.status(500);\n res.json({\n code: Parse.Error.INTERNAL_SERVER_ERROR,\n message: 'Internal server error.',\n });\n if (!(process && process.env.TESTING)) {\n next(err);\n }\n }\n}", "export function enforceMasterKeyAccess(req, res, next) {\n if (!req.auth.isMaster) {\n res.status(403);\n res.end('{\"error\":\"unauthorized: master key is required\"}');\n return;\n }\n next();\n}", "export function promiseEnforceMasterKeyAccess(request) {\n if (!request.auth.isMaster) {\n const error = new Error();\n error.status = 403;\n error.message = 'unauthorized: master key is required';\n throw error;\n }\n return Promise.resolve();\n}", "/**\n * Deduplicates a request to ensure idempotency. Duplicates are determined by the request ID\n * in the request header. If a request has no request ID, it is executed anyway.\n * @param {*} req The request to evaluate.\n * @returns Promise<{}>\n */\nexport function promiseEnsureIdempotency(req) {\n // Enable feature only for MongoDB\n if (\n !(\n req.config.database.adapter instanceof MongoStorageAdapter ||\n req.config.database.adapter instanceof PostgresStorageAdapter\n )\n ) {\n return Promise.resolve();\n }\n // Get parameters\n const config = req.config;\n const requestId = ((req || {}).headers || {})['x-parse-request-id'];\n const { paths, ttl } = config.idempotencyOptions;\n if (!requestId || !config.idempotencyOptions) {\n return Promise.resolve();\n }\n // Request path may contain trailing slashes, depending on the original request, so remove\n // leading and trailing slashes to make it easier to specify paths in the configuration\n const reqPath = req.path.replace(/^\\/|\\/$/, '');\n // Determine whether idempotency is enabled for current request path\n let match = false;\n for (const path of paths) {\n // Assume one wants a path to always match from the beginning to prevent any mistakes\n const regex = new RegExp(path.charAt(0) === '^' ? path : '^' + path);\n if (reqPath.match(regex)) {\n match = true;\n break;\n }\n }\n if (!match) {\n return Promise.resolve();\n }\n // Try to store request\n const expiryDate = new Date(new Date().setSeconds(new Date().getSeconds() + ttl));\n return rest\n .create(config, auth.master(config), '_Idempotency', {\n reqId: requestId,\n expire: Parse._encode(expiryDate),\n })\n .catch(e => {\n if (e.code == Parse.Error.DUPLICATE_VALUE) {\n throw new Parse.Error(Parse.Error.DUPLICATE_REQUEST, 'Duplicate request');\n }\n throw e;\n });\n}", "function invalidRequest(req, res) {\n res.status(403);\n res.end('{\"error\":\"unauthorized\"}');\n}", "function malformedContext(req, res) {\n res.status(400);\n res.json({ code: Parse.Error.INVALID_JSON, error: 'Invalid object for context.' });\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "import AppCache from './cache';\nimport Parse from 'parse/node';\nimport auth from './Auth';\nimport Config from './Config';\nimport ClientSDK from './ClientSDK';\nimport defaultLogger from './logger';\nimport rest from './rest';\nimport MongoStorageAdapter from './Adapters/Storage/Mongo/MongoStorageAdapter';\nimport PostgresStorageAdapter from './Adapters/Storage/Postgres/PostgresStorageAdapter';", "export const DEFAULT_ALLOWED_HEADERS =\n 'X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, X-Parse-Request-Id, Content-Type, Pragma, Cache-Control';", "const getMountForRequest = function (req) {\n const mountPathLength = req.originalUrl.length - req.url.length;\n const mountPath = req.originalUrl.slice(0, mountPathLength);\n return req.protocol + '://' + req.get('host') + mountPath;\n};", "// Checks that the request is authorized for this app and checks user\n// auth too.\n// The bodyparser should run before this middleware.\n// Adds info to the request:\n// req.config - the Config for this app\n// req.auth - the Auth for this request\nexport function handleParseHeaders(req, res, next) {\n var mount = getMountForRequest(req);", " let context = {};\n if (req.get('X-Parse-Cloud-Context') != null) {\n try {\n context = JSON.parse(req.get('X-Parse-Cloud-Context'));\n if (Object.prototype.toString.call(context) !== '[object Object]') {\n throw 'Context is not an object';\n }\n } catch (e) {\n return malformedContext(req, res);\n }\n }\n var info = {\n appId: req.get('X-Parse-Application-Id'),\n sessionToken: req.get('X-Parse-Session-Token'),\n masterKey: req.get('X-Parse-Master-Key'),\n installationId: req.get('X-Parse-Installation-Id'),\n clientKey: req.get('X-Parse-Client-Key'),\n javascriptKey: req.get('X-Parse-Javascript-Key'),\n dotNetKey: req.get('X-Parse-Windows-Key'),\n restAPIKey: req.get('X-Parse-REST-API-Key'),\n clientVersion: req.get('X-Parse-Client-Version'),\n context: context,\n };", " var basicAuth = httpAuth(req);", " if (basicAuth) {\n var basicAuthAppId = basicAuth.appId;\n if (AppCache.get(basicAuthAppId)) {\n info.appId = basicAuthAppId;\n info.masterKey = basicAuth.masterKey || info.masterKey;\n info.javascriptKey = basicAuth.javascriptKey || info.javascriptKey;\n }\n }", " if (req.body) {\n // Unity SDK sends a _noBody key which needs to be removed.\n // Unclear at this point if action needs to be taken.\n delete req.body._noBody;\n }", " var fileViaJSON = false;", " if (!info.appId || !AppCache.get(info.appId)) {\n // See if we can find the app id on the body.\n if (req.body instanceof Buffer) {\n // The only chance to find the app id is if this is a file\n // upload that actually is a JSON body. So try to parse it.\n // https://github.com/parse-community/parse-server/issues/6589\n // It is also possible that the client is trying to upload a file but forgot\n // to provide x-parse-app-id in header and parse a binary file will fail\n try {\n req.body = JSON.parse(req.body);\n } catch (e) {\n return invalidRequest(req, res);\n }\n fileViaJSON = true;\n }", " if (req.body) {\n delete req.body._RevocableSession;\n }", " if (\n req.body &&\n req.body._ApplicationId &&\n AppCache.get(req.body._ApplicationId) &&\n (!info.masterKey || AppCache.get(req.body._ApplicationId).masterKey === info.masterKey)\n ) {\n info.appId = req.body._ApplicationId;\n info.javascriptKey = req.body._JavaScriptKey || '';\n delete req.body._ApplicationId;\n delete req.body._JavaScriptKey;\n // TODO: test that the REST API formats generated by the other\n // SDKs are handled ok\n if (req.body._ClientVersion) {\n info.clientVersion = req.body._ClientVersion;\n delete req.body._ClientVersion;\n }\n if (req.body._InstallationId) {\n info.installationId = req.body._InstallationId;\n delete req.body._InstallationId;\n }\n if (req.body._SessionToken) {\n info.sessionToken = req.body._SessionToken;\n delete req.body._SessionToken;\n }\n if (req.body._MasterKey) {\n info.masterKey = req.body._MasterKey;\n delete req.body._MasterKey;\n }\n if (req.body._context) {\n if (req.body._context instanceof Object) {\n info.context = req.body._context;\n } else {\n try {\n info.context = JSON.parse(req.body._context);\n if (Object.prototype.toString.call(info.context) !== '[object Object]') {\n throw 'Context is not an object';\n }\n } catch (e) {\n return malformedContext(req, res);\n }\n }\n delete req.body._context;\n }\n if (req.body._ContentType) {\n req.headers['content-type'] = req.body._ContentType;\n delete req.body._ContentType;\n }\n } else {\n return invalidRequest(req, res);\n }\n }", " if (info.sessionToken && typeof info.sessionToken !== 'string') {\n info.sessionToken = info.sessionToken.toString();\n }", " if (info.clientVersion) {\n info.clientSDK = ClientSDK.fromString(info.clientVersion);\n }", " if (fileViaJSON) {\n req.fileData = req.body.fileData;\n // We need to repopulate req.body with a buffer\n var base64 = req.body.base64;\n req.body = Buffer.from(base64, 'base64');\n }", " const clientIp = getClientIp(req);", " info.app = AppCache.get(info.appId);\n req.config = Config.get(info.appId, mount);\n req.config.headers = req.headers || {};\n req.config.ip = clientIp;\n req.info = info;", " if (\n info.masterKey &&\n req.config.masterKeyIps &&\n req.config.masterKeyIps.length !== 0 &&\n req.config.masterKeyIps.indexOf(clientIp) === -1\n ) {\n return invalidRequest(req, res);\n }", " var isMaster = info.masterKey === req.config.masterKey;", " if (isMaster) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: true,\n });\n next();\n return;\n }", " var isReadOnlyMaster = info.masterKey === req.config.readOnlyMasterKey;\n if (\n typeof req.config.readOnlyMasterKey != 'undefined' &&\n req.config.readOnlyMasterKey &&\n isReadOnlyMaster\n ) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: true,\n isReadOnly: true,\n });\n next();\n return;\n }", " // Client keys are not required in parse-server, but if any have been configured in the server, validate them\n // to preserve original behavior.\n const keys = ['clientKey', 'javascriptKey', 'dotNetKey', 'restAPIKey'];\n const oneKeyConfigured = keys.some(function (key) {\n return req.config[key] !== undefined;\n });\n const oneKeyMatches = keys.some(function (key) {\n return req.config[key] !== undefined && info[key] === req.config[key];\n });", " if (oneKeyConfigured && !oneKeyMatches) {\n return invalidRequest(req, res);\n }", " if (req.url == '/login') {\n delete info.sessionToken;\n }", " if (req.userFromJWT) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: false,\n user: req.userFromJWT,\n });\n next();\n return;\n }", " if (!info.sessionToken) {\n req.auth = new auth.Auth({\n config: req.config,\n installationId: info.installationId,\n isMaster: false,\n });\n next();\n return;\n }", " return Promise.resolve()\n .then(() => {\n // handle the upgradeToRevocableSession path on it's own\n if (\n info.sessionToken &&\n req.url === '/upgradeToRevocableSession' &&\n info.sessionToken.indexOf('r:') != 0\n ) {\n return auth.getAuthForLegacySessionToken({\n config: req.config,\n installationId: info.installationId,\n sessionToken: info.sessionToken,\n });\n } else {\n return auth.getAuthForSessionToken({\n config: req.config,\n installationId: info.installationId,\n sessionToken: info.sessionToken,\n });\n }\n })\n .then(auth => {\n if (auth) {\n req.auth = auth;\n next();\n }\n })\n .catch(error => {\n if (error instanceof Parse.Error) {\n next(error);\n return;\n } else {\n // TODO: Determine the correct error scenario.\n req.config.loggerController.error('error getting auth for sessionToken', error);\n throw new Parse.Error(Parse.Error.UNKNOWN_ERROR, error);\n }\n });\n}", "function getClientIp(req) {", " return req.ip;", "}", "function httpAuth(req) {\n if (!(req.req || req).headers.authorization) return;", " var header = (req.req || req).headers.authorization;\n var appId, masterKey, javascriptKey;", " // parse header\n var authPrefix = 'basic ';", " var match = header.toLowerCase().indexOf(authPrefix);", " if (match == 0) {\n var encodedAuth = header.substring(authPrefix.length, header.length);\n var credentials = decodeBase64(encodedAuth).split(':');", " if (credentials.length == 2) {\n appId = credentials[0];\n var key = credentials[1];", " var jsKeyPrefix = 'javascript-key=';", " var matchKey = key.indexOf(jsKeyPrefix);\n if (matchKey == 0) {\n javascriptKey = key.substring(jsKeyPrefix.length, key.length);\n } else {\n masterKey = key;\n }\n }\n }", " return { appId: appId, masterKey: masterKey, javascriptKey: javascriptKey };\n}", "function decodeBase64(str) {\n return Buffer.from(str, 'base64').toString();\n}", "export function allowCrossDomain(appId) {\n return (req, res, next) => {\n const config = Config.get(appId, getMountForRequest(req));\n let allowHeaders = DEFAULT_ALLOWED_HEADERS;\n if (config && config.allowHeaders) {\n allowHeaders += `, ${config.allowHeaders.join(', ')}`;\n }\n const allowOrigin = (config && config.allowOrigin) || '*';\n res.header('Access-Control-Allow-Origin', allowOrigin);\n res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');\n res.header('Access-Control-Allow-Headers', allowHeaders);\n res.header('Access-Control-Expose-Headers', 'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id');\n // intercept OPTIONS method\n if ('OPTIONS' == req.method) {\n res.sendStatus(200);\n } else {\n next();\n }\n };\n}", "export function allowMethodOverride(req, res, next) {\n if (req.method === 'POST' && req.body._method) {\n req.originalMethod = req.method;\n req.method = req.body._method;\n delete req.body._method;\n }\n next();\n}", "export function handleParseErrors(err, req, res, next) {\n const log = (req.config && req.config.loggerController) || defaultLogger;\n if (err instanceof Parse.Error) {\n if (req.config && req.config.enableExpressErrorHandler) {\n return next(err);\n }\n let httpStatus;\n // TODO: fill out this mapping\n switch (err.code) {\n case Parse.Error.INTERNAL_SERVER_ERROR:\n httpStatus = 500;\n break;\n case Parse.Error.OBJECT_NOT_FOUND:\n httpStatus = 404;\n break;\n default:\n httpStatus = 400;\n }\n res.status(httpStatus);\n res.json({ code: err.code, error: err.message });\n log.error('Parse error: ', err);\n } else if (err.status && err.message) {\n res.status(err.status);\n res.json({ error: err.message });\n if (!(process && process.env.TESTING)) {\n next(err);\n }\n } else {\n log.error('Uncaught internal server error.', err, err.stack);\n res.status(500);\n res.json({\n code: Parse.Error.INTERNAL_SERVER_ERROR,\n message: 'Internal server error.',\n });\n if (!(process && process.env.TESTING)) {\n next(err);\n }\n }\n}", "export function enforceMasterKeyAccess(req, res, next) {\n if (!req.auth.isMaster) {\n res.status(403);\n res.end('{\"error\":\"unauthorized: master key is required\"}');\n return;\n }\n next();\n}", "export function promiseEnforceMasterKeyAccess(request) {\n if (!request.auth.isMaster) {\n const error = new Error();\n error.status = 403;\n error.message = 'unauthorized: master key is required';\n throw error;\n }\n return Promise.resolve();\n}", "/**\n * Deduplicates a request to ensure idempotency. Duplicates are determined by the request ID\n * in the request header. If a request has no request ID, it is executed anyway.\n * @param {*} req The request to evaluate.\n * @returns Promise<{}>\n */\nexport function promiseEnsureIdempotency(req) {\n // Enable feature only for MongoDB\n if (\n !(\n req.config.database.adapter instanceof MongoStorageAdapter ||\n req.config.database.adapter instanceof PostgresStorageAdapter\n )\n ) {\n return Promise.resolve();\n }\n // Get parameters\n const config = req.config;\n const requestId = ((req || {}).headers || {})['x-parse-request-id'];\n const { paths, ttl } = config.idempotencyOptions;\n if (!requestId || !config.idempotencyOptions) {\n return Promise.resolve();\n }\n // Request path may contain trailing slashes, depending on the original request, so remove\n // leading and trailing slashes to make it easier to specify paths in the configuration\n const reqPath = req.path.replace(/^\\/|\\/$/, '');\n // Determine whether idempotency is enabled for current request path\n let match = false;\n for (const path of paths) {\n // Assume one wants a path to always match from the beginning to prevent any mistakes\n const regex = new RegExp(path.charAt(0) === '^' ? path : '^' + path);\n if (reqPath.match(regex)) {\n match = true;\n break;\n }\n }\n if (!match) {\n return Promise.resolve();\n }\n // Try to store request\n const expiryDate = new Date(new Date().setSeconds(new Date().getSeconds() + ttl));\n return rest\n .create(config, auth.master(config), '_Idempotency', {\n reqId: requestId,\n expire: Parse._encode(expiryDate),\n })\n .catch(e => {\n if (e.code == Parse.Error.DUPLICATE_VALUE) {\n throw new Parse.Error(Parse.Error.DUPLICATE_REQUEST, 'Duplicate request');\n }\n throw e;\n });\n}", "function invalidRequest(req, res) {\n res.status(403);\n res.end('{\"error\":\"unauthorized\"}');\n}", "function malformedContext(req, res) {\n res.status(400);\n res.json({ code: Parse.Error.INVALID_JSON, error: 'Invalid object for context.' });\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [292, 479, 90, 240, 306, 299], "buggy_code_start_loc": [161, 479, 90, 240, 306, 283], "filenames": ["spec/Middlewares.spec.js", "src/Options/Definitions.js", "src/Options/docs.js", "src/Options/index.js", "src/ParseServer.js", "src/middlewares.js"], "fixing_code_end_loc": [177, 487, 92, 244, 310, 284], "fixing_code_start_loc": [160, 480, 91, 241, 307, 283], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "89DA5320-8060-4E94-8876-0C1A83C100DF", "versionEndExcluding": "5.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server uses the request header `x-forwarded-for` to determine the client IP address. If Parse Server doesn't run behind a proxy server, then a client can set this header and Parse Server will trust the value of the header. The incorrect client IP address will be used by various features in Parse Server. This allows to circumvent the security mechanism of the Parse Server option `masterKeyIps` by setting an allowed IP address as the `x-forwarded-for` header value. This issue has been patched in version 5.4.1. The mechanism to determine the client IP address has been rewritten. The correct IP address determination now requires to set the Parse Server option `trustProxy`."}], "evaluatorComment": null, "id": "CVE-2023-22474", "lastModified": "2023-02-10T17:32:28.447", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-02-03T20:15:10.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-vm5r-c87r-pf6x"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-290"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/e016d813e083ce6828f9abce245d15b681a224d8"}, "type": "CWE-290"}
292
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nsession_start();\ndefine('NO_AUTH_REQUIRED',true);\n$TAB = 'RESET PASSWORD';", "if (isset($_SESSION['user'])) {\n header(\"Location: /list/user\");\n}", "// Main include\ninclude($_SERVER['DOCUMENT_ROOT'].\"/inc/main.php\");", "if ((!empty($_POST['user'])) && (empty($_POST['code']))) {\n $v_user = escapeshellarg($_POST['user']);\n $user = $_POST['user'];\n $cmd=\"/usr/bin/sudo /usr/local/vesta/bin/v-list-user\";\n exec ($cmd.\" \".$v_user.\" json\", $output, $return_var);\n if ( $return_var == 0 ) {\n $data = json_decode(implode('', $output), true);\n $rkey = $data[$user]['RKEY'];\n $fname = $data[$user]['FNAME'];\n $lname = $data[$user]['LNAME'];\n $contact = $data[$user]['CONTACT'];\n $to = $data[$user]['CONTACT'];\n $subject = __('MAIL_RESET_SUBJECT',date(\"Y-m-d H:i:s\"));\n $hostname = exec('hostname');\n $from = __('MAIL_FROM',$hostname);\n if (!empty($fname)) {\n $mailtext = __('GREETINGS_GORDON_FREEMAN',$fname,$lname);\n } else {\n $mailtext = __('GREETINGS');\n }", " $mailtext .= __('PASSWORD_RESET_REQUEST',$_SERVER['HTTP_HOST'],$user,$rkey,$_SERVER['HTTP_HOST'],$user,$rkey);", " if (!empty($rkey)) send_email($to, $subject, $mailtext, $from);\n unset($output);\n }", " header(\"Location: /reset/?action=code&user=\".$_POST['user']);\n exit;\n}", "if ((!empty($_POST['user'])) && (!empty($_POST['code'])) && (!empty($_POST['password'])) ) {\n if ( $_POST['password'] == $_POST['password_confirm'] ) {\n $v_user = escapeshellarg($_POST['user']);\n $user = $_POST['user'];\n $cmd=\"/usr/bin/sudo /usr/local/vesta/bin/v-list-user\";\n exec ($cmd.\" \".$v_user.\" json\", $output, $return_var);\n if ( $return_var == 0 ) {\n $data = json_decode(implode('', $output), true);\n $rkey = $data[$user]['RKEY'];\n if (hash_equals($rkey, $_POST['code'])) {\n $v_password = tempnam(\"/tmp\",\"vst\");\n $fp = fopen($v_password, \"w\");\n fwrite($fp, $_POST['password'].\"\\n\");\n fclose($fp);\n $cmd=\"/usr/bin/sudo /usr/local/vesta/bin/v-change-user-password\";\n exec ($cmd.\" \".$v_user.\" \".$v_password, $output, $return_var);\n unlink($v_password);\n if ( $return_var > 0 ) {\n $ERROR = \"<a class=\\\"error\\\">\".__('An internal error occurred').\"</a>\";\n } else {\n $_SESSION['user'] = $_POST['user'];\n header(\"Location: /\");\n exit;\n }\n } else {\n $ERROR = \"<a class=\\\"error\\\">\".__('Invalid username or code').\"</a>\";\n }\n } else {\n $ERROR = \"<a class=\\\"error\\\">\".__('Invalid username or code').\"</a>\";\n }\n } else {\n $ERROR = \"<a class=\\\"error\\\">\".__('Passwords not match').\"</a>\";\n }\n}", "// Detect language\nif (empty($_SESSION['language'])) $_SESSION['language'] = detect_user_language();", "if (empty($_GET['action'])) {\n require_once '../templates/header.html';\n require_once '../templates/reset_1.html';\n} else {\n require_once '../templates/header.html';\n if ($_GET['action'] == 'code' ) {\n require_once '../templates/reset_2.html';\n }\n if (($_GET['action'] == 'confirm' ) && (!empty($_GET['code']))) {\n require_once '../templates/reset_3.html';\n }\n}", "?>" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [34], "buggy_code_start_loc": [33], "filenames": ["web/reset/index.php"], "fixing_code_end_loc": [34], "fixing_code_start_loc": [33], "message": "In the Password Reset Module in VESTA Control Panel through 0.9.8-25 and Hestia Control Panel before 1.1.1, Host header manipulation leads to account takeover because the victim receives a reset URL containing an attacker-controlled server name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:hestiacp:control_panel:*:*:*:*:*:*:*:*", "matchCriteriaId": "73066D92-0ECA-47E0-93B6-33A0A3A7582F", "versionEndExcluding": "1.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:vestacp:control_panel:*:*:*:*:*:*:*:*", "matchCriteriaId": "AA062E69-DEAB-4E77-9F13-636F8F153D02", "versionEndExcluding": null, "versionEndIncluding": "0.9.8-25", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the Password Reset Module in VESTA Control Panel through 0.9.8-25 and Hestia Control Panel before 1.1.1, Host header manipulation leads to account takeover because the victim receives a reset URL containing an attacker-controlled server name."}, {"lang": "es", "value": "En el Password Reset Module en VESTA Control Panel versiones hasta 0.9.8-25 y Hestia Control Panel versiones hasta 1.1.0, la manipulaci\u00f3n del encabezado Host conlleva a la toma de control de la cuenta porque la v\u00edctima recibe un URL de restablecimiento que contiene un nombre de servidor controlado por el atacante."}], "evaluatorComment": null, "id": "CVE-2020-10966", "lastModified": "2022-07-12T17:42:04.277", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-03-25T23:15:16.217", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/hestiacp/hestiacp/issues/748"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/hestiacp/hestiacp/releases/tag/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/serghey-rodin/vesta/commit/c3c4de43d6701560f604ca7996f717b08e3d7d1d"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/serghey-rodin/vesta/commit/c3c4de43d6701560f604ca7996f717b08e3d7d1d"}, "type": "NVD-CWE-Other"}
293
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nsession_start();\ndefine('NO_AUTH_REQUIRED',true);\n$TAB = 'RESET PASSWORD';", "if (isset($_SESSION['user'])) {\n header(\"Location: /list/user\");\n}", "// Main include\ninclude($_SERVER['DOCUMENT_ROOT'].\"/inc/main.php\");", "if ((!empty($_POST['user'])) && (empty($_POST['code']))) {\n $v_user = escapeshellarg($_POST['user']);\n $user = $_POST['user'];\n $cmd=\"/usr/bin/sudo /usr/local/vesta/bin/v-list-user\";\n exec ($cmd.\" \".$v_user.\" json\", $output, $return_var);\n if ( $return_var == 0 ) {\n $data = json_decode(implode('', $output), true);\n $rkey = $data[$user]['RKEY'];\n $fname = $data[$user]['FNAME'];\n $lname = $data[$user]['LNAME'];\n $contact = $data[$user]['CONTACT'];\n $to = $data[$user]['CONTACT'];\n $subject = __('MAIL_RESET_SUBJECT',date(\"Y-m-d H:i:s\"));\n $hostname = exec('hostname');\n $from = __('MAIL_FROM',$hostname);\n if (!empty($fname)) {\n $mailtext = __('GREETINGS_GORDON_FREEMAN',$fname,$lname);\n } else {\n $mailtext = __('GREETINGS');\n }", " $mailtext .= __('PASSWORD_RESET_REQUEST',$hostname,$user,$rkey,$hostname,$user,$rkey);", " if (!empty($rkey)) send_email($to, $subject, $mailtext, $from);\n unset($output);\n }", " header(\"Location: /reset/?action=code&user=\".$_POST['user']);\n exit;\n}", "if ((!empty($_POST['user'])) && (!empty($_POST['code'])) && (!empty($_POST['password'])) ) {\n if ( $_POST['password'] == $_POST['password_confirm'] ) {\n $v_user = escapeshellarg($_POST['user']);\n $user = $_POST['user'];\n $cmd=\"/usr/bin/sudo /usr/local/vesta/bin/v-list-user\";\n exec ($cmd.\" \".$v_user.\" json\", $output, $return_var);\n if ( $return_var == 0 ) {\n $data = json_decode(implode('', $output), true);\n $rkey = $data[$user]['RKEY'];\n if (hash_equals($rkey, $_POST['code'])) {\n $v_password = tempnam(\"/tmp\",\"vst\");\n $fp = fopen($v_password, \"w\");\n fwrite($fp, $_POST['password'].\"\\n\");\n fclose($fp);\n $cmd=\"/usr/bin/sudo /usr/local/vesta/bin/v-change-user-password\";\n exec ($cmd.\" \".$v_user.\" \".$v_password, $output, $return_var);\n unlink($v_password);\n if ( $return_var > 0 ) {\n $ERROR = \"<a class=\\\"error\\\">\".__('An internal error occurred').\"</a>\";\n } else {\n $_SESSION['user'] = $_POST['user'];\n header(\"Location: /\");\n exit;\n }\n } else {\n $ERROR = \"<a class=\\\"error\\\">\".__('Invalid username or code').\"</a>\";\n }\n } else {\n $ERROR = \"<a class=\\\"error\\\">\".__('Invalid username or code').\"</a>\";\n }\n } else {\n $ERROR = \"<a class=\\\"error\\\">\".__('Passwords not match').\"</a>\";\n }\n}", "// Detect language\nif (empty($_SESSION['language'])) $_SESSION['language'] = detect_user_language();", "if (empty($_GET['action'])) {\n require_once '../templates/header.html';\n require_once '../templates/reset_1.html';\n} else {\n require_once '../templates/header.html';\n if ($_GET['action'] == 'code' ) {\n require_once '../templates/reset_2.html';\n }\n if (($_GET['action'] == 'confirm' ) && (!empty($_GET['code']))) {\n require_once '../templates/reset_3.html';\n }\n}", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [34], "buggy_code_start_loc": [33], "filenames": ["web/reset/index.php"], "fixing_code_end_loc": [34], "fixing_code_start_loc": [33], "message": "In the Password Reset Module in VESTA Control Panel through 0.9.8-25 and Hestia Control Panel before 1.1.1, Host header manipulation leads to account takeover because the victim receives a reset URL containing an attacker-controlled server name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:hestiacp:control_panel:*:*:*:*:*:*:*:*", "matchCriteriaId": "73066D92-0ECA-47E0-93B6-33A0A3A7582F", "versionEndExcluding": "1.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:vestacp:control_panel:*:*:*:*:*:*:*:*", "matchCriteriaId": "AA062E69-DEAB-4E77-9F13-636F8F153D02", "versionEndExcluding": null, "versionEndIncluding": "0.9.8-25", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the Password Reset Module in VESTA Control Panel through 0.9.8-25 and Hestia Control Panel before 1.1.1, Host header manipulation leads to account takeover because the victim receives a reset URL containing an attacker-controlled server name."}, {"lang": "es", "value": "En el Password Reset Module en VESTA Control Panel versiones hasta 0.9.8-25 y Hestia Control Panel versiones hasta 1.1.0, la manipulaci\u00f3n del encabezado Host conlleva a la toma de control de la cuenta porque la v\u00edctima recibe un URL de restablecimiento que contiene un nombre de servidor controlado por el atacante."}], "evaluatorComment": null, "id": "CVE-2020-10966", "lastModified": "2022-07-12T17:42:04.277", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-03-25T23:15:16.217", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/hestiacp/hestiacp/issues/748"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/hestiacp/hestiacp/releases/tag/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/serghey-rodin/vesta/commit/c3c4de43d6701560f604ca7996f717b08e3d7d1d"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/serghey-rodin/vesta/commit/c3c4de43d6701560f604ca7996f717b08e3d7d1d"}, "type": "NVD-CWE-Other"}
293
Determine whether the {function_name} code is vulnerable or not.
[ "/***************************************************************************\n copyright : (C) 2002 - 2008 by Scott Wheeler\n email : wheeler@kde.org\n ***************************************************************************/", "/***************************************************************************\n * This library is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU Lesser General Public License version *\n * 2.1 as published by the Free Software Foundation. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *\n * 02110-1301 USA *\n * *\n * Alternatively, this file is available under the Mozilla Public *\n * License Version 1.1. You may obtain a copy of the License at *\n * http://www.mozilla.org/MPL/ *\n ***************************************************************************/", "#include <tdebug.h>\n#include <tzlib.h>", "#include \"id3v2framefactory.h\"\n#include \"id3v2synchdata.h\"\n#include \"id3v1genres.h\"", "#include \"frames/attachedpictureframe.h\"\n#include \"frames/commentsframe.h\"\n#include \"frames/relativevolumeframe.h\"\n#include \"frames/textidentificationframe.h\"\n#include \"frames/uniquefileidentifierframe.h\"\n#include \"frames/unknownframe.h\"\n#include \"frames/generalencapsulatedobjectframe.h\"\n#include \"frames/urllinkframe.h\"\n#include \"frames/unsynchronizedlyricsframe.h\"\n#include \"frames/popularimeterframe.h\"\n#include \"frames/privateframe.h\"\n#include \"frames/ownershipframe.h\"\n#include \"frames/synchronizedlyricsframe.h\"\n#include \"frames/eventtimingcodesframe.h\"\n#include \"frames/chapterframe.h\"\n#include \"frames/tableofcontentsframe.h\"\n#include \"frames/podcastframe.h\"", "using namespace TagLib;\nusing namespace ID3v2;", "namespace\n{\n void updateGenre(TextIdentificationFrame *frame)\n {\n StringList fields = frame->fieldList();\n StringList newfields;", " for(StringList::ConstIterator it = fields.begin(); it != fields.end(); ++it) {\n String s = *it;\n int end = s.find(\")\");", " if(s.startsWith(\"(\") && end > 0) {\n // \"(12)Genre\"\n String text = s.substr(end + 1);\n bool ok;\n int number = s.substr(1, end - 1).toInt(&ok);\n if(ok && number >= 0 && number <= 255 && !(ID3v1::genre(number) == text))\n newfields.append(s.substr(1, end - 1));\n if(!text.isEmpty())\n newfields.append(text);\n }\n else {\n // \"Genre\" or \"12\"\n newfields.append(s);\n }\n }", " if(newfields.isEmpty())\n fields.append(String());", " frame->setText(newfields);\n }\n}", "class FrameFactory::FrameFactoryPrivate\n{\npublic:\n FrameFactoryPrivate() :\n defaultEncoding(String::Latin1),\n useDefaultEncoding(false) {}", " String::Type defaultEncoding;\n bool useDefaultEncoding;", " template <class T> void setTextEncoding(T *frame)\n {\n if(useDefaultEncoding)\n frame->setTextEncoding(defaultEncoding);\n }\n};", "FrameFactory FrameFactory::factory;", "////////////////////////////////////////////////////////////////////////////////\n// public members\n////////////////////////////////////////////////////////////////////////////////", "FrameFactory *FrameFactory::instance()\n{\n return &factory;\n}", "Frame *FrameFactory::createFrame(const ByteVector &data, bool synchSafeInts) const\n{\n return createFrame(data, static_cast<unsigned int>(synchSafeInts ? 4 : 3));\n}", "Frame *FrameFactory::createFrame(const ByteVector &data, unsigned int version) const\n{\n Header tagHeader;\n tagHeader.setMajorVersion(version);\n return createFrame(data, &tagHeader);\n}", "Frame *FrameFactory::createFrame(const ByteVector &origData, Header *tagHeader) const\n{\n ByteVector data = origData;\n unsigned int version = tagHeader->majorVersion();\n Frame::Header *header = new Frame::Header(data, version);\n ByteVector frameID = header->frameID();", " // A quick sanity check -- make sure that the frameID is 4 uppercase Latin1\n // characters. Also make sure that there is data in the frame.", " if(frameID.size() != (version < 3 ? 3 : 4) ||\n header->frameSize() <= static_cast<unsigned int>(header->dataLengthIndicator() ? 4 : 0) ||\n header->frameSize() > data.size())\n {\n delete header;\n return 0;\n }", "#ifndef NO_ITUNES_HACKS\n if(version == 3 && frameID.size() == 4 && frameID[3] == '\\0') {\n // iTunes v2.3 tags store v2.2 frames - convert now\n frameID = frameID.mid(0, 3);\n header->setFrameID(frameID);\n header->setVersion(2);\n updateFrame(header);\n header->setVersion(3);\n }\n#endif", " for(ByteVector::ConstIterator it = frameID.begin(); it != frameID.end(); it++) {\n if( (*it < 'A' || *it > 'Z') && (*it < '0' || *it > '9') ) {\n delete header;\n return 0;\n }\n }", " if(version > 3 && (tagHeader->unsynchronisation() || header->unsynchronisation())) {\n // Data lengths are not part of the encoded data, but since they are synch-safe\n // integers they will be never actually encoded.\n ByteVector frameData = data.mid(Frame::Header::size(version), header->frameSize());\n frameData = SynchData::decode(frameData);\n data = data.mid(0, Frame::Header::size(version)) + frameData;\n }", " // TagLib doesn't mess with encrypted frames, so just treat them\n // as unknown frames.", " if(!zlib::isAvailable() && header->compression()) {\n debug(\"Compressed frames are currently not supported.\");\n return new UnknownFrame(data, header);\n }", " if(header->encryption()) {\n debug(\"Encrypted frames are currently not supported.\");\n return new UnknownFrame(data, header);\n }", " if(!updateFrame(header)) {\n header->setTagAlterPreservation(true);\n return new UnknownFrame(data, header);\n }", " // updateFrame() might have updated the frame ID.", " frameID = header->frameID();", " // This is where things get necissarily nasty. Here we determine which\n // Frame subclass (or if none is found simply an Frame) based\n // on the frame ID. Since there are a lot of possibilities, that means\n // a lot of if blocks.", " // Text Identification (frames 4.2)", " // Apple proprietary WFED (Podcast URL), MVNM (Movement Name), MVIN (Movement Number) are in fact text frames.\n if(frameID.startsWith(\"T\") || frameID == \"WFED\" || frameID == \"MVNM\" || frameID == \"MVIN\") {", " TextIdentificationFrame *f = frameID != \"TXXX\"\n ? new TextIdentificationFrame(data, header)\n : new UserTextIdentificationFrame(data, header);", " d->setTextEncoding(f);", " if(frameID == \"TCON\")\n updateGenre(f);", " return f;\n }", " // Comments (frames 4.10)", " if(frameID == \"COMM\") {\n CommentsFrame *f = new CommentsFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // Attached Picture (frames 4.14)", " if(frameID == \"APIC\") {\n AttachedPictureFrame *f = new AttachedPictureFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // ID3v2.2 Attached Picture", " if(frameID == \"PIC\") {\n AttachedPictureFrame *f = new AttachedPictureFrameV22(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // Relative Volume Adjustment (frames 4.11)", " if(frameID == \"RVA2\")\n return new RelativeVolumeFrame(data, header);", " // Unique File Identifier (frames 4.1)", " if(frameID == \"UFID\")\n return new UniqueFileIdentifierFrame(data, header);", " // General Encapsulated Object (frames 4.15)", " if(frameID == \"GEOB\") {\n GeneralEncapsulatedObjectFrame *f = new GeneralEncapsulatedObjectFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // URL link (frames 4.3)", " if(frameID.startsWith(\"W\")) {\n if(frameID != \"WXXX\") {\n return new UrlLinkFrame(data, header);\n }\n else {\n UserUrlLinkFrame *f = new UserUrlLinkFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }\n }", " // Unsynchronized lyric/text transcription (frames 4.8)", " if(frameID == \"USLT\") {\n UnsynchronizedLyricsFrame *f = new UnsynchronizedLyricsFrame(data, header);\n if(d->useDefaultEncoding)\n f->setTextEncoding(d->defaultEncoding);\n return f;\n }", " // Synchronised lyrics/text (frames 4.9)", " if(frameID == \"SYLT\") {\n SynchronizedLyricsFrame *f = new SynchronizedLyricsFrame(data, header);\n if(d->useDefaultEncoding)\n f->setTextEncoding(d->defaultEncoding);\n return f;\n }", " // Event timing codes (frames 4.5)", " if(frameID == \"ETCO\")\n return new EventTimingCodesFrame(data, header);", " // Popularimeter (frames 4.17)", " if(frameID == \"POPM\")\n return new PopularimeterFrame(data, header);", " // Private (frames 4.27)", " if(frameID == \"PRIV\")\n return new PrivateFrame(data, header);", " // Ownership (frames 4.22)", " if(frameID == \"OWNE\") {\n OwnershipFrame *f = new OwnershipFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // Chapter (ID3v2 chapters 1.0)", " if(frameID == \"CHAP\")\n return new ChapterFrame(tagHeader, data, header);", " // Table of contents (ID3v2 chapters 1.0)", " if(frameID == \"CTOC\")\n return new TableOfContentsFrame(tagHeader, data, header);", " // Apple proprietary PCST (Podcast)", " if(frameID == \"PCST\")\n return new PodcastFrame(data, header);", " return new UnknownFrame(data, header);\n}", "void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const\n{\n if(tag->header()->majorVersion() < 4 &&\n tag->frameList(\"TDRC\").size() == 1 &&\n tag->frameList(\"TDAT\").size() == 1)\n {\n TextIdentificationFrame *tdrc =", " static_cast<TextIdentificationFrame *>(tag->frameList(\"TDRC\").front());", " UnknownFrame *tdat = static_cast<UnknownFrame *>(tag->frameList(\"TDAT\").front());\n", " if(tdrc->fieldList().size() == 1 &&", " tdrc->fieldList().front().size() == 4 &&\n tdat->data().size() >= 5)\n {\n String date(tdat->data().mid(1), String::Type(tdat->data()[0]));\n if(date.length() == 4) {\n tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2));\n if(tag->frameList(\"TIME\").size() == 1) {\n UnknownFrame *timeframe = static_cast<UnknownFrame *>(tag->frameList(\"TIME\").front());\n if(timeframe->data().size() >= 5) {\n String time(timeframe->data().mid(1), String::Type(timeframe->data()[0]));\n if(time.length() == 4) {\n tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2));\n }\n }\n }\n }\n }\n }\n}", "String::Type FrameFactory::defaultTextEncoding() const\n{\n return d->defaultEncoding;\n}", "void FrameFactory::setDefaultTextEncoding(String::Type encoding)\n{\n d->useDefaultEncoding = true;\n d->defaultEncoding = encoding;\n}", "////////////////////////////////////////////////////////////////////////////////\n// protected members\n////////////////////////////////////////////////////////////////////////////////", "FrameFactory::FrameFactory() :\n d(new FrameFactoryPrivate())\n{\n}", "FrameFactory::~FrameFactory()\n{\n delete d;\n}", "namespace\n{\n // Frame conversion table ID3v2.2 -> 2.4\n const char *frameConversion2[][2] = {\n { \"BUF\", \"RBUF\" },\n { \"CNT\", \"PCNT\" },\n { \"COM\", \"COMM\" },\n { \"CRA\", \"AENC\" },\n { \"ETC\", \"ETCO\" },\n { \"GEO\", \"GEOB\" },\n { \"IPL\", \"TIPL\" },\n { \"MCI\", \"MCDI\" },\n { \"MLL\", \"MLLT\" },\n { \"POP\", \"POPM\" },\n { \"REV\", \"RVRB\" },\n { \"SLT\", \"SYLT\" },\n { \"STC\", \"SYTC\" },\n { \"TAL\", \"TALB\" },\n { \"TBP\", \"TBPM\" },\n { \"TCM\", \"TCOM\" },\n { \"TCO\", \"TCON\" },\n { \"TCP\", \"TCMP\" },\n { \"TCR\", \"TCOP\" },\n { \"TDY\", \"TDLY\" },\n { \"TEN\", \"TENC\" },\n { \"TFT\", \"TFLT\" },\n { \"TKE\", \"TKEY\" },\n { \"TLA\", \"TLAN\" },\n { \"TLE\", \"TLEN\" },\n { \"TMT\", \"TMED\" },\n { \"TOA\", \"TOAL\" },\n { \"TOF\", \"TOFN\" },\n { \"TOL\", \"TOLY\" },\n { \"TOR\", \"TDOR\" },\n { \"TOT\", \"TOAL\" },\n { \"TP1\", \"TPE1\" },\n { \"TP2\", \"TPE2\" },\n { \"TP3\", \"TPE3\" },\n { \"TP4\", \"TPE4\" },\n { \"TPA\", \"TPOS\" },\n { \"TPB\", \"TPUB\" },\n { \"TRC\", \"TSRC\" },\n { \"TRD\", \"TDRC\" },\n { \"TRK\", \"TRCK\" },\n { \"TS2\", \"TSO2\" },\n { \"TSA\", \"TSOA\" },\n { \"TSC\", \"TSOC\" },\n { \"TSP\", \"TSOP\" },\n { \"TSS\", \"TSSE\" },\n { \"TST\", \"TSOT\" },\n { \"TT1\", \"TIT1\" },\n { \"TT2\", \"TIT2\" },\n { \"TT3\", \"TIT3\" },\n { \"TXT\", \"TOLY\" },\n { \"TXX\", \"TXXX\" },\n { \"TYE\", \"TDRC\" },\n { \"UFI\", \"UFID\" },\n { \"ULT\", \"USLT\" },\n { \"WAF\", \"WOAF\" },\n { \"WAR\", \"WOAR\" },\n { \"WAS\", \"WOAS\" },\n { \"WCM\", \"WCOM\" },\n { \"WCP\", \"WCOP\" },\n { \"WPB\", \"WPUB\" },\n { \"WXX\", \"WXXX\" },", " // Apple iTunes nonstandard frames\n { \"PCS\", \"PCST\" },\n { \"TCT\", \"TCAT\" },\n { \"TDR\", \"TDRL\" },\n { \"TDS\", \"TDES\" },\n { \"TID\", \"TGID\" },\n { \"WFD\", \"WFED\" },\n { \"MVN\", \"MVNM\" },\n { \"MVI\", \"MVIN\" },\n };\n const size_t frameConversion2Size = sizeof(frameConversion2) / sizeof(frameConversion2[0]);", " // Frame conversion table ID3v2.3 -> 2.4\n const char *frameConversion3[][2] = {\n { \"TORY\", \"TDOR\" },\n { \"TYER\", \"TDRC\" },\n { \"IPLS\", \"TIPL\" },\n };\n const size_t frameConversion3Size = sizeof(frameConversion3) / sizeof(frameConversion3[0]);\n}", "bool FrameFactory::updateFrame(Frame::Header *header) const\n{\n const ByteVector frameID = header->frameID();", " switch(header->version()) {", " case 2: // ID3v2.2\n {\n if(frameID == \"CRM\" ||\n frameID == \"EQU\" ||\n frameID == \"LNK\" ||\n frameID == \"RVA\" ||\n frameID == \"TIM\" ||\n frameID == \"TSI\" ||\n frameID == \"TDA\")\n {\n debug(\"ID3v2.4 no longer supports the frame type \" + String(frameID) +\n \". It will be discarded from the tag.\");\n return false;\n }", " // ID3v2.2 only used 3 bytes for the frame ID, so we need to convert all of\n // the frames to their 4 byte ID3v2.4 equivalent.", " for(size_t i = 0; i < frameConversion2Size; ++i) {\n if(frameID == frameConversion2[i][0]) {\n header->setFrameID(frameConversion2[i][1]);\n break;\n }\n }", " break;\n }", " case 3: // ID3v2.3\n {\n if(frameID == \"EQUA\" ||\n frameID == \"RVAD\" ||\n frameID == \"TIME\" ||\n frameID == \"TRDA\" ||\n frameID == \"TSIZ\" ||\n frameID == \"TDAT\")\n {\n debug(\"ID3v2.4 no longer supports the frame type \" + String(frameID) +\n \". It will be discarded from the tag.\");\n return false;\n }", " for(size_t i = 0; i < frameConversion3Size; ++i) {\n if(frameID == frameConversion3[i][0]) {\n header->setFrameID(frameConversion3[i][1]);\n break;\n }\n }", " break;\n }", " default:", " // This should catch a typo that existed in TagLib up to and including\n // version 1.1 where TRDC was used for the year rather than TDRC.", " if(frameID == \"TRDC\")\n header->setFrameID(\"TDRC\");", " break;\n }", " return true;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [341], "buggy_code_start_loc": [337], "filenames": ["taglib/mpeg/id3v2/id3v2framefactory.cpp"], "fixing_code_end_loc": [342], "fixing_code_start_loc": [337], "message": "In TagLib 1.11.1, the rebuildAggregateFrames function in id3v2framefactory.cpp has a pointer to cast vulnerability, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted audio file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:taglib:taglib:1.11.1:*:*:*:*:*:*:*", "matchCriteriaId": "DFA80713-7FB3-4FBC-B1A8-D9B84913CA53", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In TagLib 1.11.1, the rebuildAggregateFrames function in id3v2framefactory.cpp has a pointer to cast vulnerability, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted audio file."}, {"lang": "es", "value": "En TagLib 1.11.1, la funci\u00f3n rebuildAggregateFrames en id3v2framefactory.cpp tiene una vulnerabilidad del tipo pointer to cast, que permite que atacantes remotos provoquen una denegaci\u00f3n de servicio u otro tipo de errores no especificados mediante un archivo de audio manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12678", "lastModified": "2021-10-18T12:11:54.023", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-08-08T01:34:00.080", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/taglib/taglib/commit/cb9f07d9dcd791b63e622da43f7b232adaec0a9a"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Vendor Advisory"], "url": "https://github.com/taglib/taglib/issues/829"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/taglib/taglib/pull/831"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/09/msg00020.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/taglib/taglib/commit/cb9f07d9dcd791b63e622da43f7b232adaec0a9a"}, "type": "CWE-434"}
294
Determine whether the {function_name} code is vulnerable or not.
[ "/***************************************************************************\n copyright : (C) 2002 - 2008 by Scott Wheeler\n email : wheeler@kde.org\n ***************************************************************************/", "/***************************************************************************\n * This library is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU Lesser General Public License version *\n * 2.1 as published by the Free Software Foundation. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *\n * 02110-1301 USA *\n * *\n * Alternatively, this file is available under the Mozilla Public *\n * License Version 1.1. You may obtain a copy of the License at *\n * http://www.mozilla.org/MPL/ *\n ***************************************************************************/", "#include <tdebug.h>\n#include <tzlib.h>", "#include \"id3v2framefactory.h\"\n#include \"id3v2synchdata.h\"\n#include \"id3v1genres.h\"", "#include \"frames/attachedpictureframe.h\"\n#include \"frames/commentsframe.h\"\n#include \"frames/relativevolumeframe.h\"\n#include \"frames/textidentificationframe.h\"\n#include \"frames/uniquefileidentifierframe.h\"\n#include \"frames/unknownframe.h\"\n#include \"frames/generalencapsulatedobjectframe.h\"\n#include \"frames/urllinkframe.h\"\n#include \"frames/unsynchronizedlyricsframe.h\"\n#include \"frames/popularimeterframe.h\"\n#include \"frames/privateframe.h\"\n#include \"frames/ownershipframe.h\"\n#include \"frames/synchronizedlyricsframe.h\"\n#include \"frames/eventtimingcodesframe.h\"\n#include \"frames/chapterframe.h\"\n#include \"frames/tableofcontentsframe.h\"\n#include \"frames/podcastframe.h\"", "using namespace TagLib;\nusing namespace ID3v2;", "namespace\n{\n void updateGenre(TextIdentificationFrame *frame)\n {\n StringList fields = frame->fieldList();\n StringList newfields;", " for(StringList::ConstIterator it = fields.begin(); it != fields.end(); ++it) {\n String s = *it;\n int end = s.find(\")\");", " if(s.startsWith(\"(\") && end > 0) {\n // \"(12)Genre\"\n String text = s.substr(end + 1);\n bool ok;\n int number = s.substr(1, end - 1).toInt(&ok);\n if(ok && number >= 0 && number <= 255 && !(ID3v1::genre(number) == text))\n newfields.append(s.substr(1, end - 1));\n if(!text.isEmpty())\n newfields.append(text);\n }\n else {\n // \"Genre\" or \"12\"\n newfields.append(s);\n }\n }", " if(newfields.isEmpty())\n fields.append(String());", " frame->setText(newfields);\n }\n}", "class FrameFactory::FrameFactoryPrivate\n{\npublic:\n FrameFactoryPrivate() :\n defaultEncoding(String::Latin1),\n useDefaultEncoding(false) {}", " String::Type defaultEncoding;\n bool useDefaultEncoding;", " template <class T> void setTextEncoding(T *frame)\n {\n if(useDefaultEncoding)\n frame->setTextEncoding(defaultEncoding);\n }\n};", "FrameFactory FrameFactory::factory;", "////////////////////////////////////////////////////////////////////////////////\n// public members\n////////////////////////////////////////////////////////////////////////////////", "FrameFactory *FrameFactory::instance()\n{\n return &factory;\n}", "Frame *FrameFactory::createFrame(const ByteVector &data, bool synchSafeInts) const\n{\n return createFrame(data, static_cast<unsigned int>(synchSafeInts ? 4 : 3));\n}", "Frame *FrameFactory::createFrame(const ByteVector &data, unsigned int version) const\n{\n Header tagHeader;\n tagHeader.setMajorVersion(version);\n return createFrame(data, &tagHeader);\n}", "Frame *FrameFactory::createFrame(const ByteVector &origData, Header *tagHeader) const\n{\n ByteVector data = origData;\n unsigned int version = tagHeader->majorVersion();\n Frame::Header *header = new Frame::Header(data, version);\n ByteVector frameID = header->frameID();", " // A quick sanity check -- make sure that the frameID is 4 uppercase Latin1\n // characters. Also make sure that there is data in the frame.", " if(frameID.size() != (version < 3 ? 3 : 4) ||\n header->frameSize() <= static_cast<unsigned int>(header->dataLengthIndicator() ? 4 : 0) ||\n header->frameSize() > data.size())\n {\n delete header;\n return 0;\n }", "#ifndef NO_ITUNES_HACKS\n if(version == 3 && frameID.size() == 4 && frameID[3] == '\\0') {\n // iTunes v2.3 tags store v2.2 frames - convert now\n frameID = frameID.mid(0, 3);\n header->setFrameID(frameID);\n header->setVersion(2);\n updateFrame(header);\n header->setVersion(3);\n }\n#endif", " for(ByteVector::ConstIterator it = frameID.begin(); it != frameID.end(); it++) {\n if( (*it < 'A' || *it > 'Z') && (*it < '0' || *it > '9') ) {\n delete header;\n return 0;\n }\n }", " if(version > 3 && (tagHeader->unsynchronisation() || header->unsynchronisation())) {\n // Data lengths are not part of the encoded data, but since they are synch-safe\n // integers they will be never actually encoded.\n ByteVector frameData = data.mid(Frame::Header::size(version), header->frameSize());\n frameData = SynchData::decode(frameData);\n data = data.mid(0, Frame::Header::size(version)) + frameData;\n }", " // TagLib doesn't mess with encrypted frames, so just treat them\n // as unknown frames.", " if(!zlib::isAvailable() && header->compression()) {\n debug(\"Compressed frames are currently not supported.\");\n return new UnknownFrame(data, header);\n }", " if(header->encryption()) {\n debug(\"Encrypted frames are currently not supported.\");\n return new UnknownFrame(data, header);\n }", " if(!updateFrame(header)) {\n header->setTagAlterPreservation(true);\n return new UnknownFrame(data, header);\n }", " // updateFrame() might have updated the frame ID.", " frameID = header->frameID();", " // This is where things get necissarily nasty. Here we determine which\n // Frame subclass (or if none is found simply an Frame) based\n // on the frame ID. Since there are a lot of possibilities, that means\n // a lot of if blocks.", " // Text Identification (frames 4.2)", " // Apple proprietary WFED (Podcast URL), MVNM (Movement Name), MVIN (Movement Number) are in fact text frames.\n if(frameID.startsWith(\"T\") || frameID == \"WFED\" || frameID == \"MVNM\" || frameID == \"MVIN\") {", " TextIdentificationFrame *f = frameID != \"TXXX\"\n ? new TextIdentificationFrame(data, header)\n : new UserTextIdentificationFrame(data, header);", " d->setTextEncoding(f);", " if(frameID == \"TCON\")\n updateGenre(f);", " return f;\n }", " // Comments (frames 4.10)", " if(frameID == \"COMM\") {\n CommentsFrame *f = new CommentsFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // Attached Picture (frames 4.14)", " if(frameID == \"APIC\") {\n AttachedPictureFrame *f = new AttachedPictureFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // ID3v2.2 Attached Picture", " if(frameID == \"PIC\") {\n AttachedPictureFrame *f = new AttachedPictureFrameV22(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // Relative Volume Adjustment (frames 4.11)", " if(frameID == \"RVA2\")\n return new RelativeVolumeFrame(data, header);", " // Unique File Identifier (frames 4.1)", " if(frameID == \"UFID\")\n return new UniqueFileIdentifierFrame(data, header);", " // General Encapsulated Object (frames 4.15)", " if(frameID == \"GEOB\") {\n GeneralEncapsulatedObjectFrame *f = new GeneralEncapsulatedObjectFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // URL link (frames 4.3)", " if(frameID.startsWith(\"W\")) {\n if(frameID != \"WXXX\") {\n return new UrlLinkFrame(data, header);\n }\n else {\n UserUrlLinkFrame *f = new UserUrlLinkFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }\n }", " // Unsynchronized lyric/text transcription (frames 4.8)", " if(frameID == \"USLT\") {\n UnsynchronizedLyricsFrame *f = new UnsynchronizedLyricsFrame(data, header);\n if(d->useDefaultEncoding)\n f->setTextEncoding(d->defaultEncoding);\n return f;\n }", " // Synchronised lyrics/text (frames 4.9)", " if(frameID == \"SYLT\") {\n SynchronizedLyricsFrame *f = new SynchronizedLyricsFrame(data, header);\n if(d->useDefaultEncoding)\n f->setTextEncoding(d->defaultEncoding);\n return f;\n }", " // Event timing codes (frames 4.5)", " if(frameID == \"ETCO\")\n return new EventTimingCodesFrame(data, header);", " // Popularimeter (frames 4.17)", " if(frameID == \"POPM\")\n return new PopularimeterFrame(data, header);", " // Private (frames 4.27)", " if(frameID == \"PRIV\")\n return new PrivateFrame(data, header);", " // Ownership (frames 4.22)", " if(frameID == \"OWNE\") {\n OwnershipFrame *f = new OwnershipFrame(data, header);\n d->setTextEncoding(f);\n return f;\n }", " // Chapter (ID3v2 chapters 1.0)", " if(frameID == \"CHAP\")\n return new ChapterFrame(tagHeader, data, header);", " // Table of contents (ID3v2 chapters 1.0)", " if(frameID == \"CTOC\")\n return new TableOfContentsFrame(tagHeader, data, header);", " // Apple proprietary PCST (Podcast)", " if(frameID == \"PCST\")\n return new PodcastFrame(data, header);", " return new UnknownFrame(data, header);\n}", "void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const\n{\n if(tag->header()->majorVersion() < 4 &&\n tag->frameList(\"TDRC\").size() == 1 &&\n tag->frameList(\"TDAT\").size() == 1)\n {\n TextIdentificationFrame *tdrc =", " dynamic_cast<TextIdentificationFrame *>(tag->frameList(\"TDRC\").front());", " UnknownFrame *tdat = static_cast<UnknownFrame *>(tag->frameList(\"TDAT\").front());\n", " if(tdrc &&\n tdrc->fieldList().size() == 1 &&", " tdrc->fieldList().front().size() == 4 &&\n tdat->data().size() >= 5)\n {\n String date(tdat->data().mid(1), String::Type(tdat->data()[0]));\n if(date.length() == 4) {\n tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2));\n if(tag->frameList(\"TIME\").size() == 1) {\n UnknownFrame *timeframe = static_cast<UnknownFrame *>(tag->frameList(\"TIME\").front());\n if(timeframe->data().size() >= 5) {\n String time(timeframe->data().mid(1), String::Type(timeframe->data()[0]));\n if(time.length() == 4) {\n tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2));\n }\n }\n }\n }\n }\n }\n}", "String::Type FrameFactory::defaultTextEncoding() const\n{\n return d->defaultEncoding;\n}", "void FrameFactory::setDefaultTextEncoding(String::Type encoding)\n{\n d->useDefaultEncoding = true;\n d->defaultEncoding = encoding;\n}", "////////////////////////////////////////////////////////////////////////////////\n// protected members\n////////////////////////////////////////////////////////////////////////////////", "FrameFactory::FrameFactory() :\n d(new FrameFactoryPrivate())\n{\n}", "FrameFactory::~FrameFactory()\n{\n delete d;\n}", "namespace\n{\n // Frame conversion table ID3v2.2 -> 2.4\n const char *frameConversion2[][2] = {\n { \"BUF\", \"RBUF\" },\n { \"CNT\", \"PCNT\" },\n { \"COM\", \"COMM\" },\n { \"CRA\", \"AENC\" },\n { \"ETC\", \"ETCO\" },\n { \"GEO\", \"GEOB\" },\n { \"IPL\", \"TIPL\" },\n { \"MCI\", \"MCDI\" },\n { \"MLL\", \"MLLT\" },\n { \"POP\", \"POPM\" },\n { \"REV\", \"RVRB\" },\n { \"SLT\", \"SYLT\" },\n { \"STC\", \"SYTC\" },\n { \"TAL\", \"TALB\" },\n { \"TBP\", \"TBPM\" },\n { \"TCM\", \"TCOM\" },\n { \"TCO\", \"TCON\" },\n { \"TCP\", \"TCMP\" },\n { \"TCR\", \"TCOP\" },\n { \"TDY\", \"TDLY\" },\n { \"TEN\", \"TENC\" },\n { \"TFT\", \"TFLT\" },\n { \"TKE\", \"TKEY\" },\n { \"TLA\", \"TLAN\" },\n { \"TLE\", \"TLEN\" },\n { \"TMT\", \"TMED\" },\n { \"TOA\", \"TOAL\" },\n { \"TOF\", \"TOFN\" },\n { \"TOL\", \"TOLY\" },\n { \"TOR\", \"TDOR\" },\n { \"TOT\", \"TOAL\" },\n { \"TP1\", \"TPE1\" },\n { \"TP2\", \"TPE2\" },\n { \"TP3\", \"TPE3\" },\n { \"TP4\", \"TPE4\" },\n { \"TPA\", \"TPOS\" },\n { \"TPB\", \"TPUB\" },\n { \"TRC\", \"TSRC\" },\n { \"TRD\", \"TDRC\" },\n { \"TRK\", \"TRCK\" },\n { \"TS2\", \"TSO2\" },\n { \"TSA\", \"TSOA\" },\n { \"TSC\", \"TSOC\" },\n { \"TSP\", \"TSOP\" },\n { \"TSS\", \"TSSE\" },\n { \"TST\", \"TSOT\" },\n { \"TT1\", \"TIT1\" },\n { \"TT2\", \"TIT2\" },\n { \"TT3\", \"TIT3\" },\n { \"TXT\", \"TOLY\" },\n { \"TXX\", \"TXXX\" },\n { \"TYE\", \"TDRC\" },\n { \"UFI\", \"UFID\" },\n { \"ULT\", \"USLT\" },\n { \"WAF\", \"WOAF\" },\n { \"WAR\", \"WOAR\" },\n { \"WAS\", \"WOAS\" },\n { \"WCM\", \"WCOM\" },\n { \"WCP\", \"WCOP\" },\n { \"WPB\", \"WPUB\" },\n { \"WXX\", \"WXXX\" },", " // Apple iTunes nonstandard frames\n { \"PCS\", \"PCST\" },\n { \"TCT\", \"TCAT\" },\n { \"TDR\", \"TDRL\" },\n { \"TDS\", \"TDES\" },\n { \"TID\", \"TGID\" },\n { \"WFD\", \"WFED\" },\n { \"MVN\", \"MVNM\" },\n { \"MVI\", \"MVIN\" },\n };\n const size_t frameConversion2Size = sizeof(frameConversion2) / sizeof(frameConversion2[0]);", " // Frame conversion table ID3v2.3 -> 2.4\n const char *frameConversion3[][2] = {\n { \"TORY\", \"TDOR\" },\n { \"TYER\", \"TDRC\" },\n { \"IPLS\", \"TIPL\" },\n };\n const size_t frameConversion3Size = sizeof(frameConversion3) / sizeof(frameConversion3[0]);\n}", "bool FrameFactory::updateFrame(Frame::Header *header) const\n{\n const ByteVector frameID = header->frameID();", " switch(header->version()) {", " case 2: // ID3v2.2\n {\n if(frameID == \"CRM\" ||\n frameID == \"EQU\" ||\n frameID == \"LNK\" ||\n frameID == \"RVA\" ||\n frameID == \"TIM\" ||\n frameID == \"TSI\" ||\n frameID == \"TDA\")\n {\n debug(\"ID3v2.4 no longer supports the frame type \" + String(frameID) +\n \". It will be discarded from the tag.\");\n return false;\n }", " // ID3v2.2 only used 3 bytes for the frame ID, so we need to convert all of\n // the frames to their 4 byte ID3v2.4 equivalent.", " for(size_t i = 0; i < frameConversion2Size; ++i) {\n if(frameID == frameConversion2[i][0]) {\n header->setFrameID(frameConversion2[i][1]);\n break;\n }\n }", " break;\n }", " case 3: // ID3v2.3\n {\n if(frameID == \"EQUA\" ||\n frameID == \"RVAD\" ||\n frameID == \"TIME\" ||\n frameID == \"TRDA\" ||\n frameID == \"TSIZ\" ||\n frameID == \"TDAT\")\n {\n debug(\"ID3v2.4 no longer supports the frame type \" + String(frameID) +\n \". It will be discarded from the tag.\");\n return false;\n }", " for(size_t i = 0; i < frameConversion3Size; ++i) {\n if(frameID == frameConversion3[i][0]) {\n header->setFrameID(frameConversion3[i][1]);\n break;\n }\n }", " break;\n }", " default:", " // This should catch a typo that existed in TagLib up to and including\n // version 1.1 where TRDC was used for the year rather than TDRC.", " if(frameID == \"TRDC\")\n header->setFrameID(\"TDRC\");", " break;\n }", " return true;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [341], "buggy_code_start_loc": [337], "filenames": ["taglib/mpeg/id3v2/id3v2framefactory.cpp"], "fixing_code_end_loc": [342], "fixing_code_start_loc": [337], "message": "In TagLib 1.11.1, the rebuildAggregateFrames function in id3v2framefactory.cpp has a pointer to cast vulnerability, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted audio file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:taglib:taglib:1.11.1:*:*:*:*:*:*:*", "matchCriteriaId": "DFA80713-7FB3-4FBC-B1A8-D9B84913CA53", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In TagLib 1.11.1, the rebuildAggregateFrames function in id3v2framefactory.cpp has a pointer to cast vulnerability, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted audio file."}, {"lang": "es", "value": "En TagLib 1.11.1, la funci\u00f3n rebuildAggregateFrames en id3v2framefactory.cpp tiene una vulnerabilidad del tipo pointer to cast, que permite que atacantes remotos provoquen una denegaci\u00f3n de servicio u otro tipo de errores no especificados mediante un archivo de audio manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12678", "lastModified": "2021-10-18T12:11:54.023", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-08-08T01:34:00.080", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/taglib/taglib/commit/cb9f07d9dcd791b63e622da43f7b232adaec0a9a"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Vendor Advisory"], "url": "https://github.com/taglib/taglib/issues/829"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/taglib/taglib/pull/831"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/09/msg00020.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/taglib/taglib/commit/cb9f07d9dcd791b63e622da43f7b232adaec0a9a"}, "type": "CWE-434"}
294
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ownCloud\n *\n * @author Tom Needham\n * @copyright 2012 Tom Needham tom@owncloud.com\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n * License as published by the Free Software Foundation; either\n * version 3 of the License, or any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n */", "\n/**\n * provides an interface to migrate users and whole ownclouds\n */\nclass OC_Migrate{", "\n\t// Array of OC_Migration_Provider objects\n\tstatic private $providers=array();\n\t// User id of the user to import/export\n\tstatic private $uid=false;\n\t// Holds the ZipArchive object\n\tstatic private $zip=false;\n\t// Stores the type of export\n\tstatic private $exporttype=false;\n\t// Array of temp files to be deleted after zip creation\n\tstatic private $tmpfiles=array();\n\t// Holds the db object\n\tstatic private $MDB2=false;\n\t// Schema db object\n\tstatic private $schema=false;\n\t// Path to the sqlite db\n\tstatic private $dbpath=false;\n\t// Holds the path to the zip file\n\tstatic private $zippath=false;\n\t// Holds the OC_Migration_Content object\n\tstatic private $content=false;", "\t/**\n\t * register a new migration provider\n\t * @param OC_Migrate_Provider $provider\n\t */\n\tpublic static function registerProvider($provider){\n\t\tself::$providers[]=$provider;\n\t}", "\t/**\n\t* @brief finds and loads the providers\n\t*/\n\tstatic private function findProviders(){\n\t\t// Find the providers\n\t\t$apps = OC_App::getAllApps();", "\t\tforeach($apps as $app){\n\t\t\t$path = OC::$SERVERROOT . '/apps/' . $app . '/appinfo/migrate.php';\n\t\t\tif( file_exists( $path ) ){\n\t\t\t\tinclude( $path );\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * @brief exports a user, or owncloud instance\n\t * @param optional $uid string user id of user to export if export type is user, defaults to current\n\t * @param ootional $type string type of export, defualts to user\n\t * @param otional $path string path to zip output folder\n\t * @return false on error, path to zip on success\n\t */\n\t public static function export( $uid=null, $type='user', $path=null ){\n\t\t$datadir = OC_Config::getValue( 'datadirectory' );\n\t \t// Validate export type\n\t \t$types = array( 'user', 'instance', 'system', 'userfiles' );\n\t \tif( !in_array( $type, $types ) ){\n\t \t\tOC_Log::write( 'migration', 'Invalid export type', OC_Log::ERROR );\n\t \t\treturn json_encode( array( array( 'success' => false ) ) );\n\t \t}\n\t \tself::$exporttype = $type;\n\t \t// Userid?\n\t \tif( self::$exporttype == 'user' ){\n\t \t\t// Check user exists\n\t \t\tif( !is_null($uid) ){\n $db = new OC_User_Database;\n\t\t \t\tif( !$db->userExists( $uid ) ){\n\t\t\t\t\tOC_Log::write('migration', 'User: '.$uid.' is not in the database and so cannot be exported.', OC_Log::ERROR);\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\tself::$uid = $uid;\n\t \t\t} else {\n\t \t\t\tself::$uid = OC_User::getUser();\n\t \t\t}\n\t \t}\n\t \t// Calculate zipname\n\t \tif( self::$exporttype == 'user' ){\n\t \t\t$zipname = 'oc_export_' . self::$uid . '_' . date(\"y-m-d_H-i-s\") . '.zip';\n\t \t} else {\n\t \t\t$zipname = 'oc_export_' . self::$exporttype . '_' . date(\"y-m-d_H-i-s\") . '.zip';\n\t \t}\n\t \t// Calculate path\n\t \tif( self::$exporttype == 'user' ){\n\t \t\tself::$zippath = $datadir . '/' . self::$uid . '/' . $zipname;\n\t \t} else {\n\t \t\tif( !is_null( $path ) ){\n\t \t\t\t// Validate custom path\n\t \t\t\tif( !file_exists( $path ) || !is_writeable( $path ) ){\n\t \t\t\t\tOC_Log::write( 'migration', 'Path supplied is invalid.', OC_Log::ERROR );\n\t \t\t\t\treturn json_encode( array( 'success' => false ) );\n\t \t\t\t}\n\t \t\t\tself::$zippath = $path . $zipname;\n\t \t\t} else {\n\t \t\t\t// Default path\n\t \t\t\tself::$zippath = get_temp_dir() . '/' . $zipname;\n\t \t\t}\n\t \t}\n\t \t// Create the zip object\n\t \tif( !self::createZip() ){\n\t \t\treturn json_encode( array( 'success' => false ) );\n\t \t}\n\t \t// Do the export\n\t \tself::findProviders();\n\t \t$exportdata = array();\n\t \tswitch( self::$exporttype ){\n\t \t\tcase 'user':\n\t \t\t\t// Connect to the db\n\t \t\t\tself::$dbpath = $datadir . '/' . self::$uid . '/migration.db';\n\t \t\t\tif( !self::connectDB() ){\n\t \t\t\t\treturn json_encode( array( 'success' => false ) );\n\t \t\t\t}\n\t \t\t\tself::$content = new OC_Migration_Content( self::$zip, self::$MDB2 );\n\t \t\t\t// Export the app info\n\t\t\t $exportdata = self::exportAppData();\n\t\t\t\t// Add the data dir to the zip\n\t\t\t\tself::$content->addDir( $datadir . '/' . self::$uid, true, '/' );\n\t \t\tbreak;\n\t \t\tcase 'instance':\n\t \t\t\tself::$content = new OC_Migration_Content( self::$zip );\n\t\t\t\t// Creates a zip that is compatable with the import function\n\t\t\t\t$dbfile = tempnam( get_temp_dir(), \"owncloud_export_data_\" );\n\t\t\t\tOC_DB::getDbStructure( $dbfile, 'MDB2_SCHEMA_DUMP_ALL');", "\t\t\t\t// Now add in *dbname* and *dbprefix*\n\t\t\t\t$dbexport = file_get_contents( $dbfile );\n\t\t\t\t$dbnamestring = \"<database>\\n\\n <name>\" . OC_Config::getValue( \"dbname\", \"owncloud\" );\n\t\t\t\t$dbtableprefixstring = \"<table>\\n\\n <name>\" . OC_Config::getValue( \"dbtableprefix\", \"oc_\" );\n\t\t\t\t$dbexport = str_replace( $dbnamestring, \"<database>\\n\\n <name>*dbname*\", $dbexport );\n\t\t\t\t$dbexport = str_replace( $dbtableprefixstring, \"<table>\\n\\n <name>*dbprefix*\", $dbexport );\n\t\t\t\t// Add the export to the zip\n\t\t\t\tself::$content->addFromString( $dbexport, \"dbexport.xml\" );\n\t\t\t\t// Add user data\n\t\t\t\tforeach(OC_User::getUsers() as $user){\n\t\t\t\t\tself::$content->addDir( $datadir . '/' . $user . '/', true, \"/userdata/\" );\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tcase 'userfiles':\n\t\t\t\tself::$content = new OC_Migration_Content( self::$zip );\n\t\t\t\t// Creates a zip with all of the users files\n\t\t\t\tforeach(OC_User::getUsers() as $user){\n\t\t\t\t\tself::$content->addDir( $datadir . '/' . $user . '/', true, \"/\" );\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tcase 'system':\n\t\t\t\tself::$content = new OC_Migration_Content( self::$zip );\n\t\t\t\t// Creates a zip with the owncloud system files\n\t\t\t\tself::$content->addDir( OC::$SERVERROOT . '/', false, '/');\n\t\t\t\tforeach (array(\".git\", \"3rdparty\", \"apps\", \"core\", \"files\", \"l10n\", \"lib\", \"ocs\", \"search\", \"settings\", \"tests\") as $dir) {\n\t\t\t \tself::$content->addDir( OC::$SERVERROOT . '/' . $dir, true, \"/\");\n\t\t\t\t}\n\t\t\tbreak;\n\t \t}\n\t \tif( !$info = self::getExportInfo( $exportdata ) ){\n\t \t\treturn json_encode( array( 'success' => false ) );\n\t \t}\n\t \t// Add the export info json to the export zip\n\t \tself::$content->addFromString( $info, 'export_info.json' );\n\t \tif( !self::$content->finish() ){\n\t \t\treturn json_encode( array( 'success' => false ) );\n\t \t}\n\t \treturn json_encode( array( 'success' => true, 'data' => self::$zippath ) );\n\t }", "\t/**\n\t* @brief imports a user, or owncloud instance\n\t* @param $path string path to zip\n\t* @param optional $type type of import (user or instance)\n\t* @param optional $uid userid of new user\n\t*/\n\tpublic static function import( $path, $type='user', $uid=null ){\n\t\t\n\t\t$datadir = OC_Config::getValue( 'datadirectory' );\n\t\t// Extract the zip\n\t\tif( !$extractpath = self::extractZip( $path ) ){\n\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t}\n\t\t// Get export_info.json\n\t\t$scan = scandir( $extractpath );\n\t\t// Check for export_info.json\n\t\tif( !in_array( 'export_info.json', $scan ) ){\n\t\t\tOC_Log::write( 'migration', 'Invalid import file, export_info.json note found', OC_Log::ERROR );\n\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t}\n\t\t$json = json_decode( file_get_contents( $extractpath . 'export_info.json' ) );\n\t\tif( $json->exporttype != $type ){\n\t\t\tOC_Log::write( 'migration', 'Invalid import file', OC_Log::ERROR );\n\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t}\n\t\tself::$exporttype = $type;", "\t\t$currentuser = OC_User::getUser();", "\t\t// Have we got a user if type is user\n\t\tif( self::$exporttype == 'user' ){\n\t\t\tself::$uid = !is_null($uid) ? $uid : $currentuser;\n\t\t}\n\t\t\n\t\t// We need to be an admin if we are not importing our own data\n\t\tif(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ){\n\t\t\tif( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){\n\t\t\t\t// Naughty.\n\t\t\t\tOC_Log::write( 'migration', 'Import not permitted.', OC_Log::ERROR );\n\t\t\t\treturn json_encode( array( 'success' => false ) ); \t\n\t\t\t}\n\t\t}", "\t\t// Handle export types\n\t\tswitch( self::$exporttype ){\n\t\t\tcase 'user':\n\t\t\t\t// Check user availability\n\t\t\t\tif( !OC_User::userExists( self::$uid ) ){\n\t\t\t\t\tOC_Log::write( 'migration', 'User doesn\\'t exist', OC_Log::ERROR );\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\t// Copy data\n\t\t\t\tif( !self::copy_r( $extractpath . $json->exporteduser, $datadir . '/' . self::$uid ) ){\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\t// Import user app data\n\t\t\t\tif( !$appsimported = self::importAppData( $extractpath . $json->exporteduser . '/migration.db', $json, self::$uid ) ){\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\t// All done!\n\t\t\t\tif( !self::unlink_r( $extractpath ) ){\n\t\t\t\t\tOC_Log::write( 'migration', 'Failed to delete the extracted zip', OC_Log::ERROR );\n\t\t\t\t}\n\t\t\t\treturn json_encode( array( 'success' => true, 'data' => $appsimported ) );\n\t\t\tbreak;\n\t\t\tcase 'instance':\n\t\t\t\t\t/*\n\t\t\t\t\t * EXPERIMENTAL\n\t\t\t\t\t// Check for new data dir and dbexport before doing anything\n\t\t\t\t\t// TODO", "\t\t\t\t\t// Delete current data folder.\n\t\t\t\t\tOC_Log::write( 'migration', \"Deleting current data dir\", OC_Log::INFO );\n\t\t\t\t\tif( !self::unlink_r( $datadir, false ) ){\n\t\t\t\t\t\tOC_Log::write( 'migration', 'Failed to delete the current data dir', OC_Log::ERROR );\n\t\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t\t}", "\t\t\t\t\t// Copy over data\n\t\t\t\t\tif( !self::copy_r( $extractpath . 'userdata', $datadir ) ){\n\t\t\t\t\t\tOC_Log::write( 'migration', 'Failed to copy over data directory', OC_Log::ERROR );\n\t\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t\t}", "\t\t\t\t\t// Import the db\n\t\t\t\t\tif( !OC_DB::replaceDB( $extractpath . 'dbexport.xml' ) ){\n\t\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t\t}\n\t\t\t\t\t// Done\n\t\t\t\t\treturn json_encode( 'success' => true );\n\t\t\t\t\t*/\n\t\t\tbreak;\n\t\t}", "\t}", "\t/**\n\t* @brief recursively deletes a directory\n\t* @param $dir string path of dir to delete\n\t* $param optional $deleteRootToo bool delete the root directory\n\t* @return bool\n\t*/\n\tprivate static function unlink_r( $dir, $deleteRootToo=true ){\n\t\tif( !$dh = @opendir( $dir ) ){\n\t\t\treturn false;\n\t\t}\n\t\twhile (false !== ($obj = readdir($dh))){\n\t\t\tif($obj == '.' || $obj == '..') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!@unlink($dir . '/' . $obj)){\n\t\t\t\tself::unlink_r($dir.'/'.$obj, true);\n\t\t\t}\n\t\t}\n\t\tclosedir($dh);\n\t\tif ( $deleteRootToo ) {\n\t\t\t@rmdir($dir);\n\t\t}\n\t\treturn true;\n\t}", "\t/**\n\t* @brief copies recursively\n\t* @param $path string path to source folder\n\t* @param $dest string path to destination\n\t* @return bool\n\t*/\n\tprivate static function copy_r( $path, $dest ){\n\t\tif( is_dir($path) ){\n\t\t\t@mkdir( $dest );\n\t\t\t$objects = scandir( $path );\n\t\t\tif( sizeof( $objects ) > 0 ){\n\t\t\t\tforeach( $objects as $file ){", "\t\t\t\t\tif( $file == \".\" || $file == \"..\" )", "\t\t\t\t\tcontinue;\n\t\t\t\t\t// go on\n\t\t\t\t\tif( is_dir( $path . '/' . $file ) ){\n\t\t\t\t\t\tself::copy_r( $path .'/' . $file, $dest . '/' . $file );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcopy( $path . '/' . $file, $dest . '/' . $file );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\telseif( is_file( $path ) ){\n\t\t\treturn copy( $path, $dest );\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "\t/**\n\t* @brief tries to extract the import zip\n\t* @param $path string path to the zip\n\t* @return string path to extract location (with a trailing slash) or false on failure\n\t*/\n\tstatic private function extractZip( $path ){\n\t\tself::$zip = new ZipArchive;\n\t\t// Validate path\n\t \tif( !file_exists( $path ) ){\n\t \t\tOC_Log::write( 'migration', 'Zip not found', OC_Log::ERROR );\n\t \t\treturn false;\n\t \t}\n\t\tif ( self::$zip->open( $path ) != TRUE ) {\n\t\t\tOC_Log::write( 'migration', \"Failed to open zip file\", OC_Log::ERROR );\n\t\t\treturn false;\n\t\t}\n\t\t$to = get_temp_dir() . '/oc_import_' . self::$exporttype . '_' . date(\"y-m-d_H-i-s\") . '/';\n\t\tif( !self::$zip->extractTo( $to ) ){\n\t\t\treturn false;\n\t\t}\n\t\tself::$zip->close();\n\t\treturn $to;\n\t}", "\t/**\n\t * @brief connects to a MDB2 database scheme\n\t * @returns bool\n\t */\n\tstatic private function connectScheme(){\n\t\t// We need a mdb2 database connection\n\t\tself::$MDB2->loadModule( 'Manager' );\n\t\tself::$MDB2->loadModule( 'Reverse' );", "\t\t// Connect if this did not happen before\n\t\tif( !self::$schema ){\n\t\t\trequire_once('MDB2/Schema.php');\n\t\t\tself::$schema=MDB2_Schema::factory( self::$MDB2 );\n\t\t}", "\t\treturn true;\n\t}", "\t/**\n\t * @brief creates a migration.db in the users data dir with their app data in\n\t * @return bool whether operation was successfull\n\t */\n\tprivate static function exportAppData( ){", "\t\t$success = true;\n\t\t$return = array();", "\t\t// Foreach provider\n\t\tforeach( self::$providers as $provider ){\n\t\t\t// Check if the app is enabled\n\t\t\tif( OC_App::isEnabled( $provider->getID() ) ){\n\t\t\t\t$success = true;\n\t\t\t\t// Does this app use the database?\n\t\t\t\tif( file_exists( OC::$SERVERROOT.'/apps/'.$provider->getID().'/appinfo/database.xml' ) ){\n\t\t\t\t\t// Create some app tables\n\t\t\t\t\t$tables = self::createAppTables( $provider->getID() );\n\t\t\t\t\tif( is_array( $tables ) ){\n\t\t\t\t\t\t// Save the table names\n\t\t\t\t\t\tforeach($tables as $table){\n\t\t\t\t\t\t\t$return['apps'][$provider->getID()]['tables'][] = $table;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// It failed to create the tables\n\t\t\t\t\t\t$success = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Run the export function?\n\t\t\t\tif( $success ){\n\t\t\t\t\t// Set the provider properties\n\t\t\t\t\t$provider->setData( self::$uid, self::$content );\n\t\t\t\t\t$return['apps'][$provider->getID()]['success'] = $provider->export();\n\t\t\t\t} else {\n\t\t\t\t\t$return['apps'][$provider->getID()]['success'] = false;\n\t\t\t\t\t$return['apps'][$provider->getID()]['message'] = 'failed to create the app tables';\n\t\t\t\t}\n\t\n\t\t\t\t// Now add some app info the the return array\n\t\t\t\t$appinfo = OC_App::getAppInfo( $provider->getID() );\n\t\t\t\t$return['apps'][$provider->getID()]['version'] = OC_App::getAppVersion($provider->getID());\n\t\t\t}\n\t\t}", "\t\treturn $return;", "\t}", "\n\t/**\n\t * @brief generates json containing export info, and merges any data supplied\n\t * @param optional $array array of data to include in the returned json\n\t * @return bool\n\t */\n\tstatic private function getExportInfo( $array=array() ){\n\t\t$info = array(\n\t\t\t\t\t\t'ocversion' => OC_Util::getVersion(),\n\t\t\t\t\t\t'exporttime' => time(),\n\t\t\t\t\t\t'exportedby' => OC_User::getUser(),\n\t\t\t\t\t\t'exporttype' => self::$exporttype\n\t\t\t\t\t);\n\t\t// Add hash if user export\n\t\tif( self::$exporttype == 'user' ){\n\t\t\t$query = OC_DB::prepare( \"SELECT password FROM *PREFIX*users WHERE uid = ?\" );\n\t\t\t$result = $query->execute( array( self::$uid ) );\n\t\t\t$row = $result->fetchRow();\n\t\t\t$hash = $row ? $row['password'] : false;\n\t\t\tif( !$hash ){\n\t\t\t\tOC_Log::write( 'migration', 'Failed to get the users password hash', OC_log::ERROR);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t$info['hash'] = $hash;\n\t\t\t$info['exporteduser'] = self::$uid;\n\t\t}\n\t\tif( !is_array( $array ) ){\n\t\t\tOC_Log::write( 'migration', 'Supplied $array was not an array in getExportInfo()', OC_Log::ERROR );\n\t\t}\n\t\t// Merge in other data\n\t\t$info = array_merge( $info, (array)$array );\n\t\t// Create json\n\t\t$json = json_encode( $info );\n\t\treturn $json;\n\t}", "\t/**\n\t * @brief connects to migration.db, or creates if not found\n\t * @param $db optional path to migration.db, defaults to user data dir\n\t * @return bool whether the operation was successful\n\t */\n\tstatic private function connectDB( $path=null ){\n\t\t// Has the dbpath been set?\n\t\tself::$dbpath = !is_null( $path ) ? $path : self::$dbpath;\n\t\tif( !self::$dbpath ){\n\t\t\tOC_Log::write( 'migration', 'connectDB() was called without dbpath being set', OC_Log::ERROR );\n\t\t\treturn false;\n\t\t}\n\t\t// Already connected\n\t\tif(!self::$MDB2){\n\t\t\trequire_once('MDB2.php');", "\t\t\t$datadir = OC_Config::getValue( \"datadirectory\", OC::$SERVERROOT.\"/data\" );", "\t\t\t// DB type\n\t\t\tif( class_exists( 'SQLite3' ) ){\n\t\t\t\t$dbtype = 'sqlite3';\n\t\t\t} else if( is_callable( 'sqlite_open' ) ){\n\t\t\t\t$dbtype = 'sqlite';\n\t\t\t} else {\n\t\t\t\tOC_Log::write( 'migration', 'SQLite not found', OC_Log::ERROR );\n\t\t\t\treturn false;\n\t\t\t}", "\t\t\t// Prepare options array\n\t\t\t$options = array(\n\t\t\t\t'portability' => MDB2_PORTABILITY_ALL & (!MDB2_PORTABILITY_FIX_CASE),\n\t\t\t\t'log_line_break' => '<br>',\n\t\t\t\t'idxname_format' => '%s',\n\t\t\t\t'debug' => true,\n\t\t\t\t'quote_identifier' => true\n\t\t\t\t);\n\t\t\t$dsn = array(\n\t\t\t\t'phptype' => $dbtype,\n\t\t\t\t'database' => self::$dbpath,\n\t\t\t\t'mode' => '0644'\n\t\t\t);", "\t\t\t// Try to establish connection\n\t\t\tself::$MDB2 = MDB2::factory( $dsn, $options );\n\t\t\t// Die if we could not connect\n\t\t\tif( PEAR::isError( self::$MDB2 ) ){\n\t\t\t\tdie( self::$MDB2->getMessage() );\n\t\t\t\tOC_Log::write( 'migration', 'Failed to create/connect to migration.db', OC_Log::FATAL );\n\t\t\t\tOC_Log::write( 'migration', self::$MDB2->getUserInfo(), OC_Log::FATAL );\n\t\t\t\tOC_Log::write( 'migration', self::$MDB2->getMessage(), OC_Log::FATAL );\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// We always, really always want associative arrays\n\t\t\tself::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC);\n\t\t}\n\t\treturn true;", "\t}", "\t/**\n\t * @brief creates the tables in migration.db from an apps database.xml\n\t * @param $appid string id of the app\n\t * @return bool whether the operation was successful\n\t */\n\tstatic private function createAppTables( $appid ){", "\t\tif( !self::connectScheme() ){\n\t\t\treturn false;\n\t\t}", "\t\t// There is a database.xml file\n\t\t$content = file_get_contents( OC::$SERVERROOT . '/apps/' . $appid . '/appinfo/database.xml' );", "\t\t$file2 = 'static://db_scheme';\n\t\t// TODO get the relative path to migration.db from the data dir\n\t\t// For now just cheat\n\t\t$path = pathinfo( self::$dbpath );\n\t\t$content = str_replace( '*dbname*', self::$uid.'/migration', $content );\n\t\t$content = str_replace( '*dbprefix*', '', $content );", "\t\t$xml = new SimpleXMLElement($content);\n\t\tforeach($xml->table as $table){\n\t\t\t$tables[] = (string)$table->name;\n\t\t}", "\t\tfile_put_contents( $file2, $content );", "\t\t// Try to create tables\n\t\t$definition = self::$schema->parseDatabaseDefinitionFile( $file2 );", "\t\tunlink( $file2 );", "\t\t// Die in case something went wrong\n\t\tif( $definition instanceof MDB2_Schema_Error ){\n\t\t\tOC_Log::write( 'migration', 'Failed to parse database.xml for: '.$appid, OC_Log::FATAL );\n\t\t\tOC_Log::write( 'migration', $definition->getMessage().': '.$definition->getUserInfo(), OC_Log::FATAL );\n\t\t\treturn false;\n\t\t}", "\t\t$definition['overwrite'] = true;", "\t\t$ret = self::$schema->createDatabase( $definition );", "\t\t// Die in case something went wrong\n\t\tif( $ret instanceof MDB2_Error ){\n\t\t\tOC_Log::write( 'migration', 'Failed to create tables for: '.$appid, OC_Log::FATAL );\n\t\t\tOC_Log::write( 'migration', $ret->getMessage().': '.$ret->getUserInfo(), OC_Log::FATAL );\n\t\t\treturn false;\n\t\t}\n\t\treturn $tables;", "\t}", "\t/**\n\t* @brief tries to create the zip\n\t* @param $path string path to zip destination\n\t* @return bool\n\t*/\n\tstatic private function createZip(){\n\t\tself::$zip = new ZipArchive;\n\t\t// Check if properties are set\n\t\tif( !self::$zippath ){\n\t\t\tOC_Log::write('migration', 'createZip() called but $zip and/or $zippath have not been set', OC_Log::ERROR);\n\t\t\treturn false;\n\t\t}\n\t\tif ( self::$zip->open( self::$zippath, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE ) !== TRUE ) {\n\t\t\tOC_Log::write('migration', 'Failed to create the zip with error: '.self::$zip->getStatusString(), OC_Log::ERROR);\n\t\t\treturn false;\n\t } else {\n\t \treturn true;\n\t }\n\t}", "\t/**\n\t* @brief returns an array of apps that support migration\n\t* @return array\n\t*/\n\tstatic public function getApps(){\n\t\t$allapps = OC_App::getAllApps();\n\t\tforeach($allapps as $app){\n\t\t\t$path = OC::$SERVERROOT . '/apps/' . $app . '/lib/migrate.php';\n\t\t\tif( file_exists( $path ) ){\n\t\t\t\t$supportsmigration[] = $app;\n\t\t\t}\n\t\t}\n\t\treturn $supportsmigration;\n\t}", "\t/**\n\t* @brief imports a new user\n\t* @param $db string path to migration.db\n\t* @param $info object of migration info\n\t* @param $uid optional uid to use\n\t* @return array of apps with import statuses, or false on failure.\n\t*/\n\tpublic static function importAppData( $db, $info, $uid=null ){\n\t\t// Check if the db exists\n\t\tif( file_exists( $db ) ){\n\t\t\t// Connect to the db\n\t\t\tif(!self::connectDB( $db )){\n\t\t\t\tOC_Log::write('migration','Failed to connect to migration.db',OC_Log::ERROR);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tOC_Log::write('migration','Migration.db not found at: '.$db, OC_Log::FATAL );\n\t\t\treturn false;\n\t\t}", "\t\t// Find providers\n\t\tself::findProviders();", "\t\t// Generate importinfo array\n\t\t$importinfo = array(\n\t\t\t\t\t\t\t'olduid' => $info->exporteduser,\n\t\t\t\t\t\t\t'newuid' => self::$uid\n\t\t\t\t\t\t\t);", "\t\tforeach( self::$providers as $provider){\n\t\t\t// Is the app in the export?\n\t\t\t$id = $provider->getID();\n\t\t\tif( isset( $info->apps->$id ) ){\n\t\t\t\t// Is the app installed\n\t\t\t\tif( !OC_App::isEnabled( $id ) ){\n\t\t\t\t\tOC_Log::write( 'migration', 'App: ' . $id . ' is not installed, can\\'t import data.', OC_Log::INFO );\n\t\t\t\t\t$appsstatus[$id] = 'notsupported';\n\t\t\t\t} else {\n\t\t\t\t\t// Did it succeed on export?\n\t\t\t\t\tif( $info->apps->$id->success ){\n\t\t\t\t\t\t// Give the provider the content object\n\t\t\t\t\t\tif( !self::connectDB( $db ) ){\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$content = new OC_Migration_Content( self::$zip, self::$MDB2 );\n\t\t\t\t\t\t$provider->setData( self::$uid, $content, $info );\n\t\t\t\t\t\t// Then do the import\n\t\t\t\t\t\tif( !$appsstatus[$id] = $provider->import( $info->apps->$id, $importinfo ) ){\n\t\t\t\t\t\t\t// Failed to import app\n\t\t\t\t\t\t\tOC_Log::write( 'migration', 'Failed to import app data for user: ' . self::$uid . ' for app: ' . $id, OC_Log::ERROR );\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Add to failed list\n\t\t\t\t\t\t$appsstatus[$id] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\treturn $appsstatus;", "\t}", "\t/*\n\t* @brief creates a new user in the database\n\t* @param $uid string user_id of the user to be created\n\t* @param $hash string hash of the user to be created\n\t* @return bool result of user creation\n\t*/\n\tpublic static function createUser( $uid, $hash ){", "\t\t// Check if userid exists\n\t\tif(OC_User::userExists( $uid )){\n\t\t\treturn false;\n\t\t}", "\t\t// Create the user\n\t\t$query = OC_DB::prepare( \"INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )\" );\n\t\t$result = $query->execute( array( $uid, $hash));\n\t\tif( !$result ){\n\t\t\tOC_Log::write('migration', 'Failed to create the new user \"'.$uid.\"\");\n\t\t}\n\t\treturn $result ? true : false;", "\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [326], "buggy_code_start_loc": [325], "filenames": ["lib/migrate.php"], "fixing_code_end_loc": [326], "fixing_code_start_loc": [325], "message": "Incomplete blacklist vulnerability in lib/migrate.php in ownCloud before 4.0.7 allows remote attackers to execute arbitrary code by uploading a crafted .htaccess file in an import.zip file and accessing an uploaded PHP file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:owncloud:owncloud:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C5EB081-BE10-49B1-8A91-3EC70F6DC6AE", "versionEndExcluding": null, "versionEndIncluding": "4.0.6", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "0A1021FF-2A5A-49AA-A376-09C98FECC519", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "3F6C12F7-5897-4DBB-A9AB-8180101F37C3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "E9CC055C-CFA3-4A23-AF91-83F7F087F282", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "AA5445B4-9115-4D31-9DF9-E7E30CAF1FFD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "8FAE7D90-6190-44E2-B4EA-F47FF3263BE6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "C7BAB402-B6A0-4314-A37A-C9465157BF5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "8A32BED8-F428-44D3-BEAC-E0BB0208B6B6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "F46F53A9-52B2-41D6-859B-9062B1F02B86", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "875B306F-92A2-4360-979E-2B53466A33F0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6EB01EA3-3071-424F-9586-83CD208D5CAE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Incomplete blacklist vulnerability in lib/migrate.php in ownCloud before 4.0.7 allows remote attackers to execute arbitrary code by uploading a crafted .htaccess file in an import.zip file and accessing an uploaded PHP file."}, {"lang": "es", "value": "Vulnerabilidad de incompatibilidad en lib/migrate.php en ownCloud anterior a v4.0.7 permite a atacantes remotos ejecutar c\u00f3digo arbitrario mediante la carga de un archivo .htaccess en un archivo import.zip y el acceso a un archivo PHP cargado."}], "evaluatorComment": "Per: http://cwe.mitre.org/data/definitions/184.html\r\n\r\n'CWE-184: Incomplete Blacklist'", "id": "CVE-2012-4389", "lastModified": "2012-09-13T04:00:00.000", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2012-09-05T23:55:02.757", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2012/09/02/2"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/owncloud/core/commit/4fd069b47906ebcf83887970c732d464dbe7d37a"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/owncloud/core/commit/4fd069b47906ebcf83887970c732d464dbe7d37a"}, "type": "NVD-CWE-Other"}
295
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * ownCloud\n *\n * @author Tom Needham\n * @copyright 2012 Tom Needham tom@owncloud.com\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n * License as published by the Free Software Foundation; either\n * version 3 of the License, or any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n */", "\n/**\n * provides an interface to migrate users and whole ownclouds\n */\nclass OC_Migrate{", "\n\t// Array of OC_Migration_Provider objects\n\tstatic private $providers=array();\n\t// User id of the user to import/export\n\tstatic private $uid=false;\n\t// Holds the ZipArchive object\n\tstatic private $zip=false;\n\t// Stores the type of export\n\tstatic private $exporttype=false;\n\t// Array of temp files to be deleted after zip creation\n\tstatic private $tmpfiles=array();\n\t// Holds the db object\n\tstatic private $MDB2=false;\n\t// Schema db object\n\tstatic private $schema=false;\n\t// Path to the sqlite db\n\tstatic private $dbpath=false;\n\t// Holds the path to the zip file\n\tstatic private $zippath=false;\n\t// Holds the OC_Migration_Content object\n\tstatic private $content=false;", "\t/**\n\t * register a new migration provider\n\t * @param OC_Migrate_Provider $provider\n\t */\n\tpublic static function registerProvider($provider){\n\t\tself::$providers[]=$provider;\n\t}", "\t/**\n\t* @brief finds and loads the providers\n\t*/\n\tstatic private function findProviders(){\n\t\t// Find the providers\n\t\t$apps = OC_App::getAllApps();", "\t\tforeach($apps as $app){\n\t\t\t$path = OC::$SERVERROOT . '/apps/' . $app . '/appinfo/migrate.php';\n\t\t\tif( file_exists( $path ) ){\n\t\t\t\tinclude( $path );\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * @brief exports a user, or owncloud instance\n\t * @param optional $uid string user id of user to export if export type is user, defaults to current\n\t * @param ootional $type string type of export, defualts to user\n\t * @param otional $path string path to zip output folder\n\t * @return false on error, path to zip on success\n\t */\n\t public static function export( $uid=null, $type='user', $path=null ){\n\t\t$datadir = OC_Config::getValue( 'datadirectory' );\n\t \t// Validate export type\n\t \t$types = array( 'user', 'instance', 'system', 'userfiles' );\n\t \tif( !in_array( $type, $types ) ){\n\t \t\tOC_Log::write( 'migration', 'Invalid export type', OC_Log::ERROR );\n\t \t\treturn json_encode( array( array( 'success' => false ) ) );\n\t \t}\n\t \tself::$exporttype = $type;\n\t \t// Userid?\n\t \tif( self::$exporttype == 'user' ){\n\t \t\t// Check user exists\n\t \t\tif( !is_null($uid) ){\n $db = new OC_User_Database;\n\t\t \t\tif( !$db->userExists( $uid ) ){\n\t\t\t\t\tOC_Log::write('migration', 'User: '.$uid.' is not in the database and so cannot be exported.', OC_Log::ERROR);\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\tself::$uid = $uid;\n\t \t\t} else {\n\t \t\t\tself::$uid = OC_User::getUser();\n\t \t\t}\n\t \t}\n\t \t// Calculate zipname\n\t \tif( self::$exporttype == 'user' ){\n\t \t\t$zipname = 'oc_export_' . self::$uid . '_' . date(\"y-m-d_H-i-s\") . '.zip';\n\t \t} else {\n\t \t\t$zipname = 'oc_export_' . self::$exporttype . '_' . date(\"y-m-d_H-i-s\") . '.zip';\n\t \t}\n\t \t// Calculate path\n\t \tif( self::$exporttype == 'user' ){\n\t \t\tself::$zippath = $datadir . '/' . self::$uid . '/' . $zipname;\n\t \t} else {\n\t \t\tif( !is_null( $path ) ){\n\t \t\t\t// Validate custom path\n\t \t\t\tif( !file_exists( $path ) || !is_writeable( $path ) ){\n\t \t\t\t\tOC_Log::write( 'migration', 'Path supplied is invalid.', OC_Log::ERROR );\n\t \t\t\t\treturn json_encode( array( 'success' => false ) );\n\t \t\t\t}\n\t \t\t\tself::$zippath = $path . $zipname;\n\t \t\t} else {\n\t \t\t\t// Default path\n\t \t\t\tself::$zippath = get_temp_dir() . '/' . $zipname;\n\t \t\t}\n\t \t}\n\t \t// Create the zip object\n\t \tif( !self::createZip() ){\n\t \t\treturn json_encode( array( 'success' => false ) );\n\t \t}\n\t \t// Do the export\n\t \tself::findProviders();\n\t \t$exportdata = array();\n\t \tswitch( self::$exporttype ){\n\t \t\tcase 'user':\n\t \t\t\t// Connect to the db\n\t \t\t\tself::$dbpath = $datadir . '/' . self::$uid . '/migration.db';\n\t \t\t\tif( !self::connectDB() ){\n\t \t\t\t\treturn json_encode( array( 'success' => false ) );\n\t \t\t\t}\n\t \t\t\tself::$content = new OC_Migration_Content( self::$zip, self::$MDB2 );\n\t \t\t\t// Export the app info\n\t\t\t $exportdata = self::exportAppData();\n\t\t\t\t// Add the data dir to the zip\n\t\t\t\tself::$content->addDir( $datadir . '/' . self::$uid, true, '/' );\n\t \t\tbreak;\n\t \t\tcase 'instance':\n\t \t\t\tself::$content = new OC_Migration_Content( self::$zip );\n\t\t\t\t// Creates a zip that is compatable with the import function\n\t\t\t\t$dbfile = tempnam( get_temp_dir(), \"owncloud_export_data_\" );\n\t\t\t\tOC_DB::getDbStructure( $dbfile, 'MDB2_SCHEMA_DUMP_ALL');", "\t\t\t\t// Now add in *dbname* and *dbprefix*\n\t\t\t\t$dbexport = file_get_contents( $dbfile );\n\t\t\t\t$dbnamestring = \"<database>\\n\\n <name>\" . OC_Config::getValue( \"dbname\", \"owncloud\" );\n\t\t\t\t$dbtableprefixstring = \"<table>\\n\\n <name>\" . OC_Config::getValue( \"dbtableprefix\", \"oc_\" );\n\t\t\t\t$dbexport = str_replace( $dbnamestring, \"<database>\\n\\n <name>*dbname*\", $dbexport );\n\t\t\t\t$dbexport = str_replace( $dbtableprefixstring, \"<table>\\n\\n <name>*dbprefix*\", $dbexport );\n\t\t\t\t// Add the export to the zip\n\t\t\t\tself::$content->addFromString( $dbexport, \"dbexport.xml\" );\n\t\t\t\t// Add user data\n\t\t\t\tforeach(OC_User::getUsers() as $user){\n\t\t\t\t\tself::$content->addDir( $datadir . '/' . $user . '/', true, \"/userdata/\" );\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tcase 'userfiles':\n\t\t\t\tself::$content = new OC_Migration_Content( self::$zip );\n\t\t\t\t// Creates a zip with all of the users files\n\t\t\t\tforeach(OC_User::getUsers() as $user){\n\t\t\t\t\tself::$content->addDir( $datadir . '/' . $user . '/', true, \"/\" );\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tcase 'system':\n\t\t\t\tself::$content = new OC_Migration_Content( self::$zip );\n\t\t\t\t// Creates a zip with the owncloud system files\n\t\t\t\tself::$content->addDir( OC::$SERVERROOT . '/', false, '/');\n\t\t\t\tforeach (array(\".git\", \"3rdparty\", \"apps\", \"core\", \"files\", \"l10n\", \"lib\", \"ocs\", \"search\", \"settings\", \"tests\") as $dir) {\n\t\t\t \tself::$content->addDir( OC::$SERVERROOT . '/' . $dir, true, \"/\");\n\t\t\t\t}\n\t\t\tbreak;\n\t \t}\n\t \tif( !$info = self::getExportInfo( $exportdata ) ){\n\t \t\treturn json_encode( array( 'success' => false ) );\n\t \t}\n\t \t// Add the export info json to the export zip\n\t \tself::$content->addFromString( $info, 'export_info.json' );\n\t \tif( !self::$content->finish() ){\n\t \t\treturn json_encode( array( 'success' => false ) );\n\t \t}\n\t \treturn json_encode( array( 'success' => true, 'data' => self::$zippath ) );\n\t }", "\t/**\n\t* @brief imports a user, or owncloud instance\n\t* @param $path string path to zip\n\t* @param optional $type type of import (user or instance)\n\t* @param optional $uid userid of new user\n\t*/\n\tpublic static function import( $path, $type='user', $uid=null ){\n\t\t\n\t\t$datadir = OC_Config::getValue( 'datadirectory' );\n\t\t// Extract the zip\n\t\tif( !$extractpath = self::extractZip( $path ) ){\n\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t}\n\t\t// Get export_info.json\n\t\t$scan = scandir( $extractpath );\n\t\t// Check for export_info.json\n\t\tif( !in_array( 'export_info.json', $scan ) ){\n\t\t\tOC_Log::write( 'migration', 'Invalid import file, export_info.json note found', OC_Log::ERROR );\n\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t}\n\t\t$json = json_decode( file_get_contents( $extractpath . 'export_info.json' ) );\n\t\tif( $json->exporttype != $type ){\n\t\t\tOC_Log::write( 'migration', 'Invalid import file', OC_Log::ERROR );\n\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t}\n\t\tself::$exporttype = $type;", "\t\t$currentuser = OC_User::getUser();", "\t\t// Have we got a user if type is user\n\t\tif( self::$exporttype == 'user' ){\n\t\t\tself::$uid = !is_null($uid) ? $uid : $currentuser;\n\t\t}\n\t\t\n\t\t// We need to be an admin if we are not importing our own data\n\t\tif(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ){\n\t\t\tif( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){\n\t\t\t\t// Naughty.\n\t\t\t\tOC_Log::write( 'migration', 'Import not permitted.', OC_Log::ERROR );\n\t\t\t\treturn json_encode( array( 'success' => false ) ); \t\n\t\t\t}\n\t\t}", "\t\t// Handle export types\n\t\tswitch( self::$exporttype ){\n\t\t\tcase 'user':\n\t\t\t\t// Check user availability\n\t\t\t\tif( !OC_User::userExists( self::$uid ) ){\n\t\t\t\t\tOC_Log::write( 'migration', 'User doesn\\'t exist', OC_Log::ERROR );\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\t// Copy data\n\t\t\t\tif( !self::copy_r( $extractpath . $json->exporteduser, $datadir . '/' . self::$uid ) ){\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\t// Import user app data\n\t\t\t\tif( !$appsimported = self::importAppData( $extractpath . $json->exporteduser . '/migration.db', $json, self::$uid ) ){\n\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t}\n\t\t\t\t// All done!\n\t\t\t\tif( !self::unlink_r( $extractpath ) ){\n\t\t\t\t\tOC_Log::write( 'migration', 'Failed to delete the extracted zip', OC_Log::ERROR );\n\t\t\t\t}\n\t\t\t\treturn json_encode( array( 'success' => true, 'data' => $appsimported ) );\n\t\t\tbreak;\n\t\t\tcase 'instance':\n\t\t\t\t\t/*\n\t\t\t\t\t * EXPERIMENTAL\n\t\t\t\t\t// Check for new data dir and dbexport before doing anything\n\t\t\t\t\t// TODO", "\t\t\t\t\t// Delete current data folder.\n\t\t\t\t\tOC_Log::write( 'migration', \"Deleting current data dir\", OC_Log::INFO );\n\t\t\t\t\tif( !self::unlink_r( $datadir, false ) ){\n\t\t\t\t\t\tOC_Log::write( 'migration', 'Failed to delete the current data dir', OC_Log::ERROR );\n\t\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t\t}", "\t\t\t\t\t// Copy over data\n\t\t\t\t\tif( !self::copy_r( $extractpath . 'userdata', $datadir ) ){\n\t\t\t\t\t\tOC_Log::write( 'migration', 'Failed to copy over data directory', OC_Log::ERROR );\n\t\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t\t}", "\t\t\t\t\t// Import the db\n\t\t\t\t\tif( !OC_DB::replaceDB( $extractpath . 'dbexport.xml' ) ){\n\t\t\t\t\t\treturn json_encode( array( 'success' => false ) );\n\t\t\t\t\t}\n\t\t\t\t\t// Done\n\t\t\t\t\treturn json_encode( 'success' => true );\n\t\t\t\t\t*/\n\t\t\tbreak;\n\t\t}", "\t}", "\t/**\n\t* @brief recursively deletes a directory\n\t* @param $dir string path of dir to delete\n\t* $param optional $deleteRootToo bool delete the root directory\n\t* @return bool\n\t*/\n\tprivate static function unlink_r( $dir, $deleteRootToo=true ){\n\t\tif( !$dh = @opendir( $dir ) ){\n\t\t\treturn false;\n\t\t}\n\t\twhile (false !== ($obj = readdir($dh))){\n\t\t\tif($obj == '.' || $obj == '..') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!@unlink($dir . '/' . $obj)){\n\t\t\t\tself::unlink_r($dir.'/'.$obj, true);\n\t\t\t}\n\t\t}\n\t\tclosedir($dh);\n\t\tif ( $deleteRootToo ) {\n\t\t\t@rmdir($dir);\n\t\t}\n\t\treturn true;\n\t}", "\t/**\n\t* @brief copies recursively\n\t* @param $path string path to source folder\n\t* @param $dest string path to destination\n\t* @return bool\n\t*/\n\tprivate static function copy_r( $path, $dest ){\n\t\tif( is_dir($path) ){\n\t\t\t@mkdir( $dest );\n\t\t\t$objects = scandir( $path );\n\t\t\tif( sizeof( $objects ) > 0 ){\n\t\t\t\tforeach( $objects as $file ){", "\t\t\t\t\tif( $file == \".\" || $file == \"..\" || $file == \".htaccess\")", "\t\t\t\t\tcontinue;\n\t\t\t\t\t// go on\n\t\t\t\t\tif( is_dir( $path . '/' . $file ) ){\n\t\t\t\t\t\tself::copy_r( $path .'/' . $file, $dest . '/' . $file );\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcopy( $path . '/' . $file, $dest . '/' . $file );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\telseif( is_file( $path ) ){\n\t\t\treturn copy( $path, $dest );\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "\t/**\n\t* @brief tries to extract the import zip\n\t* @param $path string path to the zip\n\t* @return string path to extract location (with a trailing slash) or false on failure\n\t*/\n\tstatic private function extractZip( $path ){\n\t\tself::$zip = new ZipArchive;\n\t\t// Validate path\n\t \tif( !file_exists( $path ) ){\n\t \t\tOC_Log::write( 'migration', 'Zip not found', OC_Log::ERROR );\n\t \t\treturn false;\n\t \t}\n\t\tif ( self::$zip->open( $path ) != TRUE ) {\n\t\t\tOC_Log::write( 'migration', \"Failed to open zip file\", OC_Log::ERROR );\n\t\t\treturn false;\n\t\t}\n\t\t$to = get_temp_dir() . '/oc_import_' . self::$exporttype . '_' . date(\"y-m-d_H-i-s\") . '/';\n\t\tif( !self::$zip->extractTo( $to ) ){\n\t\t\treturn false;\n\t\t}\n\t\tself::$zip->close();\n\t\treturn $to;\n\t}", "\t/**\n\t * @brief connects to a MDB2 database scheme\n\t * @returns bool\n\t */\n\tstatic private function connectScheme(){\n\t\t// We need a mdb2 database connection\n\t\tself::$MDB2->loadModule( 'Manager' );\n\t\tself::$MDB2->loadModule( 'Reverse' );", "\t\t// Connect if this did not happen before\n\t\tif( !self::$schema ){\n\t\t\trequire_once('MDB2/Schema.php');\n\t\t\tself::$schema=MDB2_Schema::factory( self::$MDB2 );\n\t\t}", "\t\treturn true;\n\t}", "\t/**\n\t * @brief creates a migration.db in the users data dir with their app data in\n\t * @return bool whether operation was successfull\n\t */\n\tprivate static function exportAppData( ){", "\t\t$success = true;\n\t\t$return = array();", "\t\t// Foreach provider\n\t\tforeach( self::$providers as $provider ){\n\t\t\t// Check if the app is enabled\n\t\t\tif( OC_App::isEnabled( $provider->getID() ) ){\n\t\t\t\t$success = true;\n\t\t\t\t// Does this app use the database?\n\t\t\t\tif( file_exists( OC::$SERVERROOT.'/apps/'.$provider->getID().'/appinfo/database.xml' ) ){\n\t\t\t\t\t// Create some app tables\n\t\t\t\t\t$tables = self::createAppTables( $provider->getID() );\n\t\t\t\t\tif( is_array( $tables ) ){\n\t\t\t\t\t\t// Save the table names\n\t\t\t\t\t\tforeach($tables as $table){\n\t\t\t\t\t\t\t$return['apps'][$provider->getID()]['tables'][] = $table;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// It failed to create the tables\n\t\t\t\t\t\t$success = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t\t// Run the export function?\n\t\t\t\tif( $success ){\n\t\t\t\t\t// Set the provider properties\n\t\t\t\t\t$provider->setData( self::$uid, self::$content );\n\t\t\t\t\t$return['apps'][$provider->getID()]['success'] = $provider->export();\n\t\t\t\t} else {\n\t\t\t\t\t$return['apps'][$provider->getID()]['success'] = false;\n\t\t\t\t\t$return['apps'][$provider->getID()]['message'] = 'failed to create the app tables';\n\t\t\t\t}\n\t\n\t\t\t\t// Now add some app info the the return array\n\t\t\t\t$appinfo = OC_App::getAppInfo( $provider->getID() );\n\t\t\t\t$return['apps'][$provider->getID()]['version'] = OC_App::getAppVersion($provider->getID());\n\t\t\t}\n\t\t}", "\t\treturn $return;", "\t}", "\n\t/**\n\t * @brief generates json containing export info, and merges any data supplied\n\t * @param optional $array array of data to include in the returned json\n\t * @return bool\n\t */\n\tstatic private function getExportInfo( $array=array() ){\n\t\t$info = array(\n\t\t\t\t\t\t'ocversion' => OC_Util::getVersion(),\n\t\t\t\t\t\t'exporttime' => time(),\n\t\t\t\t\t\t'exportedby' => OC_User::getUser(),\n\t\t\t\t\t\t'exporttype' => self::$exporttype\n\t\t\t\t\t);\n\t\t// Add hash if user export\n\t\tif( self::$exporttype == 'user' ){\n\t\t\t$query = OC_DB::prepare( \"SELECT password FROM *PREFIX*users WHERE uid = ?\" );\n\t\t\t$result = $query->execute( array( self::$uid ) );\n\t\t\t$row = $result->fetchRow();\n\t\t\t$hash = $row ? $row['password'] : false;\n\t\t\tif( !$hash ){\n\t\t\t\tOC_Log::write( 'migration', 'Failed to get the users password hash', OC_log::ERROR);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t$info['hash'] = $hash;\n\t\t\t$info['exporteduser'] = self::$uid;\n\t\t}\n\t\tif( !is_array( $array ) ){\n\t\t\tOC_Log::write( 'migration', 'Supplied $array was not an array in getExportInfo()', OC_Log::ERROR );\n\t\t}\n\t\t// Merge in other data\n\t\t$info = array_merge( $info, (array)$array );\n\t\t// Create json\n\t\t$json = json_encode( $info );\n\t\treturn $json;\n\t}", "\t/**\n\t * @brief connects to migration.db, or creates if not found\n\t * @param $db optional path to migration.db, defaults to user data dir\n\t * @return bool whether the operation was successful\n\t */\n\tstatic private function connectDB( $path=null ){\n\t\t// Has the dbpath been set?\n\t\tself::$dbpath = !is_null( $path ) ? $path : self::$dbpath;\n\t\tif( !self::$dbpath ){\n\t\t\tOC_Log::write( 'migration', 'connectDB() was called without dbpath being set', OC_Log::ERROR );\n\t\t\treturn false;\n\t\t}\n\t\t// Already connected\n\t\tif(!self::$MDB2){\n\t\t\trequire_once('MDB2.php');", "\t\t\t$datadir = OC_Config::getValue( \"datadirectory\", OC::$SERVERROOT.\"/data\" );", "\t\t\t// DB type\n\t\t\tif( class_exists( 'SQLite3' ) ){\n\t\t\t\t$dbtype = 'sqlite3';\n\t\t\t} else if( is_callable( 'sqlite_open' ) ){\n\t\t\t\t$dbtype = 'sqlite';\n\t\t\t} else {\n\t\t\t\tOC_Log::write( 'migration', 'SQLite not found', OC_Log::ERROR );\n\t\t\t\treturn false;\n\t\t\t}", "\t\t\t// Prepare options array\n\t\t\t$options = array(\n\t\t\t\t'portability' => MDB2_PORTABILITY_ALL & (!MDB2_PORTABILITY_FIX_CASE),\n\t\t\t\t'log_line_break' => '<br>',\n\t\t\t\t'idxname_format' => '%s',\n\t\t\t\t'debug' => true,\n\t\t\t\t'quote_identifier' => true\n\t\t\t\t);\n\t\t\t$dsn = array(\n\t\t\t\t'phptype' => $dbtype,\n\t\t\t\t'database' => self::$dbpath,\n\t\t\t\t'mode' => '0644'\n\t\t\t);", "\t\t\t// Try to establish connection\n\t\t\tself::$MDB2 = MDB2::factory( $dsn, $options );\n\t\t\t// Die if we could not connect\n\t\t\tif( PEAR::isError( self::$MDB2 ) ){\n\t\t\t\tdie( self::$MDB2->getMessage() );\n\t\t\t\tOC_Log::write( 'migration', 'Failed to create/connect to migration.db', OC_Log::FATAL );\n\t\t\t\tOC_Log::write( 'migration', self::$MDB2->getUserInfo(), OC_Log::FATAL );\n\t\t\t\tOC_Log::write( 'migration', self::$MDB2->getMessage(), OC_Log::FATAL );\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// We always, really always want associative arrays\n\t\t\tself::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC);\n\t\t}\n\t\treturn true;", "\t}", "\t/**\n\t * @brief creates the tables in migration.db from an apps database.xml\n\t * @param $appid string id of the app\n\t * @return bool whether the operation was successful\n\t */\n\tstatic private function createAppTables( $appid ){", "\t\tif( !self::connectScheme() ){\n\t\t\treturn false;\n\t\t}", "\t\t// There is a database.xml file\n\t\t$content = file_get_contents( OC::$SERVERROOT . '/apps/' . $appid . '/appinfo/database.xml' );", "\t\t$file2 = 'static://db_scheme';\n\t\t// TODO get the relative path to migration.db from the data dir\n\t\t// For now just cheat\n\t\t$path = pathinfo( self::$dbpath );\n\t\t$content = str_replace( '*dbname*', self::$uid.'/migration', $content );\n\t\t$content = str_replace( '*dbprefix*', '', $content );", "\t\t$xml = new SimpleXMLElement($content);\n\t\tforeach($xml->table as $table){\n\t\t\t$tables[] = (string)$table->name;\n\t\t}", "\t\tfile_put_contents( $file2, $content );", "\t\t// Try to create tables\n\t\t$definition = self::$schema->parseDatabaseDefinitionFile( $file2 );", "\t\tunlink( $file2 );", "\t\t// Die in case something went wrong\n\t\tif( $definition instanceof MDB2_Schema_Error ){\n\t\t\tOC_Log::write( 'migration', 'Failed to parse database.xml for: '.$appid, OC_Log::FATAL );\n\t\t\tOC_Log::write( 'migration', $definition->getMessage().': '.$definition->getUserInfo(), OC_Log::FATAL );\n\t\t\treturn false;\n\t\t}", "\t\t$definition['overwrite'] = true;", "\t\t$ret = self::$schema->createDatabase( $definition );", "\t\t// Die in case something went wrong\n\t\tif( $ret instanceof MDB2_Error ){\n\t\t\tOC_Log::write( 'migration', 'Failed to create tables for: '.$appid, OC_Log::FATAL );\n\t\t\tOC_Log::write( 'migration', $ret->getMessage().': '.$ret->getUserInfo(), OC_Log::FATAL );\n\t\t\treturn false;\n\t\t}\n\t\treturn $tables;", "\t}", "\t/**\n\t* @brief tries to create the zip\n\t* @param $path string path to zip destination\n\t* @return bool\n\t*/\n\tstatic private function createZip(){\n\t\tself::$zip = new ZipArchive;\n\t\t// Check if properties are set\n\t\tif( !self::$zippath ){\n\t\t\tOC_Log::write('migration', 'createZip() called but $zip and/or $zippath have not been set', OC_Log::ERROR);\n\t\t\treturn false;\n\t\t}\n\t\tif ( self::$zip->open( self::$zippath, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE ) !== TRUE ) {\n\t\t\tOC_Log::write('migration', 'Failed to create the zip with error: '.self::$zip->getStatusString(), OC_Log::ERROR);\n\t\t\treturn false;\n\t } else {\n\t \treturn true;\n\t }\n\t}", "\t/**\n\t* @brief returns an array of apps that support migration\n\t* @return array\n\t*/\n\tstatic public function getApps(){\n\t\t$allapps = OC_App::getAllApps();\n\t\tforeach($allapps as $app){\n\t\t\t$path = OC::$SERVERROOT . '/apps/' . $app . '/lib/migrate.php';\n\t\t\tif( file_exists( $path ) ){\n\t\t\t\t$supportsmigration[] = $app;\n\t\t\t}\n\t\t}\n\t\treturn $supportsmigration;\n\t}", "\t/**\n\t* @brief imports a new user\n\t* @param $db string path to migration.db\n\t* @param $info object of migration info\n\t* @param $uid optional uid to use\n\t* @return array of apps with import statuses, or false on failure.\n\t*/\n\tpublic static function importAppData( $db, $info, $uid=null ){\n\t\t// Check if the db exists\n\t\tif( file_exists( $db ) ){\n\t\t\t// Connect to the db\n\t\t\tif(!self::connectDB( $db )){\n\t\t\t\tOC_Log::write('migration','Failed to connect to migration.db',OC_Log::ERROR);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tOC_Log::write('migration','Migration.db not found at: '.$db, OC_Log::FATAL );\n\t\t\treturn false;\n\t\t}", "\t\t// Find providers\n\t\tself::findProviders();", "\t\t// Generate importinfo array\n\t\t$importinfo = array(\n\t\t\t\t\t\t\t'olduid' => $info->exporteduser,\n\t\t\t\t\t\t\t'newuid' => self::$uid\n\t\t\t\t\t\t\t);", "\t\tforeach( self::$providers as $provider){\n\t\t\t// Is the app in the export?\n\t\t\t$id = $provider->getID();\n\t\t\tif( isset( $info->apps->$id ) ){\n\t\t\t\t// Is the app installed\n\t\t\t\tif( !OC_App::isEnabled( $id ) ){\n\t\t\t\t\tOC_Log::write( 'migration', 'App: ' . $id . ' is not installed, can\\'t import data.', OC_Log::INFO );\n\t\t\t\t\t$appsstatus[$id] = 'notsupported';\n\t\t\t\t} else {\n\t\t\t\t\t// Did it succeed on export?\n\t\t\t\t\tif( $info->apps->$id->success ){\n\t\t\t\t\t\t// Give the provider the content object\n\t\t\t\t\t\tif( !self::connectDB( $db ) ){\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$content = new OC_Migration_Content( self::$zip, self::$MDB2 );\n\t\t\t\t\t\t$provider->setData( self::$uid, $content, $info );\n\t\t\t\t\t\t// Then do the import\n\t\t\t\t\t\tif( !$appsstatus[$id] = $provider->import( $info->apps->$id, $importinfo ) ){\n\t\t\t\t\t\t\t// Failed to import app\n\t\t\t\t\t\t\tOC_Log::write( 'migration', 'Failed to import app data for user: ' . self::$uid . ' for app: ' . $id, OC_Log::ERROR );\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Add to failed list\n\t\t\t\t\t\t$appsstatus[$id] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\treturn $appsstatus;", "\t}", "\t/*\n\t* @brief creates a new user in the database\n\t* @param $uid string user_id of the user to be created\n\t* @param $hash string hash of the user to be created\n\t* @return bool result of user creation\n\t*/\n\tpublic static function createUser( $uid, $hash ){", "\t\t// Check if userid exists\n\t\tif(OC_User::userExists( $uid )){\n\t\t\treturn false;\n\t\t}", "\t\t// Create the user\n\t\t$query = OC_DB::prepare( \"INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )\" );\n\t\t$result = $query->execute( array( $uid, $hash));\n\t\tif( !$result ){\n\t\t\tOC_Log::write('migration', 'Failed to create the new user \"'.$uid.\"\");\n\t\t}\n\t\treturn $result ? true : false;", "\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [326], "buggy_code_start_loc": [325], "filenames": ["lib/migrate.php"], "fixing_code_end_loc": [326], "fixing_code_start_loc": [325], "message": "Incomplete blacklist vulnerability in lib/migrate.php in ownCloud before 4.0.7 allows remote attackers to execute arbitrary code by uploading a crafted .htaccess file in an import.zip file and accessing an uploaded PHP file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:owncloud:owncloud:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C5EB081-BE10-49B1-8A91-3EC70F6DC6AE", "versionEndExcluding": null, "versionEndIncluding": "4.0.6", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "0A1021FF-2A5A-49AA-A376-09C98FECC519", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "3F6C12F7-5897-4DBB-A9AB-8180101F37C3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "E9CC055C-CFA3-4A23-AF91-83F7F087F282", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:3.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "AA5445B4-9115-4D31-9DF9-E7E30CAF1FFD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "8FAE7D90-6190-44E2-B4EA-F47FF3263BE6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "C7BAB402-B6A0-4314-A37A-C9465157BF5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "8A32BED8-F428-44D3-BEAC-E0BB0208B6B6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "F46F53A9-52B2-41D6-859B-9062B1F02B86", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "875B306F-92A2-4360-979E-2B53466A33F0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:owncloud:owncloud:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6EB01EA3-3071-424F-9586-83CD208D5CAE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Incomplete blacklist vulnerability in lib/migrate.php in ownCloud before 4.0.7 allows remote attackers to execute arbitrary code by uploading a crafted .htaccess file in an import.zip file and accessing an uploaded PHP file."}, {"lang": "es", "value": "Vulnerabilidad de incompatibilidad en lib/migrate.php en ownCloud anterior a v4.0.7 permite a atacantes remotos ejecutar c\u00f3digo arbitrario mediante la carga de un archivo .htaccess en un archivo import.zip y el acceso a un archivo PHP cargado."}], "evaluatorComment": "Per: http://cwe.mitre.org/data/definitions/184.html\r\n\r\n'CWE-184: Incomplete Blacklist'", "id": "CVE-2012-4389", "lastModified": "2012-09-13T04:00:00.000", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2012-09-05T23:55:02.757", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2012/09/02/2"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/owncloud/core/commit/4fd069b47906ebcf83887970c732d464dbe7d37a"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-Other"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/owncloud/core/commit/4fd069b47906ebcf83887970c732d464dbe7d37a"}, "type": "NVD-CWE-Other"}
295
Determine whether the {function_name} code is vulnerable or not.
[ "-*- coding: utf-8 -*-", "Changes with Apache 2.4.11\n \n *) SECURITY: CVE-2014-3583 (cve.mitre.org)\n mod_proxy_fcgi: Fix a potential crash due to buffer over-read, with \n response headers' size above 8K. [Yann Ylavic, Jeff Trawick]", " *) SECURITY: CVE-2014-3581 (cve.mitre.org)\n mod_cache: Avoid a crash when Content-Type has an empty value.\n PR 56924. [Mark Montague <mark catseye.org>, Jan Kaluza]", "", "\n *) SECURITY: CVE-2013-5704 (cve.mitre.org)\n core: HTTP trailers could be used to replace HTTP headers\n late during request processing, potentially undoing or\n otherwise confusing modules that examined or modified\n request headers earlier. Adds \"MergeTrailers\" directive to restore\n legacy behavior. [Edward Lu, Yann Ylavic, Joe Orton, Eric Covener]", " *) mod_proxy_fcgi, mod_authnz_fcgi: stop reading the response and issue an\n error when parsing or forwarding the response fails. [Yann Ylavic]", " *) mod_ssl: Fix a memory leak in case of graceful restarts with OpenSSL >= 0.9.8e\n PR 53435 [tadanori <tadanori2007 yahoo.com>, Sebastian Wiedenroth <wiedi frubar.net>]", " *) mod_proxy_connect: Don't issue AH02447 on sockets hangups, let the read\n determine whether it is a normal close or a real error. PR 57168. [Yann\n Ylavic]", " *) mod_proxy_wstunnel: abort backend connection on polling error to avoid\n further processing. [Yann Ylavic]", " *) core: Support custom ErrorDocuments for HTTP 501 and 414 status codes.\n PR 57167 [Edward Lu <Chaosed0 gmail.com>]", " *) mod_proxy_connect: Fix ProxyRemote to https:// backends on EBCDIC \n systems. PR 57092 [Edward Lu <Chaosed0 gmail.com>]", " *) mod_cache: Avoid a 304 response to an unconditional requst when an AH00752\n CacheLock error occurs during cache revalidation. [Eric Covener]\n \n *) mod_ssl: Move OCSP stapling information from a per-certificate store to\n a per-server hash. PR 54357, PR 56919. [Alex Bligh <alex alex.org.uk>,\n Yann Ylavic, Kaspar Brand]", " *) mod_cache_socache: Change average object size hint from 32 bytes to\n 2048 bytes. [Rainer Jung]", " *) mod_cache_socache: Add cache status to server-status. [Rainer Jung]", " *) event: Fix worker-listener deadlock in graceful restart.\n PR 56960.", " *) Concat strings at compile time when possible. PR 53741.", " *) mod_substitute: Restrict configuration in .htaccess to\n FileInfo as documented. [Rainer Jung]", " *) mod_substitute: Make maximum line length configurable. [Rainer Jung]", " *) mod_substitute: Fix line length limitation in case of regexp plus flatten.\n [Rainer Jung]\n \n *) mod_proxy: Truncated character worker names are no longer fatal\n errors. PR53218. [Jim Jagielski]", " *) mod_dav: Set r->status_line in dav_error_response. PR 55426.", " *) mod_proxy_http, mod_cache: Avoid (unlikely) accesses to freed memory.\n [Yann Ylavic, Christophe Jaillet]", " *) http_protocol: fix logic in ap_method_list_(add|remove) in order:\n - to correctly reset bits\n - not to modify the 'method_mask' bitfield unnecessarily\n [Christophe Jaillet]", " *) mod_slotmem_shm: Increase log level for some originally debug messages.\n [Jim Jagielski]", " *) mod_ldap: In 2.4.10, some LDAP searches or comparisons might be done with\n the wrong credentials when a backend connection is reused.\n [Eric Covener]", " *) mod_macro: Add missing APLOGNO for some Warning log messages.\n [Christophe Jaillet]", " *) mod_cache: Avoid sending 304 responses during failed revalidations\n PR56881. [Eric Covener]", " *) mod_status: Honor client IP address using mod_remoteip. PR 55886.\n [Jim Jagielski]", " *) cmake-based build for Windows: Fix incompatibility with cmake 2.8.12\n and later. PR 56615. [Chuck Liu <cliu81 gmail.com>, Jeff Trawick]", " *) mod_ratelimit: Drop severity of AH01455 and AH01457 (ap_pass_brigade\n failed) messages from ERROR to TRACE1. Other filters do not bother \n re-reporting failures from lower level filters. PR56832. [Eric Covener]", " *) core: Avoid useless warning message when parsing a section guarded by\n <IfDefine foo> if $(foo) is used within the section.\n PR 56503 [Christophe Jaillet]", " *) mod_proxy_fcgi: Fix faulty logging of large amounts of stderr from the\n application. PR 56858. [Manuel Mausz <manuel-asf mausz.at>]", " *) mod_proxy_http: Proxy responses with error status and\n \"ProxyErrorOverride On\" hang until proxy timeout.\n PR53420 [Rainer Jung]", " *) mod_log_config: Allow three character log formats to be registered. For\n backwards compatibility, the first character of a three-character format\n must be the '^' (caret) character. [Eric Covener]", " *) mod_lua: Don't quote Expires and Path values. PR 56734.\n [Keith Mashinter, <kmashint yahoo com>]", " *) mod_authz_core: Allow <AuthzProviderAlias>'es to be seen from auth\n stanzas under virtual hosts. PR 56870. [Eric Covener]", "Changes with Apache 2.4.10", " *) SECURITY: CVE-2014-0117 (cve.mitre.org)\n mod_proxy: Fix crash in Connection header handling which allowed a denial\n of service attack against a reverse proxy with a threaded MPM.\n [Ben Reser]", " *) SECURITY: CVE-2014-3523 (cve.mitre.org)\n Fix a memory consumption denial of service in the WinNT MPM, used in all\n Windows installations. Workaround: AcceptFilter <protocol> {none|connect}\n [Jeff Trawick]", " *) SECURITY: CVE-2014-0226 (cve.mitre.org)\n Fix a race condition in scoreboard handling, which could lead to\n a heap buffer overflow. [Joe Orton, Eric Covener]", " *) SECURITY: CVE-2014-0118 (cve.mitre.org)\n mod_deflate: The DEFLATE input filter (inflates request bodies) now\n limits the length and compression ratio of inflated request bodies to\n avoid denial of service via highly compressed bodies. See directives\n DeflateInflateLimitRequestBody, DeflateInflateRatioLimit,\n and DeflateInflateRatioBurst. [Yann Ylavic, Eric Covener]", " *) SECURITY: CVE-2014-0231 (cve.mitre.org)\n mod_cgid: Fix a denial of service against CGI scripts that do\n not consume stdin that could lead to lingering HTTPD child processes\n filling up the scoreboard and eventually hanging the server. By\n default, the client I/O timeout (Timeout directive) now applies to\n communication with scripts. The CGIDScriptTimeout directive can be\n used to set a different timeout for communication with scripts.\n [Rainer Jung, Eric Covener, Yann Ylavic]", " *) mod_ssl: Extend the scope of SSLSessionCacheTimeout to sessions\n resumed by TLS session resumption (RFC 5077). [Rainer Jung]", " *) mod_deflate: Don't fail when flushing inflated data to the user-agent\n and that coincides with the end of stream (\"Zlib error flushing inflate\n buffer\"). PR 56196. [Christoph Fausak <christoph fausak glueckkanja.com>]", " *) mod_proxy_ajp: Forward local IP address as a custom request attribute\n like we already do for the remote port. [Rainer Jung]", " *) core: Include any error notes set by modules in the canned error\n response for 403 errors. [Jeff Trawick]", " *) mod_ssl: Set an error note for requests rejected due to\n SSLStrictSNIVHostCheck. [Jeff Trawick]", " *) mod_ssl: Fix issue with redirects to error documents when handling\n SNI errors. [Jeff Trawick]", " *) mod_ssl: Fix tmp DH parameter leak, adjust selection to prefer\n larger keys and support up to 8192-bit keys. [Ruediger Pluem,\n Joe Orton]", " *) mod_dav: Fix improper encoding in PROPFIND responses. PR 56480.\n [Ben Reser]", " *) WinNT MPM: Improve error handling for termination events in child.\n [Jeff Trawick]", " *) mod_proxy: When ping/pong is configured for a worker, don't send or\n forward \"100 Continue\" (interim) response to the client if it does\n not expect one. [Yann Ylavic]", " *) mod_ldap: Be more conservative with the last-used time for\n LDAPConnectionPoolTTL. PR54587 [Eric Covener]", " *) mod_ldap: LDAP connections used for authn were not respecting\n LDAPConnectionPoolTTL. PR54587 [Eric Covener]", " *) mod_proxy_fcgi: Fix occasional high CPU when handling request bodies.\n [Jeff Trawick]", " *) event MPM: Fix possible crashes (third-party modules accessing c->sbh) \n or occasional missed mod_status updates under load. PR 56639.\n [Edward Lu <Chaosed0 gmail com>]", " *) mod_authnz_ldap: Support primitive LDAP servers do not accept\n filters, such as \"SDBM-backed LDAP\" on z/OS, by allowing a special\n filter \"none\" to be specified in AuthLDAPURL. [Eric Covener]", " *) mod_deflate: Fix inflation of files larger than 4GB. PR 56062.\n [Lukas Bezdicka <social v3.sk>]", " *) mod_deflate: Handle Zlib header and validation bytes received in multiple\n chunks. PR 46146. [Yann Ylavic]", " *) mod_proxy: Allow reverse-proxy to be set via explicit handler.\n [ryo takatsuki <ryotakatsuki gmail com>]", " *) ab: support custom HTTP method with -m argument. PR 56604.\n [Roman Jurkov <winfinit gmail.com>]", " *) mod_proxy_balancer: Correctly encode user provided data in management\n interface. PR 56532 [Maksymilian, <max cert.cx>]", " *) mod_proxy_fcgi: Support iobuffersize parameter. [Jeff Trawick]", " *) mod_auth_form: Add a debug message when the fields on a form are not\n recognised. [Graham Leggett]", " *) mod_cache: Preserve non-cacheable headers forwarded from an origin 304\n response. PR 55547. [Yann Ylavic]", " *) mod_proxy_wstunnel: Fix the use of SSL connections with the \"wss:\"\n scheme. PR55320. [Alex Liu <alex.leo.ca gmail.com>]", " *) mod_socache_shmcb: Correct counting of expirations for status display.\n Expirations happening during retrieval were not counted. [Rainer Jung]", " *) mod_cache: Retry unconditional request with the full URL (including the\n query-string) when the origin server's 304 response does not match the\n conditions used to revalidate the stale entry. [Yann Ylavic].", " *) mod_alias: Stop setting CONTEXT_PREFIX and CONTEXT_DOCUMENT environment\n variables as a result of AliasMatch. [Eric Covener]\n \n *) mod_cache: Don't add cached/revalidated entity headers to a 304 response.\n PR 55547. [Yann Ylavic]", " *) mod_proxy_scgi: Support Unix sockets. ap_proxy_port_of_scheme():\n Support default SCGI port (4000). [Jeff Trawick]", " *) mod_cache: Fix AH00784 errors on Windows when the the CacheLock directive\n is enabled. [Eric Covener]", " *) mod_expires: don't add Expires header to error responses (4xx/5xx),\n be they generated or forwarded. PR 55669. [Yann Ylavic]", " *) mod_proxy_fcgi: Don't segfault when failing to connect to the backend.\n (regression in 2.4.9 release) [Jeff Trawick]", " *) mod_authn_socache: Fix crash at startup in certain configurations.\n PR 56371. (regression in 2.4.7) [Jan Kaluza]", " *) mod_ssl: restore argument structure for \"exec\"-type SSLPassPhraseDialog\n programs to the form used in releases up to 2.4.7, and emulate\n a backwards-compatible behavior for existing setups. [Kaspar Brand]", " *) mod_ssl: Add SSLOCSPUseRequestNonce directive to control whether or not\n OCSP requests should use a nonce to be checked against the responder's\n one. PR 56233. [Yann Ylavic, Kaspar Brand]", " *) mod_ssl: \"SSLEngine off\" will now override a Listen-based default\n and does disable mod_ssl for the vhost. [Joe Orton]", " *) mod_lua: Enforce the max post size allowed via r:parsebody()\n [Daniel Gruno]", " *) mod_lua: Use binary comparison to find boundaries for multipart \n objects, as to not terminate our search prematurely when hitting\n a NULL byte. [Daniel Gruno]", " *) mod_ssl: add workaround for SSLCertificateFile when using OpenSSL\n versions before 0.9.8h and not specifying an SSLCertificateChainFile\n (regression introduced with 2.4.8). PR 56410. [Kaspar Brand]", " *) mod_ssl: bring SNI behavior into better conformance with RFC 6066:\n no longer send warning-level unrecognized_name(112) alerts,\n and limit startup warnings to cases where an OpenSSL version\n without TLS extension support is used. PR 56241. [Kaspar Brand]", " *) mod_proxy_html: Avoid some possible memory access violation in case of\n specially crafted files, when the ProxyHTMLMeta directive is turned on.\n Follow up of PR 56287 [Christophe Jaillet]", " *) mod_auth_form: Make sure the optional functions are loaded even when\n the AuthFormProvider isn't specified. [Graham Leggett]", " *) mod_ssl: avoid processing bogus SSLCertificateKeyFile values\n (and logging garbled file names). PR 56306. [Kaspar Brand]", " *) mod_ssl: fix merging of global and vhost-level settings with the\n SSLCertificateFile, SSLCertificateKeyFile, and SSLOpenSSLConfCmd\n directives. PR 56353. [Kaspar Brand]", " *) mod_headers: Allow the \"value\" parameter of Header and RequestHeader to \n contain an ap_expr expression if prefixed with \"expr=\". [Eric Covener]", " *) rotatelogs: Avoid creation of zombie processes when -p is used on\n Unix platforms. [Joe Orton]", " *) mod_authnz_fcgi: New module to enable FastCGI authorizer\n applications to authenticate and/or authorize clients.\n [Jeff Trawick]", " *) mod_proxy: Do not try to parse the regular expressions passed by\n ProxyPassMatch as URL as they do not follow their syntax.\n PR 56074. [Ruediger Pluem]", " *) mod_reqtimeout: Resolve unexpected timeouts on keepalive requests \n under the Event MPM. PR56216. [Frank Meier <frank meier ergon ch>]", " *) mod_proxy_fcgi: Fix sending of response without some HTTP headers\n that might be set by filters. [Jim Riggs <jim riggs.me>]", " *) mod_proxy_html: Do not delete the wrong data from HTML code when a\n \"http-equiv\" meta tag specifies a Content-Type behind any other\n \"http-equiv\" meta tag. PR 56287 [Micha Lenk <micha lenk info>]", " *) mod_proxy: Don't reuse a SSL backend connection whose requested SNI\n differs. PR 55782. [Yann Ylavic]", " *) Add suspend_connection and resume_connection hooks to notify modules\n when the thread/connection relationship changes. (Should be implemented\n for any third-party async MPMs.) [Jeff Trawick]", " *) mod_proxy_wstunnel: Don't issue AH02447 and log a 500 on routine \n hangups from websockets origin servers. PR 56299\n [Yann Ylavic, Edward Lu <Chaosed0 gmail com>, Eric Covener] ", " *) mod_proxy_wstunnel: Don't pool backend websockets connections,\n because we need to handshake every time. PR 55890.\n [Eric Covener]", " *) mod_lua: Redesign how request record table access behaves,\n in order to utilize the request record from within these tables.\n [Daniel Gruno]", " *) mod_lua: Add r:wspeek for peeking at WebSocket frames. [Daniel Gruno]\n \n *) mod_lua: Log an error when the initial parsing of a Lua file fails.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: Reformat and escape script error output.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: URL-escape cookie keys/values to prevent tainted cookie data\n from causing response splitting.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: Disallow newlines in table values inside the request_rec, \n to prevent HTTP Response Splitting via tainted headers.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: Remove the non-working early/late arguments for \n LuaHookCheckUserID. [Daniel Gruno]", " *) mod_lua: Change IVM storage to use shm [Daniel Gruno]", " *) mod_lua: More verbose error logging when a handler function cannot be\n found. [Daniel Gruno]", "Changes with Apache 2.4.9", " *) mod_ssl: Work around a bug in some older versions of OpenSSL that\n would cause a crash in SSL_get_certificate for servers where the\n certificate hadn't been sent. [Stephen Henson]", " *) mod_lua: Add a fixups hook that checks if the original request is intended \n for LuaMapHandler. This fixes a bug where FallbackResource invalidates the \n LuaMapHandler directive in certain cases by changing the URI before the map \n handler code executes [Daniel Gruno, Daniel Ferradal <dferradal gmail com>].", "Changes with Apache 2.4.8", " *) SECURITY: CVE-2014-0098 (cve.mitre.org)\n Clean up cookie logging with fewer redundant string parsing passes.\n Log only cookies with a value assignment. Prevents segfaults when\n logging truncated cookies.\n [William Rowe, Ruediger Pluem, Jim Jagielski]", " *) SECURITY: CVE-2013-6438 (cve.mitre.org)\n mod_dav: Keep track of length of cdata properly when removing\n leading spaces. Eliminates a potential denial of service from\n specifically crafted DAV WRITE requests\n [Amin Tora <Amin.Tora neustar.biz>]", " *) core: Support named groups and backreferences within the LocationMatch,\n DirectoryMatch, FilesMatch and ProxyMatch directives. (Requires\n non-ancient PCRE library) [Graham Leggett]", " *) core: draft-ietf-httpbis-p1-messaging-23 corrections regarding\n TE/CL conflicts. [Yann Ylavic, Jim Jagielski]", " *) core: Detect incomplete request and response bodies, log an error and\n forward it to the underlying filters. PR 55475 [Yann Ylavic]", " *) mod_dir: Add DirectoryCheckHandler to allow a 2.2-like behavior, skipping \n execution when a handler is already set. PR53929. [Eric Covener]", " *) mod_ssl: Do not perform SNI / Host header comparison in case of a\n forward proxy request. [Ruediger Pluem]", " *) mod_ssl: Remove the hardcoded algorithm-type dependency for the\n SSLCertificateFile and SSLCertificateKeyFile directives, to enable\n future algorithm agility, and deprecate the SSLCertificateChainFile\n directive (obsoleted by SSLCertificateFile). [Kaspar Brand]", " *) mod_rewrite: Add RewriteOptions InheritDown, InheritDownBefore, \n and IgnoreInherit to allow RewriteRules to be pushed from parent scopes\n to child scopes without explicitly configuring each child scope.\n PR56153. [Edward Lu <Chaosed0 gmail com>] ", " *) prefork: Fix long delays when doing a graceful restart.\n PR 54852 [Jim Jagielski, Arkadiusz Miskiewicz <arekm maven pl>]", " *) FreeBSD: Disable IPv4-mapped listening sockets by default for versions\n 5+ instead of just for FreeBSD 5. PR 53824. [Jeff Trawick]", " *) mod_proxy_wstunnel: Avoid busy loop on client errors, drop message\n IDs 02445, 02446, and 02448 to TRACE1 from DEBUG. PR 56145.\n [Joffroy Christen <joffroy.christen solvaxis com>, Eric Covener]", " *) mod_remoteip: Correct the trusted proxy match test. PR 54651.\n [Yoshinori Ehara <yoshinori ehara gmail com>, Eugene L <eugenel amazon com>]", " *) mod_proxy_fcgi: Fix error message when an unexpected protocol version\n number is received from the application. PR 56110. [Jeff Trawick]", " *) mod_remoteip: Use the correct IP addresses to populate the proxy_ips field.\n PR 55972. [Mike Rumph]", " *) mod_lua: Update r:setcookie() to accept a table of options and add domain,\n path and httponly to the list of options available to set.\n PR 56128 [Edward Lu <Chaosed0 gmail com>, Daniel Gruno]\n \n *) mod_lua: Fix r:setcookie() to add, rather than replace,\n the Set-Cookie header. PR56105\n [Kevin J Walters <kjw ms com>, Edward Lu <Chaosed0 gmail com>]", " *) mod_lua: Allow for database results to be returned as a hash with \n row-name/value pairs instead of just row-number/value. [Daniel Gruno]", " *) mod_rewrite: Add %{CONN_REMOTE_ADDR} as the non-useragent counterpart to\n %{REMOTE_ADDR}. PR 56094. [Edward Lu <Chaosed0 gmail com>]", " *) WinNT MPM: If ap_run_pre_connection() fails or sets c->aborted, don't\n save the socket for reuse by the next worker as if it were an \n APR_SO_DISCONNECTED socket. Restores 2.2 behavior. [Eric Covener]", " *) mod_dir: Don't search for a DirectoryIndex or DirectorySlash on a URL\n that was just rewritten by mod_rewrite. PR53929. [Eric Covener]", " *) mod_session: When we have a session we were unable to decode,\n behave as if there was no session at all. [Thomas Eckert\n <thomas.r.w.eckert gmail com>]", " *) mod_session: Fix problems interpreting the SessionInclude and\n SessionExclude configuration. PR 56038. [Erik Pearson\n <erik adaptations.com>]", " *) mod_authn_core: Allow <AuthnProviderAlias>'es to be seen from auth\n stanzas under virtual hosts. PR 55622. [Eric Covener]", " *) mod_proxy_fcgi: Use apr_socket_timeout_get instead of hard-coded\n 30 seconds timeout. [Jan Kaluza]", " *) build: only search for modules (config*.m4) in known subdirectories, see\n build/config-stubs. [Stefan Fritsch]", " *) mod_cache_disk: Fix potential hangs on Windows when using mod_cache_disk. \n PR 55833. [Eric Covener]", " *) mod_ssl: Add support for OpenSSL configuration commands by introducing\n the SSLOpenSSLConfCmd directive. [Stephen Henson, Kaspar Brand]", " *) mod_proxy: Remove (never documented) <Proxy ~ wildcard-url> syntax which\n is equivalent to <ProxyMatch wildcard-url>. [Christophe Jaillet]", " *) mod_authz_user, mod_authz_host, mod_authz_groupfile, mod_authz_dbm,\n mod_authz_dbd, mod_authnz_ldap: Support the expression parser within the\n require directives. [Graham Leggett]", " *) mod_proxy_http: Core dumped under high load. PR 50335.\n [Jan Kaluza <jkaluza redhat.com>]", " *) mod_socache_shmcb.c: Remove arbitrary restriction on shared memory size\n previously limited to 64MB. [Jens Låås <jelaas gmail.com>]", " *) mod_lua: Use binary copy when dealing with uploads through r:parsebody() \n to prevent truncating files. [Daniel Gruno]", "Changes with Apache 2.4.7", " *) SECURITY: CVE-2013-4352 (cve.mitre.org)\n mod_cache: Fix a NULL pointer deference which allowed untrusted\n origin servers to crash mod_cache in a forward proxy\n configuration. [Graham Leggett]", " *) APR 1.5.0 or later is now required for the event MPM.\n \n *) slotmem_shm: Error detection. [Jim Jagielski]", " *) event: Use skiplist data structure. [Jim Jagielski]", " *) event: Fail at startup with message AP02405 if the APR atomic\n implementation is not compatible with the MPM. [Jim Jagielski]", " *) mpm_unix: Add ap_mpm_podx_* implementation to avoid code duplication\n and align w/ trunk. [Jim Jagielski]", " *) Fix potential rejection of valid MaxMemFree and ThreadStackSize\n directives. [Mike Rumph <mike.rumph oracle.com>]", " *) mod_proxy_fcgi: Remove 64K limit on encoded length of all envvars.\n An individual envvar with an encoded length of more than 16K will be\n omitted. [Jeff Trawick]\n \n *) mod_proxy_fcgi: Handle reading protocol data that is split between\n packets. [Jeff Trawick]", " *) mod_ssl: Improve handling of ephemeral DH and ECDH keys by\n allowing custom parameters to be configured via SSLCertificateFile,\n and by adding standardized DH parameters for 1024/2048/3072/4096 bits.\n Unless custom parameters are configured, the standardized parameters\n are applied based on the certificate's RSA/DSA key size. [Kaspar Brand]", " *) mod_ssl, configure: Require OpenSSL 0.9.8a or later. [Kaspar Brand]", " *) mod_ssl: drop support for export-grade ciphers with ephemeral RSA\n keys, and unconditionally disable aNULL, eNULL and EXP ciphers\n (not overridable via SSLCipherSuite). [Kaspar Brand]", " *) mod_proxy: Added support for unix domain sockets as the\n backend server endpoint [Jim Jagielski, Blaise Tarr\n <blaise tarr gmail com>]", " *) Add experimental cmake-based build system for Windows. [Jeff Trawick,\n Tom Donovan]", " *) event MPM: Fix possible crashes (third party modules accessing c->sbh) \n or occasional missed mod_status updates for some keepalive requests \n under load. [Eric Covener]", " *) mod_authn_socache: Support optional initialization arguments for\n socache providers. [Chris Darroch]", " *) mod_session: Reset the max-age on session save. PR 47476. [Alexey\n Varlamov <alexey.v.varlamov gmail com>]", " *) mod_session: After parsing the value of the header specified by the\n SessionHeader directive, remove the value from the response. PR 55279.\n [Graham Leggett]", " *) mod_headers: Allow for format specifiers in the substitution string\n when using Header edit. [Daniel Ruggeri]", " *) mod_dav: dav_resource->uri is treated as unencoded. This was an\n unnecessary ABI changed introduced in 2.4.6. PR 55397.", " *) mod_dav: Don't require lock tokens for COPY source. PR 55306.", " *) core: Don't truncate output when sending is interrupted by a signal,\n such as from an exiting CGI process. PR 55643. [Jeff Trawick]", " *) WinNT MPM: Exit the child if the parent process crashes or is terminated.\n [Oracle Corporation]", " *) Windows: Correct failure to discard stderr in some error log\n configurations. (Error message AH00093) [Jeff Trawick]", " *) mod_session_crypto: Allow using exec: calls to obtain session\n encryption key. [Daniel Ruggeri]", " *) core: Add missing Reason-Phrase in HTTP response headers.\n PR 54946. [Rainer Jung]", " *) mod_rewrite: Make rewrite websocket-aware to allow proxying.\n PR 55598. [Chris Harris <chris.harris kitware com>]", " *) mod_ldap: When looking up sub-groups, use an implicit objectClass=*\n instead of an explicit cn=* filter. [David Hawes <dhawes vt.edu>]", " *) ab: Add wait time, fix processing time, and output write errors only if\n they occured. [Christophe Jaillet]", " *) worker MPM: Don't forcibly kill worker threads if the child process is\n exiting gracefully. [Oracle Corporation]", " *) core: apachectl -S prints wildcard name-based virtual hosts twice. \n PR54948 [Eric Covener]", " *) mod_auth_basic: Add AuthBasicUseDigestAlgorithm directive to\n allow migration of passwords from digest to basic authentication.\n [Chris Darroch]", " *) ab: Add a new -l parameter in order not to check the length of the responses.\n This can be usefull with dynamic pages.\n PR9945, PR27888, PR42040 [<ccikrs1 cranbrook edu>]\n \n *) Suppress formatting of startup messages written to the console when\n ErrorLogFormat is used. [Jeff Trawick]", " *) mod_auth_digest: Be more specific when the realm mismatches because the\n realm has not been specified. [Graham Leggett]", " *) mod_proxy: Add a note in the balancer manager stating whether changes\n will or will not be persisted and whether settings are inherited.\n [Daniel Ruggeri, Jim Jagielski]", " *) core: Add util_fcgi.h and associated definitions and support\n routines for FastCGI, based largely on mod_proxy_fcgi.\n [Jeff Trawick]", " *) mod_headers: Add 'Header note header-name note-name' for copying a response\n headers value into a note. [Eric Covener]", " *) mod_headers: Add 'setifempty' command to Header and RequestHeader.\n [Eric Covener]", " *) mod_logio: new format-specifier %S (sum) which is the sum of received\n and sent byte counts.\n PR54015 [Christophe Jaillet]", " *) mod_deflate: Improve error detection when decompressing request bodies\n with trailing garbage: handle case where trailing bytes are in\n the same bucket. [Rainer Jung]", " *) mod_authz_groupfile, mod_authz_user: Reduce severity of AH01671 and AH01663\n from ERROR to DEBUG, since these modules do not know what mod_authz_core\n is doing with their AUTHZ_DENIED return value. [Eric Covener]", " *) mod_ldap: add TRACE5 for LDAP retries. [Eric Covener]", " *) mod_ldap: retry on an LDAP timeout during authn. [Eric Covener]", " *) mod_ldap: Change \"LDAPReferrals off\" to actually set the underlying LDAP \n SDK option to OFF, and introduce \"LDAPReferrals default\" to take the SDK \n default, sans rebind authentication callback.\n [Jan Kaluza <kaluze AT redhat.com>]", " *) core: Log a message at TRACE1 when the client aborts a connection.\n [Eric Covener]", " *) WinNT MPM: Don't crash during child process initialization if the\n Listen protocol is unrecognized. [Jeff Trawick]", " *) modules: Fix some compiler warnings. [Guenter Knauf]", " *) Sync 2.4 and trunk\n - Avoid some memory allocation and work when TRACE1 is not activated\n - fix typo in include guard\n - indent\n - No need to lower the string before removing the path, it is just \n a waste of time...\n - Save a few cycles\n [Christophe Jaillet <christophe.jaillet wanadoo.fr>]", " *) mod_filter: Add \"change=no\" as a proto-flag to FilterProtocol\n to remove a providers initial flags set at registration time.\n [Eric Covener]", " *) core, mod_ssl: Enable the ability for a module to reverse the sense of\n a poll event from a read to a write or vice versa. This is a step on\n the way to allow mod_ssl taking full advantage of the event MPM.\n [Graham Leggett]", " *) Makefile.win: Install proper pcre DLL file during debug build install.\n PR 55235. [Ben Reser <ben reser org>]", " *) mod_ldap: Fix a potential memory leak or corruption. PR 54936.\n [Zhenbo Xu <zhenbo1987 gmail com>]", " *) ab: Fix potential buffer overflows when processing the T and X\n command-line options. PR 55360.\n [Mike Rumph <mike.rumph oracle.com>]", " *) fcgistarter: Specify SO_REUSEADDR to allow starting a server\n with old connections in TIME_WAIT. [Jeff Trawick]", " *) core: Add open_htaccess hook which, in conjunction with dirwalk_stat\n and post_perdir_config (introduced in 2.4.5), allows mpm-itk to be \n used without patches to httpd core. [Stefan Fritsch]", " *) support/htdbm: fix processing of -t command line switch. Regression\n introduced in 2.4.4\n PR 55264 [Jo Rhett <jrhett netconsonance com>]", " *) mod_lua: add websocket support via r:wsupgrade, r:wswrite, r:wsread \n and r:wsping. [Daniel Gruno]", " *) mod_lua: add support for writing/reading cookies via r:getcookie and \n r:setcookie. [Daniel Gruno]", " *) mod_lua: If the first yield() of a LuaOutputFilter returns a string, it should\n be prefixed to the response as documented. [Eric Covener] \n Note: Not present in 2.4.7 CHANGES", " *) mod_lua: Remove ETAG, Content-Length, and Content-MD5 when a LuaOutputFilter\n is configured without mod_filter. [Eric Covener]\n Note: Not present in 2.4.7 CHANGES", " *) mod_lua: Register LuaOutputFilter scripts as changing the content and\n content-length by default, when run my mod_filter. Previously,\n growing or shrinking a response that started with Content-Length set\n would require mod_filter and FilterProtocol change=yes. [Eric Covener]\n Note: Not present in 2.4.7 CHANGES", " *) mod_lua: Return a 500 error if a LuaHook* script doesn't return a\n numeric return code. [Eric Covener]\n Note: Not present in 2.4.7 CHANGES", "Changes with Apache 2.4.6", " *) Revert a broken fix for PR54948 that was applied to 2.4.5 (which was\n not released) and found post-2.4.5 tagging.", "Changes with Apache 2.4.5", " *) SECURITY: CVE-2013-1896 (cve.mitre.org)\n mod_dav: Sending a MERGE request against a URI handled by mod_dav_svn with\n the source href (sent as part of the request body as XML) pointing to a\n URI that is not configured for DAV will trigger a segfault. [Ben Reser\n <ben reser.org>]", " *) SECURITY: CVE-2013-2249 (cve.mitre.org)\n mod_session_dbd: Make sure that dirty flag is respected when saving\n sessions, and ensure the session ID is changed each time the session\n changes. This changes the format of the updatesession SQL statement.\n Existing configurations must be changed.\n [Takashi Sato, Graham Leggett]", " *) mod_auth_basic: Add a generic mechanism to fake basic authentication\n using the ap_expr parser. AuthBasicFake allows the administrator to \n construct their own username and password for basic authentication based \n on their needs. [Graham Leggett]", " *) mpm_event: Check that AsyncRequestWorkerFactor is not negative. PR 54254.\n [Jackie Zhang <jackie qq zhang gmail com>]", " *) mod_proxy: Ensure we don't attempt to amend a table we are iterating\n through, ensuring that all headers listed by Connection are removed.\n [Graham Leggett, Co-Advisor <coad measurement-factory.com>]", " *) mod_proxy_http: Make the proxy-interim-response environment variable\n effective by formally overriding origin server behaviour. [Graham\n Leggett, Co-Advisor <coad measurement-factory.com>]", " *) mod_proxy: Fix seg-faults when using the global pool on threaded\n MPMs [Thomas Eckert <thomas.r.w.eckert gmail.com>, Graham Leggett,\n Jim Jagielski]", " *) mod_deflate: Remove assumptions as to when an EOS bucket might arrive.\n Gracefully step aside if the body size is zero. [Graham Leggett]", " *) mod_ssl: Fix possible truncation of OCSP responses when reading from the\n server. [Joe Orton]", " *) core: Support the SINGLE_LISTEN_UNSERIALIZED_ACCEPT optimization\n on Linux kernel versions 3.x and above. PR 55121. [Bradley Heilbrun\n <apache heilbrun.org>]", " *) mod_cache_socache: Make sure the CacheSocacheMaxSize directive is merged\n correctly. [Jens Låås <jelaas gmail.com>]", " *) rotatelogs: add -n number-of-files option to rotate through a number\n of fixed-name logfiles. [Eric Covener]", " *) mod_proxy: Support web-socket tunnels via mod_proxy_wstunnel.\n [Jim Jagielski]", " *) mod_cache_socache: Use the name of the socache implementation when performing\n a lookup rather than using the raw arguments. [Martin Ksellmann\n <martin@ksellmann.de>]", " *) core: Add dirwalk_stat hook. [Jeff Trawick]", " *) core: Add post_perdir_config hook.\n [Steinar Gunderson <sgunderson bigfoot.com>]", " *) proxy_util: NULL terminate the right buffer in 'send_http_connect'.\n [Christophe Jaillet]", " *) mod_remoteip: close file in error path. [Christophe Jaillet]", " *) core: make the \"default\" parameter of the \"ErrorDocument\" option case\n insensitive. PR 54419 [Tianyin Xu <tixu cs ucsd edu>]", " *) mod_proxy_html: make the \"ProxyHTMLFixups\" options case insensitive.\n PR 54420 [Tianyin Xu <tixu cs ucsd edu>]", " *) mod_cache: Make option \"CacheDisable\" in mod_cache case insensitive.\n PR 54462 [Tianyin Xu <tixu cs ucsd edu>]", " *) mod_cache: If a 304 response indicates an entity not currently cached, then\n the cache MUST disregard the response and repeat the request without the\n conditional. [Graham Leggett, Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: Ensure that we don't attempt to replace a cached response\n with an older response as per RFC2616 13.12. [Graham Leggett, Co-Advisor\n <coad measurement-factory.com>]", " *) core, mod_cache: Ensure RFC2616 compliance in ap_meets_conditions()\n with weak validation combined with If-Range and Range headers. Break\n out explicit conditional header checks to be useable elsewhere in the\n server. Ensure weak validation RFC compliance in the byteranges filter.\n Ensure RFC validation compliance when serving cached entities. PR 16142\n [Graham Leggett, Co-Advisor <coad measurement-factory.com>]", " *) core: Add the ability to do explicit matching on weak and strong ETags\n as per RFC2616 Section 13.3.3. [Graham Leggett, Co-Advisor\n <coad measurement-factory.com>]", " *) mod_cache: Ensure that updated responses to HEAD requests don't get\n mistakenly paired with a previously cached body. Ensure that any existing\n body is removed when a HEAD request is cached. [Graham Leggett,\n Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: Honour Cache-Control: no-store in a request. [Graham Leggett]", " *) mod_cache: Make sure that contradictory entity headers present in a 304\n Not Modified response are caught and cause the entity to be removed.\n [Graham Leggett]", " *) mod_cache: Make sure Vary processing handles multivalued Vary headers and\n multivalued headers referred to via Vary. [Graham Leggett]", " *) mod_cache: When serving from cache, only the last header of a multivalued\n header was taken into account. Fixed. Ensure that Warning headers are\n correctly handled as per RFC2616. [Graham Leggett]", " *) mod_cache: Ignore response headers specified by no-cache=header and\n private=header as specified by RFC2616 14.9.1 What is Cacheable. Ensure\n that these headers are still processed when multiple Cache-Control\n headers are present in the response. PR 54706 [Graham Leggett,\n Yann Ylavic <ylavic.dev gmail.com>]", " *) mod_cache: Invalidate cached entities in response to RFC2616 Section\n 13.10 Invalidation After Updates or Deletions. PR 15868 [Graham\n Leggett]", " *) mod_dav: Improve error handling in dav_method_put(), add new\n dav_join_error() function. PR 54145. [Ben Reser <ben reser.org>]", " *) mod_dav: Do not fail PROPPATCH when prop namespace is not known.\n PR 52559 [Diego Santa Cruz <diego.santaCruz spinetix.com>]", " *) mod_dav: When a PROPPATCH attempts to remove a non-existent dead\n property on a resource for which there is no dead property in the same\n namespace httpd segfaults. PR 52559 [Diego Santa Cruz\n <diego.santaCruz spinetix.com>]", " *) mod_dav: Sending an If or If-Match header with an invalid ETag doesn't\n result in a 412 Precondition Failed for a COPY operation. PR54610\n [Timothy Wood <tjw omnigroup.com>]", " *) mod_dav: Make sure that when we prepare an If URL for Etag comparison,\n we compare unencoded paths. PR 53910 [Timothy Wood <tjw omnigroup.com>]", " *) mod_deflate: Remove assumptions as to when an EOS bucket might arrive.\n Gracefully step aside if the body size is zero. [Graham Leggett]", " *) 'AuthGroupFile' and 'AuthUserFile' do not accept anymore the optional\n 'standard' keyword . It was unused and not documented.\n PR54463 [Tianyin Xu <tixu cs.ucsd.edu> and Christophe Jaillet]", " *) core: Do not over allocate memory within 'ap_rgetline_core' for\n the common case. [Christophe Jaillet]", " *) core: speed up (for common cases) and reduce memory usage of\n ap_escape_logitem(). This should save 70-100 bytes in the request\n pool for a default config. [Christophe Jaillet]", " *) mod_dav: Ensure URI is correctly uriencoded on return. PR 54611\n [Timothy Wood <tjw omnigroup.com>]", " *) mod_proxy: Reject invalid values for Max-Forwards. [Graham Leggett,\n Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: RFC2616 14.9.3 The s-maxage directive also implies the\n semantics of the proxy-revalidate directive. [Graham Leggett]", " *) mod_ssl: add support for subjectAltName-based host name checking\n in proxy mode (SSLProxyCheckPeerName). PR 54030. [Kaspar Brand]", " *) core: Use the proper macro for HTTP/1.1. [Graham Leggett]", " *) event MPM: Provide error handling for ThreadStackSize. PR 54311\n [Tianyin Xu <tixu cs.ucsd.edu>, Christophe Jaillet]", " *) mod_dav: Do not segfault on PROPFIND with a zero length DBM.\n PR 52559 [Diego Santa Cruz <diego.santaCruz spinetix.com>]", " *) core: Improve error message where client's request-line exceeds\n LimitRequestLine. PR 54384 [Christophe Jaillet]", " *) mod_macro: New module that provides macros within configuration files.\n [Fabien Coelho]", " *) mod_cache_socache: New cache implementation backed by mod_socache\n that replaces mod_mem_cache known from httpd 2.2. [Graham\n Leggett]", " *) htpasswd: Add -v option to verify a password. [Stefan Fritsch]", " *) mod_proxy: Add BalancerInherit and ProxyPassInherit to control\n whether Proxy Balancers and Workers are inherited by vhosts\n (default is On). [Jim Jagielski]", " *) mod_authnz_ldap: Allow using exec: calls to obtain LDAP bind\n password. [Daniel Ruggeri]", " *) Added balancer parameter failontimeout to allow server admin\n to configure an IO timeout as an error in the balancer.\n [Daniel Ruggeri]", " *) mod_auth_digest: Fix crashes if shm initialization failed. [Stefan\n Fritsch]", " *) htpasswd, htdbm: Fix password generation. PR 54735. [Stefan Fritsch]", " *) core: Add workaround for gcc bug on sparc/64bit. PR 52900.\n [Stefan Fritsch]", " *) mod_setenvif: Fix crash in case SetEnvif and SetEnvIfExpr are used\n together. PR 54881. [Ruediger Pluem]", " *) htdigest: Fix buffer overflow when reading digest password file\n with very long lines. PR 54893. [Rainer Jung]", " *) ap_expr: Add the ability to base64 encode and base64 decode\n strings and to generate their SHA1 and MD5 hash.\n [Graham Leggett, Stefan Fritsch]", " *) mod_log_config: Fix crash when logging request end time for a failed\n request. PR 54828 [Rainer Jung]", " *) mod_ssl: Catch missing, mismatched or encrypted client cert/key pairs\n with SSLProxyMachineCertificateFile/Path directives. PR 52212, PR 54698.\n [Keith Burdis <keith burdis.org>, Joe Orton, Kaspar Brand]", " *) mod_ssl: Quiet FIPS mode weak keys disabled and FIPS not selected emits\n in the error log to debug level. [William Rowe]", " *) mod_cache_disk: CacheMinFileSize and CacheMaxFileSize were always\n using compiled in defaults of 1000000/1 respectively. [Eric Covener]", " *) mod_lbmethod_heartbeat, mod_heartmonitor: Respect DefaultRuntimeDir/\n DEFAULT_REL_RUNTIMEDIR for the heartbeat storage file. [Jeff Trawick]", " *) mod_include: Use new ap_expr for 'elif', like 'if', \n if legacy parser is not specified. PR 54548 [Tom Donovan]", " *) mod_lua: Add some new functions: r:htpassword(), r:mkdir(), r:mkrdir(),\n r:rmdir(), r:touch(), r:get_direntries(), r.date_parse_rfc().\n [Guenter Knauf]", " *) mod_lua: Add multipart form data handling. [Daniel Gruno]", " *) mod_lua: If a LuaMapHandler doesn't return any value, log a warning\n and treat it as apache2.OK. [Eric Covener]", " *) mod_lua: Add bindings for apr_dbd/mod_dbd database access\n [Daniel Gruno]", " *) mod_lua: Add LuaInputFilter/LuaOutputFilter for creating content\n filters in Lua [Daniel Gruno]", " *) mod_lua: Allow scripts handled by the lua-script handler to return\n a status code to the client (such as a 302 or a 500) [Daniel Gruno]", " *) mod_lua: Decline handling 'lua-script' if the file doesn't exist,\n rather than throwing an internal server error. [Daniel Gruno]", " *) mod_lua: Add functions r:flush and r:sendfile as well as additional\n request information to the request_rec structure. [Daniel Gruno]", " *) mod_lua: Add a server scope for Lua states, which creates a pool of\n states with managable minimum and maximum size. [Daniel Gruno]", " *) mod_lua: Add new directive, LuaMapHandler, for dynamically mapping\n URIs to Lua scripts and functions using regular expressions.\n [Daniel Gruno]", " *) mod_lua: Add new directive LuaCodeCache for controlling in-memory\n caching of lua scripts. [Daniel Gruno]", "Changes with Apache 2.4.4", " *) SECURITY: CVE-2012-3499 (cve.mitre.org)\n Various XSS flaws due to unescaped hostnames and URIs HTML output in\n mod_info, mod_status, mod_imagemap, mod_ldap, and mod_proxy_ftp.\n [Jim Jagielski, Stefan Fritsch, Niels Heinen <heinenn google com>]", " *) SECURITY: CVE-2012-4558 (cve.mitre.org)\n XSS in mod_proxy_balancer manager interface. [Jim Jagielski,\n Niels Heinen <heinenn google com>]", " *) mod_dir: Add support for the value 'disabled' in FallbackResource.\n [Vincent Deffontaines]", " *) mod_proxy_connect: Don't keepalive the connection to the client if the\n backend closes the connection. PR 54474. [Pavel Mateja <pavel netsafe cz>]", " *) mod_lua: Add bindings for mod_dbd/apr_dbd database access.\n [Daniel Gruno]", " *) mod_proxy: Allow for persistence of local changes made via the\n balancer-manager between graceful/normal restarts and power\n cycles. [Jim Jagielski]", " *) mod_proxy: Fix startup crash with mis-defined balancers.\n PR 52402. [Jim Jagielski]", " *) --with-module: Fix failure to integrate them into some existing\n module directories. PR 40097. [Jeff Trawick]", " *) htcacheclean: Fix potential segfault if \"-p\" is omitted. [Joe Orton]", " *) mod_proxy_http: Honour special value 0 (unlimited) of LimitRequestBody\n PR 54435. [Pavel Mateja <pavel netsafe.cz>]", " *) mod_proxy_ajp: Support unknown HTTP methods. PR 54416.\n [Rainer Jung]", " *) htcacheclean: Fix list options \"-a\" and \"-A\".\n [Rainer Jung]", " *) mod_slotmem_shm: Fix mistaken reset of num_free for restored shm.\n [Jim Jagielski]", " *) mod_proxy: non-existance of byrequests is not an immediate error.\n [Jim Jagielski]", " *) mod_proxy_balancer: Improve output of balancer-manager (re: Drn,\n Dis, Ign, Stby). PR 52478 [Danijel <dt-ng rbfh de>]\n \n *) configure: Fix processing of --disable-FEATURE for various features.\n [Jeff Trawick]", " *) mod_dialup/mod_http: Prevent a crash in mod_dialup in case of internal\n redirect. PR 52230.", " *) various modules, rotatelogs: Replace use of apr_file_write() with\n apr_file_write_full() to prevent incomplete writes. PR 53131.\n [Nicolas Viennot <apache viennot biz>, Stefan Fritsch]", " *) ab: Support socket timeout (-s timeout).\n [Guido Serra <zeph fsfe org>]", " *) httxt2dbm: Correct length computation for the 'value' stored in the\n DBM file. PR 47650 [jon buckybox com]", " *) core: Be more correct about rejecting directives that cannot work in <If>\n sections. [Stefan Fritsch]", " *) core: Fix directives like LogLevel that need to know if they are invoked\n at virtual host context or in Directory/Files/Location/If sections to\n work properly in If sections that are not in a Directory/Files/Location.\n [Stefan Fritsch]", " *) mod_xml2enc: Fix problems with charset conversion altering the\n Content-Length. [Micha Lenk <micha lenk info>]", " *) ap_expr: Add req_novary function that allows HTTP header lookups\n without adding the name to the Vary header. [Stefan Fritsch]", " *) mod_slotmem_*: Add in new fgrab() function which forces a grab and\n slot allocation on a specified slot. Allow for clearing of inuse\n array. [Jim Jagielski]", " *) mod_proxy_ftp: Fix segfaults on IPv4 requests to hosts with DNS\n AAAA records. PR 40841. [Andrew Rucker Jones <arjones simultan\n dyndns org>, <ast domdv de>, Jim Jagielski]", " *) mod_auth_form: Make sure that get_notes_auth() sets the user as does\n get_form_auth() and get_session_auth(). Makes sure that REMOTE_USER\n does not vanish during mod_include driven subrequests. [Graham\n Leggett]", " *) mod_cache_disk: Resolve errors while revalidating disk-cached files on\n Windows (\"...rename tempfile to datafile failed...\"). PR 38827\n [Eric Covener]", " *) mod_proxy_balancer: Bring XML output up to date. [Jim Jagielski]", " *) htpasswd, htdbm: Optionally read passwords from stdin, as more\n secure alternative to -b. PR 40243. [Adomas Paltanavicius <adomas\n paltanavicius gmail com>, Stefan Fritsch]", " *) htpasswd, htdbm: Add support for bcrypt algorithm (requires\n apr-util 1.5 or higher). PR 49288. [Stefan Fritsch]", " *) htpasswd, htdbm: Put full 48bit of entropy into salt, improve\n error handling. Add some of htpasswd's improvements to htdbm,\n e.g. warn if password is truncated by crypt(). [Stefan Fritsch]", " *) mod_auth_form: Support the expr parser in the\n AuthFormLoginRequiredLocation, AuthFormLoginSuccessLocation and\n AuthFormLogoutLocation directives. [Graham Leggett]", " *) mod_ssl: Add support for TLS-SRP (Secure Remote Password key exchange\n for TLS, RFC 5054). PR 51075. [Quinn Slack <sqs cs stanford edu>,\n Christophe Renou, Peter Sylvester]", " *) mod_rewrite: Stop mergeing RewriteBase down to subdirectories\n unless new option 'RewriteOptions MergeBase' is configured.\n PR 53963. [Eric Covener]", " *) mod_header: Allow for exposure of loadavg and server load using new \n format specifiers %l, %i, %b [Jim Jagielski]\n \n *) core: Make ap_regcomp() return AP_REG_ESPACE if out of memory. Make\n ap_pregcomp() abort if out of memory. This raises the minimum PCRE\n requirement to version 6.0. [Stefan Fritsch]", " *) mod_proxy: Add ability to configure the sticky session separator.\n PR 53893. [<inu inusasha de>, Jim Jagielski]", " *) mod_dumpio: Correctly log large messages\n PR 54179 [Marek Wianecki <mieszek2 interia pl>]", " *) core: Don't fail at startup with AH00554 when Include points to \n a directory without any wildcard character. [Eric Covener]", " *) core: Fail startup if the argument to ServerTokens is unrecognized.\n [Jackie Zhang <jackie.qq.zhang gmail.com>]", " *) mod_log_forensic: Don't log a spurious \"-\" if a request has been rejected\n before mod_log_forensic could attach its id to it. [Stefan Fritsch]", " *) rotatelogs: Omit the second argument for the first invocation of\n a post-rotate program when -p is used, per the documentation.\n [Joe Orton]", " *) mod_session_dbd: fix a segmentation fault in the function dbd_remove.\n PR 53452. [<rebanerebane gmail com>, Reimo Rebane]", " *) core: Functions to provide server load values: ap_get_sload() and\n ap_get_loadavg(). [Jim Jagielski, Jan Kaluza <jkaluza redhat.com>,\n Jeff Trawick]", " *) mod_ldap: Fix regression in handling \"server unavailable\" errors on \n Windows. PR 54140. [Eric Covener]\n \n *) syslog logging: Remove stray \", referer\" at the end of some messages.\n [Jeff Trawick]", " *) \"Iterate\" directives: Report an error if no arguments are provided.\n [Jeff Trawick]", " *) mod_ssl: Change default for SSLCompression to off, as compression\n causes security issues in most setups. (The so called \"CRIME\" attack).\n [Stefan Fritsch]", " *) ab: add TLS1.1/TLS1.2 options to -f switch, and adapt output\n to more accurately report the negotiated protocol. PR 53916.\n [Nicolás Pernas Maradei <nico emutex com>, Kaspar Brand]", " *) core: ErrorDocument now works for requests without a Host header.\n PR 48357. [Jeff Trawick]", " *) prefork: Avoid logging harmless errors during graceful stop.\n [Joe Orton, Jeff Trawick]", " *) mod_proxy: When concatting for PPR, avoid cases where we\n concat \".../\" and \"/...\" to create \"...//...\" [Jim Jagielski]", " *) mod_cache: Wrong content type and character set when\n mod_cache serves stale content because of a proxy error. \n PR 53539. [Rainer Jung, Ruediger Pluem]", " *) mod_proxy_ajp: Fix crash in packet dump code when logging\n with LogLevel trace7 or trace8. PR 53730. [Rainer Jung]", " *) httpd.conf: Removed the configuration directives setting a bad_DNT\n environment introduced in 2.4.3. The actual directives are commented\n out in the default conf file.", " *) core: Apply length limit when logging Status header values.\n [Jeff Trawick, Chris Darroch]", " *) mod_proxy_balancer: The nonce is only derived from the UUID iff\n not set via the 'nonce' balancer param. [Jim Jagielski]", " *) mod_ssl: Match wildcard SSL certificate names in proxy mode. \n PR 53006. [Joe Orton]", " *) Windows: Fix output of -M, -L, and similar command-line options\n which display information about the server configuration.\n [Jeff Trawick]", "Changes with Apache 2.4.3", " *) SECURITY: CVE-2012-3502 (cve.mitre.org)\n mod_proxy_ajp, mod_proxy_http: Fix an issue in back end\n connection closing which could lead to privacy issues due\n to a response mixup. PR 53727. [Rainer Jung]", " *) SECURITY: CVE-2012-2687 (cve.mitre.org)\n mod_negotiation: Escape filenames in variant list to prevent a\n possible XSS for a site where untrusted users can upload files to\n a location with MultiViews enabled. [Niels Heinen <heinenn google.com>]", " *) mod_authnz_ldap: Don't try a potentially expensive nested groups\n search before exhausting all AuthLDAPGroupAttribute checks on the\n current group. PR 52464 [Eric Covener]", " *) mod_lua: Add new directive LuaAuthzProvider to allow implementing an\n authorization provider in lua. [Stefan Fritsch]", " *) core: Be less strict when checking whether Content-Type is set to \n \"application/x-www-form-urlencoded\" when parsing POST data, \n or we risk losing data with an appended charset. PR 53698\n [Petter Berntsen <petterb gmail.com>]", " *) httpd.conf: Added configuration directives to set a bad_DNT environment\n variable based on User-Agent and to remove the DNT header field from\n incoming requests when a match occurs. This currently has the effect of\n removing DNT from requests by MSIE 10.0 because it deliberately violates\n the current specification of DNT semantics for HTTP. [Roy T. Fielding]", " *) mod_socache_shmcb: Fix bus error due to a misalignment\n in some 32 bit builds, especially on Solaris Sparc.\n PR 53040. [Rainer Jung]", " *) mod_cache: Set content type in case we return stale content.\n [Ruediger Pluem]", " *) Windows: Fix SSL failures on windows with AcceptFilter https none.\n PR 52476. [Jeff Trawick]", " *) ab: Fix read failure when targeting SSL server. [Jeff Trawick]", " *) The following now respect DefaultRuntimeDir/DEFAULT_REL_RUNTIMEDIR:\n - mod_auth_digest: shared memory file\n [Jeff Trawick]", " *) htpasswd: Use correct file mode for checking if file is writable.\n PR 45923. [Stefan Fritsch]", " *) mod_rewrite: Fix crash with dbd RewriteMaps. PR 53663. [Mikhail T.\n <mi apache aldan algebra com>]", " *) mod_ssl: Add new directive SSLCompression to disable TLS-level\n compression. PR 53219. [Björn Jacke <bjoern j3e de>, Stefan Fritsch]", " *) mod_lua: Add a few missing request_rec fields. Rename remote_ip to\n client_ip to match conn_rec. [Stefan Fritsch]", " *) mod_lua: Change prototype of vm_construct, to work around gcc bug which\n causes a segfault. PR 52779. [Dick Snippe <Dick Snippe tech omroep nl>]", " *) mpm_event: Don't count connections in lingering close state when\n calculating how many additional connections may be accepted.\n [Stefan Fritsch]", " *) mod_ssl: If exiting during initialization because of a fatal error,\n log a message to the main error log pointing to the appropriate\n virtual host error log. [Stefan Fritsch]", " *) mod_proxy_ajp: Reduce memory usage in case of many keep-alive requests on\n one connection. PR 52275. [Naohiro Ooiwa <naohiro ooiwa miraclelinux com>]", " *) mod_proxy_balancer: Restore balancing after a failed worker has\n recovered when using lbmethod_bybusyness. PR 48735. [Jeff Trawick]", " *) mod_setenvif: Compile some global regex only once during startup.\n This should save some memory, especially with .htaccess.\n [Stefan Fritsch]", " *) core: Add the port number to the vhost's name in the scoreboard.\n [Stefan Fritsch]", " *) mod_proxy: Fix ProxyPassReverse for balancer configurations.\n PR 45434. [Joe Orton]", " *) mod_lua: Add the parsebody function for parsing POST data. PR 53064.\n [Daniel Gruno]", " *) apxs: Use LDFLAGS from config_vars.mk in addition to CFLAGS and CPPFLAGS.\n [Stefan Fritsch]", " *) mod_proxy: Fix memory leak or possible corruption in ProxyBlock\n implementation. [Ruediger Pluem, Joe Orton]", " *) mod_proxy: Check hostname from request URI against ProxyBlock list,\n not forward proxy, if ProxyRemote* is configured. [Joe Orton]", " *) mod_proxy_connect: Avoid DNS lookup on hostname from request URI \n if ProxyRemote* is configured. PR 43697. [Joe Orton]", " *) mpm_event, mpm_worker: Remain active amidst prevalent child process\n resource shortages. [Jeff Trawick]", " *) Add \"strict\" and \"warnings\" pragmas to Perl scripts. [Rich Bowen]", " *) The following now respect DefaultRuntimeDir/DEFAULT_REL_RUNTIMEDIR:\n - core: the scoreboard (ScoreBoardFile), pid file (PidFile), and\n mutexes (Mutex)\n [Jim Jagielski]", " *) ab: Fix bind() errors. [Joe Orton]", " *) mpm_event: Don't do a blocking write when starting a lingering close\n from the listener thread. PR 52229. [Stefan Fritsch]", " *) mod_so: If a filename without slashes is specified for LoadFile or\n LoadModule and the file cannot be found in the server root directory,\n try to use the standard dlopen() search path. [Stefan Fritsch]", " *) mpm_event, mpm_worker: Fix cases where the spawn rate wasn't reduced\n after child process resource shortages. [Jeff Trawick]", " *) mpm_prefork: Reduce spawn rate after a child process exits due to\n unexpected poll or accept failure. [Jeff Trawick]", " *) core: Log value of Status header line in script responses rather\n than the fixed header name. [Chris Darroch]", " *) mod_ssl: Fix handling of empty response from OCSP server.\n [Jim Meyering <meyering redhat.com>, Joe Orton]", " *) mpm_event: Fix handling of MaxConnectionsPerChild. [Stefan Fritsch]", " *) mod_authz_core: If an expression in \"Require expr\" returns denied and\n references %{REMOTE_USER}, trigger authentication and retry. PR 52892.\n [Stefan Fritsch]", " *) core: Always log if LimitRequestFieldSize triggers. [Stefan Fritsch]", " *) mod_deflate: Skip compression if compression is enabled at SSL level.\n [Stefan Fritsch]", " *) core: Add missing HTTP status codes registered with IANA.\n [Julian Reschke <julian.reschke gmx.de>, Rainer Jung]", " *) mod_ldap: Treat the \"server unavailable\" condition as a transient\n error with all LDAP SDKs. [Filip Valder <filip.valder vsb.cz>]", " *) core: Fix spurious \"not allowed here\" error returned when the Options \n directive is used in .htaccess and \"AllowOverride Options\" (with no \n specific options restricted) is configured. PR 53444. [Eric Covener]", " *) mod_authz_core: Fix parsing of Require arguments in <AuthzProviderAlias>.\n PR 53048. [Stefan Fritsch]", " *) mod_log_config: Fix %{abc}C truncating cookie values at first \"=\".\n PR 53104. [Greg Ames]", " *) mod_ext_filter: Fix error_log spam when input filters are configured. \n [Joe Orton]", " *) mod_rewrite: Add \"AllowAnyURI\" option. PR 52774. [Joe Orton]", " *) htdbm, htpasswd: Don't crash if crypt() fails (e.g. with FIPS enabled). \n [Paul Wouters <pwouters redhat.com>, Joe Orton]", " *) core: Use a TLS 1.0 close_notify alert for internal dummy connection if\n the chosen listener is configured for https. [Joe Orton]", " *) mod_proxy: Use the the same hostname for SNI as for the HTTP request when\n forwarding to SSL backends. PR 53134.\n [Michael Weiser <michael weiser.dinsnail.net>, Ruediger Pluem]", " *) mod_info: Display all registered providers. [Stefan Fritsch]", " *) mod_ssl: Send the error message for speaking http to an https port using\n HTTP/1.0 instead of HTTP/0.9, and omit the link that may be wrong when\n using SNI. PR 50823. [Stefan Fritsch]", " *) core: Fix segfault in logging if r->useragent_addr or c->client_addr is\n unset. PR 53265. [Stefan Fritsch]", " *) log_server_status: Bring Perl style forward to the present, use\n standard modules, update for new format of server-status output.\n PR 45424. [Richard Bowen, Dave Brondsema, and others]", " *) mod_sed, mod_log_debug, mod_rewrite: Symbol namespace cleanups. \n [Joe Orton, André Malo]", " *) core: Prevent \"httpd -k restart\" from killing server in presence of\n config error. [Joe Orton]", " *) mod_proxy_fcgi: If there is an error reading the headers from the\n backend, send an error to the client. PR 52879. [Stefan Fritsch]", "Changes with Apache 2.4.2", " *) SECURITY: CVE-2012-0883 (cve.mitre.org)\n envvars: Fix insecure handling of LD_LIBRARY_PATH that could lead to the\n current working directory to be searched for DSOs. [Stefan Fritsch]", " *) mod_slotmem_shm: Honor DefaultRuntimeDir [Jim Jagielski]", " *) mod_ssl: Fix crash with threaded MPMs due to race condition when\n initializing EC temporary keys. [Stefan Fritsch]", " *) mod_rewrite: Fix RewriteCond integer checks to be parsed correctly.\n PR 53023. [Axel Reinhold <apache freakout.de>, André Malo]", " *) mod_proxy: Add the forcerecovery balancer parameter that determines if\n recovery for balancer workers is enforced. [Ruediger Pluem]", " *) Fix MPM DSO load failure on AIX. [Jeff Trawick]", " *) mod_proxy: Correctly set up reverse proxy worker. PR 52935.\n [Petter Berntsen <petterb gmail.com>]", " *) mod_sed: Don't define PATH_MAX to a potentially undefined value, causing\n compile problems on GNU hurd. [Stefan Fritsch]", " *) core: Add ap_runtime_dir_relative() and DefaultRuntimeDir.\n [Jeff Trawick]", " *) core: Fix breakage of Listen directives with MPMs that use a\n per-directory config. PR 52904. [Stefan Fritsch]", " *) core: Disallow directives in AllowOverrideList which are only allowed\n in VirtualHost or server context. These are usually not prepared to be\n called in .htaccess files. [Stefan Fritsch]", " *) core: In AllowOverrideList, do not allow 'None' together with other\n directives. PR 52823. [Stefan Fritsch]", " *) mod_slotmem_shm: Support DEFAULT_REL_RUNTIMEDIR for file-based shm.\n [Jim Jagielski]", " *) core: Fix merging of AllowOverrideList and ContentDigest.\n [Stefan Fritsch]", " *) mod_request: Fix validation of the KeptBodySize argument so it\n doesn't always throw a configuration error. PR 52981 [Eric Covener]", " *) core: Add filesystem paths to access denied / access failed messages\n AH00035 and AH00036. [Eric Covener]", " *) mod_dumpio: Properly handle errors from subsequent input filters.\n PR 52914. [Stefan Fritsch]", " *) Unix MPMs: Fix small memory leak in parent process if connect()\n failed when waking up children. [Joe Orton]", " *) \"DirectoryIndex disabled\" now undoes DirectoryIndex settings in\n the current configuration section, not just previous config sections.\n PR 52845. [Eric Covener]", " *) mod_xml2enc: Fix broken handling of EOS buckets which could lead to\n response headers not being sent. PR 52766. [Stefan Fritsch]", " *) mod_ssl: Properly free the GENERAL_NAMEs. PR 32652. [Kaspar Brand]", " *) core: Check during config test that directories for the access\n logs actually exist. PR 29941. [Stefan Fritsch]", " *) mod_xml2enc, mod_proxy_html: Enable per-module loglevels.\n [Stefan Fritsch]", " *) mod_filter: Fix segfault with AddOutputFilterByType. PR 52755.\n [Stefan Fritsch]", " *) mod_session: Sessions are encoded as application/x-www-form-urlencoded\n strings, however we do not handle the encoding of spaces properly.\n Fixed. [Graham Leggett]", " *) Configuration: Example in comment should use a path consistent\n with the default configuration. PR 52715.\n [Rich Bowen, Jens Schleusener, Rainer Jung]", " *) Configuration: Switch documentation links from trunk to 2.4.\n [Rainer Jung]", " *) configure: Fix out of tree build using apr and apr-util in srclib.\n [Rainer Jung]", "Changes with Apache 2.4.1", " *) SECURITY: CVE-2012-0053 (cve.mitre.org)\n Fix an issue in error responses that could expose \"httpOnly\" cookies\n when no custom ErrorDocument is specified for status code 400. \n [Eric Covener]", " *) mod_proxy_balancer: Fix crash on Windows. PR 52402 [Mladen Turk]", " *) core: Check during configtest that the directories for error logs exist.\n PR 29941 [Stefan Fritsch]", " *) Core configuration: add AllowOverride option to treat syntax\n errors in .htaccess as non-fatal. PR 52439 [Nick Kew, Jim Jagielski]", " *) core: Fix memory consumption in core output filter with streaming\n bucket types like CGI or PIPE. [Joe Orton, Stefan Fritsch]", " *) configure: Disable modules at configure time if a prerequisite module\n is not enabled. PR 52487. [Stefan Fritsch]", " *) Rewrite and proxy now decline what they don't support rather\n than fail the request. [Joe Orton]", " *) Fix building against external apr plus apr-util if apr is not installed\n in a system default path. [Rainer Jung]", " *) Doxygen fixes and improvements. [Joe Orton, Igor Galić]", " *) core: Fix building against PCRE 8.30 by switching from the obsolete\n pcre_info() to pcre_fullinfo(). PR 52623 [Ruediger Pluem, Rainer Jung]", "Changes with Apache 2.4.0", " *) SECURITY: CVE-2012-0031 (cve.mitre.org)\n Fix scoreboard issue which could allow an unprivileged child process\n to cause the parent to crash at shutdown rather than terminate\n cleanly. [Joe Orton]", " *) mod_ssl: Fix compilation with xlc on AIX. PR 52394. [Stefan Fritsch]", " *) SECURITY: CVE-2012-0021 (cve.mitre.org)\n mod_log_config: Fix segfault (crash) when the '%{cookiename}C' log format\n string is in use and a client sends a nameless, valueless cookie, causing\n a denial of service. The issue existed since version 2.2.17 and 2.3.3.\n PR 52256. [Rainer Canavan <rainer-apache 7val com>]", " *) mod_ssl: when compiled against OpenSSL 1.0.1 or later, allow explicit\n control of TLSv1.1 and TLSv1.2 through the SSLProtocol directive.\n [Kaspar Brand]", " *) mod_ssl: set OPENSSL_NO_SSL_INTERN when compiling against OpenSSL 1.0.1\n or later, to improve binary compatibility with future OpenSSL releases.\n [Kaspar Brand]", " *) mod_mime: Don't arbitrarily bypass AddOutputFilter during a ProxyPass,\n but then allow AddOutputFilter during a RewriteRule [P]. Make mod_mime\n behave identically in both cases. PR52342. [Graham Leggett]", " *) Move ab, logresolve, httxt2dbm and apxs to bin from sbin, along with\n corresponding man pages. [Graham Leggett]", " *) Distinguish properly between the bindir and sbindir directories when\n installing binaries. Previously all binaries were silently installed to\n sbindir, whether they were system administration commands or not.\n [Graham Leggett]", "Changes with Apache 2.3.16", " *) SECURITY: CVE-2011-4317 (cve.mitre.org)\n Resolve additional cases of URL rewriting with ProxyPassMatch or\n RewriteRule, where particular request-URIs could result in undesired\n backend network exposure in some configurations.\n [Joe Orton]", " *) core: Limit line length in .htaccess to 8K like in 2.2.x, to avoid\n additional DoS potential. [Stefan Fritsch]", " *) core, all modules: Add unique tag to most error log messages. [Stefan\n Fritsch]", " *) mod_socache_memcache: Change provider name from \"mc\" to \"memcache\" to\n match module name. [Stefan Fritsch]", " *) mod_slotmem_shm: Change provider name from \"shared\" to \"shm\" to match\n module name. [Stefan Fritsch]", " *) mod_ldap: Fix segfault with Solaris LDAP when enabling ldaps. This\n requires an apr-util fix in which is available in apr-util >= 1.4.0.\n PR 42682. [Stefan Fritsch]", " *) mod_rewrite: Add the AllowNoSlash RewriteOption, which makes it possible\n for RewriteRules to be placed in .htaccess files that match the directory\n with no trailing slash. PR 48304.\n [Matthew Byng-Maddick <matthew byng-maddick bbc.co.uk>]", " *) mod_session_crypto: Add a SessionCryptoPassphraseFile directive so that\n the administrator can hide the keys from the configuration. [Graham\n Leggett]", " *) Introduce a per request version of the remote IP address, which can be\n optionally modified by a module when the effective IP of the client\n is not the same as the real IP of the client (such as a load balancer).\n Introduce a per connection \"peer_ip\" and a per request \"client_ip\" to\n distinguish between the raw IP address of the connection and the effective\n IP address of the request. [Graham Leggett]", " *) ap_pass_brigade_fchk() function added. [Jim Jagielski]", " *) core: Pass ap_errorlog_info struct to error log hook. [Stefan Fritsch]", " *) mod_cache_disk: Make sure we check return codes on all writes and\n attempts to close, and clean up after ourselves in these cases.\n PR43589. [Graham Leggett]", " *) mod_cache_disk: Remove the unnecessary intermediate brigade while\n writing to disk. Fixes a problem where mod_disk_cache was leaving\n buckets in the intermediate brigade and not passing them to out on\n exit. [Florian S. <f_los_ch yahoo.com>, Graham Leggett]", " *) mod_ssl: use a shorter setting for SSLCipherSuite in the default\n default configuration file, and add some more information about\n configuring a speed-optimized alternative.\n [Kaspar Brand]", " *) mod_ssl: drop support for the SSLv2 protocol. [Kaspar Brand]", " *) mod_lua: Stop losing track of all but the most specific LuaHook* directives\n when multiple per-directory config sections are used. Adds LuaInherit \n directive to control how parent sections are merged. [Eric Covener]", " *) Server directive display (-L): Include directives of DSOs.\n [Jeff Trawick]", " *) mod_cache: Make sure we merge headers correctly when we handle a\n non cacheable conditional response. PR52120. [Graham Leggett]", " *) Pre GA removal of components that will not be included:\n - mod_noloris was superseded by mod_reqtimeout\n - mod_serf\n - mpm_simple\n [Rainer Jung]", " *) core: Set MaxMemFree 2048 by default. [Stefan Fritsch]", " *) mpm_event: Fix assertion failure during very high load. [Stefan Fritsch]", " *) configure: Additional modules loaded by default: mod_headers.\n Modules moved from module set \"few\" to \"most\" and no longer loaded\n by default: mod_actions, mod_allowmethods, mod_auth_form, mod_buffer,\n mod_cgi(d), mod_include, mod_negotiation, mod_ratelimit, mod_request,\n mod_userdir. [Rainer Jung]", " *) mod_lua: Use the right lua scope when used as a hook. [Rainer Jung]", " *) configure: Only load the really imporant modules (i.e. those enabled by\n the 'few' selection) by default. Don't handle modules enabled with\n --enable-foo specially. [Stefan Fritsch]", " *) end-generation hook: Fix false notification of end-of-generation for\n temporary intervals with no active MPM children. [Jeff Trawick]", " *) mod_ssl: Add support for configuring persistent TLS session ticket\n encryption/decryption keys (useful for clustered environments).\n [Paul Querna, Kaspar Brand]", " *) mod_usertrack: Use random value instead of remote IP address.\n [Stefan Fritsch]", "Changes with Apache 2.3.15", " *) SECURITY: CVE-2011-3348 (cve.mitre.org)\n mod_proxy_ajp: Respond with HTTP_NOT_IMPLEMENTED when the method is not\n recognized. [Jean-Frederic Clere]", " *) SECURITY: CVE-2011-3192 (cve.mitre.org)\n core: Fix handling of byte-range requests to use less memory, to avoid\n denial of service. If the sum of all ranges in a request is larger than\n the original file, ignore the ranges and send the complete file.\n PR 51714. [Stefan Fritsch, Jim Jagielski, Ruediger Pluem, Eric Covener,\n <lowprio20 gmail.com>]", " *) SECURITY: CVE-2011-3607 (cve.mitre.org)\n core: Fix integer overflow in ap_pregsub. This can be triggered e.g.\n with mod_setenvif via a malicious .htaccess. [Stefan Fritsch]", " *) SECURITY: CVE-2011-3368 (cve.mitre.org)\n Reject requests where the request-URI does not match the HTTP\n specification, preventing unexpected expansion of target URLs in\n some reverse proxy configurations. [Joe Orton]", " *) configure: Load all modules in the generated default configuration\n when using --enable-load-all-modules. [Rainer Jung]", " *) mod_reqtimeout: Change the default to set some reasonable timeout\n values. [Stefan Fritsch]", " *) core, mod_dav_fs: Change default ETag to be \"size mtime\", i.e. remove\n the inode. PR 49623. [Stefan Fritsch]", " *) mod_lua: Expose SSL variables via r:ssl_var_lookup(). [Eric Covener]", " *) mod_lua: LuaHook{AccessChecker,AuthChecker,CheckUserID,TranslateName}\n can now additionally be run as \"early\" or \"late\" relative to other modules.\n [Eric Covener]", " *) configure: By default, only load those modules that are either required\n or explicitly selected by a configure --enable-foo argument. The\n LoadModule statements for modules enabled by --enable-mods-shared=most\n and friends will be commented out. [Stefan Fritsch]", " *) mod_lua: Prevent early Lua hooks (LuaHookTranslateName and \n LuaHookQuickHandler) from being configured in <Directory>, <Files>, \n and htaccess where the configuration would have been ignored.\n [Eric Covener]", " *) mod_lua: Resolve \"attempt to index local 'r' (a userdata value)\" errors\n in LuaMapHandler scripts [Eric Covener]", " *) mod_log_debug: Rename optional argument from if= to expr=, to be more\n in line with other config directives. [Stefan Fritsch]", " *) mod_headers: Require an expression to be specified with expr=, to be more\n in line with other config directives. [Stefan Fritsch]", " *) mod_substitute: To prevent overboarding memory usage, limit line length\n to 1MB. [Stefan Fritsch]", " *) mod_lua: Make the query string (r.args) writable. [Eric Covener]", " *) mod_include: Add support for application/x-www-form-urlencoded encoding\n and decoding. [Graham Leggett]", " *) rotatelogs: Add -c option to force logfile creation in every rotation \n interval, even if empty. [Jan Kaluža <jkaluza redhat.com>]\n \n *) core: Limit ap_pregsub() to 64K, add ap_pregsub_ex() for longer strings.\n [Stefan Fritsch]", " *) mod_session_crypto: Refactor to support the new apr_crypto API.\n [Graham Leggett]", " *) http: Add missing Location header if local URL-path is used as\n ErrorDocument for 30x. [Stefan Fritsch]", " *) mod_buffer: Make sure we step down for subrequests, but not for internal\n redirects triggered by mod_rewrite. [Graham Leggett]", " *) mod_lua: add r:construct_url as a wrapper for ap_construct_url.\n [Eric Covener]\n \n *) mod_remote_ip: Fix configuration of internal proxies. PR 49272.\n [Jim Riggs <jim riggs me>]", " *) mpm_winnt: Handle AcceptFilter 'none' mode correctly; resolve specific\n server IP endpoint and remote client IP upon connection. [William Rowe]", " *) mod_setenvif: Remove OID match which is obsoleted by SetEnvIfExpr with\n PeerExtList(). [Stefan Fritsch]", " *) mpm_prefork, mpm_worker, mpm_event: If a child is created just before\n graceful restart and then exits because of a missing lock file, don't\n shutdown the whole server. PR 39311. [Shawn Michael\n <smichael rightnow com>]", " *) mpm_event: Check the return value from ap_run_create_connection.\n PR: 41194. [Davi Arnaut]", " *) mod_mime_magic: Add signatures for PNG and SWF to the example config.\n PR: 48352. [Jeremy Wagner-Kaiser <jwagner-kaiser adknowledge com>]", " *) core, unixd: Add -D DUMP_RUN_CFG option to dump some configuration items\n from the parsed (or default) config. This is useful for init scripts that\n need to setup temporary directories and permissions. [Stefan Fritsch]", " *) core, mod_actions, mod_asis: Downgrade error log messages which accompany\n a 404 request status from loglevel error to info. PR: 35768. [Stefan\n Fritsch]", " *) core: Fix hook sorting with Perl modules. PR: 45076. [Torsten Foertsch\n <torsten foertsch gmx net>]", " *) core: Enforce LimitRequestFieldSize after multiple headers with the same\n name have been merged. [Stefan Fritsch]", " *) mod_ssl: If MaxMemFree is set, ask OpenSSL >= 1.0.0 to reduce memory\n usage. PR 51618. [Cristian Rodríguez <crrodriguez opensuse org>,\n Stefan Fritsch]", " *) mod_ssl: At startup, when checking a server certificate whether it\n matches the configured ServerName, also take dNSName entries in the\n subjectAltName extension into account. PR 32652, PR 47051. [Kaspar Brand]", " *) mod_substitute: Reduce memory usage and copying of data. PR 50559.\n [Stefan Fritsch]", " *) mod_ssl/proxy: enable the SNI extension for backend TLS connections\n [Kaspar Brand]", " *) Add wrappers for malloc, calloc, realloc that check for out of memory\n situations and use them in many places. PR 51568, PR 51569, PR 51571.\n [Stefan Fritsch]", " *) Fix cross-compilation of mod_cgi/mod_cgid when APR_HAVE_STRUCT_RLIMIT is \n false but RLIMIT_* are defined. PR51371. [Eric Covener]", " *) core: Correctly obey ServerName / ServerAlias if the Host header from the\n request matches the VirtualHost address.\n PR 51709. [Micha Lenk <micha lenk.info>]", " *) mod_unique_id: Use random number generator to initialize counter.\n PR 45110. [Stefan Fritsch]", " *) core: Add convenience API for apr_random. [Stefan Fritsch]", " *) core: Add MaxRangeOverlaps and MaxRangeReversals directives to control\n the number of overlapping and reversing ranges (respectively) permitted\n before returning the entire resource, with a default limit of 20.\n [Jim Jagielski]", " *) mod_ldap: Optional function uldap_ssl_supported(r) always returned false\n if called from a virtual host with mod_ldap directives in it. Did not\n affect mod_authnz_ldap's usage of mod_ldap. [Eric Covener]", " *) mod_filter: Instead of dropping the Accept-Ranges header when a filter\n registered with AP_FILTER_PROTO_NO_BYTERANGE is present,\n set the header value to \"none\". [Eric Covener, Ruediger Pluem]", " *) core: Allow MaxRanges none|unlimited|default and set 'Accept-Ranges: none'\n in the case Ranges are being ignored with MaxRanges none.\n [Eric Covener]", " *) mod_ssl: revamp CRL-based revocation checking when validating\n certificates of clients or proxied servers. Completely delegate\n CRL processing to OpenSSL, and add a new [Proxy]CARevocationCheck\n directive for controlling the revocation checking mode. [Kaspar Brand]", " *) core: Add MaxRanges directive to control the number of ranges permitted\n before returning the entire resource, with a default limit of 200.\n [Eric Covener]", " *) mod_cache: Ensure that CacheDisable can correctly appear within\n a LocationMatch. [Graham Leggett]", " *) mod_cache: Fix the moving of the CACHE filter, which erroneously\n stood down if the original filter was not added by configuration.\n [Graham Leggett]", " *) mod_ssl: improve certificate error logging. PR 47408. [Kaspar Brand]", " *) mod_authz_groupfile: Increase length limit of lines in the group file to\n 16MB. PR 43084. [Stefan Fritsch]", " *) core: Increase length limit of lines in the configuration file to 16MB.\n PR 45888. PR 50824. [Stefan Fritsch]", " *) core: Add API for resizable buffers. [Stefan Fritsch]", " *) mod_ldap: Enable LDAPConnectionTimeout for LDAP toolkits that have\n LDAP_OPT_CONNECT_TIMEOUT instead of LDAP_OPT_NETWORK_TIMEOUT, such\n as Tivoli Directory Server 6.3 and later. [Eric Covener]", " *) mod_ldap: Change default number of retries from 10 to 3, and add\n an LDAPRetries and LDAPRetryDelay directives. [Eric Covener]", " *) mod_authnz_ldap: Don't retry during authentication, because this just\n multiplies the ample retries already being done by mod_ldap. [Eric Covener]", " *) configure: Allow to explicitly disable modules even with module selection\n 'reallyall'. [Stefan Fritsch]", " *) mod_rewrite: Check validity of each internal (int:) RewriteMap even if the\n RewriteEngine is disabled in server context, avoiding a crash while\n referencing the invalid int: map at runtime. PR 50994.\n [Ben Noordhuis <info noordhuis nl>]", " *) mod_ssl, configure: require OpenSSL 0.9.7 or later. [Kaspar Brand]", " *) mod_ssl: remove ssl_toolkit_compat layer. [Kaspar Brand]", " *) mod_ssl, configure, ab: drop support for RSA BSAFE SSL-C toolkit.\n [Kaspar Brand]", " *) mod_usertrack: Run mod_usertrack earlier in the fixups hook to ensure the\n cookie is set when modules such as mod_rewrite trigger a redirect. Also\n use r->err_headers_out for the cookie, for the same reason. PR29755.\n [Sami J. Mäkinen <sjm almamedia fi>, Eric Covener]", " *) mod_proxy_http, mod_proxy_connect: Add 'proxy-status' and\n 'proxy-source-port' request notes for logging. PR 30195. [Stefan Fritsch]", " *) configure: Enable ldap modules in 'all' and 'most' selections if ldap\n is compiled into apr-util. [Stefan Fritsch]", " *) core: Add ap_check_cmd_context()-check if a command is executed in\n .htaccess file. [Stefan Fritsch]", " *) mod_deflate: Fix endless loop if first bucket is metadata. PR 51590.\n [Torsten Foertsch <torsten foertsch gmx net>]", " *) mod_authn_socache: Fix to work in .htaccess if not configured anywhere\n in httpd.conf, and introduce an AuthnCacheEnable directive.\n PR 51991 [Nick Kew]", " *) mod_xml2enc: new (formerly third-party) module supporting\n internationalisation for filters via smart charset sniffing\n and conversion. [Nick Kew]", " *) mod_proxy_html: new (formerly third-party) module to fix up\n HTML links in a reverse proxy situation, where a backend\n generates URLs that are not resolvable by Clients. [Nick Kew]", "Changes with Apache 2.3.14", " *) mod_proxy_ajp: Improve trace logging. [Rainer Jung]", " *) mod_proxy_ajp: Respect \"reuse\" flag in END_REPONSE packets.\n [Rainer Jung]", " *) mod_proxy: enable absolute URLs to be rewritten with ProxyPassReverse,\n e.g. to reverse proxy \"Location: https://other-internal-server/login\"\n [Nick Kew]", " *) prefork, worker, event: Make sure crashes are logged to the error log if\n httpd has already detached from the console. [Stefan Fritsch]", " *) prefork, worker, event: Reduce period during startup/restart where a\n successive signal may be lost. PR 43696. [Arun Bhalla <arun shme net>]", " *) mod_allowmethods: Correct Merging of \"reset\" and do not allow an\n empty parameter list for the AllowMethods directive. [Rainer Jung]", " *) configure: Update selection of modules for 'all' and 'most'. 'all' will\n now enable all modules except for example and test modules. Make the\n selection for 'most' more useful (including ssl and proxy). Both 'all'\n and 'most' will now disable modules if dependencies are missing instead\n of aborting. If a specific module is requested with --enable-XXX=yes,\n missing dependencies will still cause configure to exit with an error.\n [Stefan Fritsch]", " *) mod_ldap: Revert the integration of apr-ldap as ap_ldap which was done\n in 2.3.13. [Stefan Fritsch]", " *) core: For '*' or '_default_' vhosts, use a wildcard address of any\n address family, rather than IPv4 only. [Joe Orton]", " *) core, mod_rewrite, mod_ssl, mod_nw_ssl: Make the SERVER_NAME variable\n include [ ] for literal IPv6 addresses, as mandated by RFC 3875.\n PR 26005. [Stefan Fritsch]", " *) mod_negotiation: Fix parsing of Content-Length in type maps. PR 42203.\n [Nagae Hidetake <nagae eagan jp>]", " *) core: Add more logging to ap_scan_script_header_err* functions. Add\n ap_scan_script_header_err*_ex functions that take a module index for\n logging.\n mod_cgi, mod_cgid, mod_proxy_fcgi, mod_proxy_scgi, mod_isapi: Use the\n new functions in order to make logging configurable per-module.\n [Stefan Fritsch]", " *) mod_dir: Add DirectoryIndexRedirect to send an external redirect to\n the proper index. [Eric Covener]", " *) mod_deflate: Don't try to compress requests with a zero sized body.\n PR 51350. [Stefan Fritsch]", " *) core: Fix startup on IPv6-only systems. PR 50592. [Joe Orton,\n <root linkage white-void net>]", " *) suexec: Add environment variables CONTEXT_DOCUMENT_ROOT, CONTEXT_PREFIX,\n REDIRECT_ERROR_NOTES, REDIRECT_SCRIPT_FILENAME, REQUEST_SCHEME to the\n whitelist in suexec. PR 51499. [Graham Laverty <graham reg ca>,\n Stefan Fritsch]", " *) mod_rewrite: Fix regexp RewriteCond with NoCase. [Stefan Fritsch]", " *) mod_log_debug: New module that allows to log custom messages at various\n phases in the request processing. [Stefan Fritsch]", " *) mod_ssl: Add some debug logging when loading server certificates.\n PR 37912. [Nick Burch <nick burch alfresco com>]", " *) configure: Support reallyall option also for --enable-mods-static.\n [Rainer Jung]", " *) mod_socache_dc: add --with-distcache to configure for choosing\n the distcache installation directory. [Rainer Jung]", " *) mod_socache_dc: use correct build variable MOD_SOCACHE_DC_LDADD\n instead of MOD_SOCACHE_LDADD in build macro. [Rainer Jung]", " *) mod_lua, mod_deflate: respect platform specific runpath linker\n flag. [Rainer Jung]", " *) configure: Only link the httpd binary against PCRE. No other support\n binary needs PCRE. [Rainer Jung]", " *) configure: tolerate dependency checking failures for modules if\n they have been enabled implicitely. [Rainer Jung]", " *) configure: Allow to specify module specific custom linker flags via\n the MOD_XXX_LDADD variables. [Rainer Jung]", "Changes with Apache 2.3.13", " *) ab: Support specifying the local address to use. PR 48930.\n [Peter Schuller <scode spotify com>]", " *) core: Add support to ErrorLogFormat for logging the system unique\n thread id under Linux. [Stefan Fritsch]", " *) event: New AsyncRequestWorkerFactor directive to influence how many\n connections will be accepted per process. [Stefan Fritsch]", " *) prefork, worker, event: Rename MaxClients to MaxRequestWorkers which\n describes more accurately what it does. [Stefan Fritsch]", " *) rotatelogs: Add -p argument to specify custom program to invoke\n after a log rotation. PR 51285. [Sven Ulland <sveniu ifi.uio.no>,\n Joe Orton]", " *) mod_ssl: Don't do OCSP checks for valid self-issued certs. [Kaspar Brand]", " *) mod_ssl: Avoid unnecessary renegotiations with SSLVerifyDepth 0.\n PR 48215. [Kaspar Brand]", " *) mod_status: Display information about asynchronous connections in the\n server-status. PR 44377. [Stefan Fritsch]", " *) mpm_event: If the number of connections of a process is very high, or if\n all workers are busy, don't accept new connections in that process.\n [Stefan Fritsch]", " *) mpm_event: Process lingering close asynchronously instead of tying up\n worker threads. [Jeff Trawick, Stefan Fritsch]", " *) mpm_event: If MaxMemFree is set, limit the number of pools that is kept\n around. [Stefan Fritsch]", " *) mpm_event: Fix graceful restart aborting connections. PR 43359.\n [Takashi Sato <takashi lans-tv com>]", " *) mod_ssl: Disable AECDH ciphers in example config. PR 51363.\n [Rob Stradling <rob comodo com>]", " *) core: Introduce new function ap_get_conn_socket() to access the socket of\n a connection. [Stefan Fritsch]", " *) mod_data: Introduce a filter to support RFC2397 data URLs. [Graham\n Leggett]", " *) mod_userdir/mod_alias/mod_vhost_alias: Correctly set DOCUMENT_ROOT,\n CONTEXT_DOCUMENT_ROOT, CONTEXT_PREFIX. PR 26052. PR 46198.\n [Stefan Fritsch]", " *) core: Allow to override document_root on a per-request basis. Introduce\n new context_document_root and context_prefix which provide information\n about non-global URI-to-directory mappings (from e.g. mod_userdir or\n mod_alias) to scripts. PR 49705. [Stefan Fritsch]", " *) core: Add <ElseIf> and <Else> to complement <If> sections.\n [Stefan Fritsch]", " *) mod_ext_filter: Remove DebugLevel option in favor of per-module loglevel.\n [Stefan Fritsch]", " *) mod_include: Make the \"#if expr\" element use the new \"ap_expr\" expression\n parser. The old parser can still be used by setting the new directive\n SSILegacyExprParser. [Stefan Fritsch]", " *) core: Add some features to ap_expr for use by mod_include: a restricted\n mode that does not allow to bypass request access restrictions; new\n variables DOCUMENT_URI (alias for REQUEST_URI), LAST_MODIFIED; -A as an\n alias for -U; an additional data entry in ap_expr_eval_ctx_t for use by\n the consumer; an extensible ap_expr_exec_ctx() API that allows to use that\n data entry. [Stefan Fritsch]", " *) mod_include: Merge directory configs instead of one SSI* config directive\n causing all other per-directory SSI* config directives to be reset.\n [Stefan Fritsch]", " *) mod_charset_lite: Remove DebugLevel option in favour of per-module\n loglevel. [Stefan Fritsch]", " *) core: Add ap_regexec_len() function that works with non-null-terminated\n strings. PR 51231. [Yehezkel Horowitz <horowity checkpoint com>]", " *) mod_authnz_ldap: If the LDAP server returns constraint violation,\n don't treat this as an error but as \"auth denied\". [Stefan Fritsch]", " *) mod_proxy_fcgi|scgi: Add support for \"best guess\" of PATH_INFO\n for SCGI/FCGI. PR 50880, 50851. [Mark Montague <mark catseye.org>,\n Jim Jagielski]", " *) mod_cache: When content is served stale, and there is no means to\n revalidate the content using ETag or Last-Modified, and we have\n mandated no stale-on-error behaviour, stand down and don't cache.\n Saves a cache write that will never be read.\n [Graham Leggett]", " *) mod_reqtimeout: Fix a timed out connection going into the keep-alive\n state after a timeout when discarding a request body. PR 51103.\n [Stefan Fritsch]", " *) core: Add various file existance test operators to ap_expr.\n [Stefan Fritsch]", " *) mod_proxy_express: New mass reverse-proxy switch extension for\n mod_proxy. [Jim Jagielski]", " *) configure: Fix script error when configuring module set \"reallyall\".\n [Rainer Jung]", "Changes with Apache 2.3.12", " *) configure, core: Provide easier support for APR's hook probe\n capability. [Jim Jagielski, Jeff Trawick]", " *) Silence autoconf 2.68 warnings. [Rainer Jung]", " *) mod_authnz_ldap: Resolve crash when LDAP is used for authorization only\n [Scott Hill <shill genscape.com>]", " *) support: Make sure check_forensic works with mod_unique_id loaded\n [Joe Schaefer]", " *) Add child_status hook for tracking creation/termination of MPM child\n processes. Add end_generation hook for notification when the last\n MPM child of a generation exits. [Jeff Trawick]", " *) mod_ldap: Make LDAPSharedCacheSize 0 create a non-shared-memory cache per\n process as opposed to disabling caching completely. This allows to use\n the non-shared-memory cache as a workaround for the shared memory cache\n not being available during graceful restarts. PR 48958. [Stefan Fritsch]", " *) Add new ap_reserve_module_slots/ap_reserve_module_slots_directive API,\n necessary if a module (like mod_perl) registers additional modules late\n in the startup phase. [Stefan Fritsch]", " *) core: Prevent segfault if DYNAMIC_MODULE_LIMIT is reached. PR 51072.\n [Torsten Förtsch <torsten foertsch gmx net>]", " *) WinNT MPM: Improve robustness under heavy load. [Jeff Trawick]", " *) MinGW build improvements. PR 49535. [John Vandenberg\n <jayvdb gmail.com>, Jeff Trawick]", " *) core: Support module names with colons in loglevel configuration.\n [Torsten Förtsch <torsten foertsch gmx net>]", " *) mod_ssl, ab: Support OpenSSL compiled without SSLv2 support.\n [Stefan Fritsch]", " *) core: Abort if the MPM is changed across restart. [Jeff Trawick]", " *) mod_proxy_ajp: Add support for 'ProxyErrorOverride on'. PR 50945.\n [Peter Pramberger <peter pramberger.at>, Jim Jagielski]", " *) mod_proxy_fcgi: Add support for 'ProxyErrorOverride on'. PR 50913.\n [Mark Montague <mark catseye.org>, Jim Jagielski]", " *) core: Change the APIs of ap_cfg_getline() and ap_cfg_getc() to return an\n error code. Abort with a nice error message if a config line is too long.\n Partial fix for PR 50824. [Stefan Fritsch]", " *) mod_info: Dump config to stdout during startup if -DDUMP_CONFIG is\n specified. PR 31956. [Stefan Fritsch]", " *) Restore visibility of DEFAULT_PIDLOG to core and modules. MPM\n helper function ap_remove_pid() added. [Jeff Trawick]", " *) Enable DEFAULT_REL_RUNTIMEDIR on Windows and NetWare. [various]", " *) Correct C++ incompatibility with http_log.h. [Stefan Fritsch, Jeff\n Trawick]", " *) mod_log_config: Prevent segfault. PR 50861. [Torsten Förtsch\n <torsten.foertsch gmx.net>]", " *) core: AllowEncodedSlashes new option NoDecode to allow encoded slashes\n in request URL path info but not decode them. Change behavior of option\n \"On\" to decode the encoded slashes as 2.0 and 2.2 do. PR 35256,\n PR 46830. [Dan Poirier]", " *) mod_ssl: Check SNI hostname against Host header case-insensitively.\n PR 49491. [Mayank Agrawal <magrawal.08 gmail.com>]", " *) mod_ldap: Add LDAPConnectionPoolTTL to give control over lifetime\n of bound backend LDAP connections. PR47634 [Eric Covener]", " *) mod_cache: Make CacheEnable and CacheDisable configurable per\n directory in addition to per server, making them work from within\n a LocationMatch. [Graham Leggett]", " *) worker, event, prefork: Correct several issues when built as\n DSOs; most notably, the scoreboard was reinitialized during graceful\n restart, such that processes of the previous generation were not\n observable. [Jeff Trawick]", "Changes with Apache 2.3.11", " *) mod_win32: Added shebang check for '! so that .vbs scripts work as CGI.\n Win32's cscript interpreter can only use a single quote as comment char.\n [Guenter Knauf]", " *) mod_proxy: balancer-manager now uses POST instead of GET.\n [Jim Jagielski]", " *) core: new util function: ap_parse_form_data(). Previously,\n this capability was tucked away in mod_request. [Jim Jagielski]", " *) core: new hook: ap_run_pre_read_request. [Jim Jagielski]", " *) modules: Fix many modules that were not correctly initializing if they\n were not active during server startup but got enabled later during a\n graceful restart. [Stefan Fritsch]", " *) core: Create new ap_state_query function that allows modules to determine\n if the current configuration run is the initial one at server startup,\n and if the server is started for testing/config dumping only.\n [Stefan Fritsch]", " *) mod_proxy: Runtime configuration of many parameters for existing\n balancers via the balancer-manager. [Jim Jagielski]", " *) mod_proxy: Runtime addition of new workers (BalancerMember) for existing\n balancers via the balancer-manager. [Jim Jagielski]", " *) mod_cache: When a bad Expires date is present, we need to behave as if\n the Expires is in the past, not as if the Expires is missing. PR 16521.\n [Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: We must ignore quoted-string values that appear in a\n Cache-Control header. PR 50199. [Graham Leggett]", " *) mod_dav: Revert change to send 501 error if unknown Content-* header is\n received for a PUT request. PR 42978. [Stefan Fritsch]", " *) mod_cache: Respect s-maxage as described by RFC2616 14.9.3, which must\n take precedence if present. PR 35247. [Graham Leggett]", " *) mod_ssl: Fix a possible startup failure if multiple SSL vhosts\n are configured with the same ServerName and private key file.\n [Masahiro Matsuya <mmatsuya redhat.com>, Joe Orton]", " *) mod_socache_dc: Make module compile by fixing some typos.\n PR 50735 [Mark Montague <mark catseye.org>]", " *) prefork: Update MPM state in children during a graceful stop or\n restart. PR 41743. [Andrew Punch <andrew.punch 247realmedia.com>]", " *) mod_mime: Ignore leading dots when looking for mime extensions.\n PR 50434 [Stefan Fritsch]", " *) core: Add support to set variables with the 'Define' directive. The\n variables that can then be used in the config using the ${VAR} syntax\n known from envvar interpolation. [Stefan Fritsch]", " *) mod_proxy_http: make adding of X-Forwarded-* headers configurable.\n ProxyAddHeaders defaults to On. [Vincent Deffontaines]", " *) mod_slotmem_shm: Increase memory alignment for slotmem data.\n [Rainer Jung]", " *) mod_ssl: Add config options for OCSP: SSLOCSPResponderTimeout,\n SSLOCSPResponseMaxAge, SSLOCSPResponseTimeSkew.\n [Kaspar Brand <httpd-dev.2011 velox.ch>]", " *) mod_ssl: Revamp output buffering to reduce network overhead for\n output fragmented into many buckets, such as chunked HTTP responses.\n [Joe Orton]", " *) core: Apply <If> sections to all requests, not only to file base requests.\n Allow to use <If> inside <Directory>, <Location>, and <Files> sections.\n The merging of <If> sections now happens after the merging of <Location>\n sections, even if an <If> section is embedded inside a <Directory> or\n <Files> section. [Stefan Fritsch]", " *) mod_proxy: Refactor usage of shared data by dropping the scoreboard\n and using slotmem. Create foundation for dynamic growth/changes of\n members within a balancer. Remove BalancerNonce in favor of a\n per-balancer 'nonce' parameter. [Jim Jagielski]", " *) mod_status: Don't show slots which are disabled by MaxClients as open.\n PR: 47022 [Jordi Prats <jordi prats gmail com>, Stefan Fritsch]", " *) mpm_prefork: Fix ap_mpm_query results for AP_MPMQ_MAX_DAEMONS and\n AP_MPMQ_MAX_THREADS.", " *) mod_authz_core: Fix bug in merging logic if user-based and non-user-based\n authorization directives were mixed. [Stefan Fritsch]", " *) mod_authn_socache: change directive name from AuthnCacheProvider\n to AuthnCacheProvideFor. The term \"provider\" is overloaded in\n this module, and we should avoid confusion between the provider\n of a backend (AuthnCacheSOCache) and the authn provider(s) for\n which this module provides cacheing (AuthnCacheProvideFor).\n [Nick Kew]", " *) mod_proxy_http: Allocate the fake backend request from a child pool\n of the backend connection, instead of misusing the pool of the frontend\n request. Fixes a thread safety issue where buckets set aside in the\n backend connection leak into other threads, and then disappear when\n the frontend request is cleaned up, in turn causing corrupted buckets\n to make other threads spin. [Graham Leggett]", " *) mod_ssl: Change the format of the SSL_{CLIENT,SERVER}_{I,S}_DN variables\n to be RFC 2253 compatible, convert non-ASCII characters to UTF8, and\n escape other special characters with backslashes. The old format can\n still be used with the LegacyDNStringFormat argument to SSLOptions.", " *) core, mod_rewrite: Make the REQUEST_SCHEME variable available to\n scripts and mod_rewrite. [Stefan Fritsch]", " *) mod_rewrite: Allow to use arbitrary boolean expressions (ap_expr) in\n RewriteCond. [Stefan Fritsch]", " *) mod_rewrite: Allow to unset environment variables using E=!VAR.\n PR 49512. [Mark Drayton <mark markdrayton info>, Stefan Fritsch]", " *) mod_headers: Restore the 2.3.8 and earlier default for the first\n argument of the Header directive (\"onsuccess\"). [Eric Covener]", " *) core: Disallow the mixing of relative and absolute Options PR 33708.\n [Sönke Tesch <st kino-fahrplan.de>]", " *) core: When exporting request headers to HTTP_* environment variables,\n drop variables whose names contain invalid characters. Describe in the\n docs how to restore the old behaviour. [Malte S. Stretz <mss apache org>]", " *) core: When selecting an IP-based virtual host, favor an exact match for\n the port over a wildcard (or omitted) port instead of favoring the one\n that came first in the configuration file. [Eric Covener]", " *) core: Overlapping virtual host address/port combinations now implicitly\n enable name-based virtual hosting for that address. The NameVirtualHost\n directive has no effect, and _default_ is interpreted the same as \"*\".\n [Eric Covener]", " *) core: In the absence of any Options directives, the default is now\n \"FollowSymlinks\" instead of \"All\". [Igor Galić]", " *) rotatelogs: Add -e option to write logs through to stdout for optional\n further processing. [Graham Leggett]", " *) mod_ssl: Correctly read full lines in input filter when the line is\n incomplete during first read. PR 50481. [Ruediger Pluem]", " *) mod_authz_core: Add AuthzSendForbiddenOnFailure directive to allow\n sending '403 FORBIDDEN' instead of '401 UNAUTHORIZED' if authorization\n fails for an authenticated user. PR 40721. [Stefan Fritsch]", "Changes with Apache 2.3.10", " *) mod_rewrite: Don't implicitly URL-escape the original query string\n when no substitution has changed it. PR 50447. [Eric Covener]", " *) core: Honor 'AcceptPathInfo OFF' during internal redirects,\n such as per-directory mod_rewrite substitutions. PR 50349.\n [Eric Covener]", " *) mod_rewrite: Add 'RewriteOptions InheritBefore' to put the base\n rules/conditions before the overridden rules/conditions. PR 39313.\n [Jérôme Grandjanny <jerome.grandjanny cea.fr>]", " *) mod_autoindex: add IndexIgnoreReset to reset the list of IndexIgnored\n filenames in higher precedence configuration sections. PR 24243.\n [Eric Covener]", " *) mod_cgid: RLimit* directive support for mod_cgid. PR 42135\n [Eric Covener]", " *) core: Fail startup when the argument to ServerName looks like a glob\n or a regular expression instead of a hostname (*?[]). PR 39863\n [Rahul Nair <rahul.g.nair gmail.com>]", " *) mod_userdir: Add merging of enable, disable, and filename arguments\n to UserDir directive, leaving enable/disable of userlists unmerged.\n PR 44076 [Eric Covener]", " *) httpd: When no -k option is provided on the httpd command line, the server\n was starting without checking for an existing pidfile. PR 50350\n [Eric Covener]", " *) mod_proxy: Put the worker in error state if the SSL handshake with the\n backend fails. PR 50332.\n [Daniel Ruggeri <DRuggeri primary.net>, Ruediger Pluem]", " *) mod_cache_disk: Fix Windows build which was broken after renaming\n the module. [Gregg L. Smith]", "Changes with Apache 2.3.9", " *) SECURITY: CVE-2010-1623 (cve.mitre.org)\n Fix a denial of service attack against mod_reqtimeout.\n [Stefan Fritsch]", " *) mod_headers: Change default first argument of Header directive\n from \"onsuccess\" to \"always\". [Eric Covener]", " *) mod_include: Add the onerror attribute to the include element,\n allowing an URL to be specified to include on error. [Graham\n Leggett]", " *) mod_cache_disk: mod_disk_cache renamed to mod_cache_disk, to be\n consistent with the naming of other modules. [Graham Leggett]", " *) mod_setenvif: Add SetEnvIfExpr directive to set env var depending on\n expression. [Stefan Fritsch]", " *) mod_proxy: Fix ProxyPassInterpolateEnv directive. PR 50292.\n [Stefan Fritsch]", " *) suEXEC: Add Suexec directive to disable suEXEC without renaming the\n binary (Suexec Off), or force startup failure if suEXEC is required\n but not supported (Suexec On). Change SuexecUserGroup to fail\n startup instead of just printing a warning if suEXEC is disabled.\n [Jeff Trawick]", " *) core: Add Error directive for aborting startup or htaccess processing\n with a specified error message. [Jeff Trawick]", " *) mod_rewrite: Fix the RewriteEngine directive to work within a\n location. Previously, once RewriteEngine was switched on globally,\n it was impossible to switch off. [Graham Leggett]", " *) core, mod_include, mod_ssl: Move the expression parser derived from\n mod_include back into mod_include. Replace ap_expr with a parser\n derived from mod_ssl's parser. Make mod_ssl use the new parser. Rework\n ap_expr's public interface and provide hooks for modules to add variables\n and functions. [Stefan Fritsch]", " *) core: Do the hook sorting earlier so that the hooks are properly sorted\n for the pre_config hook and during parsing the config. [Stefan Fritsch]", " *) core: In the absence of any AllowOverride directives, the default is now\n \"None\" instead of \"All\". PR49823 [Eric Covener]", " *) mod_proxy: Don't allow ProxyPass or ProxyPassReverse in\n <Directory> or <Files>. PR47765 [Eric Covener]", " *) prefork/worker/event MPMS: default value (when no directive is present)\n of MaxConnectionsPerChild/MaxRequestsPerChild is changed to 0 from 10000\n to match default configuration and manual. PR47782 [Eric Covener]", " *) proxy_connect: Don't give up in the middle of a CONNECT tunnel\n when the child process is starting to exit. PR50220. [Eric Covener]", " *) mod_autoindex: Fix inheritance of mod_autoindex directives into\n contexts that don't have any mod_autoindex directives. PR47766.\n [Eric Covener]", " *) mod_rewrite: Add END flag for RewriteRule to prevent further rounds\n of rewrite processing when a per-directory substitution occurs.\n [Eric Covener]", " *) mod_ssl: Make sure to always log an error if loading of CA certificates\n fails. PR 40312. [Paul Tiemann <issues apache org ourdetour com>]", " *) mod_dav: Send 501 error if unknown Content-* header is received for a PUT\n request (RFC 2616 9.6). PR 42978. [Stefan Fritsch]", " *) mod_dav: Send 400 error if malformed Content-Range header is received for\n a put request (RFC 2616 14.16). PR 49825. [Stefan Fritsch]", " *) mod_proxy: Release the backend connection as soon as EOS is detected,\n so the backend isn't forced to wait for the client to eventually\n acknowledge the data. [Graham Leggett]", " *) mod_proxy: Optimise ProxyPass within a Location so that it is stored\n per-directory, and chosen during the location walk. Make ProxyPass\n work correctly from within a LocationMatch. [Graham Leggett]", " *) core: Fix segfault if per-module LogLevel is on virtual host\n scope. PR 50117. [Stefan Fritsch]", " *) mod_proxy: Move the ProxyErrorOverride directive to have per\n directory scope. [Graham Leggett]", " *) mod_allowmethods: New module to deny certain HTTP methods without\n interfering with authentication/authorization. [Paul Querna,\n Igor Galić, Stefan Fritsch]", " *) mod_ssl: Log certificate information and improve error message if client\n cert verification fails. PR 50093, PR 50094. [Lassi Tuura <lat cern ch>,\n Stefan Fritsch]", " *) htcacheclean: Teach htcacheclean to limit cache size by number of\n inodes in addition to size of files. Prevents a cache disk from\n running out of space when many small files are cached.\n [Graham Leggett]", " *) core: Rename MaxRequestsPerChild to MaxConnectionsPerChild, which\n describes more accurately what the directive does. The old name\n still works but logs a warning. [Stefan Fritsch]", " *) mod_cache: Optionally serve stale data when a revalidation returns a\n 5xx response, controlled by the CacheStaleOnError directive.\n [Graham Leggett]", " *) htcacheclean: Allow the listing of valid URLs within the cache, with\n the option to list entry metadata such as sizes and times. [Graham\n Leggett]", " *) mod_cache: correctly parse quoted strings in cache headers.\n PR 50199 [Nick Kew]", " *) mod_cache: Allow control over the base URL of reverse proxied requests\n using the CacheKeyBaseURL directive, so that the cache key can be\n calculated from the endpoint URL instead of the server URL. [Graham\n Leggett]", " *) mod_cache: CacheLastModifiedFactor, CacheStoreNoStore, CacheStorePrivate,\n CacheStoreExpired, CacheIgnoreNoLastMod, CacheDefaultExpire,\n CacheMinExpire and CacheMaxExpire can be set per directory/location.\n [Graham Leggett]", " *) mod_disk_cache: CacheMaxFileSize, CacheMinFileSize, CacheReadSize and\n CacheReadTime can be set per directory/location. [Graham Leggett]", " *) core: Speed up config parsing if using a very large number of config\n files. PR 50002 [andrew cloudaccess net]", " *) mod_cache: Support the caching of HEAD requests. [Graham Leggett]", " *) htcacheclean: Allow the option to round up file sizes to a given\n block size, improving the accuracy of disk usage. [Graham Leggett]", " *) mod_ssl: Add authz providers for use with mod_authz_core and its\n RequireAny/RequireAll containers: 'ssl' (equivalent to SSLRequireSSL),\n 'ssl-verify-client' (for use with 'SSLVerifyClient optional'), and\n 'ssl-require' (expressions with same syntax as SSLRequire).\n [Stefan Fritsch]", " *) mod_ssl: Make the ssl expression parser thread-safe. It now requires\n bison instead of yacc. [Stefan Fritsch]", " *) mod_disk_cache: Change on-disk header file format to support the\n link of the device/inode of the data file to the matching header\n file, and to support the option of not writing a data file when\n the data file is empty. [Graham Leggett]", " *) core/mod_unique_id: Add generate_log_id hook to allow to use\n the ID generated by mod_unique_id as error log ID for requests.\n [Stefan Fritsch]", " *) mod_cache: Make sure that we never allow a 304 Not Modified response\n that we asked for to leak to the client should the 304 response be\n uncacheable. PR45341 [Graham Leggett]", " *) mod_cache: Add the cache_status hook to register the final cache\n decision hit/miss/revalidate. Add optional support for an X-Cache\n and/or an X-Cache-Detail header to add the cache status to the\n response. PR48241 [Graham Leggett]", " *) mod_authz_host: Add 'local' provider that matches connections originating\n on the local host. PR 19938. [Stefan Fritsch]", " *) Event MPM: Fix crash accessing pollset on worker thread when child\n process is exiting. [Jeff Trawick]", " *) core: For process invocation (cgi, fcgid, piped loggers and so forth)\n pass the system library path (LD_LIBRARY_PATH or platform-specific\n variables) along with the system PATH, by default. Both should be\n overridden together as desired using PassEnv etc; see mod_env.\n [William Rowe]", " *) mod_cache: Introduce CacheStoreExpired, to allow administrators to\n capture a stale backend response, perform If-Modified-Since requests\n against the backend, and serving from the cache all 304 responses.\n This restores pre-2.2.4 cache behavior. [William Rowe]", " *) mod_rewrite: Introduce <=, >= string comparison operators, and integer\n comparators -lt, -le, -eq, -ge, and -gt. To help bash users and drop\n the ambiguity of the symlink test \"-ltest\", introduce -h or -L as\n symlink test operators. [William Rowe]", " *) mod_cache: Give the cache provider the opportunity to choose to cache\n or not cache based on the buckets present in the brigade, such as the\n presence of a FILE bucket.\n [Graham Leggett]", " *) mod_authz_core: Allow authz providers to check args while reading the\n config and allow to cache parsed args. Move 'all' and 'env' authz\n providers from mod_authz_host to mod_authz_core. Add 'method' authz\n provider depending on the HTTP method. [Stefan Fritsch]", " *) mod_include: Move the request_rec within mod_include to be\n exposed within include_ctx_t. [Graham Leggett]", " *) mod_include: Reinstate support for UTF-8 character sets by allowing a\n variable being echoed or set to be decoded and then encoded as separate\n steps. PR47686 [Graham Leggett]", " *) mod_cache: Add a discrete commit_entity() provider function within the\n mod_cache provider interface which is called to indicate to the\n provider that caching is complete, giving the provider the opportunity\n to commit temporary files permanently to the cache in an atomic\n fashion. Replace the inconsistent use of error cleanups with a formal\n set of pool cleanups attached to a subpool, which is destroyed on error.\n [Graham Leggett]", " *) mod_cache: Change the signature of the store_body() provider function\n within the mod_cache provider interface to support an \"in\" brigade\n and an \"out\" brigade instead of just a single input brigade. This\n gives a cache provider the option to consume only part of the brigade\n passed to it, rather than the whole brigade as was required before.\n This fixes an out of memory and a request timeout condition that would\n occur when the original document was a large file. Introduce\n CacheReadSize and CacheReadTime directives to mod_disk_cache to control\n the amount of data to attempt to cache at a time. [Graham Leggett]", " *) core: Add ErrorLogFormat to allow configuring error log format, including\n additional information that is logged once per connection or request. Add\n error log IDs for connections and request to allow correlating error log\n lines and the corresponding access log entry. [Stefan Fritsch]", " *) core: Disable sendfile by default. [Stefan Fritsch]", " *) mod_cache: Check the request to determine whether we are allowed\n to return cached content at all, and respect a \"Cache-Control:\n no-cache\" header from a client. Previously, \"no-cache\" would\n behave like \"max-age=0\". [Graham Leggett]", " *) mod_cache: Use a proper filter context to hold filter data instead\n of misusing the per-request configuration. Fixes a segfault on trunk\n when the normal handler is used. [Graham Leggett]", " *) mod_cgid: Log a warning if the ScriptSock path is truncated because\n it is too long. PR 49388. [Stefan Fritsch]", " *) vhosts: Do not allow _default_ in NameVirtualHost, or mixing *\n and non-* ports on NameVirtualHost, or multiple NameVirtualHost\n directives for the same address:port, or NameVirtualHost\n directives with no matching VirtualHosts, or multiple ip-based\n VirtualHost sections for the same address:port. These were\n previously accepted with a warning, but the behavior was\n undefined. [Dan Poirier]", " *) mod_remoteip: Fix a segfault when using mod_remoteip in conjunction with\n Allow/Deny. PR 49838. [Andrew Skalski <voltara gmail.com>]", " *) core: DirectoryMatch can now match on the end of line character ($),\n and sub-directories of matched directories are no longer implicitly\n matched. PR49809 [Eric Covener]", " *) Regexps: introduce new higher-level regexp utility including parsing\n and executing perl-style regexp ops (e.g s/foo/bar/i) and regexp memory\n [Nick Kew]", " *) Proxy: support setting source address. PR 29404\n [Multiple contributors iterating through bugzilla,\n Aron Ujvari <xanco nikhok.hu>, Aleksey Midenkov <asm uezku.kemsu.ru>,\n <dan listening-station.net; trunk version Nick Kew]", " *) HTTP protocol: return 400 not 503 if we have to abort due to malformed\n chunked encoding. [Nick Kew]", "Changes with Apache 2.3.8", " *) suexec: Support large log files. PR 45856. [Stefan Fritsch]", " *) core: Abort with sensible error message if no or more than one MPM is\n loaded. [Stefan Fritsch]", " *) mod_proxy: Rename erroronstatus to failonstatus.\n [Daniel Ruggeri <DRuggeri primary.net>]", " *) mod_dav_fs: Fix broken \"creationdate\" property.\n Regression in version 2.3.7. [Rainer Jung]", "Changes with Apache 2.3.7", " *) SECURITY: CVE-2010-1452 (cve.mitre.org)\n mod_dav, mod_cache, mod_session: Fix Handling of requests without a path\n segment. PR: 49246 [Mark Drayton, Jeff Trawick]", " *) mod_ldap: Properly check the result returned by apr_ldap_init. PR 46076.\n [Stefan Fritsch]", " *) mod_rewrite: Log errors if rewrite map files cannot be opened. PR 49639.\n [Stefan Fritsch]", " *) mod_proxy_http: Support the 'ping' property for backend HTTP/1.1 servers\n via leveraging 100-Continue as the initial \"request\".\n [Jim Jagielski]", " *) core/mod_authz_core: Introduce new access_checker_ex hook that enables\n mod_authz_core to bypass authentication if access should be allowed by\n IP address/env var/... [Stefan Fritsch]", " *) core: Introduce note_auth_failure hook to allow modules to add support\n for additional auth types. This makes ap_note_auth_failure() work with\n mod_auth_digest again. PR 48807. [Stefan Fritsch]", " *) socache modules: return APR_NOTFOUND when a lookup is not found [Nick Kew]", " *) mod_authn_socache: new module [Nick Kew]", " *) configure: Add reallyall option for --enable-mods-shared. [Stefan Fritsch]", " *) Fix Windows build when using VC6. [Gregg L. Smith <lists glewis com>]", " *) mod_rewrite: Allow to set environment variables without explicitly\n giving a value. [Rainer Jung]", " *) mod_rewrite: Remove superfluous EOL from rewrite logging. [Rainer Jung]", " *) mod_include: recognise \"text/html; parameters\" as text/html\n PR 49616 [Andrey Chernov <ache nagual.pp.ru>]", " *) CGI vars: allow PATH to be set by SetEnv, consistent with LD_LIBRARY_PATH\n PR 43906 [Nick Kew]", " *) Core: Extra robustness: don't try authz and segfault if authn\n fails to set r->user. Log bug and return 500 instead.\n PR 42995 [Nick Kew]", " *) HTTP protocol filter: fix handling of longer chunk extensions\n PR 49474 [<tee.bee gmx.de>]", " *) Update SSL cipher suite and add example for SSLHonorCipherOrder.\n [Lars Eilebrecht, Rainer Jung]", " *) move AddOutputFilterByType from core to mod_filter. This should\n fix nasty side-effects that happen when content_type is set\n more than once in processing a request, and make it fully\n compatible with dynamic and proxied contents. [Nick Kew]", " *) mod_log_config: Implement logging for sub second timestamps and\n request end time. [Rainer Jung]", "Changes with Apache 2.3.6", " *) SECURITY: CVE-2009-3555 (cve.mitre.org)\n mod_ssl: Comprehensive fix of the TLS renegotiation prefix injection\n attack when compiled against OpenSSL version 0.9.8m or later. Introduces\n the 'SSLInsecureRenegotiation' directive to reopen this vulnerability\n and offer unsafe legacy renegotiation with clients which do not yet\n support the new secure renegotiation protocol, RFC 5746.\n [Joe Orton, and with thanks to the OpenSSL Team]", " *) SECURITY: CVE-2009-3555 (cve.mitre.org)\n mod_ssl: A partial fix for the TLS renegotiation prefix injection attack\n by rejecting any client-initiated renegotiations. Forcibly disable\n keepalive for the connection if there is any buffered data readable. Any\n configuration which requires renegotiation for per-directory/location\n access control is still vulnerable, unless using OpenSSL >= 0.9.8l.\n [Joe Orton, Ruediger Pluem, Hartmut Keil <Hartmut.Keil adnovum.ch>]", " *) SECURITY: CVE-2010-0408 (cve.mitre.org)\n mod_proxy_ajp: Respond with HTTP_BAD_REQUEST when the body is not sent\n when request headers indicate a request body is incoming; not a case of\n HTTP_INTERNAL_SERVER_ERROR. [Niku Toivola <niku.toivola sulake.com>]", " *) SECURITY: CVE-2010-0425 (cve.mitre.org)\n mod_isapi: Do not unload an isapi .dll module until the request\n processing is completed, avoiding orphaned callback pointers.\n [Brett Gervasoni <brettg senseofsecurity.com>, Jeff Trawick]", " *) core: Filter init functions are now run strictly once per request\n before handler invocation. The init functions are no longer run\n for connection filters. PR 49328. [Joe Orton]", " *) core: Adjust the output filter chain correctly in an internal\n redirect from a subrequest, preserving filters from the main\n request as necessary. PR 17629. [Joe Orton]", " *) mod_cache: Explicitly allow cache implementations to cache a 206 Partial\n Response if they so choose to do so. Previously an attempt to cache a 206\n was arbitrarily allowed if the response contained an Expires or\n Cache-Control header, and arbitrarily denied if both headers were missing.\n [Graham Leggett]", " *) core: Add microsecond timestamp fractions, process id and thread id\n to the error log. [Rainer Jung]", " *) configure: The \"most\" module set gets build by default. [Rainer Jung]", " *) configure: Building dynamic modules (DSO) by default. [Rainer Jung]", " *) configure: Fix broken VPATH build when using included APR.\n [Rainer Jung]", " *) mod_session_crypto: Fix configure problem when building\n with APR 2 and for VPATH builds with included APR.\n [Rainer Jung]", " *) mod_session_crypto: API compatibility with APR 2 crypto and\n APR Util 1.x crypto. [Rainer Jung]", " *) ab: Fix memory leak with -v2 and SSL. PR 49383.\n [Pavel Kankovsky <peak argo troja mff cuni cz>]", " *) core: Add per-module and per-directory loglevel configuration.\n Add some more trace logging.\n mod_rewrite: Replace RewriteLog/RewriteLogLevel with trace log levels.\n mod_ssl: Replace LogLevelDebugDump with trace log levels.\n mod_ssl/mod_proxy*: Adjust loglevels to be less verbose at levels info\n and debug.\n mod_dumpio: Replace DumpIOLogLevel with trace log levels.\n [Stefan Fritsch]", " *) mod_ldap: LDAP caching was suppressed (and ldap-status handler returns\n title page only) when any mod_ldap directives were used in VirtualHost\n context. [Eric Covener]", " *) mod_disk_cache: Decline the opportunity to cache if the response is\n a 206 Partial Content. This stops a reverse proxied partial response\n from becoming cached, and then being served in subsequent responses.\n [Graham Leggett]", " *) mod_deflate: avoid the risk of forwarding data before headers are set.\n PR 49369 [Matthew Steele <mdsteele google.com>]", " *) mod_authnz_ldap: Ensure nested groups are checked when the\n top-level group doesn't have any direct non-group members\n of attributes in AuthLDAPGroupAttribute. [Eric Covener]", " *) mod_authnz_ldap: Search or Comparison during authorization phase\n can use the credentials from the authentication phase\n (AuthLDAPSearchAsUSer,AuthLDAPCompareAsUser).\n PR 48340 [Domenico Rotiroti, Eric Covener]", " *) mod_authnz_ldap: Allow the initial DN search during authentication\n to use the HTTP username/pass instead of an anonymous or hard-coded\n LDAP id (AuthLDAPInitialBindAsUser, AuthLDAPInitialBindPattern).\n [Eric Covener]", " *) mod_authnz_ldap: Publish requested LDAP data with an AUTHORIZE_ prefix\n when this module is used for authorization. See AuthLDAPAuthorizePrefix.\n PR 45584 [Eric Covener]", " *) apxs -q: Stop filtering out ':' characters from the reported values.\n PR 45343. [Bill Cole]", " *) prefork MPM: Work around possible crashes on child exit in APR reslist\n cleanup code. PR 43857. [Tom Donovan]", " *) ab: fix number of requests sent by ab when keepalive is enabled. PR 48497.\n [Bryn Dole <dole blekko.com>]", " *) Log an error for failures to read a chunk-size, and return 408 instead of\n 413 when this is due to a read timeout. This change also fixes some cases\n of two error documents being sent in the response for the same scenario.\n [Eric Covener] PR49167", " *) mod_proxy_balancer: Add new directive BalancerNonce to allow admin\n to control/set the nonce used in the balancer-manager application.\n [Jim Jagielski]", " *) mod_proxy_connect: Support port ranges in AllowConnect. PR 23673.\n [Stefan Fritsch]", " *) Proxy balancer: support setting error status according to HTTP response\n code from a backend. PR 48939. [Daniel Ruggeri <DRuggeri primary.net>]", " *) htcacheclean: Introduce the ability to clean specific URLs from the\n cache, if provided as an optional parameter on the command line.\n [Graham Leggett]", " *) core: Introduce the IncludeStrict directive, which explicitly fails\n server startup if no files or directories match a wildcard path.\n [Graham Leggett]", " *) htcacheclean: Report additional statistics about entries deleted.\n PR 48944. [Mark Drayton mark markdrayton.info]", " *) Introduce SSLFIPS directive to support OpenSSL FIPS_mode; permits all\n builds of mod_ssl to use 'SSLFIPS off' for portability, but the proper\n build of openssl is required for 'SSLFIPS on'. PR 46270.\n [Dr Stephen Henson <steve openssl.org>, William Rowe]", " *) mod_proxy_http: Log the port of the remote server in various messages.\n PR 48812. [Igor Galić <i galic brainsware org>]", " *) mod_reqtimeout: Do not wrongly enforce timeouts for mod_proxy's backend\n connections and other protocol handlers (like mod_ftp). [Stefan Fritsch]", " *) mod_proxy_ajp: Really regard the operation a success, when the client\n aborted the connection. In addition adjust the log message if the client\n aborted the connection. [Ruediger Pluem]", " *) mod_ssl: Add the 'SSLInsecureRenegotiation' directive, which\n allows insecure renegotiation with clients which do not yet\n support the secure renegotiation protocol. [Joe Orton]", " *) mod_ssl: Fix a potential I/O hang if a long list of trusted CAs\n is configured for client cert auth. PR 46952. [Joe Orton]", " *) core: Only log a 408 if it is no keepalive timeout. PR 39785\n [Ruediger Pluem, Mark Montague <markmont umich.edu>]", " *) support/rotatelogs: Add -L option to create a link to the current\n log file. PR 48761 [<lyndon orthanc.ca>, Dan Poirier]", " *) mod_ldap: Update LDAPTrustedClientCert to consistently be a per-directory\n setting only, matching most of the documentation and examples.\n PR 46541 [Paul Reder, Eric Covener]", " *) mod_ldap: LDAPTrustedClientCert now accepts CA_DER/CA_BASE64 argument\n types previously allowed only in LDAPTrustedGlobalCert. [Eric Covener]", " *) mod_negotiation: Preserve query string over multiviews negotiation.\n This buglet was fixed for type maps in 2.2.6, but the same issue\n affected multiviews and was overlooked.\n PR 33112 [Joergen Thomsen <apache jth.net>]", " *) mod_ldap: Eliminate a potential crash with multiple LDAPTrustedClientCert\n when some are not password-protected. [Eric Covener]", " *) Fix startup segfault when the Mutex directive is used but no loaded\n modules use httpd mutexes. PR 48787. [Jeff Trawick]", " *) Proxy: get the headers right in a HEAD request with\n ProxyErrorOverride, by checking for an overridden error\n before not after going into a catch-all code path.\n PR 41646. [Nick Kew, Stuart Children]", " *) support/rotatelogs: Support the simplest log rotation case, log\n truncation. Useful when the log is being processed in real time\n using a command like tail. [Graham Leggett]", " *) support/htcacheclean: Teach it how to write a pid file (modelled on\n httpd's writing of a pid file) so that it becomes possible to run\n more than one instance of htcacheclean on the same machine.\n [Graham Leggett]", " *) Log command line on startup, so there's a record of command line\n arguments like -f. PR 48752. [Dan Poirier]", " *) Introduce mod_reflector, a handler capable of reflecting POSTed\n request bodies back within the response through the output filter\n stack. Can be used to turn an output filter into a web service.\n [Graham Leggett]", " *) mod_proxy_http: Make sure that when an ErrorDocument is served\n from a reverse proxied URL, that the subrequest respects the status\n of the original request. This brings the behaviour of proxy_handler\n in line with default_handler. PR 47106. [Graham Leggett]", " *) Support wildcards in both the directory and file components of\n the path specified by the Include directive. [Graham Leggett]", " *) mod_proxy, mod_proxy_http: Support remote https proxies\n by using HTTP CONNECT. PR 19188.\n [Philippe Dutrueux <lilas evidian.com>, Rainer Jung]", " *) apxs: Fix -A and -a options to ignore whitespace in httpd.conf\n [Philip M. Gollucci]", " *) worker: Don't report server has reached MaxClients until it has.\n Add message when server gets within MinSpareThreads of MaxClients.\n PR 46996. [Dan Poirier]", " *) mod_session: Session expiry was being initialised, but not updated\n on each session save, resulting in timed out sessions when there\n should not have been. Fixed. [Graham Leggett]", " *) mod_log_config: Add the R option to log the handler used within the\n request. [Christian Folini <christian.folini netnea com>]", " *) mod_include: Allow fine control over the removal of Last-Modified and\n ETag headers within the INCLUDES filter, making it possible to cache\n responses if desired. Fix the default value of the SSIAccessEnable\n directive. [Graham Leggett]", " *) Add new UnDefine directive to undefine a variable. PR 35350.\n [Stefan Fritsch]", " *) Make ap_pregsub(), used by AliasMatch and friends, use the same syntax\n for regex backreferences as mod_rewrite and mod_include: Remove the use\n of '&' as an alias for '$0' and allow to escape any character with a\n backslash. PR 48351. [Stefan Fritsch]", " *) mod_authnz_ldap: If AuthLDAPCharsetConfig is set, also convert the\n password to UTF-8. PR 45318.\n [Johannes Müller <joh_m gmx.de>, Stefan Fritsch]", " *) ab: Fix calculation of requests per second in HTML output. PR 48594.\n [Stefan Fritsch]", " *) mod_authnz_ldap: Failures to map a username to a DN, or to check a user\n password now result in an informational level log entry instead of\n warning level. [Eric Covener]", "Changes with Apache 2.3.5", " *) SECURITY: CVE-2010-0434 (cve.mitre.org)\n Ensure each subrequest has a shallow copy of headers_in so that the\n parent request headers are not corrupted. Eliminates a problematic\n optimization in the case of no request body. PR 48359\n [Jake Scott, William Rowe, Ruediger Pluem]", " *) Turn static function get_server_name_for_url() into public\n ap_get_server_name_for_url() and use it where appropriate. This\n fixes mod_rewrite generating invalid URLs for redirects to IPv6\n literal addresses. [Stefan Fritsch]", " *) mod_ldap: Introduce new config option LDAPTimeout to set the timeout\n for LDAP operations like bind and search. [Stefan Fritsch]", " *) mod_proxy, mod_proxy_ftp: Move ProxyFtpDirCharset from mod_proxy to\n mod_proxy_ftp. [Takashi Sato]", " *) mod_proxy, mod_proxy_connect: Move AllowCONNECT from mod_proxy to\n mod_proxy_connect. [Takashi Sato]", " *) mod_cache: Do an exact match of the keys defined by\n CacheIgnoreURLSessionIdentifiers against the querystring instead of\n a partial match. PR 48401.\n [Dodou Wang <wangdong.08 gmail.com>, Ruediger Pluem]", " *) mod_proxy_balancer: Fix crash in balancer-manager. [Rainer Jung]", " *) Core HTTP: disable keepalive when the Client has sent\n Expect: 100-continue\n but we respond directly with a non-100 response.\n Keepalive here led to data from clients continuing being treated as\n a new request.\n PR 47087 [Nick Kew]", " *) Core: reject NULLs in request line or request headers.\n PR 43039 [Nick Kew]", " *) Core: (re)-introduce -T commandline option to suppress documentroot\n check at startup.\n PR 41887 [Jan van den Berg <janvdberg gmail.com>]", " *) mod_autoindex: support XHTML as equivalent to HTML in IndexOptions,\n ScanHTMLTitles, ReadmeName, HeaderName\n PR 48416 [Dmitry Bakshaev <dab18 izhnet.ru>, Nick Kew]", " *) Proxy: Fix ProxyPassReverse with relative URL\n Derived (slightly erroneously) from PR 38864 [Nick Kew]", " *) mod_headers: align Header Edit with Header Set when used on Content-Type\n PR 48422 [Cyril Bonté <cyril.bonte free.fr>, Nick Kew>]", " *) mod_headers: Enable multi-match-and-replace edit option\n PR 46594 [Nick Kew]", " *) mod_filter: enable it to act on non-200 responses.\n PR 48377 [Nick Kew]", "Changes with Apache 2.3.4", " *) Replace AcceptMutex, LockFile, RewriteLock, SSLMutex, SSLStaplingMutex,\n and WatchdogMutexPath with a single Mutex directive. Add APIs to\n simplify setup and user customization of APR proc and global mutexes.\n (See util_mutex.h.) Build-time setting DEFAULT_LOCKFILE is no longer\n respected; set DEFAULT_REL_RUNTIMEDIR instead. [Jeff Trawick]", " *) http_core: KeepAlive no longer accepts other than On|Off.\n [Takashi Sato]", " *) mod_dav: Remove errno from dav_error interface. Calls to dav_new_error()\n and dav_new_error_tag() must be adjusted to add an apr_status_t parameter.\n [Jeff Trawick]", " *) mod_authnz_ldap: Add AuthLDAPBindAuthoritative to allow Authentication to\n try other providers in the case of an LDAP bind failure.\n PR 46608 [Justin Erenkrantz, Joe Schaefer, Tony Stevenson]", " *) Build: fix --with-module to work as documented\n PR 43881 [Gez Saunders <gez.saunders virgin.net>]", "Changes with Apache 2.3.3", " *) SECURITY: CVE-2009-3095 (cve.mitre.org)\n mod_proxy_ftp: sanity check authn credentials.\n [Stefan Fritsch <sf fritsch.de>, Joe Orton]", " *) SECURITY: CVE-2009-3094 (cve.mitre.org)\n mod_proxy_ftp: NULL pointer dereference on error paths.\n [Stefan Fritsch <sf fritsch.de>, Joe Orton]", " *) mod_ssl: enable support for ECC keys and ECDH ciphers. Tested against\n OpenSSL 1.0.0b3. [Vipul Gupta <vipul.gupta sun.com>, Sander Temme]", " *) mod_dav: Include uri when logging a PUT error due to connection abort.\n PR 38149. [Stefan Fritsch]", " *) mod_dav: Return 409 instead of 500 for a LOCK request if the parent\n resource does not exist or is not a collection. PR 43465. [Stefan Fritsch]", " *) mod_dav_fs: Return 409 instead of 500 for Litmus test case copy_nodestcoll\n (a COPY request where the parent of the destination resource does not\n exist). PR 39299. [Stefan Fritsch]", " *) mod_dav_fs: Don't delete the whole file if a PUT with content-range failed.\n PR 42896. [Stefan Fritsch]", " *) mod_dav_fs: Make PUT create files atomically and no longer destroy the\n old file if the transfer aborted. PR 39815. [Paul Querna, Stefan Fritsch]", " *) mod_dav_fs: Remove inode keyed locking as this conflicts with atomically\n creating files. On systems with inode numbers, this is a format change of\n the DavLockDB. The old DavLockDB must be deleted on upgrade.\n [Stefan Fritsch]", " *) mod_log_config: Make ${cookie}C correctly match whole cookie names\n instead of substrings. PR 28037. [Dan Franklin <dan dan-franklin.com>,\n Stefan Fritsch]", " *) vhost: A purely-numeric Host: header should not be treated as a port.\n PR 44979 [Nick Kew]", " *) mod_ldap: Avoid 500 errors with \"Unable to set LDAP_OPT_REFHOPLIMIT option to 5\"\n when built against openldap by using SDK LDAP_OPT_REFHOPLIMIT defaults unless\n LDAPReferralHopLimit is explicitly configured.\n [Eric Covener]", " *) mod_charset_lite: Honor 'CharsetOptions NoImplicitAdd'.\n [Eric Covener]", " *) mod_ssl: Add support for OCSP Stapling. PR 43822.\n [Dr Stephen Henson <shenson oss-institute.org>]", " *) mod_socache_shmcb: Allow parens in file name if cache size is given.\n Fixes SSLSessionCache directive mis-parsing parens in pathname.\n PR 47945. [Stefan Fritsch]", " *) htpasswd: Improve out of disk space handling. PR 30877. [Stefan Fritsch]", " *) htpasswd: Use MD5 hash by default on all platforms. [Stefan Fritsch]", " *) mod_sed: Reduce memory consumption when processing very long lines.\n PR 48024 [Basant Kumar Kukreja <basant.kukreja sun.com>]", " *) ab: Fix segfault in case the argument for -n is a very large number.\n PR 47178. [Philipp Hagemeister <oss phihag.de>]", " *) Allow ProxyPreserveHost to work in <Proxy> sections. PR 34901.\n [Stefan Fritsch]", " *) configure: Fix THREADED_MPMS so that mod_cgid is enabled again\n for worker MPM. [Takashi Sato]", " *) mod_dav: Provide a mechanism to obtain the request_rec and pathname\n from the dav_resource. [Jari Urpalainen <jari.urpalainen nokia.com>,\n Brian France <brian brianfrance.com>]", " *) Build: Use install instead of cp if available on installing\n modules to avoid segmentation fault. PR 47951. [hirose31 gmail.com]", " *) mod_cache: correctly consider s-maxage in cacheability\n decisions. [Dan Poirier]", " *) mod_logio/core: Report more accurate byte counts in mod_status if\n mod_logio is loaded. PR 25656. [Stefan Fritsch]", " *) mod_ldap: If LDAPSharedCacheSize is too small, try harder to purge\n some cache entries and log a warning. Also increase the default\n LDAPSharedCacheSize to 500000. This is a more realistic size suitable\n for the default values of 1024 for LdapCacheEntries/LdapOpCacheEntries.\n PR 46749. [Stefan Fritsch]", " *) mod_rewrite: Make sure that a hostname:port isn't fully qualified if\n the request is a CONNECT request. [Bill Zajac <billz consultla.com>]", " *) mod_cache: Teach CacheEnable and CacheDisable to work from within a\n Location section, in line with how ProxyPass works. [Graham Leggett]", " *) mod_reqtimeout: New module to set timeouts and minimum data rates for\n receiving requests from the client. [Stefan Fritsch]", " *) core: Fix potential memory leaks by making sure to not destroy\n bucket brigades that have been created by earlier filters.\n [Stefan Fritsch]", " *) core, mod_deflate, mod_sed: Reduce memory usage by reusing bucket\n brigades in several places. [Stefan Fritsch]", " *) mod_cache: Fix uri_meets_conditions() so that CacheEnable will\n match by scheme, or by a wildcarded hostname. PR 40169\n [Peter Grandi <pg_asf asf.for.sabi.co.uk>, Graham Leggett]", " *) suxec: Allow to log an error if exec fails by setting FD_CLOEXEC\n on the log file instead of closing it. PR 10744. [Nicolas Rachinsky]", " *) mod_mime: Make RemoveType override the info from TypesConfig.\n PR 38330. [Stefan Fritsch]", " *) mod_cache: Introduce the option to run the cache from within the\n normal request handler, and to allow fine grained control over\n where in the filter chain content is cached. Adds CacheQuickHandler\n directive. [Graham Leggett]", " *) core: Treat timeout reading request as 408 error, not 400.\n Log 408 errors in access log as was done in Apache 1.3.x.\n PR 39785 [Nobutaka Mantani <nobutaka nobutaka.org>,\n Stefan Fritsch <sf fritsch.de>, Dan Poirier]", " *) mod_ssl: Reintroduce SSL_CLIENT_S_DN, SSL_CLIENT_I_DN, SSL_SERVER_S_DN,\n SSL_SERVER_I_DN back to the environment variables to be set by mod_ssl.\n [Peter Sylvester <peter.sylvester edelweb.fr>]", " *) mod_disk_cache: don't cache incomplete responses, per RFC 2616, 13.8.\n PR15866. [Dan Poirier]", " *) ab: ab segfaults in verbose mode on https sites\n PR46393. [Ryan Niebur]", " *) mod_dav: Allow other modules to become providers and add resource types\n to the DAV response. [Jari Urpalainen <jari.urpalainen nokia.com>,\n Brian France <brian brianfrance.com>]", " *) mod_dav: Allow other modules to add things to the DAV or Allow headers\n of an OPTIONS request. [Jari Urpalainen <jari.urpalainen nokia.com>,\n Brian France <brian brianfrance.com>]", " *) core: Lower memory usage of core output filter.\n [Stefan Fritsch <sf sfritsch.de>]", " *) mod_mime: Detect invalid use of MultiviewsMatch inside Location and\n LocationMatch sections. PR47754. [Dan Poirier]", " *) mod_request: Make sure the KeptBodySize directive rejects values\n that aren't valid numbers. [Graham Leggett]", " *) mod_session_crypto: Sanity check should the potentially encrypted\n session cookie be too short. [Graham Leggett]", " *) mod_session.c: Prevent a segfault when session is added but not\n configured. [Graham Leggett]", " *) htcacheclean: 19 ways to fail, 1 error message. Fixed. [Graham Leggett]", " *) mod_auth_digest: Fail server start when nonce count checking\n is configured without shared memory, or md5-sess algorithm is\n configured. [Dan Poirier]", " *) mod_proxy_connect: The connect method doesn't work if the client is\n connecting to the apache proxy through an ssl socket. Fixed.\n PR29744. [Brad Boyer, Mark Cave-Ayland, Julian Gilbey, Fabrice Durand,\n David Gence, Tim Dodge, Per Gunnar Hans, Emmanuel Elango,\n Kevin Croft, Rudolf Cardinal]", " *) mod_ssl: The error message when SSLCertificateFile is missing should\n at least give the name or position of the problematic virtual host\n definition. [Stefan Fritsch sf sfritsch.de]", " *) mod_auth_digest: Fix null pointer when qop=none. [Dan Poirier]", " *) Add support for HTTP PUT to ab. [Jeff Barnes <jbarnesweb yahoo.com>]", " *) mod_headers: generalise the envclause to support expression\n evaluation with ap_expr parser [Nick Kew]", " *) mod_cache: Introduce the thundering herd lock, a mechanism to keep\n the flood of requests at bay that strike a backend webserver as\n a cached entity goes stale. [Graham Leggett]", " *) mod_auth_digest: Fix usage of shared memory and re-enable it.\n PR 16057 [Dan Poirier]", " *) Preserve Port information over internal redirects\n PR 35999 [Jonas Ringh <jonas.ringh cixit.se>]", " *) Proxy: unable to connect to a backend is SERVICE_UNAVAILABLE,\n rather than BAD_GATEWAY or (especially) NOT_FOUND.\n PR 46971 [evanc nortel.com]", " *) Various modules: Do better checking of pollset operations in order to\n avoid segmentation faults if they fail. PR 46467\n [Stefan Fritsch <sf sfritsch.de>]", " *) mod_autoindex: Correctly create an empty cell if the description\n for a file is missing. PR 47682 [Peter Poeml <poeml suse.de>]", " *) ab: Fix broken error messages after resolver or connect() failures.\n [Jeff Trawick]", " *) SECURITY: CVE-2009-1890 (cve.mitre.org)\n Fix a potential Denial-of-Service attack against mod_proxy in a\n reverse proxy configuration, where a remote attacker can force a\n proxy process to consume CPU time indefinitely. [Nick Kew, Joe Orton]", " *) SECURITY: CVE-2009-1191 (cve.mitre.org)\n mod_proxy_ajp: Avoid delivering content from a previous request which\n failed to send a request body. PR 46949 [Ruediger Pluem]", " *) htdbm: Fix possible buffer overflow if dbm database has very\n long values. PR 30586 [Dan Poirier]", " *) core: Return APR_EOF if request body is shorter than the length announced\n by the client. PR 33098 [ Stefan Fritsch <sf sfritsch.de>]", " *) mod_suexec: correctly set suexec_enabled when httpd is run by a\n non-root user and may have insufficient permissions.\n PR 42175 [Jim Radford <radford blackbean.org>]", " *) mod_ssl: Fix SSL_*_DN_UID variables to use the 'userID' attribute\n type. PR 45107. [Michael Ströder <michael stroeder.com>,\n Peter Sylvester <peter.sylvester edelweb.fr>]", " *) mod_proxy_http: fix case sensitivity checking transfer encoding\n PR 47383 [Ryuzo Yamamoto <ryuzo.yamamoto gmail.com>]", " *) mod_alias: ensure Redirect issues a valid URL.\n PR 44020 [Håkon Stordahl <hakon stordahl.org>]", " *) mod_dir: add FallbackResource directive, to enable admin to specify\n an action to happen when a URL maps to no file, without resorting\n to ErrorDocument or mod_rewrite. PR 47184 [Nick Kew]", " *) mod_cgid: Do not leak the listening Unix socket file descriptor to the\n CGI process. PR 47335 [Kornél Pál <kornelpal gmail.com>]", " *) mod_rewrite: Remove locking for writing to the rewritelog.\n PR 46942 [Dan Poirier <poirier pobox.com>]", " *) mod_alias: check sanity in Redirect arguments.\n PR 44729 [Sönke Tesch <st kino-fahrplan.de>, Jim Jagielski]", " *) mod_proxy_http: fix Host: header for literal IPv6 addresses.\n PR 47177 [Carlos Garcia Braschi <cgbraschi gmail.com>]", " *) mod_cache: Add CacheIgnoreURLSessionIdentifiers directive to ignore\n defined session identifiers encoded in the URL when caching.\n [Ruediger Pluem]", " *) mod_rewrite: Fix the error string returned by RewriteRule.\n RewriteRule returned \"RewriteCond: bad flag delimiters\" when the 3rd\n argument of RewriteRule was not started with \"[\" or not ended with \"]\".\n PR 45082 [Vitaly Polonetsky <m_vitaly topixoft.com>]", " *) Windows: Fix usage message.\n [Rainer Jung]", " *) apachectl: When passing through arguments to httpd in\n non-SysV mode, use the \"$@\" syntax to preserve arguments.\n [Eric Covener]", " *) mod_dbd: add DBDInitSQL directive to enable SQL statements to\n be run when a connection is opened. PR 46827\n [Marko Kevac <mkevac gmail.com>]", " *) mod_cgid: Improve handling of long AF_UNIX socket names (ScriptSock).\n PR 47037. [Jeff Trawick]", " *) mod_proxy_ajp: Check more strictly that the backend follows the AJP\n protocol. [Mladen Turk]", " *) mod_proxy_ajp: Forward remote port information by default.\n [Rainer Jung]", " *) Allow MPMs to be loaded dynamically, as with most other modules. Use\n --enable-mpms-shared={list|\"all\"} to enable. This required changes to\n the MPM interfaces. Removed: mpm.h, mpm_default.h (as an installed\n header), APACHE_MPM_DIR, MPM_NAME, ap_threads_per_child,\n ap_max_daemons_limit, ap_my_generation, etc. ap_mpm_query() can't be\n called until after the register-hooks phase. [Jeff Trawick]", " *) mod_ssl: Add SSLProxyCheckPeerExpire and SSLProxyCheckPeerCN directives\n to enable stricter checking of remote server certificates.\n [Ruediger Pluem]", " *) ab: Fix a 100% CPU loop on platforms where a failed non-blocking connect\n returns EINPROGRESS and a subsequent poll() returns only POLLERR.\n Observed on HP-UX. [Eric Covener]", " *) Remove broken support for BeOS, TPF, and even older platforms such\n as A/UX, Next, and Tandem. [Jeff Trawick]", " *) mod_proxy_ftp: Add ProxyFtpListOnWildcard directive to allow files with\n globbing characters to be retrieved instead of converted into a\n directory listing. PR 46789 [Dan Poirier <poirier pobox.com>]", " *) Provide ap_retained_data_create()/ap_retained_data_get() for preservation\n of module state across unload/load. [Jeff Trawick]", " *) mod_substitute: Fix a memory leak. PR 44948\n [Dan Poirier <poirier pobox.com>]", "Changes with Apache 2.3.2", " *) mod_mime_magic: Fix detection of compressed content. [Rainer Jung]", " *) mod_negotiation: Escape pathes of filenames in 406 responses to avoid\n HTML injections and HTTP response splitting. PR 46837.\n [Geoff Keating <geoffk apple.com>]", " *) mod_ssl: add support for type-safe STACK constructs in OpenSSL\n development HEAD. PR 45521. [Kaspar Brand, Sander Temme]", " *) ab: Fix maintenance of the pollset to resolve EALREADY errors\n with kqueue (BSD/OS X) and excessive CPU with event ports (Solaris).\n PR 44584. Use APR_POLLSET_NOCOPY for better performance with some\n pollset implementations. [Jeff Trawick]", " *) mod_disk_cache: The module now turns off sendfile support if\n 'EnableSendfile off' is defined globally. [Lars Eilebrecht]", " *) mod_deflate: Adjust content metadata before bailing out on 304\n responses so that the metadata does not differ from 200 response.\n [Roy T. Fielding]", " *) mod_deflate: Fix creation of invalid Etag headers. We now make sure\n that the Etag value is properly quoted when adding the gzip marker.\n PR 39727, 45023. [Lars Eilebrecht, Roy T. Fielding]", " *) Added 20x22 icons for ODF, SVG, and XML documents. PR 37185.\n [Peter Harlow]", " *) Disabled DefaultType directive and removed ap_default_type()\n from core. We now exclude Content-Type from responses for which\n a media type has not been configured via mime.types, AddType,\n ForceType, or some other mechanism. PR 13986. [Roy T. Fielding]", " *) mod_rewrite: Add IPV6 variable to RewriteCond\n [Ryan Phillips <ryan-apache trolocsis.com>]", " *) core: Enhance KeepAliveTimeout to support a value in milliseconds.\n PR 46275. [Takashi Sato]", " *) rotatelogs: Allow size units B, K, M, G and combination of\n time and size based rotation. [Rainer Jung]", " *) rotatelogs: Add flag for verbose (debug) output. [Rainer Jung]", " *) mod_ssl: Fix merging of SSLRenegBufferSize directive. PR 46508\n [<tlhackque yahoo.com>]", " *) core: Translate the the status line to ASCII on EBCDIC platforms in\n ap_send_interim_response() and for locally generated \"100 Continue\"\n responses. [Eric Covener]", " *) prefork: Fix child process hang during graceful restart/stop in\n configurations with multiple listening sockets. PR 42829. [Joe Orton,\n Jeff Trawick]", " *) mod_session_crypto: Ensure that SessionCryptoDriver can only be\n set in the global scope. [Graham Leggett]", " *) mod_ext_filter: We need to detect failure to startup the filter\n program (a mangled response is not acceptable). Fix to detect\n failure, and offer configuration option either to abort or\n to remove the filter and continue.\n PR 41120 [Nick Kew]", " *) mod_session_crypto: Rewrite the session_crypto module against the\n apr_crypto API. [Graham Leggett]", " *) mod_auth_form: Fix a pool lifetime issue, don't remove the subrequest\n until the main request is cleaned up. [Graham Leggett]", "Changes with Apache 2.3.1", " *) ap_slotmem: Add in new slot-based memory access API impl., including\n 2 providers (mod_sharedmem and mod_plainmem) [Jim Jagielski,\n Jean-Frederic Clere, Brian Akins <brian.akins turner.com>]", " *) mod_include: support generating non-ASCII characters as entities in SSI\n PR 25202 [Nick Kew]", " *) core/utils: Enhance ap_escape_html API to support escaping non-ASCII chars\n PR 25202 [Nick Kew]", " *) mod_rewrite: fix \"B\" flag breakage by reverting r5589343\n PR 45529 [Bob Ionescu <bobsiegen googlemail.com>]", " *) CGI: return 504 (Gateway timeout) rather than 500 when a script\n times out before returning status line/headers.\n PR 42190 [Nick Kew]", " *) mod_cgid: fix segfault problem on solaris.\n PR 39332 [Masaoki Kobayashi <masaoki techfirm.co.jp>]", " *) mod_proxy_scgi: Added. [André Malo]", " *) mod_cache: Introduce 'no-cache' per-request environment variable\n to prevent the saving of an otherwise cacheable response.\n [Eric Covener]", " *) mod_rewrite: Introduce DiscardPathInfo|DPI flag to stop the troublesome\n way that per-directory rewrites append the previous notion of PATH_INFO\n to each substitution before evaluating subsequent rules.\n PR 38642 [Eric Covener]", " *) mod_cgid: Do not add an empty argument when calling the CGI script.\n PR 46380 [Ruediger Pluem]", " *) scoreboard: Remove unused sb_type from process_score.\n [Torsten Foertsch <torsten.foertsch gmx.net>, Chris Darroch]", " *) mod_ssl: Add SSLRenegBufferSize directive to allow changing the\n size of the buffer used for the request-body where necessary\n during a per-dir renegotiation. PR 39243. [Joe Orton]", " *) mod_proxy_fdpass: New module to pass a client connection over to a separate\n process that is reading from a unix daemon socket.", " *) mod_ssl: Improve environment variable extraction to be more\n efficient and to correctly handle DNs with duplicate tags.\n PR 45975. [Joe Orton]", " *) Remove the obsolete serial attribute from the RPM spec file. Compile\n against the external pcre. Add missing binaries fcgistarter, and\n mod_socache* and mod_session*. [Graham Leggett]", "Changes with Apache 2.3.0", " *) mod_ratelimit: New module to do bandwidth rate limiting. [Paul Querna]", " *) Remove X-Pad header which was added as a work around to a bug in\n Netscape 2.x to 4.0b2. [Takashi Sato <takashi lans-tv.com>]", " *) Add DTrace Statically Defined Tracing (SDT) probes.\n [Theo Schlossnagle <jesus omniti.com>, Paul Querna]", " *) mod_proxy_balancer: Move all load balancing implementations\n as individual, self-contained mod_proxy submodules under\n modules/proxy/balancers [Jim Jagielski]", " *) Rename APIs to include ap_ prefix:\n find_child_by_pid -> ap_find_child_by_pid\n suck_in_APR -> ap_suck_in_APR\n sys_privileges_handlers -> ap_sys_privileges_handlers\n unixd_accept -> ap_unixd_accept\n unixd_config -> ap_unixd_config\n unixd_killpg -> ap_unixd_killpg\n unixd_set_global_mutex_perms -> ap_unixd_set_global_mutex_perms\n unixd_set_proc_mutex_perms -> ap_unixd_set_proc_mutex_perms\n unixd_set_rlimit -> ap_unixd_set_rlimit\n [Paul Querna]", " *) mod_lbmethod_heartbeat: New module to load balance mod_proxy workers\n based on heartbeats. [Paul Querna]", " *) mod_heartmonitor: New module to collect heartbeats, and write out a file\n so that other modules can load balance traffic as needed. [Paul Querna]", " *) mod_heartbeat: New module to generate multicast heartbeats to know if a\n server is online. [Paul Querna]", " *) mod_buffer: Honour the flush bucket and flush the buffer in the\n input filter. Make sure that metadata buckets are written to\n the buffer, not to the final brigade. [Graham Leggett]", " *) mod_buffer: Optimise the buffering of heap buckets when the heap\n buckets stay exactly APR_BUCKET_BUFF_SIZE long. [Graham Leggett,\n Ruediger Pluem]", " *) mod_buffer: Optional support for buffering of the input and output\n filter stacks. Can collapse many small buckets into fewer larger\n buckets, and prevents excessively small chunks being sent over\n the wire. [Graham Leggett]", " *) mod_privileges: new module to make httpd on Solaris privileges-aware\n and to enable different virtualhosts to run with different\n privileges and Unix user/group IDs [Nick Kew]", " *) mod_mem_cache: this module has been removed. [William Rowe]", " *) authn/z: Remove mod_authn_default and mod_authz_default.\n [Chris Darroch]", " *) authz: Fix handling of authz configurations, make default authz\n logic replicate 2.2.x authz logic, and replace <Satisfy*>, Reject,\n and AuthzMergeRules directives with Match, <Match*>, and AuthzMerge\n directives. [Chris Darroch]", " *) mod_authn_core: Prevent crash when provider alias created to\n provider which is not yet registered. [Chris Darroch]", " *) mod_authn_core: Add AuthType of None to support disabling\n authentication. [Chris Darroch]", " *) core: Allow <Limit> and <LimitExcept> directives to nest, and\n constrain their use to conform with that of other access control\n and authorization directives. [Chris Darroch]", " *) unixd: turn existing code into a module, and turn the set user/group\n and chroot into a child_init function. [Nick Kew]", " *) mod_dir: Support \"DirectoryIndex disabled\"\n Suggested By André Warnier <aw ice-sa.com> [Eric Covener]", " *) mod_ssl: Send Content-Type application/ocsp-request for POST requests to\n OSCP responders. PR 46014 [Dr Stephen Henson <steve openssl.org>]", " *) mod_authnz_ldap: don't return NULL-valued environment variables to\n other modules. PR 39045 [Francois Pesce <francois.pesce gmail.com>]", " *) Don't adjust case in pathname components that are not of interest\n to mod_mime. Fixes mod_negotiation's use of such components.\n PR 43250 [Basant Kumar Kukreja <basant.kukreja sun.com>]", " *) Be tolerant in what you accept - accept slightly broken\n status lines from a backend provided they include a valid status code.\n PR 44995 [Rainer Jung <rainer.jung kippdata.de>]", " *) New module mod_sed: filter Request/Response bodies through sed\n [Basant Kumar Kukreja <basant.kukreja sun.com>]", " *) mod_auth_form: Make sure that basic authentication is correctly\n faked directly after login. [Graham Leggett]", " *) mod_session_cookie, mod_session_dbd: Make sure cookies are set both\n within the output headers and error output headers, so that the\n session is maintained across redirects. [Graham Leggett]", " *) mod_auth_form: Make sure the logged in user is populated correctly\n after a form login. Fixes a missing REMOTE_USER variable directly\n following a login. [Graham Leggett]", " *) mod_session_cookie: Make sure that cookie attributes are correctly\n included in the blank cookie when cookies are removed. This fixes an\n inability to log out when using mod_auth_form. [Graham Leggett]", " *) mod_session: Prevent a segfault when a CGI script sets a cookie with a\n null value. [David Shane Holden <dpejesh apache.org>]", " *) core, authn/z: Determine registered authn/z providers directly in\n ap_setup_auth_internal(), which allows optional functions that just\n wrapped ap_list_provider_names() to be removed from authn/z modules.\n [Chris Darroch]", " *) authn/z: Convert common provider version strings to macros.\n [Chris Darroch]", " *) core: When testing for slash-terminated configuration paths in\n ap_location_walk(), don't look past the start of an empty string\n such as that created by a <Location \"\"> directive.\n [Chris Darroch]", " *) core, mod_proxy: If a kept_body is present, it becomes safe for\n subrequests to support message bodies. Make sure that safety\n checks within the core and within the proxy are not triggered\n when kept_body is present. This makes it possible to embed\n proxied POST requests within mod_include. [Graham Leggett]", " *) mod_auth_form: Make sure the input filter stack is properly set\n up before reading the login form. Make sure the kept body filter\n is correctly inserted to ensure the body can be read a second\n time safely should the authn be successful. [Graham Leggett,\n Ruediger Pluem]", " *) mod_request: Insert the KEPT_BODY filter via the insert_filter\n hook instead of during fixups. Add a safety check to ensure the\n filters cannot be inserted more than once. [Graham Leggett,\n Ruediger Pluem]", " *) ap_cache_cacheable_headers_out() will (now) always\n merge an error headers _before_ clearing them and _before_\n merging in the actual entity headers and doing normal\n hop-by-hop cleansing. [Dirk-Willem van Gulik].", " *) cache: retire ap_cache_cacheable_hdrs_out() which was used\n for both in- and out-put headers; and replace it by a single\n ap_cache_cacheable_headers() wrapped in a in- and out-put\n specific ap_cache_cacheable_headers_in()/out(). The latter\n which will also merge error and ensure content-type. To keep\n cache modules consistent with ease. This API change bumps\n up the minor MM by one [Dirk-Willem van Gulik].", " *) Move the KeptBodySize directive, kept_body filters and the\n ap_parse_request_body function out of the http module and into a\n new module called mod_request, reducing the size of the core.\n [Graham Leggett]", " *) mod_dbd: Handle integer configuration directive parameters with a\n dedicated function.", " *) Change the directives within the mod_session* modules to be valid\n both inside and outside the location/directory sections, as\n suggested by wrowe. [Graham Leggett]", " *) mod_auth_form: Add a module capable of allowing end users to log\n in using an HTML form, storing the credentials within mod_session.\n [Graham Leggett]", " *) Add a function to the http filters that is able to parse an HTML\n form request with the type of application/x-www-form-urlencoded.\n [Graham Leggett]", " *) mod_session_crypto: Initialise SSL in the post config hook.\n [Ruediger Pluem, Graham Leggett]", " *) mod_session_dbd: Add a session implementation capable of storing\n session information in a SQL database via the dbd interface. Useful\n for sites where session privacy is important. [Graham Leggett]", " *) mod_session_crypto: Add a session encoding implementation capable\n of encrypting and decrypting sessions wherever they may be stored.\n Introduces a level of privacy when sessions are stored on the\n browser. [Graham Leggett]", " *) mod_session_cookie: Add a session implementation capable of storing\n session information within cookies on the browser. Useful for high\n volume sites where server bound sessions are too resource intensive.\n [Graham Leggett]", " *) mod_session: Add a generic session interface to unify the different\n attempts at saving persistent sessions across requests.\n [Graham Leggett]", " *) core, authn/z: Avoid calling access control hooks for internal requests\n with configurations which match those of initial request. Revert to\n original behaviour (call access control hooks for internal requests\n with URIs different from initial request) if any access control hooks or\n providers are not registered as permitting this optimization.\n Introduce wrappers for access control hook and provider registration\n which can accept additional mode and flag data. [Chris Darroch]", " *) Introduced ap_expr API for expression evaluation.\n This is adapted from mod_include, which is the first module\n to use the new API.\n [Nick Kew]", " *) mod_authz_dbd: When redirecting after successful login/logout per\n AuthzDBDRedirectQuery, do not report authorization failure, and use\n first row returned by database query instead of last row.\n [Chris Darroch]", " *) mod_ldap: Correctly return all requested attribute values\n when some attributes have a null value.\n PR 44560 [Anders Kaseorg <anders kaseorg.com>]", " *) core: check symlink ownership if both FollowSymlinks and\n SymlinksIfOwnerMatch are set [Nick Kew]", " *) core: fix origin checking in SymlinksIfOwnerMatch\n PR 36783 [Robert L Mathews <rob-apache.org.bugs tigertech.net>]", " *) Activate mod_cache, mod_file_cache and mod_disk_cache as part of the\n 'most' set for '--enable-modules' and '--enable-shared-mods'. Include\n mod_mem_cache in 'all' as well. [Dirk-Willem van Gulik]", " *) Also install mod_so.h, mod_rewrite.h and mod_cache.h; as these\n contain public function declarations which are useful for\n third party module authors. PR 42431 [Dirk-Willem van Gulik].", " *) mod_dir, mod_negotiation: pass the output filter information\n to newly created sub requests; as these are later on used\n as true requests with an internal redirect. This allows for\n mod_cache et.al. to trap the results of the redirect.\n [Dirk-Willem van Gulik, Ruediger Pluem]", " *) mod_ldap: Add support (taking advantage of the new APR capability)\n for ldap rebind callback while chasing referrals. This allows direct\n searches on LDAP servers (in particular MS Active Directory 2003+)\n using referrals without the use of the global catalog.\n PRs 26538, 40268, and 42557 [Paul J. Reder]", " *) ApacheMonitor.exe: Introduce --kill argument for use by the\n installer. This will permit the installation tool to remove\n all running instances before attempting to remove the .exe.\n [William Rowe]", " *) mod_ssl: Add support for OCSP validation of client certificates.\n PR 41123. [Marc Stern <marc.stern approach.be>, Joe Orton]", " *) mod_serf: New module for Reverse Proxying. [Paul Querna]", " *) core: Add the option to keep aside a request body up to a certain\n size that would otherwise be discarded, to be consumed by filters\n such as mod_include. When enabled for a directory, POST requests\n to shtml files can be passed through to embedded scripts as POST\n requests, rather being downgraded to GET requests. [Graham Leggett]", " *) mod_ssl: Fix TLS upgrade (RFC 2817) support. PR 41231. [Joe Orton]", " *) scoreboard: Correctly declare ap_time_process_request.\n PR 43789 [Tom Donovan <Tom.Donovan acm.org>]", " *) core; scoreboard: ap_get_scoreboard_worker(sbh) now takes the sbh member\n from the connection rec, ap_get_scoreboard_worker(proc, thread) will now\n provide the unusual legacy lookup. [William Rowe]", " *) mpm winnt: fix null pointer dereference\n PR 42572 [Davi Arnaut]", " *) mod_authnz_ldap, mod_authn_dbd: Tidy up the code to expose authn\n parameters to the environment. Improve portability to\n EBCDIC machines by using apr_toupper(). [Martin Kraemer]", " *) mod_ldap, mod_authnz_ldap: Add support for nested groups (i.e. the ability\n to authorize an authenticated user via a \"require ldap-group X\" directive\n where the user is not in group X, but is in a subgroup contained in X.\n PR 42891 [Paul J. Reder]", " *) mod_ssl: Add support for caching SSL Sessions in memcached. [Paul Querna]", " *) apxs: Enhance -q flag to print all known variables and their values\n when invoked without variable name(s).\n [William Rowe, Sander Temme]", " *) apxs: Eliminate run-time check for mod_so. PR 40653.\n [David M. Lee <dmlee crossroads.com>]", " *) beos MPM: Create pmain pool and run modules' child_init hooks when\n entering ap_mpm_run(), then destroy pmain when exiting ap_mpm_run().\n [Chris Darroch]", " *) netware MPM: Destroy pmain pool when exiting ap_mpm_run() so that\n cleanups registered in modules' child_init hooks are performed.\n [Chris Darroch]", " *) Fix issue which could cause error messages to be written to access logs\n on Win32. PR 40476. [Tom Donovan <Tom.Donovan acm.org>]", " *) The LockFile directive, which specifies the location of\n the accept() mutex lockfile, is deprecated. Instead, the\n AcceptMutex directive now takes an optional lockfile\n location parameter, ala SSLMutex. [Jim Jagielski]", " *) mod_authn_dbd: Export any additional columns queried in the SQL select\n into the environment with the name AUTHENTICATE_<COLUMN>. This brings\n mod_authn_dbd behaviour in line with mod_authnz_ldap. [Graham Leggett]", " *) mod_dbd: Key the storage of prepared statements on the hex string\n value of server_rec, rather than the server name, as the server name\n may change (eg when the server name is set) at any time, causing\n weird behaviour in modules dependent on mod_dbd. [Graham Leggett]", " *) mod_proxy_fcgi: Added win32 build. [Mladen Turk]", " *) sendfile_nonblocking() takes the _brigade_ as an argument, gets\n the first bucket from the brigade, finds it not to be a FILE\n bucket and barfs. The fix is to pass a bucket rather than a brigade.\n [Niklas Edmundsson <nikke acc.umu.se>]", " *) mod_rewrite: support rewritemap by SQL query [Nick Kew]", " *) ap_get_server_version() has been removed. Third-party modules must\n now use ap_get_server_banner() or ap_get_server_description().\n [Jeff Trawick]", " *) All MPMs: Introduce a check_config phase between pre_config and\n open_logs, to allow modules to review interdependent configuration\n directive values and adjust them while messages can still be logged\n to the console. Handle relevant MPM directives during this phase\n and format messages for both the console and the error log, as\n appropriate. [Chris Darroch]", " *) core: Do not allow internal redirects like the DirectoryIndex of mod_dir\n to circumvent the symbolic link checks imposed by FollowSymLinks and\n SymLinksIfOwnerMatch. [Nick Kew, Ruediger Pluem, William Rowe]", " *) New SSLLogLevelDebugDump [ None (default) | IO (not bytes) | Bytes ]\n configures the I/O Dump of SSL traffic, when LogLevel is set to Debug.\n The default is none as this is far greater debugging resolution than\n the typical administrator is prepared to untangle. [William Rowe]", " *) mod_disk_cache: If possible, check if the size of an object to cache is\n within the configured boundaries before actually saving data.\n [Niklas Edmundsson <nikke acc.umu.se>]", " *) Worker and event MPMs: Remove improper scoreboard updates which were\n performed in the event of a fork() failure. [Chris Darroch]", " *) Add support for fcgi:// proxies to mod_rewrite.\n [Markus Schiegl <ms schiegl.com>]", " *) Remove incorrect comments from scoreboard.h regarding conditional\n loading of worker_score structure with mod_status, and remove unused\n definitions relating to old life_status field.\n [Chris Darroch <chrisd pearsoncmg.com>]", " *) Remove allocation of memory for unused array of lb_score pointers\n in ap_init_scoreboard(). [Chris Darroch <chrisd pearsoncmg.com>]", " *) Add mod_proxy_fcgi, a FastCGI back end for mod_proxy.\n [Garrett Rooney, Jim Jagielski, Paul Querna]", " *) Event MPM: Fill in the scoreboard's tid field. PR 38736.\n [Chris Darroch <chrisd pearsoncmg.com>]", " *) mod_charset_lite: Remove Content-Length when output filter can\n invalidate it. Warn when input filter can invalidate it.\n [Jeff Trawick]", " *) Authz: Add the new module mod_authn_core that will provide common\n authn directives such as 'AuthType', 'AuthName'. Move the directives\n 'AuthType' and 'AuthName' out of the core module and merge mod_authz_alias\n into mod_authn_core. [Brad Nicholes]", " *) Authz: Move the directives 'Order', 'Allow', 'Deny' and 'Satisfy'\n into the new module mod_access_compat which can be loaded to provide\n support for these directives.\n [Brad Nicholes]", " *) Authz: Move the 'Require' directive from the core module as well as\n add the directives '<SatisfyAll>', '<SatisfyOne>', '<RequireAlias>'\n and 'Reject' to mod_authz_core. The new directives introduce 'AND/OR'\n logic into the authorization processing. [Brad Nicholes]", " *) Authz: Add the new module mod_authz_core which acts as the\n authorization provider vector and contains common authz\n directives. [Brad Nicholes]", " *) Authz: Renamed mod_authz_dbm authz providers from 'group' and\n 'file-group' to 'dbm-group' and 'dbm-file-group'. [Brad Nicholes]", " *) Authz: Added the new authz providers 'env', 'ip', 'host', 'all' to handle\n host-based access control provided by mod_authz_host and invoked\n through the 'Require' directive. [Brad Nicholes]", " *) Authz: Convert all of the authz modules from hook based to\n provider based. [Brad Nicholes]", " *) mod_cache: Add CacheMinExpire directive to set the minimum time in\n seconds to cache a document.\n [Brian Akins <brian.akins turner.com>, Ruediger Pluem]", " *) mod_authz_dbd: SQL authz with Login/Session support [Nick Kew]", " *) Fix typo in ProxyStatus syntax error message.\n [Christophe Jaillet <christophe.jaillet wanadoo.fr>]", " *) Asynchronous write completion for the Event MPM. [Brian Pane]", " *) Added an End-Of-Request bucket type. The logging of a request and\n the freeing of its pool are now done when the EOR bucket is destroyed.\n This has the effect of delaying the logging until right after the last\n of the response is sent; ap_core_output_filter() calls the access logger\n indirectly when it destroys the EOR bucket. [Brian Pane]", " *) Rewrite of logresolve support utility: IPv6 addresses are now supported\n and the format of statistical output has changed. [Colm MacCarthaigh]", " *) Rewrite of ap_coreoutput_filter to do nonblocking writes [Brian Pane]", " *) Added new connection states for handler and write completion\n [Brian Pane]", " *) mod_cgid: Refuse to work on Solaris 10 due to OS bugs. PR 34264.\n [Justin Erenkrantz]", " *) Teach mod_ssl to use arbitrary OIDs in an SSLRequire directive,\n allowing string-valued client certificate attributes to be used for\n access control, as in: SSLRequire \"value\" in OID(\"1.3.6.1.4.1.18060.1\")\n [Martin Kraemer, David Reid]", " [Apache 2.3.0-dev includes those bug fixes and changes with the\n Apache 2.2.xx tree as documented, and except as noted, below.]", "Changes with Apache 2.2.x and later:", " *) http://svn.apache.org/viewvc/httpd/httpd/branches/2.2.x/CHANGES?view=markup", "Changes with Apache 2.0.x and later:", " *) http://svn.apache.org/viewvc/httpd/httpd/branches/2.0.x/CHANGES?view=markup" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 114, 1760], "buggy_code_start_loc": [11, 107, 68], "filenames": ["CHANGES", "STATUS", "modules/lua/mod_lua.c"], "fixing_code_end_loc": [17, 106, 1767], "fixing_code_start_loc": [12, 106, 69], "message": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:http_server:2.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "6FCD3C8C-9BF8-4F30-981A-593EEAEB9EDD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "046487A3-752B-4D0F-8984-96486B828EAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "89D2E052-51CD-4B57-A8B8-FAE51988D654", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "EAA27058-BACF-4F94-8E3C-7D38EC302EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "8FEAB0DF-04A9-4F99-8666-0BADC5D642B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E7D924D1-8A36-4C43-9E56-52814F9A6350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "39CDFECC-E26D-47E0-976F-6629040B3764", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "E3ECBCB1-0675-41F5-857B-438F36925F63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:-:*:*:*", "matchCriteriaId": "CB66DB75-2B16-4EBF-9B93-CE49D8086E41", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.10:*:*:*:*:*:*:*", "matchCriteriaId": "49A63F39-30BE-443F-AF10-6245587D3359", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:21:*:*:*:*:*:*:*", "matchCriteriaId": "56BDB5A0-0839-4A20-A003-B8CD56F48171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:*:*:*:*:*:*:*:*", "matchCriteriaId": "A70BB445-EF2B-4C9D-8502-FDD6A19F8C30", "versionEndExcluding": "12.1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "4725EA61-9BAB-4E72-9F92-ADE4624439CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0879FB1-58E2-4EC4-8111-044642E046BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "C7CF2929-4CBC-4B56-87AE-F45F53BD8DD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory."}, {"lang": "es", "value": "El m\u00f3dulo mod_lua.c en el m\u00f3dulo mod_lua en Apache HTTP Server 2.3.x y 2.4.x a trav\u00e9s de 2.4.10 no soporta la configuraci\u00f3n httpd en la cual el proveedor de autorizaci\u00f3n Lua se usa con argumentos diferentes dentro de contextos diferentes, lo que permite a atacantes remotos saltarse las restricciones de acceso en ciertas circunstancias aprovechando m\u00faltiples directivas requeridas, como se demuestra por una configuraci\u00f3n que especifica la autorizaci\u00f3n para un grupo para acceder a un directorio determinado, y una autorizaci\u00f3n para un segundo grupo para acceder a un segundo directorio."}], "evaluatorComment": null, "id": "CVE-2014-8109", "lastModified": "2023-02-13T00:42:40.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-29T23:59:00.053", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://advisories.mageia.org/MGASA-2015-0011.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Aug/msg00001.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Sep/msg00004.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2015-June/159352.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/28/5"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/cpujan2016-2367955.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/73040"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2523-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1174077"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://issues.apache.org/bugzilla/show_bug.cgi?id=57204"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/56c2e7cc9deb1c12a843d0dc251ea7fd3e7e80293cde02fcd65286ba%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/84a3714f0878781f6ed84473d1a503d2cc382277e100450209231830%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r76142b8c5119df2178be7c2dba88fde552eedeec37ea993dfce68d1d%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r83109088737656fa6307bd99ab40f8ff0269ae58d3f7272d7048494a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r9f93cf6dde308d42a9c807784e8102600d0397f5f834890708bf6920%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/ra7f6aeb28661fbf826969526585f16856abc4615877875f9d3b35ef4%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rb14daf9cc4e28d18cdc15d6a6ca74e565672fabf7ad89541071d008b%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rc998b18880df98bafaade071346690c2bc1444adaa1a1ea464b93f0a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rcc44594d4d6579b90deccd4536b5d31f099ef563df39b094be286b9e%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rd18c3c43602e66f9cdcf09f1de233804975b9572b0456cc582390b6f%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/re3d27b6250aa8548b8845d314bb8a350b3df326cacbbfdfe4d455234%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rf6449464fd8b7437704c55f88361b66f12d5b5f90bcce66af4be4ba9%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT205219"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT205031"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, "type": "CWE-863"}
296
Determine whether the {function_name} code is vulnerable or not.
[ "-*- coding: utf-8 -*-", "Changes with Apache 2.4.11\n \n *) SECURITY: CVE-2014-3583 (cve.mitre.org)\n mod_proxy_fcgi: Fix a potential crash due to buffer over-read, with \n response headers' size above 8K. [Yann Ylavic, Jeff Trawick]", " *) SECURITY: CVE-2014-3581 (cve.mitre.org)\n mod_cache: Avoid a crash when Content-Type has an empty value.\n PR 56924. [Mark Montague <mark catseye.org>, Jan Kaluza]", "\n *) SECURITY: CVE-2014-8109 (cve.mitre.org)\n mod_lua: Fix handling of the Require line when a LuaAuthzProvider is\n used in multiple Require directives with different arguments.\n PR57204 [Edward Lu <Chaosed0 gmail.com>]", "\n *) SECURITY: CVE-2013-5704 (cve.mitre.org)\n core: HTTP trailers could be used to replace HTTP headers\n late during request processing, potentially undoing or\n otherwise confusing modules that examined or modified\n request headers earlier. Adds \"MergeTrailers\" directive to restore\n legacy behavior. [Edward Lu, Yann Ylavic, Joe Orton, Eric Covener]", " *) mod_proxy_fcgi, mod_authnz_fcgi: stop reading the response and issue an\n error when parsing or forwarding the response fails. [Yann Ylavic]", " *) mod_ssl: Fix a memory leak in case of graceful restarts with OpenSSL >= 0.9.8e\n PR 53435 [tadanori <tadanori2007 yahoo.com>, Sebastian Wiedenroth <wiedi frubar.net>]", " *) mod_proxy_connect: Don't issue AH02447 on sockets hangups, let the read\n determine whether it is a normal close or a real error. PR 57168. [Yann\n Ylavic]", " *) mod_proxy_wstunnel: abort backend connection on polling error to avoid\n further processing. [Yann Ylavic]", " *) core: Support custom ErrorDocuments for HTTP 501 and 414 status codes.\n PR 57167 [Edward Lu <Chaosed0 gmail.com>]", " *) mod_proxy_connect: Fix ProxyRemote to https:// backends on EBCDIC \n systems. PR 57092 [Edward Lu <Chaosed0 gmail.com>]", " *) mod_cache: Avoid a 304 response to an unconditional requst when an AH00752\n CacheLock error occurs during cache revalidation. [Eric Covener]\n \n *) mod_ssl: Move OCSP stapling information from a per-certificate store to\n a per-server hash. PR 54357, PR 56919. [Alex Bligh <alex alex.org.uk>,\n Yann Ylavic, Kaspar Brand]", " *) mod_cache_socache: Change average object size hint from 32 bytes to\n 2048 bytes. [Rainer Jung]", " *) mod_cache_socache: Add cache status to server-status. [Rainer Jung]", " *) event: Fix worker-listener deadlock in graceful restart.\n PR 56960.", " *) Concat strings at compile time when possible. PR 53741.", " *) mod_substitute: Restrict configuration in .htaccess to\n FileInfo as documented. [Rainer Jung]", " *) mod_substitute: Make maximum line length configurable. [Rainer Jung]", " *) mod_substitute: Fix line length limitation in case of regexp plus flatten.\n [Rainer Jung]\n \n *) mod_proxy: Truncated character worker names are no longer fatal\n errors. PR53218. [Jim Jagielski]", " *) mod_dav: Set r->status_line in dav_error_response. PR 55426.", " *) mod_proxy_http, mod_cache: Avoid (unlikely) accesses to freed memory.\n [Yann Ylavic, Christophe Jaillet]", " *) http_protocol: fix logic in ap_method_list_(add|remove) in order:\n - to correctly reset bits\n - not to modify the 'method_mask' bitfield unnecessarily\n [Christophe Jaillet]", " *) mod_slotmem_shm: Increase log level for some originally debug messages.\n [Jim Jagielski]", " *) mod_ldap: In 2.4.10, some LDAP searches or comparisons might be done with\n the wrong credentials when a backend connection is reused.\n [Eric Covener]", " *) mod_macro: Add missing APLOGNO for some Warning log messages.\n [Christophe Jaillet]", " *) mod_cache: Avoid sending 304 responses during failed revalidations\n PR56881. [Eric Covener]", " *) mod_status: Honor client IP address using mod_remoteip. PR 55886.\n [Jim Jagielski]", " *) cmake-based build for Windows: Fix incompatibility with cmake 2.8.12\n and later. PR 56615. [Chuck Liu <cliu81 gmail.com>, Jeff Trawick]", " *) mod_ratelimit: Drop severity of AH01455 and AH01457 (ap_pass_brigade\n failed) messages from ERROR to TRACE1. Other filters do not bother \n re-reporting failures from lower level filters. PR56832. [Eric Covener]", " *) core: Avoid useless warning message when parsing a section guarded by\n <IfDefine foo> if $(foo) is used within the section.\n PR 56503 [Christophe Jaillet]", " *) mod_proxy_fcgi: Fix faulty logging of large amounts of stderr from the\n application. PR 56858. [Manuel Mausz <manuel-asf mausz.at>]", " *) mod_proxy_http: Proxy responses with error status and\n \"ProxyErrorOverride On\" hang until proxy timeout.\n PR53420 [Rainer Jung]", " *) mod_log_config: Allow three character log formats to be registered. For\n backwards compatibility, the first character of a three-character format\n must be the '^' (caret) character. [Eric Covener]", " *) mod_lua: Don't quote Expires and Path values. PR 56734.\n [Keith Mashinter, <kmashint yahoo com>]", " *) mod_authz_core: Allow <AuthzProviderAlias>'es to be seen from auth\n stanzas under virtual hosts. PR 56870. [Eric Covener]", "Changes with Apache 2.4.10", " *) SECURITY: CVE-2014-0117 (cve.mitre.org)\n mod_proxy: Fix crash in Connection header handling which allowed a denial\n of service attack against a reverse proxy with a threaded MPM.\n [Ben Reser]", " *) SECURITY: CVE-2014-3523 (cve.mitre.org)\n Fix a memory consumption denial of service in the WinNT MPM, used in all\n Windows installations. Workaround: AcceptFilter <protocol> {none|connect}\n [Jeff Trawick]", " *) SECURITY: CVE-2014-0226 (cve.mitre.org)\n Fix a race condition in scoreboard handling, which could lead to\n a heap buffer overflow. [Joe Orton, Eric Covener]", " *) SECURITY: CVE-2014-0118 (cve.mitre.org)\n mod_deflate: The DEFLATE input filter (inflates request bodies) now\n limits the length and compression ratio of inflated request bodies to\n avoid denial of service via highly compressed bodies. See directives\n DeflateInflateLimitRequestBody, DeflateInflateRatioLimit,\n and DeflateInflateRatioBurst. [Yann Ylavic, Eric Covener]", " *) SECURITY: CVE-2014-0231 (cve.mitre.org)\n mod_cgid: Fix a denial of service against CGI scripts that do\n not consume stdin that could lead to lingering HTTPD child processes\n filling up the scoreboard and eventually hanging the server. By\n default, the client I/O timeout (Timeout directive) now applies to\n communication with scripts. The CGIDScriptTimeout directive can be\n used to set a different timeout for communication with scripts.\n [Rainer Jung, Eric Covener, Yann Ylavic]", " *) mod_ssl: Extend the scope of SSLSessionCacheTimeout to sessions\n resumed by TLS session resumption (RFC 5077). [Rainer Jung]", " *) mod_deflate: Don't fail when flushing inflated data to the user-agent\n and that coincides with the end of stream (\"Zlib error flushing inflate\n buffer\"). PR 56196. [Christoph Fausak <christoph fausak glueckkanja.com>]", " *) mod_proxy_ajp: Forward local IP address as a custom request attribute\n like we already do for the remote port. [Rainer Jung]", " *) core: Include any error notes set by modules in the canned error\n response for 403 errors. [Jeff Trawick]", " *) mod_ssl: Set an error note for requests rejected due to\n SSLStrictSNIVHostCheck. [Jeff Trawick]", " *) mod_ssl: Fix issue with redirects to error documents when handling\n SNI errors. [Jeff Trawick]", " *) mod_ssl: Fix tmp DH parameter leak, adjust selection to prefer\n larger keys and support up to 8192-bit keys. [Ruediger Pluem,\n Joe Orton]", " *) mod_dav: Fix improper encoding in PROPFIND responses. PR 56480.\n [Ben Reser]", " *) WinNT MPM: Improve error handling for termination events in child.\n [Jeff Trawick]", " *) mod_proxy: When ping/pong is configured for a worker, don't send or\n forward \"100 Continue\" (interim) response to the client if it does\n not expect one. [Yann Ylavic]", " *) mod_ldap: Be more conservative with the last-used time for\n LDAPConnectionPoolTTL. PR54587 [Eric Covener]", " *) mod_ldap: LDAP connections used for authn were not respecting\n LDAPConnectionPoolTTL. PR54587 [Eric Covener]", " *) mod_proxy_fcgi: Fix occasional high CPU when handling request bodies.\n [Jeff Trawick]", " *) event MPM: Fix possible crashes (third-party modules accessing c->sbh) \n or occasional missed mod_status updates under load. PR 56639.\n [Edward Lu <Chaosed0 gmail com>]", " *) mod_authnz_ldap: Support primitive LDAP servers do not accept\n filters, such as \"SDBM-backed LDAP\" on z/OS, by allowing a special\n filter \"none\" to be specified in AuthLDAPURL. [Eric Covener]", " *) mod_deflate: Fix inflation of files larger than 4GB. PR 56062.\n [Lukas Bezdicka <social v3.sk>]", " *) mod_deflate: Handle Zlib header and validation bytes received in multiple\n chunks. PR 46146. [Yann Ylavic]", " *) mod_proxy: Allow reverse-proxy to be set via explicit handler.\n [ryo takatsuki <ryotakatsuki gmail com>]", " *) ab: support custom HTTP method with -m argument. PR 56604.\n [Roman Jurkov <winfinit gmail.com>]", " *) mod_proxy_balancer: Correctly encode user provided data in management\n interface. PR 56532 [Maksymilian, <max cert.cx>]", " *) mod_proxy_fcgi: Support iobuffersize parameter. [Jeff Trawick]", " *) mod_auth_form: Add a debug message when the fields on a form are not\n recognised. [Graham Leggett]", " *) mod_cache: Preserve non-cacheable headers forwarded from an origin 304\n response. PR 55547. [Yann Ylavic]", " *) mod_proxy_wstunnel: Fix the use of SSL connections with the \"wss:\"\n scheme. PR55320. [Alex Liu <alex.leo.ca gmail.com>]", " *) mod_socache_shmcb: Correct counting of expirations for status display.\n Expirations happening during retrieval were not counted. [Rainer Jung]", " *) mod_cache: Retry unconditional request with the full URL (including the\n query-string) when the origin server's 304 response does not match the\n conditions used to revalidate the stale entry. [Yann Ylavic].", " *) mod_alias: Stop setting CONTEXT_PREFIX and CONTEXT_DOCUMENT environment\n variables as a result of AliasMatch. [Eric Covener]\n \n *) mod_cache: Don't add cached/revalidated entity headers to a 304 response.\n PR 55547. [Yann Ylavic]", " *) mod_proxy_scgi: Support Unix sockets. ap_proxy_port_of_scheme():\n Support default SCGI port (4000). [Jeff Trawick]", " *) mod_cache: Fix AH00784 errors on Windows when the the CacheLock directive\n is enabled. [Eric Covener]", " *) mod_expires: don't add Expires header to error responses (4xx/5xx),\n be they generated or forwarded. PR 55669. [Yann Ylavic]", " *) mod_proxy_fcgi: Don't segfault when failing to connect to the backend.\n (regression in 2.4.9 release) [Jeff Trawick]", " *) mod_authn_socache: Fix crash at startup in certain configurations.\n PR 56371. (regression in 2.4.7) [Jan Kaluza]", " *) mod_ssl: restore argument structure for \"exec\"-type SSLPassPhraseDialog\n programs to the form used in releases up to 2.4.7, and emulate\n a backwards-compatible behavior for existing setups. [Kaspar Brand]", " *) mod_ssl: Add SSLOCSPUseRequestNonce directive to control whether or not\n OCSP requests should use a nonce to be checked against the responder's\n one. PR 56233. [Yann Ylavic, Kaspar Brand]", " *) mod_ssl: \"SSLEngine off\" will now override a Listen-based default\n and does disable mod_ssl for the vhost. [Joe Orton]", " *) mod_lua: Enforce the max post size allowed via r:parsebody()\n [Daniel Gruno]", " *) mod_lua: Use binary comparison to find boundaries for multipart \n objects, as to not terminate our search prematurely when hitting\n a NULL byte. [Daniel Gruno]", " *) mod_ssl: add workaround for SSLCertificateFile when using OpenSSL\n versions before 0.9.8h and not specifying an SSLCertificateChainFile\n (regression introduced with 2.4.8). PR 56410. [Kaspar Brand]", " *) mod_ssl: bring SNI behavior into better conformance with RFC 6066:\n no longer send warning-level unrecognized_name(112) alerts,\n and limit startup warnings to cases where an OpenSSL version\n without TLS extension support is used. PR 56241. [Kaspar Brand]", " *) mod_proxy_html: Avoid some possible memory access violation in case of\n specially crafted files, when the ProxyHTMLMeta directive is turned on.\n Follow up of PR 56287 [Christophe Jaillet]", " *) mod_auth_form: Make sure the optional functions are loaded even when\n the AuthFormProvider isn't specified. [Graham Leggett]", " *) mod_ssl: avoid processing bogus SSLCertificateKeyFile values\n (and logging garbled file names). PR 56306. [Kaspar Brand]", " *) mod_ssl: fix merging of global and vhost-level settings with the\n SSLCertificateFile, SSLCertificateKeyFile, and SSLOpenSSLConfCmd\n directives. PR 56353. [Kaspar Brand]", " *) mod_headers: Allow the \"value\" parameter of Header and RequestHeader to \n contain an ap_expr expression if prefixed with \"expr=\". [Eric Covener]", " *) rotatelogs: Avoid creation of zombie processes when -p is used on\n Unix platforms. [Joe Orton]", " *) mod_authnz_fcgi: New module to enable FastCGI authorizer\n applications to authenticate and/or authorize clients.\n [Jeff Trawick]", " *) mod_proxy: Do not try to parse the regular expressions passed by\n ProxyPassMatch as URL as they do not follow their syntax.\n PR 56074. [Ruediger Pluem]", " *) mod_reqtimeout: Resolve unexpected timeouts on keepalive requests \n under the Event MPM. PR56216. [Frank Meier <frank meier ergon ch>]", " *) mod_proxy_fcgi: Fix sending of response without some HTTP headers\n that might be set by filters. [Jim Riggs <jim riggs.me>]", " *) mod_proxy_html: Do not delete the wrong data from HTML code when a\n \"http-equiv\" meta tag specifies a Content-Type behind any other\n \"http-equiv\" meta tag. PR 56287 [Micha Lenk <micha lenk info>]", " *) mod_proxy: Don't reuse a SSL backend connection whose requested SNI\n differs. PR 55782. [Yann Ylavic]", " *) Add suspend_connection and resume_connection hooks to notify modules\n when the thread/connection relationship changes. (Should be implemented\n for any third-party async MPMs.) [Jeff Trawick]", " *) mod_proxy_wstunnel: Don't issue AH02447 and log a 500 on routine \n hangups from websockets origin servers. PR 56299\n [Yann Ylavic, Edward Lu <Chaosed0 gmail com>, Eric Covener] ", " *) mod_proxy_wstunnel: Don't pool backend websockets connections,\n because we need to handshake every time. PR 55890.\n [Eric Covener]", " *) mod_lua: Redesign how request record table access behaves,\n in order to utilize the request record from within these tables.\n [Daniel Gruno]", " *) mod_lua: Add r:wspeek for peeking at WebSocket frames. [Daniel Gruno]\n \n *) mod_lua: Log an error when the initial parsing of a Lua file fails.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: Reformat and escape script error output.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: URL-escape cookie keys/values to prevent tainted cookie data\n from causing response splitting.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: Disallow newlines in table values inside the request_rec, \n to prevent HTTP Response Splitting via tainted headers.\n [Daniel Gruno, Felipe Daragon <filipe syhunt com>]", " *) mod_lua: Remove the non-working early/late arguments for \n LuaHookCheckUserID. [Daniel Gruno]", " *) mod_lua: Change IVM storage to use shm [Daniel Gruno]", " *) mod_lua: More verbose error logging when a handler function cannot be\n found. [Daniel Gruno]", "Changes with Apache 2.4.9", " *) mod_ssl: Work around a bug in some older versions of OpenSSL that\n would cause a crash in SSL_get_certificate for servers where the\n certificate hadn't been sent. [Stephen Henson]", " *) mod_lua: Add a fixups hook that checks if the original request is intended \n for LuaMapHandler. This fixes a bug where FallbackResource invalidates the \n LuaMapHandler directive in certain cases by changing the URI before the map \n handler code executes [Daniel Gruno, Daniel Ferradal <dferradal gmail com>].", "Changes with Apache 2.4.8", " *) SECURITY: CVE-2014-0098 (cve.mitre.org)\n Clean up cookie logging with fewer redundant string parsing passes.\n Log only cookies with a value assignment. Prevents segfaults when\n logging truncated cookies.\n [William Rowe, Ruediger Pluem, Jim Jagielski]", " *) SECURITY: CVE-2013-6438 (cve.mitre.org)\n mod_dav: Keep track of length of cdata properly when removing\n leading spaces. Eliminates a potential denial of service from\n specifically crafted DAV WRITE requests\n [Amin Tora <Amin.Tora neustar.biz>]", " *) core: Support named groups and backreferences within the LocationMatch,\n DirectoryMatch, FilesMatch and ProxyMatch directives. (Requires\n non-ancient PCRE library) [Graham Leggett]", " *) core: draft-ietf-httpbis-p1-messaging-23 corrections regarding\n TE/CL conflicts. [Yann Ylavic, Jim Jagielski]", " *) core: Detect incomplete request and response bodies, log an error and\n forward it to the underlying filters. PR 55475 [Yann Ylavic]", " *) mod_dir: Add DirectoryCheckHandler to allow a 2.2-like behavior, skipping \n execution when a handler is already set. PR53929. [Eric Covener]", " *) mod_ssl: Do not perform SNI / Host header comparison in case of a\n forward proxy request. [Ruediger Pluem]", " *) mod_ssl: Remove the hardcoded algorithm-type dependency for the\n SSLCertificateFile and SSLCertificateKeyFile directives, to enable\n future algorithm agility, and deprecate the SSLCertificateChainFile\n directive (obsoleted by SSLCertificateFile). [Kaspar Brand]", " *) mod_rewrite: Add RewriteOptions InheritDown, InheritDownBefore, \n and IgnoreInherit to allow RewriteRules to be pushed from parent scopes\n to child scopes without explicitly configuring each child scope.\n PR56153. [Edward Lu <Chaosed0 gmail com>] ", " *) prefork: Fix long delays when doing a graceful restart.\n PR 54852 [Jim Jagielski, Arkadiusz Miskiewicz <arekm maven pl>]", " *) FreeBSD: Disable IPv4-mapped listening sockets by default for versions\n 5+ instead of just for FreeBSD 5. PR 53824. [Jeff Trawick]", " *) mod_proxy_wstunnel: Avoid busy loop on client errors, drop message\n IDs 02445, 02446, and 02448 to TRACE1 from DEBUG. PR 56145.\n [Joffroy Christen <joffroy.christen solvaxis com>, Eric Covener]", " *) mod_remoteip: Correct the trusted proxy match test. PR 54651.\n [Yoshinori Ehara <yoshinori ehara gmail com>, Eugene L <eugenel amazon com>]", " *) mod_proxy_fcgi: Fix error message when an unexpected protocol version\n number is received from the application. PR 56110. [Jeff Trawick]", " *) mod_remoteip: Use the correct IP addresses to populate the proxy_ips field.\n PR 55972. [Mike Rumph]", " *) mod_lua: Update r:setcookie() to accept a table of options and add domain,\n path and httponly to the list of options available to set.\n PR 56128 [Edward Lu <Chaosed0 gmail com>, Daniel Gruno]\n \n *) mod_lua: Fix r:setcookie() to add, rather than replace,\n the Set-Cookie header. PR56105\n [Kevin J Walters <kjw ms com>, Edward Lu <Chaosed0 gmail com>]", " *) mod_lua: Allow for database results to be returned as a hash with \n row-name/value pairs instead of just row-number/value. [Daniel Gruno]", " *) mod_rewrite: Add %{CONN_REMOTE_ADDR} as the non-useragent counterpart to\n %{REMOTE_ADDR}. PR 56094. [Edward Lu <Chaosed0 gmail com>]", " *) WinNT MPM: If ap_run_pre_connection() fails or sets c->aborted, don't\n save the socket for reuse by the next worker as if it were an \n APR_SO_DISCONNECTED socket. Restores 2.2 behavior. [Eric Covener]", " *) mod_dir: Don't search for a DirectoryIndex or DirectorySlash on a URL\n that was just rewritten by mod_rewrite. PR53929. [Eric Covener]", " *) mod_session: When we have a session we were unable to decode,\n behave as if there was no session at all. [Thomas Eckert\n <thomas.r.w.eckert gmail com>]", " *) mod_session: Fix problems interpreting the SessionInclude and\n SessionExclude configuration. PR 56038. [Erik Pearson\n <erik adaptations.com>]", " *) mod_authn_core: Allow <AuthnProviderAlias>'es to be seen from auth\n stanzas under virtual hosts. PR 55622. [Eric Covener]", " *) mod_proxy_fcgi: Use apr_socket_timeout_get instead of hard-coded\n 30 seconds timeout. [Jan Kaluza]", " *) build: only search for modules (config*.m4) in known subdirectories, see\n build/config-stubs. [Stefan Fritsch]", " *) mod_cache_disk: Fix potential hangs on Windows when using mod_cache_disk. \n PR 55833. [Eric Covener]", " *) mod_ssl: Add support for OpenSSL configuration commands by introducing\n the SSLOpenSSLConfCmd directive. [Stephen Henson, Kaspar Brand]", " *) mod_proxy: Remove (never documented) <Proxy ~ wildcard-url> syntax which\n is equivalent to <ProxyMatch wildcard-url>. [Christophe Jaillet]", " *) mod_authz_user, mod_authz_host, mod_authz_groupfile, mod_authz_dbm,\n mod_authz_dbd, mod_authnz_ldap: Support the expression parser within the\n require directives. [Graham Leggett]", " *) mod_proxy_http: Core dumped under high load. PR 50335.\n [Jan Kaluza <jkaluza redhat.com>]", " *) mod_socache_shmcb.c: Remove arbitrary restriction on shared memory size\n previously limited to 64MB. [Jens Låås <jelaas gmail.com>]", " *) mod_lua: Use binary copy when dealing with uploads through r:parsebody() \n to prevent truncating files. [Daniel Gruno]", "Changes with Apache 2.4.7", " *) SECURITY: CVE-2013-4352 (cve.mitre.org)\n mod_cache: Fix a NULL pointer deference which allowed untrusted\n origin servers to crash mod_cache in a forward proxy\n configuration. [Graham Leggett]", " *) APR 1.5.0 or later is now required for the event MPM.\n \n *) slotmem_shm: Error detection. [Jim Jagielski]", " *) event: Use skiplist data structure. [Jim Jagielski]", " *) event: Fail at startup with message AP02405 if the APR atomic\n implementation is not compatible with the MPM. [Jim Jagielski]", " *) mpm_unix: Add ap_mpm_podx_* implementation to avoid code duplication\n and align w/ trunk. [Jim Jagielski]", " *) Fix potential rejection of valid MaxMemFree and ThreadStackSize\n directives. [Mike Rumph <mike.rumph oracle.com>]", " *) mod_proxy_fcgi: Remove 64K limit on encoded length of all envvars.\n An individual envvar with an encoded length of more than 16K will be\n omitted. [Jeff Trawick]\n \n *) mod_proxy_fcgi: Handle reading protocol data that is split between\n packets. [Jeff Trawick]", " *) mod_ssl: Improve handling of ephemeral DH and ECDH keys by\n allowing custom parameters to be configured via SSLCertificateFile,\n and by adding standardized DH parameters for 1024/2048/3072/4096 bits.\n Unless custom parameters are configured, the standardized parameters\n are applied based on the certificate's RSA/DSA key size. [Kaspar Brand]", " *) mod_ssl, configure: Require OpenSSL 0.9.8a or later. [Kaspar Brand]", " *) mod_ssl: drop support for export-grade ciphers with ephemeral RSA\n keys, and unconditionally disable aNULL, eNULL and EXP ciphers\n (not overridable via SSLCipherSuite). [Kaspar Brand]", " *) mod_proxy: Added support for unix domain sockets as the\n backend server endpoint [Jim Jagielski, Blaise Tarr\n <blaise tarr gmail com>]", " *) Add experimental cmake-based build system for Windows. [Jeff Trawick,\n Tom Donovan]", " *) event MPM: Fix possible crashes (third party modules accessing c->sbh) \n or occasional missed mod_status updates for some keepalive requests \n under load. [Eric Covener]", " *) mod_authn_socache: Support optional initialization arguments for\n socache providers. [Chris Darroch]", " *) mod_session: Reset the max-age on session save. PR 47476. [Alexey\n Varlamov <alexey.v.varlamov gmail com>]", " *) mod_session: After parsing the value of the header specified by the\n SessionHeader directive, remove the value from the response. PR 55279.\n [Graham Leggett]", " *) mod_headers: Allow for format specifiers in the substitution string\n when using Header edit. [Daniel Ruggeri]", " *) mod_dav: dav_resource->uri is treated as unencoded. This was an\n unnecessary ABI changed introduced in 2.4.6. PR 55397.", " *) mod_dav: Don't require lock tokens for COPY source. PR 55306.", " *) core: Don't truncate output when sending is interrupted by a signal,\n such as from an exiting CGI process. PR 55643. [Jeff Trawick]", " *) WinNT MPM: Exit the child if the parent process crashes or is terminated.\n [Oracle Corporation]", " *) Windows: Correct failure to discard stderr in some error log\n configurations. (Error message AH00093) [Jeff Trawick]", " *) mod_session_crypto: Allow using exec: calls to obtain session\n encryption key. [Daniel Ruggeri]", " *) core: Add missing Reason-Phrase in HTTP response headers.\n PR 54946. [Rainer Jung]", " *) mod_rewrite: Make rewrite websocket-aware to allow proxying.\n PR 55598. [Chris Harris <chris.harris kitware com>]", " *) mod_ldap: When looking up sub-groups, use an implicit objectClass=*\n instead of an explicit cn=* filter. [David Hawes <dhawes vt.edu>]", " *) ab: Add wait time, fix processing time, and output write errors only if\n they occured. [Christophe Jaillet]", " *) worker MPM: Don't forcibly kill worker threads if the child process is\n exiting gracefully. [Oracle Corporation]", " *) core: apachectl -S prints wildcard name-based virtual hosts twice. \n PR54948 [Eric Covener]", " *) mod_auth_basic: Add AuthBasicUseDigestAlgorithm directive to\n allow migration of passwords from digest to basic authentication.\n [Chris Darroch]", " *) ab: Add a new -l parameter in order not to check the length of the responses.\n This can be usefull with dynamic pages.\n PR9945, PR27888, PR42040 [<ccikrs1 cranbrook edu>]\n \n *) Suppress formatting of startup messages written to the console when\n ErrorLogFormat is used. [Jeff Trawick]", " *) mod_auth_digest: Be more specific when the realm mismatches because the\n realm has not been specified. [Graham Leggett]", " *) mod_proxy: Add a note in the balancer manager stating whether changes\n will or will not be persisted and whether settings are inherited.\n [Daniel Ruggeri, Jim Jagielski]", " *) core: Add util_fcgi.h and associated definitions and support\n routines for FastCGI, based largely on mod_proxy_fcgi.\n [Jeff Trawick]", " *) mod_headers: Add 'Header note header-name note-name' for copying a response\n headers value into a note. [Eric Covener]", " *) mod_headers: Add 'setifempty' command to Header and RequestHeader.\n [Eric Covener]", " *) mod_logio: new format-specifier %S (sum) which is the sum of received\n and sent byte counts.\n PR54015 [Christophe Jaillet]", " *) mod_deflate: Improve error detection when decompressing request bodies\n with trailing garbage: handle case where trailing bytes are in\n the same bucket. [Rainer Jung]", " *) mod_authz_groupfile, mod_authz_user: Reduce severity of AH01671 and AH01663\n from ERROR to DEBUG, since these modules do not know what mod_authz_core\n is doing with their AUTHZ_DENIED return value. [Eric Covener]", " *) mod_ldap: add TRACE5 for LDAP retries. [Eric Covener]", " *) mod_ldap: retry on an LDAP timeout during authn. [Eric Covener]", " *) mod_ldap: Change \"LDAPReferrals off\" to actually set the underlying LDAP \n SDK option to OFF, and introduce \"LDAPReferrals default\" to take the SDK \n default, sans rebind authentication callback.\n [Jan Kaluza <kaluze AT redhat.com>]", " *) core: Log a message at TRACE1 when the client aborts a connection.\n [Eric Covener]", " *) WinNT MPM: Don't crash during child process initialization if the\n Listen protocol is unrecognized. [Jeff Trawick]", " *) modules: Fix some compiler warnings. [Guenter Knauf]", " *) Sync 2.4 and trunk\n - Avoid some memory allocation and work when TRACE1 is not activated\n - fix typo in include guard\n - indent\n - No need to lower the string before removing the path, it is just \n a waste of time...\n - Save a few cycles\n [Christophe Jaillet <christophe.jaillet wanadoo.fr>]", " *) mod_filter: Add \"change=no\" as a proto-flag to FilterProtocol\n to remove a providers initial flags set at registration time.\n [Eric Covener]", " *) core, mod_ssl: Enable the ability for a module to reverse the sense of\n a poll event from a read to a write or vice versa. This is a step on\n the way to allow mod_ssl taking full advantage of the event MPM.\n [Graham Leggett]", " *) Makefile.win: Install proper pcre DLL file during debug build install.\n PR 55235. [Ben Reser <ben reser org>]", " *) mod_ldap: Fix a potential memory leak or corruption. PR 54936.\n [Zhenbo Xu <zhenbo1987 gmail com>]", " *) ab: Fix potential buffer overflows when processing the T and X\n command-line options. PR 55360.\n [Mike Rumph <mike.rumph oracle.com>]", " *) fcgistarter: Specify SO_REUSEADDR to allow starting a server\n with old connections in TIME_WAIT. [Jeff Trawick]", " *) core: Add open_htaccess hook which, in conjunction with dirwalk_stat\n and post_perdir_config (introduced in 2.4.5), allows mpm-itk to be \n used without patches to httpd core. [Stefan Fritsch]", " *) support/htdbm: fix processing of -t command line switch. Regression\n introduced in 2.4.4\n PR 55264 [Jo Rhett <jrhett netconsonance com>]", " *) mod_lua: add websocket support via r:wsupgrade, r:wswrite, r:wsread \n and r:wsping. [Daniel Gruno]", " *) mod_lua: add support for writing/reading cookies via r:getcookie and \n r:setcookie. [Daniel Gruno]", " *) mod_lua: If the first yield() of a LuaOutputFilter returns a string, it should\n be prefixed to the response as documented. [Eric Covener] \n Note: Not present in 2.4.7 CHANGES", " *) mod_lua: Remove ETAG, Content-Length, and Content-MD5 when a LuaOutputFilter\n is configured without mod_filter. [Eric Covener]\n Note: Not present in 2.4.7 CHANGES", " *) mod_lua: Register LuaOutputFilter scripts as changing the content and\n content-length by default, when run my mod_filter. Previously,\n growing or shrinking a response that started with Content-Length set\n would require mod_filter and FilterProtocol change=yes. [Eric Covener]\n Note: Not present in 2.4.7 CHANGES", " *) mod_lua: Return a 500 error if a LuaHook* script doesn't return a\n numeric return code. [Eric Covener]\n Note: Not present in 2.4.7 CHANGES", "Changes with Apache 2.4.6", " *) Revert a broken fix for PR54948 that was applied to 2.4.5 (which was\n not released) and found post-2.4.5 tagging.", "Changes with Apache 2.4.5", " *) SECURITY: CVE-2013-1896 (cve.mitre.org)\n mod_dav: Sending a MERGE request against a URI handled by mod_dav_svn with\n the source href (sent as part of the request body as XML) pointing to a\n URI that is not configured for DAV will trigger a segfault. [Ben Reser\n <ben reser.org>]", " *) SECURITY: CVE-2013-2249 (cve.mitre.org)\n mod_session_dbd: Make sure that dirty flag is respected when saving\n sessions, and ensure the session ID is changed each time the session\n changes. This changes the format of the updatesession SQL statement.\n Existing configurations must be changed.\n [Takashi Sato, Graham Leggett]", " *) mod_auth_basic: Add a generic mechanism to fake basic authentication\n using the ap_expr parser. AuthBasicFake allows the administrator to \n construct their own username and password for basic authentication based \n on their needs. [Graham Leggett]", " *) mpm_event: Check that AsyncRequestWorkerFactor is not negative. PR 54254.\n [Jackie Zhang <jackie qq zhang gmail com>]", " *) mod_proxy: Ensure we don't attempt to amend a table we are iterating\n through, ensuring that all headers listed by Connection are removed.\n [Graham Leggett, Co-Advisor <coad measurement-factory.com>]", " *) mod_proxy_http: Make the proxy-interim-response environment variable\n effective by formally overriding origin server behaviour. [Graham\n Leggett, Co-Advisor <coad measurement-factory.com>]", " *) mod_proxy: Fix seg-faults when using the global pool on threaded\n MPMs [Thomas Eckert <thomas.r.w.eckert gmail.com>, Graham Leggett,\n Jim Jagielski]", " *) mod_deflate: Remove assumptions as to when an EOS bucket might arrive.\n Gracefully step aside if the body size is zero. [Graham Leggett]", " *) mod_ssl: Fix possible truncation of OCSP responses when reading from the\n server. [Joe Orton]", " *) core: Support the SINGLE_LISTEN_UNSERIALIZED_ACCEPT optimization\n on Linux kernel versions 3.x and above. PR 55121. [Bradley Heilbrun\n <apache heilbrun.org>]", " *) mod_cache_socache: Make sure the CacheSocacheMaxSize directive is merged\n correctly. [Jens Låås <jelaas gmail.com>]", " *) rotatelogs: add -n number-of-files option to rotate through a number\n of fixed-name logfiles. [Eric Covener]", " *) mod_proxy: Support web-socket tunnels via mod_proxy_wstunnel.\n [Jim Jagielski]", " *) mod_cache_socache: Use the name of the socache implementation when performing\n a lookup rather than using the raw arguments. [Martin Ksellmann\n <martin@ksellmann.de>]", " *) core: Add dirwalk_stat hook. [Jeff Trawick]", " *) core: Add post_perdir_config hook.\n [Steinar Gunderson <sgunderson bigfoot.com>]", " *) proxy_util: NULL terminate the right buffer in 'send_http_connect'.\n [Christophe Jaillet]", " *) mod_remoteip: close file in error path. [Christophe Jaillet]", " *) core: make the \"default\" parameter of the \"ErrorDocument\" option case\n insensitive. PR 54419 [Tianyin Xu <tixu cs ucsd edu>]", " *) mod_proxy_html: make the \"ProxyHTMLFixups\" options case insensitive.\n PR 54420 [Tianyin Xu <tixu cs ucsd edu>]", " *) mod_cache: Make option \"CacheDisable\" in mod_cache case insensitive.\n PR 54462 [Tianyin Xu <tixu cs ucsd edu>]", " *) mod_cache: If a 304 response indicates an entity not currently cached, then\n the cache MUST disregard the response and repeat the request without the\n conditional. [Graham Leggett, Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: Ensure that we don't attempt to replace a cached response\n with an older response as per RFC2616 13.12. [Graham Leggett, Co-Advisor\n <coad measurement-factory.com>]", " *) core, mod_cache: Ensure RFC2616 compliance in ap_meets_conditions()\n with weak validation combined with If-Range and Range headers. Break\n out explicit conditional header checks to be useable elsewhere in the\n server. Ensure weak validation RFC compliance in the byteranges filter.\n Ensure RFC validation compliance when serving cached entities. PR 16142\n [Graham Leggett, Co-Advisor <coad measurement-factory.com>]", " *) core: Add the ability to do explicit matching on weak and strong ETags\n as per RFC2616 Section 13.3.3. [Graham Leggett, Co-Advisor\n <coad measurement-factory.com>]", " *) mod_cache: Ensure that updated responses to HEAD requests don't get\n mistakenly paired with a previously cached body. Ensure that any existing\n body is removed when a HEAD request is cached. [Graham Leggett,\n Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: Honour Cache-Control: no-store in a request. [Graham Leggett]", " *) mod_cache: Make sure that contradictory entity headers present in a 304\n Not Modified response are caught and cause the entity to be removed.\n [Graham Leggett]", " *) mod_cache: Make sure Vary processing handles multivalued Vary headers and\n multivalued headers referred to via Vary. [Graham Leggett]", " *) mod_cache: When serving from cache, only the last header of a multivalued\n header was taken into account. Fixed. Ensure that Warning headers are\n correctly handled as per RFC2616. [Graham Leggett]", " *) mod_cache: Ignore response headers specified by no-cache=header and\n private=header as specified by RFC2616 14.9.1 What is Cacheable. Ensure\n that these headers are still processed when multiple Cache-Control\n headers are present in the response. PR 54706 [Graham Leggett,\n Yann Ylavic <ylavic.dev gmail.com>]", " *) mod_cache: Invalidate cached entities in response to RFC2616 Section\n 13.10 Invalidation After Updates or Deletions. PR 15868 [Graham\n Leggett]", " *) mod_dav: Improve error handling in dav_method_put(), add new\n dav_join_error() function. PR 54145. [Ben Reser <ben reser.org>]", " *) mod_dav: Do not fail PROPPATCH when prop namespace is not known.\n PR 52559 [Diego Santa Cruz <diego.santaCruz spinetix.com>]", " *) mod_dav: When a PROPPATCH attempts to remove a non-existent dead\n property on a resource for which there is no dead property in the same\n namespace httpd segfaults. PR 52559 [Diego Santa Cruz\n <diego.santaCruz spinetix.com>]", " *) mod_dav: Sending an If or If-Match header with an invalid ETag doesn't\n result in a 412 Precondition Failed for a COPY operation. PR54610\n [Timothy Wood <tjw omnigroup.com>]", " *) mod_dav: Make sure that when we prepare an If URL for Etag comparison,\n we compare unencoded paths. PR 53910 [Timothy Wood <tjw omnigroup.com>]", " *) mod_deflate: Remove assumptions as to when an EOS bucket might arrive.\n Gracefully step aside if the body size is zero. [Graham Leggett]", " *) 'AuthGroupFile' and 'AuthUserFile' do not accept anymore the optional\n 'standard' keyword . It was unused and not documented.\n PR54463 [Tianyin Xu <tixu cs.ucsd.edu> and Christophe Jaillet]", " *) core: Do not over allocate memory within 'ap_rgetline_core' for\n the common case. [Christophe Jaillet]", " *) core: speed up (for common cases) and reduce memory usage of\n ap_escape_logitem(). This should save 70-100 bytes in the request\n pool for a default config. [Christophe Jaillet]", " *) mod_dav: Ensure URI is correctly uriencoded on return. PR 54611\n [Timothy Wood <tjw omnigroup.com>]", " *) mod_proxy: Reject invalid values for Max-Forwards. [Graham Leggett,\n Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: RFC2616 14.9.3 The s-maxage directive also implies the\n semantics of the proxy-revalidate directive. [Graham Leggett]", " *) mod_ssl: add support for subjectAltName-based host name checking\n in proxy mode (SSLProxyCheckPeerName). PR 54030. [Kaspar Brand]", " *) core: Use the proper macro for HTTP/1.1. [Graham Leggett]", " *) event MPM: Provide error handling for ThreadStackSize. PR 54311\n [Tianyin Xu <tixu cs.ucsd.edu>, Christophe Jaillet]", " *) mod_dav: Do not segfault on PROPFIND with a zero length DBM.\n PR 52559 [Diego Santa Cruz <diego.santaCruz spinetix.com>]", " *) core: Improve error message where client's request-line exceeds\n LimitRequestLine. PR 54384 [Christophe Jaillet]", " *) mod_macro: New module that provides macros within configuration files.\n [Fabien Coelho]", " *) mod_cache_socache: New cache implementation backed by mod_socache\n that replaces mod_mem_cache known from httpd 2.2. [Graham\n Leggett]", " *) htpasswd: Add -v option to verify a password. [Stefan Fritsch]", " *) mod_proxy: Add BalancerInherit and ProxyPassInherit to control\n whether Proxy Balancers and Workers are inherited by vhosts\n (default is On). [Jim Jagielski]", " *) mod_authnz_ldap: Allow using exec: calls to obtain LDAP bind\n password. [Daniel Ruggeri]", " *) Added balancer parameter failontimeout to allow server admin\n to configure an IO timeout as an error in the balancer.\n [Daniel Ruggeri]", " *) mod_auth_digest: Fix crashes if shm initialization failed. [Stefan\n Fritsch]", " *) htpasswd, htdbm: Fix password generation. PR 54735. [Stefan Fritsch]", " *) core: Add workaround for gcc bug on sparc/64bit. PR 52900.\n [Stefan Fritsch]", " *) mod_setenvif: Fix crash in case SetEnvif and SetEnvIfExpr are used\n together. PR 54881. [Ruediger Pluem]", " *) htdigest: Fix buffer overflow when reading digest password file\n with very long lines. PR 54893. [Rainer Jung]", " *) ap_expr: Add the ability to base64 encode and base64 decode\n strings and to generate their SHA1 and MD5 hash.\n [Graham Leggett, Stefan Fritsch]", " *) mod_log_config: Fix crash when logging request end time for a failed\n request. PR 54828 [Rainer Jung]", " *) mod_ssl: Catch missing, mismatched or encrypted client cert/key pairs\n with SSLProxyMachineCertificateFile/Path directives. PR 52212, PR 54698.\n [Keith Burdis <keith burdis.org>, Joe Orton, Kaspar Brand]", " *) mod_ssl: Quiet FIPS mode weak keys disabled and FIPS not selected emits\n in the error log to debug level. [William Rowe]", " *) mod_cache_disk: CacheMinFileSize and CacheMaxFileSize were always\n using compiled in defaults of 1000000/1 respectively. [Eric Covener]", " *) mod_lbmethod_heartbeat, mod_heartmonitor: Respect DefaultRuntimeDir/\n DEFAULT_REL_RUNTIMEDIR for the heartbeat storage file. [Jeff Trawick]", " *) mod_include: Use new ap_expr for 'elif', like 'if', \n if legacy parser is not specified. PR 54548 [Tom Donovan]", " *) mod_lua: Add some new functions: r:htpassword(), r:mkdir(), r:mkrdir(),\n r:rmdir(), r:touch(), r:get_direntries(), r.date_parse_rfc().\n [Guenter Knauf]", " *) mod_lua: Add multipart form data handling. [Daniel Gruno]", " *) mod_lua: If a LuaMapHandler doesn't return any value, log a warning\n and treat it as apache2.OK. [Eric Covener]", " *) mod_lua: Add bindings for apr_dbd/mod_dbd database access\n [Daniel Gruno]", " *) mod_lua: Add LuaInputFilter/LuaOutputFilter for creating content\n filters in Lua [Daniel Gruno]", " *) mod_lua: Allow scripts handled by the lua-script handler to return\n a status code to the client (such as a 302 or a 500) [Daniel Gruno]", " *) mod_lua: Decline handling 'lua-script' if the file doesn't exist,\n rather than throwing an internal server error. [Daniel Gruno]", " *) mod_lua: Add functions r:flush and r:sendfile as well as additional\n request information to the request_rec structure. [Daniel Gruno]", " *) mod_lua: Add a server scope for Lua states, which creates a pool of\n states with managable minimum and maximum size. [Daniel Gruno]", " *) mod_lua: Add new directive, LuaMapHandler, for dynamically mapping\n URIs to Lua scripts and functions using regular expressions.\n [Daniel Gruno]", " *) mod_lua: Add new directive LuaCodeCache for controlling in-memory\n caching of lua scripts. [Daniel Gruno]", "Changes with Apache 2.4.4", " *) SECURITY: CVE-2012-3499 (cve.mitre.org)\n Various XSS flaws due to unescaped hostnames and URIs HTML output in\n mod_info, mod_status, mod_imagemap, mod_ldap, and mod_proxy_ftp.\n [Jim Jagielski, Stefan Fritsch, Niels Heinen <heinenn google com>]", " *) SECURITY: CVE-2012-4558 (cve.mitre.org)\n XSS in mod_proxy_balancer manager interface. [Jim Jagielski,\n Niels Heinen <heinenn google com>]", " *) mod_dir: Add support for the value 'disabled' in FallbackResource.\n [Vincent Deffontaines]", " *) mod_proxy_connect: Don't keepalive the connection to the client if the\n backend closes the connection. PR 54474. [Pavel Mateja <pavel netsafe cz>]", " *) mod_lua: Add bindings for mod_dbd/apr_dbd database access.\n [Daniel Gruno]", " *) mod_proxy: Allow for persistence of local changes made via the\n balancer-manager between graceful/normal restarts and power\n cycles. [Jim Jagielski]", " *) mod_proxy: Fix startup crash with mis-defined balancers.\n PR 52402. [Jim Jagielski]", " *) --with-module: Fix failure to integrate them into some existing\n module directories. PR 40097. [Jeff Trawick]", " *) htcacheclean: Fix potential segfault if \"-p\" is omitted. [Joe Orton]", " *) mod_proxy_http: Honour special value 0 (unlimited) of LimitRequestBody\n PR 54435. [Pavel Mateja <pavel netsafe.cz>]", " *) mod_proxy_ajp: Support unknown HTTP methods. PR 54416.\n [Rainer Jung]", " *) htcacheclean: Fix list options \"-a\" and \"-A\".\n [Rainer Jung]", " *) mod_slotmem_shm: Fix mistaken reset of num_free for restored shm.\n [Jim Jagielski]", " *) mod_proxy: non-existance of byrequests is not an immediate error.\n [Jim Jagielski]", " *) mod_proxy_balancer: Improve output of balancer-manager (re: Drn,\n Dis, Ign, Stby). PR 52478 [Danijel <dt-ng rbfh de>]\n \n *) configure: Fix processing of --disable-FEATURE for various features.\n [Jeff Trawick]", " *) mod_dialup/mod_http: Prevent a crash in mod_dialup in case of internal\n redirect. PR 52230.", " *) various modules, rotatelogs: Replace use of apr_file_write() with\n apr_file_write_full() to prevent incomplete writes. PR 53131.\n [Nicolas Viennot <apache viennot biz>, Stefan Fritsch]", " *) ab: Support socket timeout (-s timeout).\n [Guido Serra <zeph fsfe org>]", " *) httxt2dbm: Correct length computation for the 'value' stored in the\n DBM file. PR 47650 [jon buckybox com]", " *) core: Be more correct about rejecting directives that cannot work in <If>\n sections. [Stefan Fritsch]", " *) core: Fix directives like LogLevel that need to know if they are invoked\n at virtual host context or in Directory/Files/Location/If sections to\n work properly in If sections that are not in a Directory/Files/Location.\n [Stefan Fritsch]", " *) mod_xml2enc: Fix problems with charset conversion altering the\n Content-Length. [Micha Lenk <micha lenk info>]", " *) ap_expr: Add req_novary function that allows HTTP header lookups\n without adding the name to the Vary header. [Stefan Fritsch]", " *) mod_slotmem_*: Add in new fgrab() function which forces a grab and\n slot allocation on a specified slot. Allow for clearing of inuse\n array. [Jim Jagielski]", " *) mod_proxy_ftp: Fix segfaults on IPv4 requests to hosts with DNS\n AAAA records. PR 40841. [Andrew Rucker Jones <arjones simultan\n dyndns org>, <ast domdv de>, Jim Jagielski]", " *) mod_auth_form: Make sure that get_notes_auth() sets the user as does\n get_form_auth() and get_session_auth(). Makes sure that REMOTE_USER\n does not vanish during mod_include driven subrequests. [Graham\n Leggett]", " *) mod_cache_disk: Resolve errors while revalidating disk-cached files on\n Windows (\"...rename tempfile to datafile failed...\"). PR 38827\n [Eric Covener]", " *) mod_proxy_balancer: Bring XML output up to date. [Jim Jagielski]", " *) htpasswd, htdbm: Optionally read passwords from stdin, as more\n secure alternative to -b. PR 40243. [Adomas Paltanavicius <adomas\n paltanavicius gmail com>, Stefan Fritsch]", " *) htpasswd, htdbm: Add support for bcrypt algorithm (requires\n apr-util 1.5 or higher). PR 49288. [Stefan Fritsch]", " *) htpasswd, htdbm: Put full 48bit of entropy into salt, improve\n error handling. Add some of htpasswd's improvements to htdbm,\n e.g. warn if password is truncated by crypt(). [Stefan Fritsch]", " *) mod_auth_form: Support the expr parser in the\n AuthFormLoginRequiredLocation, AuthFormLoginSuccessLocation and\n AuthFormLogoutLocation directives. [Graham Leggett]", " *) mod_ssl: Add support for TLS-SRP (Secure Remote Password key exchange\n for TLS, RFC 5054). PR 51075. [Quinn Slack <sqs cs stanford edu>,\n Christophe Renou, Peter Sylvester]", " *) mod_rewrite: Stop mergeing RewriteBase down to subdirectories\n unless new option 'RewriteOptions MergeBase' is configured.\n PR 53963. [Eric Covener]", " *) mod_header: Allow for exposure of loadavg and server load using new \n format specifiers %l, %i, %b [Jim Jagielski]\n \n *) core: Make ap_regcomp() return AP_REG_ESPACE if out of memory. Make\n ap_pregcomp() abort if out of memory. This raises the minimum PCRE\n requirement to version 6.0. [Stefan Fritsch]", " *) mod_proxy: Add ability to configure the sticky session separator.\n PR 53893. [<inu inusasha de>, Jim Jagielski]", " *) mod_dumpio: Correctly log large messages\n PR 54179 [Marek Wianecki <mieszek2 interia pl>]", " *) core: Don't fail at startup with AH00554 when Include points to \n a directory without any wildcard character. [Eric Covener]", " *) core: Fail startup if the argument to ServerTokens is unrecognized.\n [Jackie Zhang <jackie.qq.zhang gmail.com>]", " *) mod_log_forensic: Don't log a spurious \"-\" if a request has been rejected\n before mod_log_forensic could attach its id to it. [Stefan Fritsch]", " *) rotatelogs: Omit the second argument for the first invocation of\n a post-rotate program when -p is used, per the documentation.\n [Joe Orton]", " *) mod_session_dbd: fix a segmentation fault in the function dbd_remove.\n PR 53452. [<rebanerebane gmail com>, Reimo Rebane]", " *) core: Functions to provide server load values: ap_get_sload() and\n ap_get_loadavg(). [Jim Jagielski, Jan Kaluza <jkaluza redhat.com>,\n Jeff Trawick]", " *) mod_ldap: Fix regression in handling \"server unavailable\" errors on \n Windows. PR 54140. [Eric Covener]\n \n *) syslog logging: Remove stray \", referer\" at the end of some messages.\n [Jeff Trawick]", " *) \"Iterate\" directives: Report an error if no arguments are provided.\n [Jeff Trawick]", " *) mod_ssl: Change default for SSLCompression to off, as compression\n causes security issues in most setups. (The so called \"CRIME\" attack).\n [Stefan Fritsch]", " *) ab: add TLS1.1/TLS1.2 options to -f switch, and adapt output\n to more accurately report the negotiated protocol. PR 53916.\n [Nicolás Pernas Maradei <nico emutex com>, Kaspar Brand]", " *) core: ErrorDocument now works for requests without a Host header.\n PR 48357. [Jeff Trawick]", " *) prefork: Avoid logging harmless errors during graceful stop.\n [Joe Orton, Jeff Trawick]", " *) mod_proxy: When concatting for PPR, avoid cases where we\n concat \".../\" and \"/...\" to create \"...//...\" [Jim Jagielski]", " *) mod_cache: Wrong content type and character set when\n mod_cache serves stale content because of a proxy error. \n PR 53539. [Rainer Jung, Ruediger Pluem]", " *) mod_proxy_ajp: Fix crash in packet dump code when logging\n with LogLevel trace7 or trace8. PR 53730. [Rainer Jung]", " *) httpd.conf: Removed the configuration directives setting a bad_DNT\n environment introduced in 2.4.3. The actual directives are commented\n out in the default conf file.", " *) core: Apply length limit when logging Status header values.\n [Jeff Trawick, Chris Darroch]", " *) mod_proxy_balancer: The nonce is only derived from the UUID iff\n not set via the 'nonce' balancer param. [Jim Jagielski]", " *) mod_ssl: Match wildcard SSL certificate names in proxy mode. \n PR 53006. [Joe Orton]", " *) Windows: Fix output of -M, -L, and similar command-line options\n which display information about the server configuration.\n [Jeff Trawick]", "Changes with Apache 2.4.3", " *) SECURITY: CVE-2012-3502 (cve.mitre.org)\n mod_proxy_ajp, mod_proxy_http: Fix an issue in back end\n connection closing which could lead to privacy issues due\n to a response mixup. PR 53727. [Rainer Jung]", " *) SECURITY: CVE-2012-2687 (cve.mitre.org)\n mod_negotiation: Escape filenames in variant list to prevent a\n possible XSS for a site where untrusted users can upload files to\n a location with MultiViews enabled. [Niels Heinen <heinenn google.com>]", " *) mod_authnz_ldap: Don't try a potentially expensive nested groups\n search before exhausting all AuthLDAPGroupAttribute checks on the\n current group. PR 52464 [Eric Covener]", " *) mod_lua: Add new directive LuaAuthzProvider to allow implementing an\n authorization provider in lua. [Stefan Fritsch]", " *) core: Be less strict when checking whether Content-Type is set to \n \"application/x-www-form-urlencoded\" when parsing POST data, \n or we risk losing data with an appended charset. PR 53698\n [Petter Berntsen <petterb gmail.com>]", " *) httpd.conf: Added configuration directives to set a bad_DNT environment\n variable based on User-Agent and to remove the DNT header field from\n incoming requests when a match occurs. This currently has the effect of\n removing DNT from requests by MSIE 10.0 because it deliberately violates\n the current specification of DNT semantics for HTTP. [Roy T. Fielding]", " *) mod_socache_shmcb: Fix bus error due to a misalignment\n in some 32 bit builds, especially on Solaris Sparc.\n PR 53040. [Rainer Jung]", " *) mod_cache: Set content type in case we return stale content.\n [Ruediger Pluem]", " *) Windows: Fix SSL failures on windows with AcceptFilter https none.\n PR 52476. [Jeff Trawick]", " *) ab: Fix read failure when targeting SSL server. [Jeff Trawick]", " *) The following now respect DefaultRuntimeDir/DEFAULT_REL_RUNTIMEDIR:\n - mod_auth_digest: shared memory file\n [Jeff Trawick]", " *) htpasswd: Use correct file mode for checking if file is writable.\n PR 45923. [Stefan Fritsch]", " *) mod_rewrite: Fix crash with dbd RewriteMaps. PR 53663. [Mikhail T.\n <mi apache aldan algebra com>]", " *) mod_ssl: Add new directive SSLCompression to disable TLS-level\n compression. PR 53219. [Björn Jacke <bjoern j3e de>, Stefan Fritsch]", " *) mod_lua: Add a few missing request_rec fields. Rename remote_ip to\n client_ip to match conn_rec. [Stefan Fritsch]", " *) mod_lua: Change prototype of vm_construct, to work around gcc bug which\n causes a segfault. PR 52779. [Dick Snippe <Dick Snippe tech omroep nl>]", " *) mpm_event: Don't count connections in lingering close state when\n calculating how many additional connections may be accepted.\n [Stefan Fritsch]", " *) mod_ssl: If exiting during initialization because of a fatal error,\n log a message to the main error log pointing to the appropriate\n virtual host error log. [Stefan Fritsch]", " *) mod_proxy_ajp: Reduce memory usage in case of many keep-alive requests on\n one connection. PR 52275. [Naohiro Ooiwa <naohiro ooiwa miraclelinux com>]", " *) mod_proxy_balancer: Restore balancing after a failed worker has\n recovered when using lbmethod_bybusyness. PR 48735. [Jeff Trawick]", " *) mod_setenvif: Compile some global regex only once during startup.\n This should save some memory, especially with .htaccess.\n [Stefan Fritsch]", " *) core: Add the port number to the vhost's name in the scoreboard.\n [Stefan Fritsch]", " *) mod_proxy: Fix ProxyPassReverse for balancer configurations.\n PR 45434. [Joe Orton]", " *) mod_lua: Add the parsebody function for parsing POST data. PR 53064.\n [Daniel Gruno]", " *) apxs: Use LDFLAGS from config_vars.mk in addition to CFLAGS and CPPFLAGS.\n [Stefan Fritsch]", " *) mod_proxy: Fix memory leak or possible corruption in ProxyBlock\n implementation. [Ruediger Pluem, Joe Orton]", " *) mod_proxy: Check hostname from request URI against ProxyBlock list,\n not forward proxy, if ProxyRemote* is configured. [Joe Orton]", " *) mod_proxy_connect: Avoid DNS lookup on hostname from request URI \n if ProxyRemote* is configured. PR 43697. [Joe Orton]", " *) mpm_event, mpm_worker: Remain active amidst prevalent child process\n resource shortages. [Jeff Trawick]", " *) Add \"strict\" and \"warnings\" pragmas to Perl scripts. [Rich Bowen]", " *) The following now respect DefaultRuntimeDir/DEFAULT_REL_RUNTIMEDIR:\n - core: the scoreboard (ScoreBoardFile), pid file (PidFile), and\n mutexes (Mutex)\n [Jim Jagielski]", " *) ab: Fix bind() errors. [Joe Orton]", " *) mpm_event: Don't do a blocking write when starting a lingering close\n from the listener thread. PR 52229. [Stefan Fritsch]", " *) mod_so: If a filename without slashes is specified for LoadFile or\n LoadModule and the file cannot be found in the server root directory,\n try to use the standard dlopen() search path. [Stefan Fritsch]", " *) mpm_event, mpm_worker: Fix cases where the spawn rate wasn't reduced\n after child process resource shortages. [Jeff Trawick]", " *) mpm_prefork: Reduce spawn rate after a child process exits due to\n unexpected poll or accept failure. [Jeff Trawick]", " *) core: Log value of Status header line in script responses rather\n than the fixed header name. [Chris Darroch]", " *) mod_ssl: Fix handling of empty response from OCSP server.\n [Jim Meyering <meyering redhat.com>, Joe Orton]", " *) mpm_event: Fix handling of MaxConnectionsPerChild. [Stefan Fritsch]", " *) mod_authz_core: If an expression in \"Require expr\" returns denied and\n references %{REMOTE_USER}, trigger authentication and retry. PR 52892.\n [Stefan Fritsch]", " *) core: Always log if LimitRequestFieldSize triggers. [Stefan Fritsch]", " *) mod_deflate: Skip compression if compression is enabled at SSL level.\n [Stefan Fritsch]", " *) core: Add missing HTTP status codes registered with IANA.\n [Julian Reschke <julian.reschke gmx.de>, Rainer Jung]", " *) mod_ldap: Treat the \"server unavailable\" condition as a transient\n error with all LDAP SDKs. [Filip Valder <filip.valder vsb.cz>]", " *) core: Fix spurious \"not allowed here\" error returned when the Options \n directive is used in .htaccess and \"AllowOverride Options\" (with no \n specific options restricted) is configured. PR 53444. [Eric Covener]", " *) mod_authz_core: Fix parsing of Require arguments in <AuthzProviderAlias>.\n PR 53048. [Stefan Fritsch]", " *) mod_log_config: Fix %{abc}C truncating cookie values at first \"=\".\n PR 53104. [Greg Ames]", " *) mod_ext_filter: Fix error_log spam when input filters are configured. \n [Joe Orton]", " *) mod_rewrite: Add \"AllowAnyURI\" option. PR 52774. [Joe Orton]", " *) htdbm, htpasswd: Don't crash if crypt() fails (e.g. with FIPS enabled). \n [Paul Wouters <pwouters redhat.com>, Joe Orton]", " *) core: Use a TLS 1.0 close_notify alert for internal dummy connection if\n the chosen listener is configured for https. [Joe Orton]", " *) mod_proxy: Use the the same hostname for SNI as for the HTTP request when\n forwarding to SSL backends. PR 53134.\n [Michael Weiser <michael weiser.dinsnail.net>, Ruediger Pluem]", " *) mod_info: Display all registered providers. [Stefan Fritsch]", " *) mod_ssl: Send the error message for speaking http to an https port using\n HTTP/1.0 instead of HTTP/0.9, and omit the link that may be wrong when\n using SNI. PR 50823. [Stefan Fritsch]", " *) core: Fix segfault in logging if r->useragent_addr or c->client_addr is\n unset. PR 53265. [Stefan Fritsch]", " *) log_server_status: Bring Perl style forward to the present, use\n standard modules, update for new format of server-status output.\n PR 45424. [Richard Bowen, Dave Brondsema, and others]", " *) mod_sed, mod_log_debug, mod_rewrite: Symbol namespace cleanups. \n [Joe Orton, André Malo]", " *) core: Prevent \"httpd -k restart\" from killing server in presence of\n config error. [Joe Orton]", " *) mod_proxy_fcgi: If there is an error reading the headers from the\n backend, send an error to the client. PR 52879. [Stefan Fritsch]", "Changes with Apache 2.4.2", " *) SECURITY: CVE-2012-0883 (cve.mitre.org)\n envvars: Fix insecure handling of LD_LIBRARY_PATH that could lead to the\n current working directory to be searched for DSOs. [Stefan Fritsch]", " *) mod_slotmem_shm: Honor DefaultRuntimeDir [Jim Jagielski]", " *) mod_ssl: Fix crash with threaded MPMs due to race condition when\n initializing EC temporary keys. [Stefan Fritsch]", " *) mod_rewrite: Fix RewriteCond integer checks to be parsed correctly.\n PR 53023. [Axel Reinhold <apache freakout.de>, André Malo]", " *) mod_proxy: Add the forcerecovery balancer parameter that determines if\n recovery for balancer workers is enforced. [Ruediger Pluem]", " *) Fix MPM DSO load failure on AIX. [Jeff Trawick]", " *) mod_proxy: Correctly set up reverse proxy worker. PR 52935.\n [Petter Berntsen <petterb gmail.com>]", " *) mod_sed: Don't define PATH_MAX to a potentially undefined value, causing\n compile problems on GNU hurd. [Stefan Fritsch]", " *) core: Add ap_runtime_dir_relative() and DefaultRuntimeDir.\n [Jeff Trawick]", " *) core: Fix breakage of Listen directives with MPMs that use a\n per-directory config. PR 52904. [Stefan Fritsch]", " *) core: Disallow directives in AllowOverrideList which are only allowed\n in VirtualHost or server context. These are usually not prepared to be\n called in .htaccess files. [Stefan Fritsch]", " *) core: In AllowOverrideList, do not allow 'None' together with other\n directives. PR 52823. [Stefan Fritsch]", " *) mod_slotmem_shm: Support DEFAULT_REL_RUNTIMEDIR for file-based shm.\n [Jim Jagielski]", " *) core: Fix merging of AllowOverrideList and ContentDigest.\n [Stefan Fritsch]", " *) mod_request: Fix validation of the KeptBodySize argument so it\n doesn't always throw a configuration error. PR 52981 [Eric Covener]", " *) core: Add filesystem paths to access denied / access failed messages\n AH00035 and AH00036. [Eric Covener]", " *) mod_dumpio: Properly handle errors from subsequent input filters.\n PR 52914. [Stefan Fritsch]", " *) Unix MPMs: Fix small memory leak in parent process if connect()\n failed when waking up children. [Joe Orton]", " *) \"DirectoryIndex disabled\" now undoes DirectoryIndex settings in\n the current configuration section, not just previous config sections.\n PR 52845. [Eric Covener]", " *) mod_xml2enc: Fix broken handling of EOS buckets which could lead to\n response headers not being sent. PR 52766. [Stefan Fritsch]", " *) mod_ssl: Properly free the GENERAL_NAMEs. PR 32652. [Kaspar Brand]", " *) core: Check during config test that directories for the access\n logs actually exist. PR 29941. [Stefan Fritsch]", " *) mod_xml2enc, mod_proxy_html: Enable per-module loglevels.\n [Stefan Fritsch]", " *) mod_filter: Fix segfault with AddOutputFilterByType. PR 52755.\n [Stefan Fritsch]", " *) mod_session: Sessions are encoded as application/x-www-form-urlencoded\n strings, however we do not handle the encoding of spaces properly.\n Fixed. [Graham Leggett]", " *) Configuration: Example in comment should use a path consistent\n with the default configuration. PR 52715.\n [Rich Bowen, Jens Schleusener, Rainer Jung]", " *) Configuration: Switch documentation links from trunk to 2.4.\n [Rainer Jung]", " *) configure: Fix out of tree build using apr and apr-util in srclib.\n [Rainer Jung]", "Changes with Apache 2.4.1", " *) SECURITY: CVE-2012-0053 (cve.mitre.org)\n Fix an issue in error responses that could expose \"httpOnly\" cookies\n when no custom ErrorDocument is specified for status code 400. \n [Eric Covener]", " *) mod_proxy_balancer: Fix crash on Windows. PR 52402 [Mladen Turk]", " *) core: Check during configtest that the directories for error logs exist.\n PR 29941 [Stefan Fritsch]", " *) Core configuration: add AllowOverride option to treat syntax\n errors in .htaccess as non-fatal. PR 52439 [Nick Kew, Jim Jagielski]", " *) core: Fix memory consumption in core output filter with streaming\n bucket types like CGI or PIPE. [Joe Orton, Stefan Fritsch]", " *) configure: Disable modules at configure time if a prerequisite module\n is not enabled. PR 52487. [Stefan Fritsch]", " *) Rewrite and proxy now decline what they don't support rather\n than fail the request. [Joe Orton]", " *) Fix building against external apr plus apr-util if apr is not installed\n in a system default path. [Rainer Jung]", " *) Doxygen fixes and improvements. [Joe Orton, Igor Galić]", " *) core: Fix building against PCRE 8.30 by switching from the obsolete\n pcre_info() to pcre_fullinfo(). PR 52623 [Ruediger Pluem, Rainer Jung]", "Changes with Apache 2.4.0", " *) SECURITY: CVE-2012-0031 (cve.mitre.org)\n Fix scoreboard issue which could allow an unprivileged child process\n to cause the parent to crash at shutdown rather than terminate\n cleanly. [Joe Orton]", " *) mod_ssl: Fix compilation with xlc on AIX. PR 52394. [Stefan Fritsch]", " *) SECURITY: CVE-2012-0021 (cve.mitre.org)\n mod_log_config: Fix segfault (crash) when the '%{cookiename}C' log format\n string is in use and a client sends a nameless, valueless cookie, causing\n a denial of service. The issue existed since version 2.2.17 and 2.3.3.\n PR 52256. [Rainer Canavan <rainer-apache 7val com>]", " *) mod_ssl: when compiled against OpenSSL 1.0.1 or later, allow explicit\n control of TLSv1.1 and TLSv1.2 through the SSLProtocol directive.\n [Kaspar Brand]", " *) mod_ssl: set OPENSSL_NO_SSL_INTERN when compiling against OpenSSL 1.0.1\n or later, to improve binary compatibility with future OpenSSL releases.\n [Kaspar Brand]", " *) mod_mime: Don't arbitrarily bypass AddOutputFilter during a ProxyPass,\n but then allow AddOutputFilter during a RewriteRule [P]. Make mod_mime\n behave identically in both cases. PR52342. [Graham Leggett]", " *) Move ab, logresolve, httxt2dbm and apxs to bin from sbin, along with\n corresponding man pages. [Graham Leggett]", " *) Distinguish properly between the bindir and sbindir directories when\n installing binaries. Previously all binaries were silently installed to\n sbindir, whether they were system administration commands or not.\n [Graham Leggett]", "Changes with Apache 2.3.16", " *) SECURITY: CVE-2011-4317 (cve.mitre.org)\n Resolve additional cases of URL rewriting with ProxyPassMatch or\n RewriteRule, where particular request-URIs could result in undesired\n backend network exposure in some configurations.\n [Joe Orton]", " *) core: Limit line length in .htaccess to 8K like in 2.2.x, to avoid\n additional DoS potential. [Stefan Fritsch]", " *) core, all modules: Add unique tag to most error log messages. [Stefan\n Fritsch]", " *) mod_socache_memcache: Change provider name from \"mc\" to \"memcache\" to\n match module name. [Stefan Fritsch]", " *) mod_slotmem_shm: Change provider name from \"shared\" to \"shm\" to match\n module name. [Stefan Fritsch]", " *) mod_ldap: Fix segfault with Solaris LDAP when enabling ldaps. This\n requires an apr-util fix in which is available in apr-util >= 1.4.0.\n PR 42682. [Stefan Fritsch]", " *) mod_rewrite: Add the AllowNoSlash RewriteOption, which makes it possible\n for RewriteRules to be placed in .htaccess files that match the directory\n with no trailing slash. PR 48304.\n [Matthew Byng-Maddick <matthew byng-maddick bbc.co.uk>]", " *) mod_session_crypto: Add a SessionCryptoPassphraseFile directive so that\n the administrator can hide the keys from the configuration. [Graham\n Leggett]", " *) Introduce a per request version of the remote IP address, which can be\n optionally modified by a module when the effective IP of the client\n is not the same as the real IP of the client (such as a load balancer).\n Introduce a per connection \"peer_ip\" and a per request \"client_ip\" to\n distinguish between the raw IP address of the connection and the effective\n IP address of the request. [Graham Leggett]", " *) ap_pass_brigade_fchk() function added. [Jim Jagielski]", " *) core: Pass ap_errorlog_info struct to error log hook. [Stefan Fritsch]", " *) mod_cache_disk: Make sure we check return codes on all writes and\n attempts to close, and clean up after ourselves in these cases.\n PR43589. [Graham Leggett]", " *) mod_cache_disk: Remove the unnecessary intermediate brigade while\n writing to disk. Fixes a problem where mod_disk_cache was leaving\n buckets in the intermediate brigade and not passing them to out on\n exit. [Florian S. <f_los_ch yahoo.com>, Graham Leggett]", " *) mod_ssl: use a shorter setting for SSLCipherSuite in the default\n default configuration file, and add some more information about\n configuring a speed-optimized alternative.\n [Kaspar Brand]", " *) mod_ssl: drop support for the SSLv2 protocol. [Kaspar Brand]", " *) mod_lua: Stop losing track of all but the most specific LuaHook* directives\n when multiple per-directory config sections are used. Adds LuaInherit \n directive to control how parent sections are merged. [Eric Covener]", " *) Server directive display (-L): Include directives of DSOs.\n [Jeff Trawick]", " *) mod_cache: Make sure we merge headers correctly when we handle a\n non cacheable conditional response. PR52120. [Graham Leggett]", " *) Pre GA removal of components that will not be included:\n - mod_noloris was superseded by mod_reqtimeout\n - mod_serf\n - mpm_simple\n [Rainer Jung]", " *) core: Set MaxMemFree 2048 by default. [Stefan Fritsch]", " *) mpm_event: Fix assertion failure during very high load. [Stefan Fritsch]", " *) configure: Additional modules loaded by default: mod_headers.\n Modules moved from module set \"few\" to \"most\" and no longer loaded\n by default: mod_actions, mod_allowmethods, mod_auth_form, mod_buffer,\n mod_cgi(d), mod_include, mod_negotiation, mod_ratelimit, mod_request,\n mod_userdir. [Rainer Jung]", " *) mod_lua: Use the right lua scope when used as a hook. [Rainer Jung]", " *) configure: Only load the really imporant modules (i.e. those enabled by\n the 'few' selection) by default. Don't handle modules enabled with\n --enable-foo specially. [Stefan Fritsch]", " *) end-generation hook: Fix false notification of end-of-generation for\n temporary intervals with no active MPM children. [Jeff Trawick]", " *) mod_ssl: Add support for configuring persistent TLS session ticket\n encryption/decryption keys (useful for clustered environments).\n [Paul Querna, Kaspar Brand]", " *) mod_usertrack: Use random value instead of remote IP address.\n [Stefan Fritsch]", "Changes with Apache 2.3.15", " *) SECURITY: CVE-2011-3348 (cve.mitre.org)\n mod_proxy_ajp: Respond with HTTP_NOT_IMPLEMENTED when the method is not\n recognized. [Jean-Frederic Clere]", " *) SECURITY: CVE-2011-3192 (cve.mitre.org)\n core: Fix handling of byte-range requests to use less memory, to avoid\n denial of service. If the sum of all ranges in a request is larger than\n the original file, ignore the ranges and send the complete file.\n PR 51714. [Stefan Fritsch, Jim Jagielski, Ruediger Pluem, Eric Covener,\n <lowprio20 gmail.com>]", " *) SECURITY: CVE-2011-3607 (cve.mitre.org)\n core: Fix integer overflow in ap_pregsub. This can be triggered e.g.\n with mod_setenvif via a malicious .htaccess. [Stefan Fritsch]", " *) SECURITY: CVE-2011-3368 (cve.mitre.org)\n Reject requests where the request-URI does not match the HTTP\n specification, preventing unexpected expansion of target URLs in\n some reverse proxy configurations. [Joe Orton]", " *) configure: Load all modules in the generated default configuration\n when using --enable-load-all-modules. [Rainer Jung]", " *) mod_reqtimeout: Change the default to set some reasonable timeout\n values. [Stefan Fritsch]", " *) core, mod_dav_fs: Change default ETag to be \"size mtime\", i.e. remove\n the inode. PR 49623. [Stefan Fritsch]", " *) mod_lua: Expose SSL variables via r:ssl_var_lookup(). [Eric Covener]", " *) mod_lua: LuaHook{AccessChecker,AuthChecker,CheckUserID,TranslateName}\n can now additionally be run as \"early\" or \"late\" relative to other modules.\n [Eric Covener]", " *) configure: By default, only load those modules that are either required\n or explicitly selected by a configure --enable-foo argument. The\n LoadModule statements for modules enabled by --enable-mods-shared=most\n and friends will be commented out. [Stefan Fritsch]", " *) mod_lua: Prevent early Lua hooks (LuaHookTranslateName and \n LuaHookQuickHandler) from being configured in <Directory>, <Files>, \n and htaccess where the configuration would have been ignored.\n [Eric Covener]", " *) mod_lua: Resolve \"attempt to index local 'r' (a userdata value)\" errors\n in LuaMapHandler scripts [Eric Covener]", " *) mod_log_debug: Rename optional argument from if= to expr=, to be more\n in line with other config directives. [Stefan Fritsch]", " *) mod_headers: Require an expression to be specified with expr=, to be more\n in line with other config directives. [Stefan Fritsch]", " *) mod_substitute: To prevent overboarding memory usage, limit line length\n to 1MB. [Stefan Fritsch]", " *) mod_lua: Make the query string (r.args) writable. [Eric Covener]", " *) mod_include: Add support for application/x-www-form-urlencoded encoding\n and decoding. [Graham Leggett]", " *) rotatelogs: Add -c option to force logfile creation in every rotation \n interval, even if empty. [Jan Kaluža <jkaluza redhat.com>]\n \n *) core: Limit ap_pregsub() to 64K, add ap_pregsub_ex() for longer strings.\n [Stefan Fritsch]", " *) mod_session_crypto: Refactor to support the new apr_crypto API.\n [Graham Leggett]", " *) http: Add missing Location header if local URL-path is used as\n ErrorDocument for 30x. [Stefan Fritsch]", " *) mod_buffer: Make sure we step down for subrequests, but not for internal\n redirects triggered by mod_rewrite. [Graham Leggett]", " *) mod_lua: add r:construct_url as a wrapper for ap_construct_url.\n [Eric Covener]\n \n *) mod_remote_ip: Fix configuration of internal proxies. PR 49272.\n [Jim Riggs <jim riggs me>]", " *) mpm_winnt: Handle AcceptFilter 'none' mode correctly; resolve specific\n server IP endpoint and remote client IP upon connection. [William Rowe]", " *) mod_setenvif: Remove OID match which is obsoleted by SetEnvIfExpr with\n PeerExtList(). [Stefan Fritsch]", " *) mpm_prefork, mpm_worker, mpm_event: If a child is created just before\n graceful restart and then exits because of a missing lock file, don't\n shutdown the whole server. PR 39311. [Shawn Michael\n <smichael rightnow com>]", " *) mpm_event: Check the return value from ap_run_create_connection.\n PR: 41194. [Davi Arnaut]", " *) mod_mime_magic: Add signatures for PNG and SWF to the example config.\n PR: 48352. [Jeremy Wagner-Kaiser <jwagner-kaiser adknowledge com>]", " *) core, unixd: Add -D DUMP_RUN_CFG option to dump some configuration items\n from the parsed (or default) config. This is useful for init scripts that\n need to setup temporary directories and permissions. [Stefan Fritsch]", " *) core, mod_actions, mod_asis: Downgrade error log messages which accompany\n a 404 request status from loglevel error to info. PR: 35768. [Stefan\n Fritsch]", " *) core: Fix hook sorting with Perl modules. PR: 45076. [Torsten Foertsch\n <torsten foertsch gmx net>]", " *) core: Enforce LimitRequestFieldSize after multiple headers with the same\n name have been merged. [Stefan Fritsch]", " *) mod_ssl: If MaxMemFree is set, ask OpenSSL >= 1.0.0 to reduce memory\n usage. PR 51618. [Cristian Rodríguez <crrodriguez opensuse org>,\n Stefan Fritsch]", " *) mod_ssl: At startup, when checking a server certificate whether it\n matches the configured ServerName, also take dNSName entries in the\n subjectAltName extension into account. PR 32652, PR 47051. [Kaspar Brand]", " *) mod_substitute: Reduce memory usage and copying of data. PR 50559.\n [Stefan Fritsch]", " *) mod_ssl/proxy: enable the SNI extension for backend TLS connections\n [Kaspar Brand]", " *) Add wrappers for malloc, calloc, realloc that check for out of memory\n situations and use them in many places. PR 51568, PR 51569, PR 51571.\n [Stefan Fritsch]", " *) Fix cross-compilation of mod_cgi/mod_cgid when APR_HAVE_STRUCT_RLIMIT is \n false but RLIMIT_* are defined. PR51371. [Eric Covener]", " *) core: Correctly obey ServerName / ServerAlias if the Host header from the\n request matches the VirtualHost address.\n PR 51709. [Micha Lenk <micha lenk.info>]", " *) mod_unique_id: Use random number generator to initialize counter.\n PR 45110. [Stefan Fritsch]", " *) core: Add convenience API for apr_random. [Stefan Fritsch]", " *) core: Add MaxRangeOverlaps and MaxRangeReversals directives to control\n the number of overlapping and reversing ranges (respectively) permitted\n before returning the entire resource, with a default limit of 20.\n [Jim Jagielski]", " *) mod_ldap: Optional function uldap_ssl_supported(r) always returned false\n if called from a virtual host with mod_ldap directives in it. Did not\n affect mod_authnz_ldap's usage of mod_ldap. [Eric Covener]", " *) mod_filter: Instead of dropping the Accept-Ranges header when a filter\n registered with AP_FILTER_PROTO_NO_BYTERANGE is present,\n set the header value to \"none\". [Eric Covener, Ruediger Pluem]", " *) core: Allow MaxRanges none|unlimited|default and set 'Accept-Ranges: none'\n in the case Ranges are being ignored with MaxRanges none.\n [Eric Covener]", " *) mod_ssl: revamp CRL-based revocation checking when validating\n certificates of clients or proxied servers. Completely delegate\n CRL processing to OpenSSL, and add a new [Proxy]CARevocationCheck\n directive for controlling the revocation checking mode. [Kaspar Brand]", " *) core: Add MaxRanges directive to control the number of ranges permitted\n before returning the entire resource, with a default limit of 200.\n [Eric Covener]", " *) mod_cache: Ensure that CacheDisable can correctly appear within\n a LocationMatch. [Graham Leggett]", " *) mod_cache: Fix the moving of the CACHE filter, which erroneously\n stood down if the original filter was not added by configuration.\n [Graham Leggett]", " *) mod_ssl: improve certificate error logging. PR 47408. [Kaspar Brand]", " *) mod_authz_groupfile: Increase length limit of lines in the group file to\n 16MB. PR 43084. [Stefan Fritsch]", " *) core: Increase length limit of lines in the configuration file to 16MB.\n PR 45888. PR 50824. [Stefan Fritsch]", " *) core: Add API for resizable buffers. [Stefan Fritsch]", " *) mod_ldap: Enable LDAPConnectionTimeout for LDAP toolkits that have\n LDAP_OPT_CONNECT_TIMEOUT instead of LDAP_OPT_NETWORK_TIMEOUT, such\n as Tivoli Directory Server 6.3 and later. [Eric Covener]", " *) mod_ldap: Change default number of retries from 10 to 3, and add\n an LDAPRetries and LDAPRetryDelay directives. [Eric Covener]", " *) mod_authnz_ldap: Don't retry during authentication, because this just\n multiplies the ample retries already being done by mod_ldap. [Eric Covener]", " *) configure: Allow to explicitly disable modules even with module selection\n 'reallyall'. [Stefan Fritsch]", " *) mod_rewrite: Check validity of each internal (int:) RewriteMap even if the\n RewriteEngine is disabled in server context, avoiding a crash while\n referencing the invalid int: map at runtime. PR 50994.\n [Ben Noordhuis <info noordhuis nl>]", " *) mod_ssl, configure: require OpenSSL 0.9.7 or later. [Kaspar Brand]", " *) mod_ssl: remove ssl_toolkit_compat layer. [Kaspar Brand]", " *) mod_ssl, configure, ab: drop support for RSA BSAFE SSL-C toolkit.\n [Kaspar Brand]", " *) mod_usertrack: Run mod_usertrack earlier in the fixups hook to ensure the\n cookie is set when modules such as mod_rewrite trigger a redirect. Also\n use r->err_headers_out for the cookie, for the same reason. PR29755.\n [Sami J. Mäkinen <sjm almamedia fi>, Eric Covener]", " *) mod_proxy_http, mod_proxy_connect: Add 'proxy-status' and\n 'proxy-source-port' request notes for logging. PR 30195. [Stefan Fritsch]", " *) configure: Enable ldap modules in 'all' and 'most' selections if ldap\n is compiled into apr-util. [Stefan Fritsch]", " *) core: Add ap_check_cmd_context()-check if a command is executed in\n .htaccess file. [Stefan Fritsch]", " *) mod_deflate: Fix endless loop if first bucket is metadata. PR 51590.\n [Torsten Foertsch <torsten foertsch gmx net>]", " *) mod_authn_socache: Fix to work in .htaccess if not configured anywhere\n in httpd.conf, and introduce an AuthnCacheEnable directive.\n PR 51991 [Nick Kew]", " *) mod_xml2enc: new (formerly third-party) module supporting\n internationalisation for filters via smart charset sniffing\n and conversion. [Nick Kew]", " *) mod_proxy_html: new (formerly third-party) module to fix up\n HTML links in a reverse proxy situation, where a backend\n generates URLs that are not resolvable by Clients. [Nick Kew]", "Changes with Apache 2.3.14", " *) mod_proxy_ajp: Improve trace logging. [Rainer Jung]", " *) mod_proxy_ajp: Respect \"reuse\" flag in END_REPONSE packets.\n [Rainer Jung]", " *) mod_proxy: enable absolute URLs to be rewritten with ProxyPassReverse,\n e.g. to reverse proxy \"Location: https://other-internal-server/login\"\n [Nick Kew]", " *) prefork, worker, event: Make sure crashes are logged to the error log if\n httpd has already detached from the console. [Stefan Fritsch]", " *) prefork, worker, event: Reduce period during startup/restart where a\n successive signal may be lost. PR 43696. [Arun Bhalla <arun shme net>]", " *) mod_allowmethods: Correct Merging of \"reset\" and do not allow an\n empty parameter list for the AllowMethods directive. [Rainer Jung]", " *) configure: Update selection of modules for 'all' and 'most'. 'all' will\n now enable all modules except for example and test modules. Make the\n selection for 'most' more useful (including ssl and proxy). Both 'all'\n and 'most' will now disable modules if dependencies are missing instead\n of aborting. If a specific module is requested with --enable-XXX=yes,\n missing dependencies will still cause configure to exit with an error.\n [Stefan Fritsch]", " *) mod_ldap: Revert the integration of apr-ldap as ap_ldap which was done\n in 2.3.13. [Stefan Fritsch]", " *) core: For '*' or '_default_' vhosts, use a wildcard address of any\n address family, rather than IPv4 only. [Joe Orton]", " *) core, mod_rewrite, mod_ssl, mod_nw_ssl: Make the SERVER_NAME variable\n include [ ] for literal IPv6 addresses, as mandated by RFC 3875.\n PR 26005. [Stefan Fritsch]", " *) mod_negotiation: Fix parsing of Content-Length in type maps. PR 42203.\n [Nagae Hidetake <nagae eagan jp>]", " *) core: Add more logging to ap_scan_script_header_err* functions. Add\n ap_scan_script_header_err*_ex functions that take a module index for\n logging.\n mod_cgi, mod_cgid, mod_proxy_fcgi, mod_proxy_scgi, mod_isapi: Use the\n new functions in order to make logging configurable per-module.\n [Stefan Fritsch]", " *) mod_dir: Add DirectoryIndexRedirect to send an external redirect to\n the proper index. [Eric Covener]", " *) mod_deflate: Don't try to compress requests with a zero sized body.\n PR 51350. [Stefan Fritsch]", " *) core: Fix startup on IPv6-only systems. PR 50592. [Joe Orton,\n <root linkage white-void net>]", " *) suexec: Add environment variables CONTEXT_DOCUMENT_ROOT, CONTEXT_PREFIX,\n REDIRECT_ERROR_NOTES, REDIRECT_SCRIPT_FILENAME, REQUEST_SCHEME to the\n whitelist in suexec. PR 51499. [Graham Laverty <graham reg ca>,\n Stefan Fritsch]", " *) mod_rewrite: Fix regexp RewriteCond with NoCase. [Stefan Fritsch]", " *) mod_log_debug: New module that allows to log custom messages at various\n phases in the request processing. [Stefan Fritsch]", " *) mod_ssl: Add some debug logging when loading server certificates.\n PR 37912. [Nick Burch <nick burch alfresco com>]", " *) configure: Support reallyall option also for --enable-mods-static.\n [Rainer Jung]", " *) mod_socache_dc: add --with-distcache to configure for choosing\n the distcache installation directory. [Rainer Jung]", " *) mod_socache_dc: use correct build variable MOD_SOCACHE_DC_LDADD\n instead of MOD_SOCACHE_LDADD in build macro. [Rainer Jung]", " *) mod_lua, mod_deflate: respect platform specific runpath linker\n flag. [Rainer Jung]", " *) configure: Only link the httpd binary against PCRE. No other support\n binary needs PCRE. [Rainer Jung]", " *) configure: tolerate dependency checking failures for modules if\n they have been enabled implicitely. [Rainer Jung]", " *) configure: Allow to specify module specific custom linker flags via\n the MOD_XXX_LDADD variables. [Rainer Jung]", "Changes with Apache 2.3.13", " *) ab: Support specifying the local address to use. PR 48930.\n [Peter Schuller <scode spotify com>]", " *) core: Add support to ErrorLogFormat for logging the system unique\n thread id under Linux. [Stefan Fritsch]", " *) event: New AsyncRequestWorkerFactor directive to influence how many\n connections will be accepted per process. [Stefan Fritsch]", " *) prefork, worker, event: Rename MaxClients to MaxRequestWorkers which\n describes more accurately what it does. [Stefan Fritsch]", " *) rotatelogs: Add -p argument to specify custom program to invoke\n after a log rotation. PR 51285. [Sven Ulland <sveniu ifi.uio.no>,\n Joe Orton]", " *) mod_ssl: Don't do OCSP checks for valid self-issued certs. [Kaspar Brand]", " *) mod_ssl: Avoid unnecessary renegotiations with SSLVerifyDepth 0.\n PR 48215. [Kaspar Brand]", " *) mod_status: Display information about asynchronous connections in the\n server-status. PR 44377. [Stefan Fritsch]", " *) mpm_event: If the number of connections of a process is very high, or if\n all workers are busy, don't accept new connections in that process.\n [Stefan Fritsch]", " *) mpm_event: Process lingering close asynchronously instead of tying up\n worker threads. [Jeff Trawick, Stefan Fritsch]", " *) mpm_event: If MaxMemFree is set, limit the number of pools that is kept\n around. [Stefan Fritsch]", " *) mpm_event: Fix graceful restart aborting connections. PR 43359.\n [Takashi Sato <takashi lans-tv com>]", " *) mod_ssl: Disable AECDH ciphers in example config. PR 51363.\n [Rob Stradling <rob comodo com>]", " *) core: Introduce new function ap_get_conn_socket() to access the socket of\n a connection. [Stefan Fritsch]", " *) mod_data: Introduce a filter to support RFC2397 data URLs. [Graham\n Leggett]", " *) mod_userdir/mod_alias/mod_vhost_alias: Correctly set DOCUMENT_ROOT,\n CONTEXT_DOCUMENT_ROOT, CONTEXT_PREFIX. PR 26052. PR 46198.\n [Stefan Fritsch]", " *) core: Allow to override document_root on a per-request basis. Introduce\n new context_document_root and context_prefix which provide information\n about non-global URI-to-directory mappings (from e.g. mod_userdir or\n mod_alias) to scripts. PR 49705. [Stefan Fritsch]", " *) core: Add <ElseIf> and <Else> to complement <If> sections.\n [Stefan Fritsch]", " *) mod_ext_filter: Remove DebugLevel option in favor of per-module loglevel.\n [Stefan Fritsch]", " *) mod_include: Make the \"#if expr\" element use the new \"ap_expr\" expression\n parser. The old parser can still be used by setting the new directive\n SSILegacyExprParser. [Stefan Fritsch]", " *) core: Add some features to ap_expr for use by mod_include: a restricted\n mode that does not allow to bypass request access restrictions; new\n variables DOCUMENT_URI (alias for REQUEST_URI), LAST_MODIFIED; -A as an\n alias for -U; an additional data entry in ap_expr_eval_ctx_t for use by\n the consumer; an extensible ap_expr_exec_ctx() API that allows to use that\n data entry. [Stefan Fritsch]", " *) mod_include: Merge directory configs instead of one SSI* config directive\n causing all other per-directory SSI* config directives to be reset.\n [Stefan Fritsch]", " *) mod_charset_lite: Remove DebugLevel option in favour of per-module\n loglevel. [Stefan Fritsch]", " *) core: Add ap_regexec_len() function that works with non-null-terminated\n strings. PR 51231. [Yehezkel Horowitz <horowity checkpoint com>]", " *) mod_authnz_ldap: If the LDAP server returns constraint violation,\n don't treat this as an error but as \"auth denied\". [Stefan Fritsch]", " *) mod_proxy_fcgi|scgi: Add support for \"best guess\" of PATH_INFO\n for SCGI/FCGI. PR 50880, 50851. [Mark Montague <mark catseye.org>,\n Jim Jagielski]", " *) mod_cache: When content is served stale, and there is no means to\n revalidate the content using ETag or Last-Modified, and we have\n mandated no stale-on-error behaviour, stand down and don't cache.\n Saves a cache write that will never be read.\n [Graham Leggett]", " *) mod_reqtimeout: Fix a timed out connection going into the keep-alive\n state after a timeout when discarding a request body. PR 51103.\n [Stefan Fritsch]", " *) core: Add various file existance test operators to ap_expr.\n [Stefan Fritsch]", " *) mod_proxy_express: New mass reverse-proxy switch extension for\n mod_proxy. [Jim Jagielski]", " *) configure: Fix script error when configuring module set \"reallyall\".\n [Rainer Jung]", "Changes with Apache 2.3.12", " *) configure, core: Provide easier support for APR's hook probe\n capability. [Jim Jagielski, Jeff Trawick]", " *) Silence autoconf 2.68 warnings. [Rainer Jung]", " *) mod_authnz_ldap: Resolve crash when LDAP is used for authorization only\n [Scott Hill <shill genscape.com>]", " *) support: Make sure check_forensic works with mod_unique_id loaded\n [Joe Schaefer]", " *) Add child_status hook for tracking creation/termination of MPM child\n processes. Add end_generation hook for notification when the last\n MPM child of a generation exits. [Jeff Trawick]", " *) mod_ldap: Make LDAPSharedCacheSize 0 create a non-shared-memory cache per\n process as opposed to disabling caching completely. This allows to use\n the non-shared-memory cache as a workaround for the shared memory cache\n not being available during graceful restarts. PR 48958. [Stefan Fritsch]", " *) Add new ap_reserve_module_slots/ap_reserve_module_slots_directive API,\n necessary if a module (like mod_perl) registers additional modules late\n in the startup phase. [Stefan Fritsch]", " *) core: Prevent segfault if DYNAMIC_MODULE_LIMIT is reached. PR 51072.\n [Torsten Förtsch <torsten foertsch gmx net>]", " *) WinNT MPM: Improve robustness under heavy load. [Jeff Trawick]", " *) MinGW build improvements. PR 49535. [John Vandenberg\n <jayvdb gmail.com>, Jeff Trawick]", " *) core: Support module names with colons in loglevel configuration.\n [Torsten Förtsch <torsten foertsch gmx net>]", " *) mod_ssl, ab: Support OpenSSL compiled without SSLv2 support.\n [Stefan Fritsch]", " *) core: Abort if the MPM is changed across restart. [Jeff Trawick]", " *) mod_proxy_ajp: Add support for 'ProxyErrorOverride on'. PR 50945.\n [Peter Pramberger <peter pramberger.at>, Jim Jagielski]", " *) mod_proxy_fcgi: Add support for 'ProxyErrorOverride on'. PR 50913.\n [Mark Montague <mark catseye.org>, Jim Jagielski]", " *) core: Change the APIs of ap_cfg_getline() and ap_cfg_getc() to return an\n error code. Abort with a nice error message if a config line is too long.\n Partial fix for PR 50824. [Stefan Fritsch]", " *) mod_info: Dump config to stdout during startup if -DDUMP_CONFIG is\n specified. PR 31956. [Stefan Fritsch]", " *) Restore visibility of DEFAULT_PIDLOG to core and modules. MPM\n helper function ap_remove_pid() added. [Jeff Trawick]", " *) Enable DEFAULT_REL_RUNTIMEDIR on Windows and NetWare. [various]", " *) Correct C++ incompatibility with http_log.h. [Stefan Fritsch, Jeff\n Trawick]", " *) mod_log_config: Prevent segfault. PR 50861. [Torsten Förtsch\n <torsten.foertsch gmx.net>]", " *) core: AllowEncodedSlashes new option NoDecode to allow encoded slashes\n in request URL path info but not decode them. Change behavior of option\n \"On\" to decode the encoded slashes as 2.0 and 2.2 do. PR 35256,\n PR 46830. [Dan Poirier]", " *) mod_ssl: Check SNI hostname against Host header case-insensitively.\n PR 49491. [Mayank Agrawal <magrawal.08 gmail.com>]", " *) mod_ldap: Add LDAPConnectionPoolTTL to give control over lifetime\n of bound backend LDAP connections. PR47634 [Eric Covener]", " *) mod_cache: Make CacheEnable and CacheDisable configurable per\n directory in addition to per server, making them work from within\n a LocationMatch. [Graham Leggett]", " *) worker, event, prefork: Correct several issues when built as\n DSOs; most notably, the scoreboard was reinitialized during graceful\n restart, such that processes of the previous generation were not\n observable. [Jeff Trawick]", "Changes with Apache 2.3.11", " *) mod_win32: Added shebang check for '! so that .vbs scripts work as CGI.\n Win32's cscript interpreter can only use a single quote as comment char.\n [Guenter Knauf]", " *) mod_proxy: balancer-manager now uses POST instead of GET.\n [Jim Jagielski]", " *) core: new util function: ap_parse_form_data(). Previously,\n this capability was tucked away in mod_request. [Jim Jagielski]", " *) core: new hook: ap_run_pre_read_request. [Jim Jagielski]", " *) modules: Fix many modules that were not correctly initializing if they\n were not active during server startup but got enabled later during a\n graceful restart. [Stefan Fritsch]", " *) core: Create new ap_state_query function that allows modules to determine\n if the current configuration run is the initial one at server startup,\n and if the server is started for testing/config dumping only.\n [Stefan Fritsch]", " *) mod_proxy: Runtime configuration of many parameters for existing\n balancers via the balancer-manager. [Jim Jagielski]", " *) mod_proxy: Runtime addition of new workers (BalancerMember) for existing\n balancers via the balancer-manager. [Jim Jagielski]", " *) mod_cache: When a bad Expires date is present, we need to behave as if\n the Expires is in the past, not as if the Expires is missing. PR 16521.\n [Co-Advisor <coad measurement-factory.com>]", " *) mod_cache: We must ignore quoted-string values that appear in a\n Cache-Control header. PR 50199. [Graham Leggett]", " *) mod_dav: Revert change to send 501 error if unknown Content-* header is\n received for a PUT request. PR 42978. [Stefan Fritsch]", " *) mod_cache: Respect s-maxage as described by RFC2616 14.9.3, which must\n take precedence if present. PR 35247. [Graham Leggett]", " *) mod_ssl: Fix a possible startup failure if multiple SSL vhosts\n are configured with the same ServerName and private key file.\n [Masahiro Matsuya <mmatsuya redhat.com>, Joe Orton]", " *) mod_socache_dc: Make module compile by fixing some typos.\n PR 50735 [Mark Montague <mark catseye.org>]", " *) prefork: Update MPM state in children during a graceful stop or\n restart. PR 41743. [Andrew Punch <andrew.punch 247realmedia.com>]", " *) mod_mime: Ignore leading dots when looking for mime extensions.\n PR 50434 [Stefan Fritsch]", " *) core: Add support to set variables with the 'Define' directive. The\n variables that can then be used in the config using the ${VAR} syntax\n known from envvar interpolation. [Stefan Fritsch]", " *) mod_proxy_http: make adding of X-Forwarded-* headers configurable.\n ProxyAddHeaders defaults to On. [Vincent Deffontaines]", " *) mod_slotmem_shm: Increase memory alignment for slotmem data.\n [Rainer Jung]", " *) mod_ssl: Add config options for OCSP: SSLOCSPResponderTimeout,\n SSLOCSPResponseMaxAge, SSLOCSPResponseTimeSkew.\n [Kaspar Brand <httpd-dev.2011 velox.ch>]", " *) mod_ssl: Revamp output buffering to reduce network overhead for\n output fragmented into many buckets, such as chunked HTTP responses.\n [Joe Orton]", " *) core: Apply <If> sections to all requests, not only to file base requests.\n Allow to use <If> inside <Directory>, <Location>, and <Files> sections.\n The merging of <If> sections now happens after the merging of <Location>\n sections, even if an <If> section is embedded inside a <Directory> or\n <Files> section. [Stefan Fritsch]", " *) mod_proxy: Refactor usage of shared data by dropping the scoreboard\n and using slotmem. Create foundation for dynamic growth/changes of\n members within a balancer. Remove BalancerNonce in favor of a\n per-balancer 'nonce' parameter. [Jim Jagielski]", " *) mod_status: Don't show slots which are disabled by MaxClients as open.\n PR: 47022 [Jordi Prats <jordi prats gmail com>, Stefan Fritsch]", " *) mpm_prefork: Fix ap_mpm_query results for AP_MPMQ_MAX_DAEMONS and\n AP_MPMQ_MAX_THREADS.", " *) mod_authz_core: Fix bug in merging logic if user-based and non-user-based\n authorization directives were mixed. [Stefan Fritsch]", " *) mod_authn_socache: change directive name from AuthnCacheProvider\n to AuthnCacheProvideFor. The term \"provider\" is overloaded in\n this module, and we should avoid confusion between the provider\n of a backend (AuthnCacheSOCache) and the authn provider(s) for\n which this module provides cacheing (AuthnCacheProvideFor).\n [Nick Kew]", " *) mod_proxy_http: Allocate the fake backend request from a child pool\n of the backend connection, instead of misusing the pool of the frontend\n request. Fixes a thread safety issue where buckets set aside in the\n backend connection leak into other threads, and then disappear when\n the frontend request is cleaned up, in turn causing corrupted buckets\n to make other threads spin. [Graham Leggett]", " *) mod_ssl: Change the format of the SSL_{CLIENT,SERVER}_{I,S}_DN variables\n to be RFC 2253 compatible, convert non-ASCII characters to UTF8, and\n escape other special characters with backslashes. The old format can\n still be used with the LegacyDNStringFormat argument to SSLOptions.", " *) core, mod_rewrite: Make the REQUEST_SCHEME variable available to\n scripts and mod_rewrite. [Stefan Fritsch]", " *) mod_rewrite: Allow to use arbitrary boolean expressions (ap_expr) in\n RewriteCond. [Stefan Fritsch]", " *) mod_rewrite: Allow to unset environment variables using E=!VAR.\n PR 49512. [Mark Drayton <mark markdrayton info>, Stefan Fritsch]", " *) mod_headers: Restore the 2.3.8 and earlier default for the first\n argument of the Header directive (\"onsuccess\"). [Eric Covener]", " *) core: Disallow the mixing of relative and absolute Options PR 33708.\n [Sönke Tesch <st kino-fahrplan.de>]", " *) core: When exporting request headers to HTTP_* environment variables,\n drop variables whose names contain invalid characters. Describe in the\n docs how to restore the old behaviour. [Malte S. Stretz <mss apache org>]", " *) core: When selecting an IP-based virtual host, favor an exact match for\n the port over a wildcard (or omitted) port instead of favoring the one\n that came first in the configuration file. [Eric Covener]", " *) core: Overlapping virtual host address/port combinations now implicitly\n enable name-based virtual hosting for that address. The NameVirtualHost\n directive has no effect, and _default_ is interpreted the same as \"*\".\n [Eric Covener]", " *) core: In the absence of any Options directives, the default is now\n \"FollowSymlinks\" instead of \"All\". [Igor Galić]", " *) rotatelogs: Add -e option to write logs through to stdout for optional\n further processing. [Graham Leggett]", " *) mod_ssl: Correctly read full lines in input filter when the line is\n incomplete during first read. PR 50481. [Ruediger Pluem]", " *) mod_authz_core: Add AuthzSendForbiddenOnFailure directive to allow\n sending '403 FORBIDDEN' instead of '401 UNAUTHORIZED' if authorization\n fails for an authenticated user. PR 40721. [Stefan Fritsch]", "Changes with Apache 2.3.10", " *) mod_rewrite: Don't implicitly URL-escape the original query string\n when no substitution has changed it. PR 50447. [Eric Covener]", " *) core: Honor 'AcceptPathInfo OFF' during internal redirects,\n such as per-directory mod_rewrite substitutions. PR 50349.\n [Eric Covener]", " *) mod_rewrite: Add 'RewriteOptions InheritBefore' to put the base\n rules/conditions before the overridden rules/conditions. PR 39313.\n [Jérôme Grandjanny <jerome.grandjanny cea.fr>]", " *) mod_autoindex: add IndexIgnoreReset to reset the list of IndexIgnored\n filenames in higher precedence configuration sections. PR 24243.\n [Eric Covener]", " *) mod_cgid: RLimit* directive support for mod_cgid. PR 42135\n [Eric Covener]", " *) core: Fail startup when the argument to ServerName looks like a glob\n or a regular expression instead of a hostname (*?[]). PR 39863\n [Rahul Nair <rahul.g.nair gmail.com>]", " *) mod_userdir: Add merging of enable, disable, and filename arguments\n to UserDir directive, leaving enable/disable of userlists unmerged.\n PR 44076 [Eric Covener]", " *) httpd: When no -k option is provided on the httpd command line, the server\n was starting without checking for an existing pidfile. PR 50350\n [Eric Covener]", " *) mod_proxy: Put the worker in error state if the SSL handshake with the\n backend fails. PR 50332.\n [Daniel Ruggeri <DRuggeri primary.net>, Ruediger Pluem]", " *) mod_cache_disk: Fix Windows build which was broken after renaming\n the module. [Gregg L. Smith]", "Changes with Apache 2.3.9", " *) SECURITY: CVE-2010-1623 (cve.mitre.org)\n Fix a denial of service attack against mod_reqtimeout.\n [Stefan Fritsch]", " *) mod_headers: Change default first argument of Header directive\n from \"onsuccess\" to \"always\". [Eric Covener]", " *) mod_include: Add the onerror attribute to the include element,\n allowing an URL to be specified to include on error. [Graham\n Leggett]", " *) mod_cache_disk: mod_disk_cache renamed to mod_cache_disk, to be\n consistent with the naming of other modules. [Graham Leggett]", " *) mod_setenvif: Add SetEnvIfExpr directive to set env var depending on\n expression. [Stefan Fritsch]", " *) mod_proxy: Fix ProxyPassInterpolateEnv directive. PR 50292.\n [Stefan Fritsch]", " *) suEXEC: Add Suexec directive to disable suEXEC without renaming the\n binary (Suexec Off), or force startup failure if suEXEC is required\n but not supported (Suexec On). Change SuexecUserGroup to fail\n startup instead of just printing a warning if suEXEC is disabled.\n [Jeff Trawick]", " *) core: Add Error directive for aborting startup or htaccess processing\n with a specified error message. [Jeff Trawick]", " *) mod_rewrite: Fix the RewriteEngine directive to work within a\n location. Previously, once RewriteEngine was switched on globally,\n it was impossible to switch off. [Graham Leggett]", " *) core, mod_include, mod_ssl: Move the expression parser derived from\n mod_include back into mod_include. Replace ap_expr with a parser\n derived from mod_ssl's parser. Make mod_ssl use the new parser. Rework\n ap_expr's public interface and provide hooks for modules to add variables\n and functions. [Stefan Fritsch]", " *) core: Do the hook sorting earlier so that the hooks are properly sorted\n for the pre_config hook and during parsing the config. [Stefan Fritsch]", " *) core: In the absence of any AllowOverride directives, the default is now\n \"None\" instead of \"All\". PR49823 [Eric Covener]", " *) mod_proxy: Don't allow ProxyPass or ProxyPassReverse in\n <Directory> or <Files>. PR47765 [Eric Covener]", " *) prefork/worker/event MPMS: default value (when no directive is present)\n of MaxConnectionsPerChild/MaxRequestsPerChild is changed to 0 from 10000\n to match default configuration and manual. PR47782 [Eric Covener]", " *) proxy_connect: Don't give up in the middle of a CONNECT tunnel\n when the child process is starting to exit. PR50220. [Eric Covener]", " *) mod_autoindex: Fix inheritance of mod_autoindex directives into\n contexts that don't have any mod_autoindex directives. PR47766.\n [Eric Covener]", " *) mod_rewrite: Add END flag for RewriteRule to prevent further rounds\n of rewrite processing when a per-directory substitution occurs.\n [Eric Covener]", " *) mod_ssl: Make sure to always log an error if loading of CA certificates\n fails. PR 40312. [Paul Tiemann <issues apache org ourdetour com>]", " *) mod_dav: Send 501 error if unknown Content-* header is received for a PUT\n request (RFC 2616 9.6). PR 42978. [Stefan Fritsch]", " *) mod_dav: Send 400 error if malformed Content-Range header is received for\n a put request (RFC 2616 14.16). PR 49825. [Stefan Fritsch]", " *) mod_proxy: Release the backend connection as soon as EOS is detected,\n so the backend isn't forced to wait for the client to eventually\n acknowledge the data. [Graham Leggett]", " *) mod_proxy: Optimise ProxyPass within a Location so that it is stored\n per-directory, and chosen during the location walk. Make ProxyPass\n work correctly from within a LocationMatch. [Graham Leggett]", " *) core: Fix segfault if per-module LogLevel is on virtual host\n scope. PR 50117. [Stefan Fritsch]", " *) mod_proxy: Move the ProxyErrorOverride directive to have per\n directory scope. [Graham Leggett]", " *) mod_allowmethods: New module to deny certain HTTP methods without\n interfering with authentication/authorization. [Paul Querna,\n Igor Galić, Stefan Fritsch]", " *) mod_ssl: Log certificate information and improve error message if client\n cert verification fails. PR 50093, PR 50094. [Lassi Tuura <lat cern ch>,\n Stefan Fritsch]", " *) htcacheclean: Teach htcacheclean to limit cache size by number of\n inodes in addition to size of files. Prevents a cache disk from\n running out of space when many small files are cached.\n [Graham Leggett]", " *) core: Rename MaxRequestsPerChild to MaxConnectionsPerChild, which\n describes more accurately what the directive does. The old name\n still works but logs a warning. [Stefan Fritsch]", " *) mod_cache: Optionally serve stale data when a revalidation returns a\n 5xx response, controlled by the CacheStaleOnError directive.\n [Graham Leggett]", " *) htcacheclean: Allow the listing of valid URLs within the cache, with\n the option to list entry metadata such as sizes and times. [Graham\n Leggett]", " *) mod_cache: correctly parse quoted strings in cache headers.\n PR 50199 [Nick Kew]", " *) mod_cache: Allow control over the base URL of reverse proxied requests\n using the CacheKeyBaseURL directive, so that the cache key can be\n calculated from the endpoint URL instead of the server URL. [Graham\n Leggett]", " *) mod_cache: CacheLastModifiedFactor, CacheStoreNoStore, CacheStorePrivate,\n CacheStoreExpired, CacheIgnoreNoLastMod, CacheDefaultExpire,\n CacheMinExpire and CacheMaxExpire can be set per directory/location.\n [Graham Leggett]", " *) mod_disk_cache: CacheMaxFileSize, CacheMinFileSize, CacheReadSize and\n CacheReadTime can be set per directory/location. [Graham Leggett]", " *) core: Speed up config parsing if using a very large number of config\n files. PR 50002 [andrew cloudaccess net]", " *) mod_cache: Support the caching of HEAD requests. [Graham Leggett]", " *) htcacheclean: Allow the option to round up file sizes to a given\n block size, improving the accuracy of disk usage. [Graham Leggett]", " *) mod_ssl: Add authz providers for use with mod_authz_core and its\n RequireAny/RequireAll containers: 'ssl' (equivalent to SSLRequireSSL),\n 'ssl-verify-client' (for use with 'SSLVerifyClient optional'), and\n 'ssl-require' (expressions with same syntax as SSLRequire).\n [Stefan Fritsch]", " *) mod_ssl: Make the ssl expression parser thread-safe. It now requires\n bison instead of yacc. [Stefan Fritsch]", " *) mod_disk_cache: Change on-disk header file format to support the\n link of the device/inode of the data file to the matching header\n file, and to support the option of not writing a data file when\n the data file is empty. [Graham Leggett]", " *) core/mod_unique_id: Add generate_log_id hook to allow to use\n the ID generated by mod_unique_id as error log ID for requests.\n [Stefan Fritsch]", " *) mod_cache: Make sure that we never allow a 304 Not Modified response\n that we asked for to leak to the client should the 304 response be\n uncacheable. PR45341 [Graham Leggett]", " *) mod_cache: Add the cache_status hook to register the final cache\n decision hit/miss/revalidate. Add optional support for an X-Cache\n and/or an X-Cache-Detail header to add the cache status to the\n response. PR48241 [Graham Leggett]", " *) mod_authz_host: Add 'local' provider that matches connections originating\n on the local host. PR 19938. [Stefan Fritsch]", " *) Event MPM: Fix crash accessing pollset on worker thread when child\n process is exiting. [Jeff Trawick]", " *) core: For process invocation (cgi, fcgid, piped loggers and so forth)\n pass the system library path (LD_LIBRARY_PATH or platform-specific\n variables) along with the system PATH, by default. Both should be\n overridden together as desired using PassEnv etc; see mod_env.\n [William Rowe]", " *) mod_cache: Introduce CacheStoreExpired, to allow administrators to\n capture a stale backend response, perform If-Modified-Since requests\n against the backend, and serving from the cache all 304 responses.\n This restores pre-2.2.4 cache behavior. [William Rowe]", " *) mod_rewrite: Introduce <=, >= string comparison operators, and integer\n comparators -lt, -le, -eq, -ge, and -gt. To help bash users and drop\n the ambiguity of the symlink test \"-ltest\", introduce -h or -L as\n symlink test operators. [William Rowe]", " *) mod_cache: Give the cache provider the opportunity to choose to cache\n or not cache based on the buckets present in the brigade, such as the\n presence of a FILE bucket.\n [Graham Leggett]", " *) mod_authz_core: Allow authz providers to check args while reading the\n config and allow to cache parsed args. Move 'all' and 'env' authz\n providers from mod_authz_host to mod_authz_core. Add 'method' authz\n provider depending on the HTTP method. [Stefan Fritsch]", " *) mod_include: Move the request_rec within mod_include to be\n exposed within include_ctx_t. [Graham Leggett]", " *) mod_include: Reinstate support for UTF-8 character sets by allowing a\n variable being echoed or set to be decoded and then encoded as separate\n steps. PR47686 [Graham Leggett]", " *) mod_cache: Add a discrete commit_entity() provider function within the\n mod_cache provider interface which is called to indicate to the\n provider that caching is complete, giving the provider the opportunity\n to commit temporary files permanently to the cache in an atomic\n fashion. Replace the inconsistent use of error cleanups with a formal\n set of pool cleanups attached to a subpool, which is destroyed on error.\n [Graham Leggett]", " *) mod_cache: Change the signature of the store_body() provider function\n within the mod_cache provider interface to support an \"in\" brigade\n and an \"out\" brigade instead of just a single input brigade. This\n gives a cache provider the option to consume only part of the brigade\n passed to it, rather than the whole brigade as was required before.\n This fixes an out of memory and a request timeout condition that would\n occur when the original document was a large file. Introduce\n CacheReadSize and CacheReadTime directives to mod_disk_cache to control\n the amount of data to attempt to cache at a time. [Graham Leggett]", " *) core: Add ErrorLogFormat to allow configuring error log format, including\n additional information that is logged once per connection or request. Add\n error log IDs for connections and request to allow correlating error log\n lines and the corresponding access log entry. [Stefan Fritsch]", " *) core: Disable sendfile by default. [Stefan Fritsch]", " *) mod_cache: Check the request to determine whether we are allowed\n to return cached content at all, and respect a \"Cache-Control:\n no-cache\" header from a client. Previously, \"no-cache\" would\n behave like \"max-age=0\". [Graham Leggett]", " *) mod_cache: Use a proper filter context to hold filter data instead\n of misusing the per-request configuration. Fixes a segfault on trunk\n when the normal handler is used. [Graham Leggett]", " *) mod_cgid: Log a warning if the ScriptSock path is truncated because\n it is too long. PR 49388. [Stefan Fritsch]", " *) vhosts: Do not allow _default_ in NameVirtualHost, or mixing *\n and non-* ports on NameVirtualHost, or multiple NameVirtualHost\n directives for the same address:port, or NameVirtualHost\n directives with no matching VirtualHosts, or multiple ip-based\n VirtualHost sections for the same address:port. These were\n previously accepted with a warning, but the behavior was\n undefined. [Dan Poirier]", " *) mod_remoteip: Fix a segfault when using mod_remoteip in conjunction with\n Allow/Deny. PR 49838. [Andrew Skalski <voltara gmail.com>]", " *) core: DirectoryMatch can now match on the end of line character ($),\n and sub-directories of matched directories are no longer implicitly\n matched. PR49809 [Eric Covener]", " *) Regexps: introduce new higher-level regexp utility including parsing\n and executing perl-style regexp ops (e.g s/foo/bar/i) and regexp memory\n [Nick Kew]", " *) Proxy: support setting source address. PR 29404\n [Multiple contributors iterating through bugzilla,\n Aron Ujvari <xanco nikhok.hu>, Aleksey Midenkov <asm uezku.kemsu.ru>,\n <dan listening-station.net; trunk version Nick Kew]", " *) HTTP protocol: return 400 not 503 if we have to abort due to malformed\n chunked encoding. [Nick Kew]", "Changes with Apache 2.3.8", " *) suexec: Support large log files. PR 45856. [Stefan Fritsch]", " *) core: Abort with sensible error message if no or more than one MPM is\n loaded. [Stefan Fritsch]", " *) mod_proxy: Rename erroronstatus to failonstatus.\n [Daniel Ruggeri <DRuggeri primary.net>]", " *) mod_dav_fs: Fix broken \"creationdate\" property.\n Regression in version 2.3.7. [Rainer Jung]", "Changes with Apache 2.3.7", " *) SECURITY: CVE-2010-1452 (cve.mitre.org)\n mod_dav, mod_cache, mod_session: Fix Handling of requests without a path\n segment. PR: 49246 [Mark Drayton, Jeff Trawick]", " *) mod_ldap: Properly check the result returned by apr_ldap_init. PR 46076.\n [Stefan Fritsch]", " *) mod_rewrite: Log errors if rewrite map files cannot be opened. PR 49639.\n [Stefan Fritsch]", " *) mod_proxy_http: Support the 'ping' property for backend HTTP/1.1 servers\n via leveraging 100-Continue as the initial \"request\".\n [Jim Jagielski]", " *) core/mod_authz_core: Introduce new access_checker_ex hook that enables\n mod_authz_core to bypass authentication if access should be allowed by\n IP address/env var/... [Stefan Fritsch]", " *) core: Introduce note_auth_failure hook to allow modules to add support\n for additional auth types. This makes ap_note_auth_failure() work with\n mod_auth_digest again. PR 48807. [Stefan Fritsch]", " *) socache modules: return APR_NOTFOUND when a lookup is not found [Nick Kew]", " *) mod_authn_socache: new module [Nick Kew]", " *) configure: Add reallyall option for --enable-mods-shared. [Stefan Fritsch]", " *) Fix Windows build when using VC6. [Gregg L. Smith <lists glewis com>]", " *) mod_rewrite: Allow to set environment variables without explicitly\n giving a value. [Rainer Jung]", " *) mod_rewrite: Remove superfluous EOL from rewrite logging. [Rainer Jung]", " *) mod_include: recognise \"text/html; parameters\" as text/html\n PR 49616 [Andrey Chernov <ache nagual.pp.ru>]", " *) CGI vars: allow PATH to be set by SetEnv, consistent with LD_LIBRARY_PATH\n PR 43906 [Nick Kew]", " *) Core: Extra robustness: don't try authz and segfault if authn\n fails to set r->user. Log bug and return 500 instead.\n PR 42995 [Nick Kew]", " *) HTTP protocol filter: fix handling of longer chunk extensions\n PR 49474 [<tee.bee gmx.de>]", " *) Update SSL cipher suite and add example for SSLHonorCipherOrder.\n [Lars Eilebrecht, Rainer Jung]", " *) move AddOutputFilterByType from core to mod_filter. This should\n fix nasty side-effects that happen when content_type is set\n more than once in processing a request, and make it fully\n compatible with dynamic and proxied contents. [Nick Kew]", " *) mod_log_config: Implement logging for sub second timestamps and\n request end time. [Rainer Jung]", "Changes with Apache 2.3.6", " *) SECURITY: CVE-2009-3555 (cve.mitre.org)\n mod_ssl: Comprehensive fix of the TLS renegotiation prefix injection\n attack when compiled against OpenSSL version 0.9.8m or later. Introduces\n the 'SSLInsecureRenegotiation' directive to reopen this vulnerability\n and offer unsafe legacy renegotiation with clients which do not yet\n support the new secure renegotiation protocol, RFC 5746.\n [Joe Orton, and with thanks to the OpenSSL Team]", " *) SECURITY: CVE-2009-3555 (cve.mitre.org)\n mod_ssl: A partial fix for the TLS renegotiation prefix injection attack\n by rejecting any client-initiated renegotiations. Forcibly disable\n keepalive for the connection if there is any buffered data readable. Any\n configuration which requires renegotiation for per-directory/location\n access control is still vulnerable, unless using OpenSSL >= 0.9.8l.\n [Joe Orton, Ruediger Pluem, Hartmut Keil <Hartmut.Keil adnovum.ch>]", " *) SECURITY: CVE-2010-0408 (cve.mitre.org)\n mod_proxy_ajp: Respond with HTTP_BAD_REQUEST when the body is not sent\n when request headers indicate a request body is incoming; not a case of\n HTTP_INTERNAL_SERVER_ERROR. [Niku Toivola <niku.toivola sulake.com>]", " *) SECURITY: CVE-2010-0425 (cve.mitre.org)\n mod_isapi: Do not unload an isapi .dll module until the request\n processing is completed, avoiding orphaned callback pointers.\n [Brett Gervasoni <brettg senseofsecurity.com>, Jeff Trawick]", " *) core: Filter init functions are now run strictly once per request\n before handler invocation. The init functions are no longer run\n for connection filters. PR 49328. [Joe Orton]", " *) core: Adjust the output filter chain correctly in an internal\n redirect from a subrequest, preserving filters from the main\n request as necessary. PR 17629. [Joe Orton]", " *) mod_cache: Explicitly allow cache implementations to cache a 206 Partial\n Response if they so choose to do so. Previously an attempt to cache a 206\n was arbitrarily allowed if the response contained an Expires or\n Cache-Control header, and arbitrarily denied if both headers were missing.\n [Graham Leggett]", " *) core: Add microsecond timestamp fractions, process id and thread id\n to the error log. [Rainer Jung]", " *) configure: The \"most\" module set gets build by default. [Rainer Jung]", " *) configure: Building dynamic modules (DSO) by default. [Rainer Jung]", " *) configure: Fix broken VPATH build when using included APR.\n [Rainer Jung]", " *) mod_session_crypto: Fix configure problem when building\n with APR 2 and for VPATH builds with included APR.\n [Rainer Jung]", " *) mod_session_crypto: API compatibility with APR 2 crypto and\n APR Util 1.x crypto. [Rainer Jung]", " *) ab: Fix memory leak with -v2 and SSL. PR 49383.\n [Pavel Kankovsky <peak argo troja mff cuni cz>]", " *) core: Add per-module and per-directory loglevel configuration.\n Add some more trace logging.\n mod_rewrite: Replace RewriteLog/RewriteLogLevel with trace log levels.\n mod_ssl: Replace LogLevelDebugDump with trace log levels.\n mod_ssl/mod_proxy*: Adjust loglevels to be less verbose at levels info\n and debug.\n mod_dumpio: Replace DumpIOLogLevel with trace log levels.\n [Stefan Fritsch]", " *) mod_ldap: LDAP caching was suppressed (and ldap-status handler returns\n title page only) when any mod_ldap directives were used in VirtualHost\n context. [Eric Covener]", " *) mod_disk_cache: Decline the opportunity to cache if the response is\n a 206 Partial Content. This stops a reverse proxied partial response\n from becoming cached, and then being served in subsequent responses.\n [Graham Leggett]", " *) mod_deflate: avoid the risk of forwarding data before headers are set.\n PR 49369 [Matthew Steele <mdsteele google.com>]", " *) mod_authnz_ldap: Ensure nested groups are checked when the\n top-level group doesn't have any direct non-group members\n of attributes in AuthLDAPGroupAttribute. [Eric Covener]", " *) mod_authnz_ldap: Search or Comparison during authorization phase\n can use the credentials from the authentication phase\n (AuthLDAPSearchAsUSer,AuthLDAPCompareAsUser).\n PR 48340 [Domenico Rotiroti, Eric Covener]", " *) mod_authnz_ldap: Allow the initial DN search during authentication\n to use the HTTP username/pass instead of an anonymous or hard-coded\n LDAP id (AuthLDAPInitialBindAsUser, AuthLDAPInitialBindPattern).\n [Eric Covener]", " *) mod_authnz_ldap: Publish requested LDAP data with an AUTHORIZE_ prefix\n when this module is used for authorization. See AuthLDAPAuthorizePrefix.\n PR 45584 [Eric Covener]", " *) apxs -q: Stop filtering out ':' characters from the reported values.\n PR 45343. [Bill Cole]", " *) prefork MPM: Work around possible crashes on child exit in APR reslist\n cleanup code. PR 43857. [Tom Donovan]", " *) ab: fix number of requests sent by ab when keepalive is enabled. PR 48497.\n [Bryn Dole <dole blekko.com>]", " *) Log an error for failures to read a chunk-size, and return 408 instead of\n 413 when this is due to a read timeout. This change also fixes some cases\n of two error documents being sent in the response for the same scenario.\n [Eric Covener] PR49167", " *) mod_proxy_balancer: Add new directive BalancerNonce to allow admin\n to control/set the nonce used in the balancer-manager application.\n [Jim Jagielski]", " *) mod_proxy_connect: Support port ranges in AllowConnect. PR 23673.\n [Stefan Fritsch]", " *) Proxy balancer: support setting error status according to HTTP response\n code from a backend. PR 48939. [Daniel Ruggeri <DRuggeri primary.net>]", " *) htcacheclean: Introduce the ability to clean specific URLs from the\n cache, if provided as an optional parameter on the command line.\n [Graham Leggett]", " *) core: Introduce the IncludeStrict directive, which explicitly fails\n server startup if no files or directories match a wildcard path.\n [Graham Leggett]", " *) htcacheclean: Report additional statistics about entries deleted.\n PR 48944. [Mark Drayton mark markdrayton.info]", " *) Introduce SSLFIPS directive to support OpenSSL FIPS_mode; permits all\n builds of mod_ssl to use 'SSLFIPS off' for portability, but the proper\n build of openssl is required for 'SSLFIPS on'. PR 46270.\n [Dr Stephen Henson <steve openssl.org>, William Rowe]", " *) mod_proxy_http: Log the port of the remote server in various messages.\n PR 48812. [Igor Galić <i galic brainsware org>]", " *) mod_reqtimeout: Do not wrongly enforce timeouts for mod_proxy's backend\n connections and other protocol handlers (like mod_ftp). [Stefan Fritsch]", " *) mod_proxy_ajp: Really regard the operation a success, when the client\n aborted the connection. In addition adjust the log message if the client\n aborted the connection. [Ruediger Pluem]", " *) mod_ssl: Add the 'SSLInsecureRenegotiation' directive, which\n allows insecure renegotiation with clients which do not yet\n support the secure renegotiation protocol. [Joe Orton]", " *) mod_ssl: Fix a potential I/O hang if a long list of trusted CAs\n is configured for client cert auth. PR 46952. [Joe Orton]", " *) core: Only log a 408 if it is no keepalive timeout. PR 39785\n [Ruediger Pluem, Mark Montague <markmont umich.edu>]", " *) support/rotatelogs: Add -L option to create a link to the current\n log file. PR 48761 [<lyndon orthanc.ca>, Dan Poirier]", " *) mod_ldap: Update LDAPTrustedClientCert to consistently be a per-directory\n setting only, matching most of the documentation and examples.\n PR 46541 [Paul Reder, Eric Covener]", " *) mod_ldap: LDAPTrustedClientCert now accepts CA_DER/CA_BASE64 argument\n types previously allowed only in LDAPTrustedGlobalCert. [Eric Covener]", " *) mod_negotiation: Preserve query string over multiviews negotiation.\n This buglet was fixed for type maps in 2.2.6, but the same issue\n affected multiviews and was overlooked.\n PR 33112 [Joergen Thomsen <apache jth.net>]", " *) mod_ldap: Eliminate a potential crash with multiple LDAPTrustedClientCert\n when some are not password-protected. [Eric Covener]", " *) Fix startup segfault when the Mutex directive is used but no loaded\n modules use httpd mutexes. PR 48787. [Jeff Trawick]", " *) Proxy: get the headers right in a HEAD request with\n ProxyErrorOverride, by checking for an overridden error\n before not after going into a catch-all code path.\n PR 41646. [Nick Kew, Stuart Children]", " *) support/rotatelogs: Support the simplest log rotation case, log\n truncation. Useful when the log is being processed in real time\n using a command like tail. [Graham Leggett]", " *) support/htcacheclean: Teach it how to write a pid file (modelled on\n httpd's writing of a pid file) so that it becomes possible to run\n more than one instance of htcacheclean on the same machine.\n [Graham Leggett]", " *) Log command line on startup, so there's a record of command line\n arguments like -f. PR 48752. [Dan Poirier]", " *) Introduce mod_reflector, a handler capable of reflecting POSTed\n request bodies back within the response through the output filter\n stack. Can be used to turn an output filter into a web service.\n [Graham Leggett]", " *) mod_proxy_http: Make sure that when an ErrorDocument is served\n from a reverse proxied URL, that the subrequest respects the status\n of the original request. This brings the behaviour of proxy_handler\n in line with default_handler. PR 47106. [Graham Leggett]", " *) Support wildcards in both the directory and file components of\n the path specified by the Include directive. [Graham Leggett]", " *) mod_proxy, mod_proxy_http: Support remote https proxies\n by using HTTP CONNECT. PR 19188.\n [Philippe Dutrueux <lilas evidian.com>, Rainer Jung]", " *) apxs: Fix -A and -a options to ignore whitespace in httpd.conf\n [Philip M. Gollucci]", " *) worker: Don't report server has reached MaxClients until it has.\n Add message when server gets within MinSpareThreads of MaxClients.\n PR 46996. [Dan Poirier]", " *) mod_session: Session expiry was being initialised, but not updated\n on each session save, resulting in timed out sessions when there\n should not have been. Fixed. [Graham Leggett]", " *) mod_log_config: Add the R option to log the handler used within the\n request. [Christian Folini <christian.folini netnea com>]", " *) mod_include: Allow fine control over the removal of Last-Modified and\n ETag headers within the INCLUDES filter, making it possible to cache\n responses if desired. Fix the default value of the SSIAccessEnable\n directive. [Graham Leggett]", " *) Add new UnDefine directive to undefine a variable. PR 35350.\n [Stefan Fritsch]", " *) Make ap_pregsub(), used by AliasMatch and friends, use the same syntax\n for regex backreferences as mod_rewrite and mod_include: Remove the use\n of '&' as an alias for '$0' and allow to escape any character with a\n backslash. PR 48351. [Stefan Fritsch]", " *) mod_authnz_ldap: If AuthLDAPCharsetConfig is set, also convert the\n password to UTF-8. PR 45318.\n [Johannes Müller <joh_m gmx.de>, Stefan Fritsch]", " *) ab: Fix calculation of requests per second in HTML output. PR 48594.\n [Stefan Fritsch]", " *) mod_authnz_ldap: Failures to map a username to a DN, or to check a user\n password now result in an informational level log entry instead of\n warning level. [Eric Covener]", "Changes with Apache 2.3.5", " *) SECURITY: CVE-2010-0434 (cve.mitre.org)\n Ensure each subrequest has a shallow copy of headers_in so that the\n parent request headers are not corrupted. Eliminates a problematic\n optimization in the case of no request body. PR 48359\n [Jake Scott, William Rowe, Ruediger Pluem]", " *) Turn static function get_server_name_for_url() into public\n ap_get_server_name_for_url() and use it where appropriate. This\n fixes mod_rewrite generating invalid URLs for redirects to IPv6\n literal addresses. [Stefan Fritsch]", " *) mod_ldap: Introduce new config option LDAPTimeout to set the timeout\n for LDAP operations like bind and search. [Stefan Fritsch]", " *) mod_proxy, mod_proxy_ftp: Move ProxyFtpDirCharset from mod_proxy to\n mod_proxy_ftp. [Takashi Sato]", " *) mod_proxy, mod_proxy_connect: Move AllowCONNECT from mod_proxy to\n mod_proxy_connect. [Takashi Sato]", " *) mod_cache: Do an exact match of the keys defined by\n CacheIgnoreURLSessionIdentifiers against the querystring instead of\n a partial match. PR 48401.\n [Dodou Wang <wangdong.08 gmail.com>, Ruediger Pluem]", " *) mod_proxy_balancer: Fix crash in balancer-manager. [Rainer Jung]", " *) Core HTTP: disable keepalive when the Client has sent\n Expect: 100-continue\n but we respond directly with a non-100 response.\n Keepalive here led to data from clients continuing being treated as\n a new request.\n PR 47087 [Nick Kew]", " *) Core: reject NULLs in request line or request headers.\n PR 43039 [Nick Kew]", " *) Core: (re)-introduce -T commandline option to suppress documentroot\n check at startup.\n PR 41887 [Jan van den Berg <janvdberg gmail.com>]", " *) mod_autoindex: support XHTML as equivalent to HTML in IndexOptions,\n ScanHTMLTitles, ReadmeName, HeaderName\n PR 48416 [Dmitry Bakshaev <dab18 izhnet.ru>, Nick Kew]", " *) Proxy: Fix ProxyPassReverse with relative URL\n Derived (slightly erroneously) from PR 38864 [Nick Kew]", " *) mod_headers: align Header Edit with Header Set when used on Content-Type\n PR 48422 [Cyril Bonté <cyril.bonte free.fr>, Nick Kew>]", " *) mod_headers: Enable multi-match-and-replace edit option\n PR 46594 [Nick Kew]", " *) mod_filter: enable it to act on non-200 responses.\n PR 48377 [Nick Kew]", "Changes with Apache 2.3.4", " *) Replace AcceptMutex, LockFile, RewriteLock, SSLMutex, SSLStaplingMutex,\n and WatchdogMutexPath with a single Mutex directive. Add APIs to\n simplify setup and user customization of APR proc and global mutexes.\n (See util_mutex.h.) Build-time setting DEFAULT_LOCKFILE is no longer\n respected; set DEFAULT_REL_RUNTIMEDIR instead. [Jeff Trawick]", " *) http_core: KeepAlive no longer accepts other than On|Off.\n [Takashi Sato]", " *) mod_dav: Remove errno from dav_error interface. Calls to dav_new_error()\n and dav_new_error_tag() must be adjusted to add an apr_status_t parameter.\n [Jeff Trawick]", " *) mod_authnz_ldap: Add AuthLDAPBindAuthoritative to allow Authentication to\n try other providers in the case of an LDAP bind failure.\n PR 46608 [Justin Erenkrantz, Joe Schaefer, Tony Stevenson]", " *) Build: fix --with-module to work as documented\n PR 43881 [Gez Saunders <gez.saunders virgin.net>]", "Changes with Apache 2.3.3", " *) SECURITY: CVE-2009-3095 (cve.mitre.org)\n mod_proxy_ftp: sanity check authn credentials.\n [Stefan Fritsch <sf fritsch.de>, Joe Orton]", " *) SECURITY: CVE-2009-3094 (cve.mitre.org)\n mod_proxy_ftp: NULL pointer dereference on error paths.\n [Stefan Fritsch <sf fritsch.de>, Joe Orton]", " *) mod_ssl: enable support for ECC keys and ECDH ciphers. Tested against\n OpenSSL 1.0.0b3. [Vipul Gupta <vipul.gupta sun.com>, Sander Temme]", " *) mod_dav: Include uri when logging a PUT error due to connection abort.\n PR 38149. [Stefan Fritsch]", " *) mod_dav: Return 409 instead of 500 for a LOCK request if the parent\n resource does not exist or is not a collection. PR 43465. [Stefan Fritsch]", " *) mod_dav_fs: Return 409 instead of 500 for Litmus test case copy_nodestcoll\n (a COPY request where the parent of the destination resource does not\n exist). PR 39299. [Stefan Fritsch]", " *) mod_dav_fs: Don't delete the whole file if a PUT with content-range failed.\n PR 42896. [Stefan Fritsch]", " *) mod_dav_fs: Make PUT create files atomically and no longer destroy the\n old file if the transfer aborted. PR 39815. [Paul Querna, Stefan Fritsch]", " *) mod_dav_fs: Remove inode keyed locking as this conflicts with atomically\n creating files. On systems with inode numbers, this is a format change of\n the DavLockDB. The old DavLockDB must be deleted on upgrade.\n [Stefan Fritsch]", " *) mod_log_config: Make ${cookie}C correctly match whole cookie names\n instead of substrings. PR 28037. [Dan Franklin <dan dan-franklin.com>,\n Stefan Fritsch]", " *) vhost: A purely-numeric Host: header should not be treated as a port.\n PR 44979 [Nick Kew]", " *) mod_ldap: Avoid 500 errors with \"Unable to set LDAP_OPT_REFHOPLIMIT option to 5\"\n when built against openldap by using SDK LDAP_OPT_REFHOPLIMIT defaults unless\n LDAPReferralHopLimit is explicitly configured.\n [Eric Covener]", " *) mod_charset_lite: Honor 'CharsetOptions NoImplicitAdd'.\n [Eric Covener]", " *) mod_ssl: Add support for OCSP Stapling. PR 43822.\n [Dr Stephen Henson <shenson oss-institute.org>]", " *) mod_socache_shmcb: Allow parens in file name if cache size is given.\n Fixes SSLSessionCache directive mis-parsing parens in pathname.\n PR 47945. [Stefan Fritsch]", " *) htpasswd: Improve out of disk space handling. PR 30877. [Stefan Fritsch]", " *) htpasswd: Use MD5 hash by default on all platforms. [Stefan Fritsch]", " *) mod_sed: Reduce memory consumption when processing very long lines.\n PR 48024 [Basant Kumar Kukreja <basant.kukreja sun.com>]", " *) ab: Fix segfault in case the argument for -n is a very large number.\n PR 47178. [Philipp Hagemeister <oss phihag.de>]", " *) Allow ProxyPreserveHost to work in <Proxy> sections. PR 34901.\n [Stefan Fritsch]", " *) configure: Fix THREADED_MPMS so that mod_cgid is enabled again\n for worker MPM. [Takashi Sato]", " *) mod_dav: Provide a mechanism to obtain the request_rec and pathname\n from the dav_resource. [Jari Urpalainen <jari.urpalainen nokia.com>,\n Brian France <brian brianfrance.com>]", " *) Build: Use install instead of cp if available on installing\n modules to avoid segmentation fault. PR 47951. [hirose31 gmail.com]", " *) mod_cache: correctly consider s-maxage in cacheability\n decisions. [Dan Poirier]", " *) mod_logio/core: Report more accurate byte counts in mod_status if\n mod_logio is loaded. PR 25656. [Stefan Fritsch]", " *) mod_ldap: If LDAPSharedCacheSize is too small, try harder to purge\n some cache entries and log a warning. Also increase the default\n LDAPSharedCacheSize to 500000. This is a more realistic size suitable\n for the default values of 1024 for LdapCacheEntries/LdapOpCacheEntries.\n PR 46749. [Stefan Fritsch]", " *) mod_rewrite: Make sure that a hostname:port isn't fully qualified if\n the request is a CONNECT request. [Bill Zajac <billz consultla.com>]", " *) mod_cache: Teach CacheEnable and CacheDisable to work from within a\n Location section, in line with how ProxyPass works. [Graham Leggett]", " *) mod_reqtimeout: New module to set timeouts and minimum data rates for\n receiving requests from the client. [Stefan Fritsch]", " *) core: Fix potential memory leaks by making sure to not destroy\n bucket brigades that have been created by earlier filters.\n [Stefan Fritsch]", " *) core, mod_deflate, mod_sed: Reduce memory usage by reusing bucket\n brigades in several places. [Stefan Fritsch]", " *) mod_cache: Fix uri_meets_conditions() so that CacheEnable will\n match by scheme, or by a wildcarded hostname. PR 40169\n [Peter Grandi <pg_asf asf.for.sabi.co.uk>, Graham Leggett]", " *) suxec: Allow to log an error if exec fails by setting FD_CLOEXEC\n on the log file instead of closing it. PR 10744. [Nicolas Rachinsky]", " *) mod_mime: Make RemoveType override the info from TypesConfig.\n PR 38330. [Stefan Fritsch]", " *) mod_cache: Introduce the option to run the cache from within the\n normal request handler, and to allow fine grained control over\n where in the filter chain content is cached. Adds CacheQuickHandler\n directive. [Graham Leggett]", " *) core: Treat timeout reading request as 408 error, not 400.\n Log 408 errors in access log as was done in Apache 1.3.x.\n PR 39785 [Nobutaka Mantani <nobutaka nobutaka.org>,\n Stefan Fritsch <sf fritsch.de>, Dan Poirier]", " *) mod_ssl: Reintroduce SSL_CLIENT_S_DN, SSL_CLIENT_I_DN, SSL_SERVER_S_DN,\n SSL_SERVER_I_DN back to the environment variables to be set by mod_ssl.\n [Peter Sylvester <peter.sylvester edelweb.fr>]", " *) mod_disk_cache: don't cache incomplete responses, per RFC 2616, 13.8.\n PR15866. [Dan Poirier]", " *) ab: ab segfaults in verbose mode on https sites\n PR46393. [Ryan Niebur]", " *) mod_dav: Allow other modules to become providers and add resource types\n to the DAV response. [Jari Urpalainen <jari.urpalainen nokia.com>,\n Brian France <brian brianfrance.com>]", " *) mod_dav: Allow other modules to add things to the DAV or Allow headers\n of an OPTIONS request. [Jari Urpalainen <jari.urpalainen nokia.com>,\n Brian France <brian brianfrance.com>]", " *) core: Lower memory usage of core output filter.\n [Stefan Fritsch <sf sfritsch.de>]", " *) mod_mime: Detect invalid use of MultiviewsMatch inside Location and\n LocationMatch sections. PR47754. [Dan Poirier]", " *) mod_request: Make sure the KeptBodySize directive rejects values\n that aren't valid numbers. [Graham Leggett]", " *) mod_session_crypto: Sanity check should the potentially encrypted\n session cookie be too short. [Graham Leggett]", " *) mod_session.c: Prevent a segfault when session is added but not\n configured. [Graham Leggett]", " *) htcacheclean: 19 ways to fail, 1 error message. Fixed. [Graham Leggett]", " *) mod_auth_digest: Fail server start when nonce count checking\n is configured without shared memory, or md5-sess algorithm is\n configured. [Dan Poirier]", " *) mod_proxy_connect: The connect method doesn't work if the client is\n connecting to the apache proxy through an ssl socket. Fixed.\n PR29744. [Brad Boyer, Mark Cave-Ayland, Julian Gilbey, Fabrice Durand,\n David Gence, Tim Dodge, Per Gunnar Hans, Emmanuel Elango,\n Kevin Croft, Rudolf Cardinal]", " *) mod_ssl: The error message when SSLCertificateFile is missing should\n at least give the name or position of the problematic virtual host\n definition. [Stefan Fritsch sf sfritsch.de]", " *) mod_auth_digest: Fix null pointer when qop=none. [Dan Poirier]", " *) Add support for HTTP PUT to ab. [Jeff Barnes <jbarnesweb yahoo.com>]", " *) mod_headers: generalise the envclause to support expression\n evaluation with ap_expr parser [Nick Kew]", " *) mod_cache: Introduce the thundering herd lock, a mechanism to keep\n the flood of requests at bay that strike a backend webserver as\n a cached entity goes stale. [Graham Leggett]", " *) mod_auth_digest: Fix usage of shared memory and re-enable it.\n PR 16057 [Dan Poirier]", " *) Preserve Port information over internal redirects\n PR 35999 [Jonas Ringh <jonas.ringh cixit.se>]", " *) Proxy: unable to connect to a backend is SERVICE_UNAVAILABLE,\n rather than BAD_GATEWAY or (especially) NOT_FOUND.\n PR 46971 [evanc nortel.com]", " *) Various modules: Do better checking of pollset operations in order to\n avoid segmentation faults if they fail. PR 46467\n [Stefan Fritsch <sf sfritsch.de>]", " *) mod_autoindex: Correctly create an empty cell if the description\n for a file is missing. PR 47682 [Peter Poeml <poeml suse.de>]", " *) ab: Fix broken error messages after resolver or connect() failures.\n [Jeff Trawick]", " *) SECURITY: CVE-2009-1890 (cve.mitre.org)\n Fix a potential Denial-of-Service attack against mod_proxy in a\n reverse proxy configuration, where a remote attacker can force a\n proxy process to consume CPU time indefinitely. [Nick Kew, Joe Orton]", " *) SECURITY: CVE-2009-1191 (cve.mitre.org)\n mod_proxy_ajp: Avoid delivering content from a previous request which\n failed to send a request body. PR 46949 [Ruediger Pluem]", " *) htdbm: Fix possible buffer overflow if dbm database has very\n long values. PR 30586 [Dan Poirier]", " *) core: Return APR_EOF if request body is shorter than the length announced\n by the client. PR 33098 [ Stefan Fritsch <sf sfritsch.de>]", " *) mod_suexec: correctly set suexec_enabled when httpd is run by a\n non-root user and may have insufficient permissions.\n PR 42175 [Jim Radford <radford blackbean.org>]", " *) mod_ssl: Fix SSL_*_DN_UID variables to use the 'userID' attribute\n type. PR 45107. [Michael Ströder <michael stroeder.com>,\n Peter Sylvester <peter.sylvester edelweb.fr>]", " *) mod_proxy_http: fix case sensitivity checking transfer encoding\n PR 47383 [Ryuzo Yamamoto <ryuzo.yamamoto gmail.com>]", " *) mod_alias: ensure Redirect issues a valid URL.\n PR 44020 [Håkon Stordahl <hakon stordahl.org>]", " *) mod_dir: add FallbackResource directive, to enable admin to specify\n an action to happen when a URL maps to no file, without resorting\n to ErrorDocument or mod_rewrite. PR 47184 [Nick Kew]", " *) mod_cgid: Do not leak the listening Unix socket file descriptor to the\n CGI process. PR 47335 [Kornél Pál <kornelpal gmail.com>]", " *) mod_rewrite: Remove locking for writing to the rewritelog.\n PR 46942 [Dan Poirier <poirier pobox.com>]", " *) mod_alias: check sanity in Redirect arguments.\n PR 44729 [Sönke Tesch <st kino-fahrplan.de>, Jim Jagielski]", " *) mod_proxy_http: fix Host: header for literal IPv6 addresses.\n PR 47177 [Carlos Garcia Braschi <cgbraschi gmail.com>]", " *) mod_cache: Add CacheIgnoreURLSessionIdentifiers directive to ignore\n defined session identifiers encoded in the URL when caching.\n [Ruediger Pluem]", " *) mod_rewrite: Fix the error string returned by RewriteRule.\n RewriteRule returned \"RewriteCond: bad flag delimiters\" when the 3rd\n argument of RewriteRule was not started with \"[\" or not ended with \"]\".\n PR 45082 [Vitaly Polonetsky <m_vitaly topixoft.com>]", " *) Windows: Fix usage message.\n [Rainer Jung]", " *) apachectl: When passing through arguments to httpd in\n non-SysV mode, use the \"$@\" syntax to preserve arguments.\n [Eric Covener]", " *) mod_dbd: add DBDInitSQL directive to enable SQL statements to\n be run when a connection is opened. PR 46827\n [Marko Kevac <mkevac gmail.com>]", " *) mod_cgid: Improve handling of long AF_UNIX socket names (ScriptSock).\n PR 47037. [Jeff Trawick]", " *) mod_proxy_ajp: Check more strictly that the backend follows the AJP\n protocol. [Mladen Turk]", " *) mod_proxy_ajp: Forward remote port information by default.\n [Rainer Jung]", " *) Allow MPMs to be loaded dynamically, as with most other modules. Use\n --enable-mpms-shared={list|\"all\"} to enable. This required changes to\n the MPM interfaces. Removed: mpm.h, mpm_default.h (as an installed\n header), APACHE_MPM_DIR, MPM_NAME, ap_threads_per_child,\n ap_max_daemons_limit, ap_my_generation, etc. ap_mpm_query() can't be\n called until after the register-hooks phase. [Jeff Trawick]", " *) mod_ssl: Add SSLProxyCheckPeerExpire and SSLProxyCheckPeerCN directives\n to enable stricter checking of remote server certificates.\n [Ruediger Pluem]", " *) ab: Fix a 100% CPU loop on platforms where a failed non-blocking connect\n returns EINPROGRESS and a subsequent poll() returns only POLLERR.\n Observed on HP-UX. [Eric Covener]", " *) Remove broken support for BeOS, TPF, and even older platforms such\n as A/UX, Next, and Tandem. [Jeff Trawick]", " *) mod_proxy_ftp: Add ProxyFtpListOnWildcard directive to allow files with\n globbing characters to be retrieved instead of converted into a\n directory listing. PR 46789 [Dan Poirier <poirier pobox.com>]", " *) Provide ap_retained_data_create()/ap_retained_data_get() for preservation\n of module state across unload/load. [Jeff Trawick]", " *) mod_substitute: Fix a memory leak. PR 44948\n [Dan Poirier <poirier pobox.com>]", "Changes with Apache 2.3.2", " *) mod_mime_magic: Fix detection of compressed content. [Rainer Jung]", " *) mod_negotiation: Escape pathes of filenames in 406 responses to avoid\n HTML injections and HTTP response splitting. PR 46837.\n [Geoff Keating <geoffk apple.com>]", " *) mod_ssl: add support for type-safe STACK constructs in OpenSSL\n development HEAD. PR 45521. [Kaspar Brand, Sander Temme]", " *) ab: Fix maintenance of the pollset to resolve EALREADY errors\n with kqueue (BSD/OS X) and excessive CPU with event ports (Solaris).\n PR 44584. Use APR_POLLSET_NOCOPY for better performance with some\n pollset implementations. [Jeff Trawick]", " *) mod_disk_cache: The module now turns off sendfile support if\n 'EnableSendfile off' is defined globally. [Lars Eilebrecht]", " *) mod_deflate: Adjust content metadata before bailing out on 304\n responses so that the metadata does not differ from 200 response.\n [Roy T. Fielding]", " *) mod_deflate: Fix creation of invalid Etag headers. We now make sure\n that the Etag value is properly quoted when adding the gzip marker.\n PR 39727, 45023. [Lars Eilebrecht, Roy T. Fielding]", " *) Added 20x22 icons for ODF, SVG, and XML documents. PR 37185.\n [Peter Harlow]", " *) Disabled DefaultType directive and removed ap_default_type()\n from core. We now exclude Content-Type from responses for which\n a media type has not been configured via mime.types, AddType,\n ForceType, or some other mechanism. PR 13986. [Roy T. Fielding]", " *) mod_rewrite: Add IPV6 variable to RewriteCond\n [Ryan Phillips <ryan-apache trolocsis.com>]", " *) core: Enhance KeepAliveTimeout to support a value in milliseconds.\n PR 46275. [Takashi Sato]", " *) rotatelogs: Allow size units B, K, M, G and combination of\n time and size based rotation. [Rainer Jung]", " *) rotatelogs: Add flag for verbose (debug) output. [Rainer Jung]", " *) mod_ssl: Fix merging of SSLRenegBufferSize directive. PR 46508\n [<tlhackque yahoo.com>]", " *) core: Translate the the status line to ASCII on EBCDIC platforms in\n ap_send_interim_response() and for locally generated \"100 Continue\"\n responses. [Eric Covener]", " *) prefork: Fix child process hang during graceful restart/stop in\n configurations with multiple listening sockets. PR 42829. [Joe Orton,\n Jeff Trawick]", " *) mod_session_crypto: Ensure that SessionCryptoDriver can only be\n set in the global scope. [Graham Leggett]", " *) mod_ext_filter: We need to detect failure to startup the filter\n program (a mangled response is not acceptable). Fix to detect\n failure, and offer configuration option either to abort or\n to remove the filter and continue.\n PR 41120 [Nick Kew]", " *) mod_session_crypto: Rewrite the session_crypto module against the\n apr_crypto API. [Graham Leggett]", " *) mod_auth_form: Fix a pool lifetime issue, don't remove the subrequest\n until the main request is cleaned up. [Graham Leggett]", "Changes with Apache 2.3.1", " *) ap_slotmem: Add in new slot-based memory access API impl., including\n 2 providers (mod_sharedmem and mod_plainmem) [Jim Jagielski,\n Jean-Frederic Clere, Brian Akins <brian.akins turner.com>]", " *) mod_include: support generating non-ASCII characters as entities in SSI\n PR 25202 [Nick Kew]", " *) core/utils: Enhance ap_escape_html API to support escaping non-ASCII chars\n PR 25202 [Nick Kew]", " *) mod_rewrite: fix \"B\" flag breakage by reverting r5589343\n PR 45529 [Bob Ionescu <bobsiegen googlemail.com>]", " *) CGI: return 504 (Gateway timeout) rather than 500 when a script\n times out before returning status line/headers.\n PR 42190 [Nick Kew]", " *) mod_cgid: fix segfault problem on solaris.\n PR 39332 [Masaoki Kobayashi <masaoki techfirm.co.jp>]", " *) mod_proxy_scgi: Added. [André Malo]", " *) mod_cache: Introduce 'no-cache' per-request environment variable\n to prevent the saving of an otherwise cacheable response.\n [Eric Covener]", " *) mod_rewrite: Introduce DiscardPathInfo|DPI flag to stop the troublesome\n way that per-directory rewrites append the previous notion of PATH_INFO\n to each substitution before evaluating subsequent rules.\n PR 38642 [Eric Covener]", " *) mod_cgid: Do not add an empty argument when calling the CGI script.\n PR 46380 [Ruediger Pluem]", " *) scoreboard: Remove unused sb_type from process_score.\n [Torsten Foertsch <torsten.foertsch gmx.net>, Chris Darroch]", " *) mod_ssl: Add SSLRenegBufferSize directive to allow changing the\n size of the buffer used for the request-body where necessary\n during a per-dir renegotiation. PR 39243. [Joe Orton]", " *) mod_proxy_fdpass: New module to pass a client connection over to a separate\n process that is reading from a unix daemon socket.", " *) mod_ssl: Improve environment variable extraction to be more\n efficient and to correctly handle DNs with duplicate tags.\n PR 45975. [Joe Orton]", " *) Remove the obsolete serial attribute from the RPM spec file. Compile\n against the external pcre. Add missing binaries fcgistarter, and\n mod_socache* and mod_session*. [Graham Leggett]", "Changes with Apache 2.3.0", " *) mod_ratelimit: New module to do bandwidth rate limiting. [Paul Querna]", " *) Remove X-Pad header which was added as a work around to a bug in\n Netscape 2.x to 4.0b2. [Takashi Sato <takashi lans-tv.com>]", " *) Add DTrace Statically Defined Tracing (SDT) probes.\n [Theo Schlossnagle <jesus omniti.com>, Paul Querna]", " *) mod_proxy_balancer: Move all load balancing implementations\n as individual, self-contained mod_proxy submodules under\n modules/proxy/balancers [Jim Jagielski]", " *) Rename APIs to include ap_ prefix:\n find_child_by_pid -> ap_find_child_by_pid\n suck_in_APR -> ap_suck_in_APR\n sys_privileges_handlers -> ap_sys_privileges_handlers\n unixd_accept -> ap_unixd_accept\n unixd_config -> ap_unixd_config\n unixd_killpg -> ap_unixd_killpg\n unixd_set_global_mutex_perms -> ap_unixd_set_global_mutex_perms\n unixd_set_proc_mutex_perms -> ap_unixd_set_proc_mutex_perms\n unixd_set_rlimit -> ap_unixd_set_rlimit\n [Paul Querna]", " *) mod_lbmethod_heartbeat: New module to load balance mod_proxy workers\n based on heartbeats. [Paul Querna]", " *) mod_heartmonitor: New module to collect heartbeats, and write out a file\n so that other modules can load balance traffic as needed. [Paul Querna]", " *) mod_heartbeat: New module to generate multicast heartbeats to know if a\n server is online. [Paul Querna]", " *) mod_buffer: Honour the flush bucket and flush the buffer in the\n input filter. Make sure that metadata buckets are written to\n the buffer, not to the final brigade. [Graham Leggett]", " *) mod_buffer: Optimise the buffering of heap buckets when the heap\n buckets stay exactly APR_BUCKET_BUFF_SIZE long. [Graham Leggett,\n Ruediger Pluem]", " *) mod_buffer: Optional support for buffering of the input and output\n filter stacks. Can collapse many small buckets into fewer larger\n buckets, and prevents excessively small chunks being sent over\n the wire. [Graham Leggett]", " *) mod_privileges: new module to make httpd on Solaris privileges-aware\n and to enable different virtualhosts to run with different\n privileges and Unix user/group IDs [Nick Kew]", " *) mod_mem_cache: this module has been removed. [William Rowe]", " *) authn/z: Remove mod_authn_default and mod_authz_default.\n [Chris Darroch]", " *) authz: Fix handling of authz configurations, make default authz\n logic replicate 2.2.x authz logic, and replace <Satisfy*>, Reject,\n and AuthzMergeRules directives with Match, <Match*>, and AuthzMerge\n directives. [Chris Darroch]", " *) mod_authn_core: Prevent crash when provider alias created to\n provider which is not yet registered. [Chris Darroch]", " *) mod_authn_core: Add AuthType of None to support disabling\n authentication. [Chris Darroch]", " *) core: Allow <Limit> and <LimitExcept> directives to nest, and\n constrain their use to conform with that of other access control\n and authorization directives. [Chris Darroch]", " *) unixd: turn existing code into a module, and turn the set user/group\n and chroot into a child_init function. [Nick Kew]", " *) mod_dir: Support \"DirectoryIndex disabled\"\n Suggested By André Warnier <aw ice-sa.com> [Eric Covener]", " *) mod_ssl: Send Content-Type application/ocsp-request for POST requests to\n OSCP responders. PR 46014 [Dr Stephen Henson <steve openssl.org>]", " *) mod_authnz_ldap: don't return NULL-valued environment variables to\n other modules. PR 39045 [Francois Pesce <francois.pesce gmail.com>]", " *) Don't adjust case in pathname components that are not of interest\n to mod_mime. Fixes mod_negotiation's use of such components.\n PR 43250 [Basant Kumar Kukreja <basant.kukreja sun.com>]", " *) Be tolerant in what you accept - accept slightly broken\n status lines from a backend provided they include a valid status code.\n PR 44995 [Rainer Jung <rainer.jung kippdata.de>]", " *) New module mod_sed: filter Request/Response bodies through sed\n [Basant Kumar Kukreja <basant.kukreja sun.com>]", " *) mod_auth_form: Make sure that basic authentication is correctly\n faked directly after login. [Graham Leggett]", " *) mod_session_cookie, mod_session_dbd: Make sure cookies are set both\n within the output headers and error output headers, so that the\n session is maintained across redirects. [Graham Leggett]", " *) mod_auth_form: Make sure the logged in user is populated correctly\n after a form login. Fixes a missing REMOTE_USER variable directly\n following a login. [Graham Leggett]", " *) mod_session_cookie: Make sure that cookie attributes are correctly\n included in the blank cookie when cookies are removed. This fixes an\n inability to log out when using mod_auth_form. [Graham Leggett]", " *) mod_session: Prevent a segfault when a CGI script sets a cookie with a\n null value. [David Shane Holden <dpejesh apache.org>]", " *) core, authn/z: Determine registered authn/z providers directly in\n ap_setup_auth_internal(), which allows optional functions that just\n wrapped ap_list_provider_names() to be removed from authn/z modules.\n [Chris Darroch]", " *) authn/z: Convert common provider version strings to macros.\n [Chris Darroch]", " *) core: When testing for slash-terminated configuration paths in\n ap_location_walk(), don't look past the start of an empty string\n such as that created by a <Location \"\"> directive.\n [Chris Darroch]", " *) core, mod_proxy: If a kept_body is present, it becomes safe for\n subrequests to support message bodies. Make sure that safety\n checks within the core and within the proxy are not triggered\n when kept_body is present. This makes it possible to embed\n proxied POST requests within mod_include. [Graham Leggett]", " *) mod_auth_form: Make sure the input filter stack is properly set\n up before reading the login form. Make sure the kept body filter\n is correctly inserted to ensure the body can be read a second\n time safely should the authn be successful. [Graham Leggett,\n Ruediger Pluem]", " *) mod_request: Insert the KEPT_BODY filter via the insert_filter\n hook instead of during fixups. Add a safety check to ensure the\n filters cannot be inserted more than once. [Graham Leggett,\n Ruediger Pluem]", " *) ap_cache_cacheable_headers_out() will (now) always\n merge an error headers _before_ clearing them and _before_\n merging in the actual entity headers and doing normal\n hop-by-hop cleansing. [Dirk-Willem van Gulik].", " *) cache: retire ap_cache_cacheable_hdrs_out() which was used\n for both in- and out-put headers; and replace it by a single\n ap_cache_cacheable_headers() wrapped in a in- and out-put\n specific ap_cache_cacheable_headers_in()/out(). The latter\n which will also merge error and ensure content-type. To keep\n cache modules consistent with ease. This API change bumps\n up the minor MM by one [Dirk-Willem van Gulik].", " *) Move the KeptBodySize directive, kept_body filters and the\n ap_parse_request_body function out of the http module and into a\n new module called mod_request, reducing the size of the core.\n [Graham Leggett]", " *) mod_dbd: Handle integer configuration directive parameters with a\n dedicated function.", " *) Change the directives within the mod_session* modules to be valid\n both inside and outside the location/directory sections, as\n suggested by wrowe. [Graham Leggett]", " *) mod_auth_form: Add a module capable of allowing end users to log\n in using an HTML form, storing the credentials within mod_session.\n [Graham Leggett]", " *) Add a function to the http filters that is able to parse an HTML\n form request with the type of application/x-www-form-urlencoded.\n [Graham Leggett]", " *) mod_session_crypto: Initialise SSL in the post config hook.\n [Ruediger Pluem, Graham Leggett]", " *) mod_session_dbd: Add a session implementation capable of storing\n session information in a SQL database via the dbd interface. Useful\n for sites where session privacy is important. [Graham Leggett]", " *) mod_session_crypto: Add a session encoding implementation capable\n of encrypting and decrypting sessions wherever they may be stored.\n Introduces a level of privacy when sessions are stored on the\n browser. [Graham Leggett]", " *) mod_session_cookie: Add a session implementation capable of storing\n session information within cookies on the browser. Useful for high\n volume sites where server bound sessions are too resource intensive.\n [Graham Leggett]", " *) mod_session: Add a generic session interface to unify the different\n attempts at saving persistent sessions across requests.\n [Graham Leggett]", " *) core, authn/z: Avoid calling access control hooks for internal requests\n with configurations which match those of initial request. Revert to\n original behaviour (call access control hooks for internal requests\n with URIs different from initial request) if any access control hooks or\n providers are not registered as permitting this optimization.\n Introduce wrappers for access control hook and provider registration\n which can accept additional mode and flag data. [Chris Darroch]", " *) Introduced ap_expr API for expression evaluation.\n This is adapted from mod_include, which is the first module\n to use the new API.\n [Nick Kew]", " *) mod_authz_dbd: When redirecting after successful login/logout per\n AuthzDBDRedirectQuery, do not report authorization failure, and use\n first row returned by database query instead of last row.\n [Chris Darroch]", " *) mod_ldap: Correctly return all requested attribute values\n when some attributes have a null value.\n PR 44560 [Anders Kaseorg <anders kaseorg.com>]", " *) core: check symlink ownership if both FollowSymlinks and\n SymlinksIfOwnerMatch are set [Nick Kew]", " *) core: fix origin checking in SymlinksIfOwnerMatch\n PR 36783 [Robert L Mathews <rob-apache.org.bugs tigertech.net>]", " *) Activate mod_cache, mod_file_cache and mod_disk_cache as part of the\n 'most' set for '--enable-modules' and '--enable-shared-mods'. Include\n mod_mem_cache in 'all' as well. [Dirk-Willem van Gulik]", " *) Also install mod_so.h, mod_rewrite.h and mod_cache.h; as these\n contain public function declarations which are useful for\n third party module authors. PR 42431 [Dirk-Willem van Gulik].", " *) mod_dir, mod_negotiation: pass the output filter information\n to newly created sub requests; as these are later on used\n as true requests with an internal redirect. This allows for\n mod_cache et.al. to trap the results of the redirect.\n [Dirk-Willem van Gulik, Ruediger Pluem]", " *) mod_ldap: Add support (taking advantage of the new APR capability)\n for ldap rebind callback while chasing referrals. This allows direct\n searches on LDAP servers (in particular MS Active Directory 2003+)\n using referrals without the use of the global catalog.\n PRs 26538, 40268, and 42557 [Paul J. Reder]", " *) ApacheMonitor.exe: Introduce --kill argument for use by the\n installer. This will permit the installation tool to remove\n all running instances before attempting to remove the .exe.\n [William Rowe]", " *) mod_ssl: Add support for OCSP validation of client certificates.\n PR 41123. [Marc Stern <marc.stern approach.be>, Joe Orton]", " *) mod_serf: New module for Reverse Proxying. [Paul Querna]", " *) core: Add the option to keep aside a request body up to a certain\n size that would otherwise be discarded, to be consumed by filters\n such as mod_include. When enabled for a directory, POST requests\n to shtml files can be passed through to embedded scripts as POST\n requests, rather being downgraded to GET requests. [Graham Leggett]", " *) mod_ssl: Fix TLS upgrade (RFC 2817) support. PR 41231. [Joe Orton]", " *) scoreboard: Correctly declare ap_time_process_request.\n PR 43789 [Tom Donovan <Tom.Donovan acm.org>]", " *) core; scoreboard: ap_get_scoreboard_worker(sbh) now takes the sbh member\n from the connection rec, ap_get_scoreboard_worker(proc, thread) will now\n provide the unusual legacy lookup. [William Rowe]", " *) mpm winnt: fix null pointer dereference\n PR 42572 [Davi Arnaut]", " *) mod_authnz_ldap, mod_authn_dbd: Tidy up the code to expose authn\n parameters to the environment. Improve portability to\n EBCDIC machines by using apr_toupper(). [Martin Kraemer]", " *) mod_ldap, mod_authnz_ldap: Add support for nested groups (i.e. the ability\n to authorize an authenticated user via a \"require ldap-group X\" directive\n where the user is not in group X, but is in a subgroup contained in X.\n PR 42891 [Paul J. Reder]", " *) mod_ssl: Add support for caching SSL Sessions in memcached. [Paul Querna]", " *) apxs: Enhance -q flag to print all known variables and their values\n when invoked without variable name(s).\n [William Rowe, Sander Temme]", " *) apxs: Eliminate run-time check for mod_so. PR 40653.\n [David M. Lee <dmlee crossroads.com>]", " *) beos MPM: Create pmain pool and run modules' child_init hooks when\n entering ap_mpm_run(), then destroy pmain when exiting ap_mpm_run().\n [Chris Darroch]", " *) netware MPM: Destroy pmain pool when exiting ap_mpm_run() so that\n cleanups registered in modules' child_init hooks are performed.\n [Chris Darroch]", " *) Fix issue which could cause error messages to be written to access logs\n on Win32. PR 40476. [Tom Donovan <Tom.Donovan acm.org>]", " *) The LockFile directive, which specifies the location of\n the accept() mutex lockfile, is deprecated. Instead, the\n AcceptMutex directive now takes an optional lockfile\n location parameter, ala SSLMutex. [Jim Jagielski]", " *) mod_authn_dbd: Export any additional columns queried in the SQL select\n into the environment with the name AUTHENTICATE_<COLUMN>. This brings\n mod_authn_dbd behaviour in line with mod_authnz_ldap. [Graham Leggett]", " *) mod_dbd: Key the storage of prepared statements on the hex string\n value of server_rec, rather than the server name, as the server name\n may change (eg when the server name is set) at any time, causing\n weird behaviour in modules dependent on mod_dbd. [Graham Leggett]", " *) mod_proxy_fcgi: Added win32 build. [Mladen Turk]", " *) sendfile_nonblocking() takes the _brigade_ as an argument, gets\n the first bucket from the brigade, finds it not to be a FILE\n bucket and barfs. The fix is to pass a bucket rather than a brigade.\n [Niklas Edmundsson <nikke acc.umu.se>]", " *) mod_rewrite: support rewritemap by SQL query [Nick Kew]", " *) ap_get_server_version() has been removed. Third-party modules must\n now use ap_get_server_banner() or ap_get_server_description().\n [Jeff Trawick]", " *) All MPMs: Introduce a check_config phase between pre_config and\n open_logs, to allow modules to review interdependent configuration\n directive values and adjust them while messages can still be logged\n to the console. Handle relevant MPM directives during this phase\n and format messages for both the console and the error log, as\n appropriate. [Chris Darroch]", " *) core: Do not allow internal redirects like the DirectoryIndex of mod_dir\n to circumvent the symbolic link checks imposed by FollowSymLinks and\n SymLinksIfOwnerMatch. [Nick Kew, Ruediger Pluem, William Rowe]", " *) New SSLLogLevelDebugDump [ None (default) | IO (not bytes) | Bytes ]\n configures the I/O Dump of SSL traffic, when LogLevel is set to Debug.\n The default is none as this is far greater debugging resolution than\n the typical administrator is prepared to untangle. [William Rowe]", " *) mod_disk_cache: If possible, check if the size of an object to cache is\n within the configured boundaries before actually saving data.\n [Niklas Edmundsson <nikke acc.umu.se>]", " *) Worker and event MPMs: Remove improper scoreboard updates which were\n performed in the event of a fork() failure. [Chris Darroch]", " *) Add support for fcgi:// proxies to mod_rewrite.\n [Markus Schiegl <ms schiegl.com>]", " *) Remove incorrect comments from scoreboard.h regarding conditional\n loading of worker_score structure with mod_status, and remove unused\n definitions relating to old life_status field.\n [Chris Darroch <chrisd pearsoncmg.com>]", " *) Remove allocation of memory for unused array of lb_score pointers\n in ap_init_scoreboard(). [Chris Darroch <chrisd pearsoncmg.com>]", " *) Add mod_proxy_fcgi, a FastCGI back end for mod_proxy.\n [Garrett Rooney, Jim Jagielski, Paul Querna]", " *) Event MPM: Fill in the scoreboard's tid field. PR 38736.\n [Chris Darroch <chrisd pearsoncmg.com>]", " *) mod_charset_lite: Remove Content-Length when output filter can\n invalidate it. Warn when input filter can invalidate it.\n [Jeff Trawick]", " *) Authz: Add the new module mod_authn_core that will provide common\n authn directives such as 'AuthType', 'AuthName'. Move the directives\n 'AuthType' and 'AuthName' out of the core module and merge mod_authz_alias\n into mod_authn_core. [Brad Nicholes]", " *) Authz: Move the directives 'Order', 'Allow', 'Deny' and 'Satisfy'\n into the new module mod_access_compat which can be loaded to provide\n support for these directives.\n [Brad Nicholes]", " *) Authz: Move the 'Require' directive from the core module as well as\n add the directives '<SatisfyAll>', '<SatisfyOne>', '<RequireAlias>'\n and 'Reject' to mod_authz_core. The new directives introduce 'AND/OR'\n logic into the authorization processing. [Brad Nicholes]", " *) Authz: Add the new module mod_authz_core which acts as the\n authorization provider vector and contains common authz\n directives. [Brad Nicholes]", " *) Authz: Renamed mod_authz_dbm authz providers from 'group' and\n 'file-group' to 'dbm-group' and 'dbm-file-group'. [Brad Nicholes]", " *) Authz: Added the new authz providers 'env', 'ip', 'host', 'all' to handle\n host-based access control provided by mod_authz_host and invoked\n through the 'Require' directive. [Brad Nicholes]", " *) Authz: Convert all of the authz modules from hook based to\n provider based. [Brad Nicholes]", " *) mod_cache: Add CacheMinExpire directive to set the minimum time in\n seconds to cache a document.\n [Brian Akins <brian.akins turner.com>, Ruediger Pluem]", " *) mod_authz_dbd: SQL authz with Login/Session support [Nick Kew]", " *) Fix typo in ProxyStatus syntax error message.\n [Christophe Jaillet <christophe.jaillet wanadoo.fr>]", " *) Asynchronous write completion for the Event MPM. [Brian Pane]", " *) Added an End-Of-Request bucket type. The logging of a request and\n the freeing of its pool are now done when the EOR bucket is destroyed.\n This has the effect of delaying the logging until right after the last\n of the response is sent; ap_core_output_filter() calls the access logger\n indirectly when it destroys the EOR bucket. [Brian Pane]", " *) Rewrite of logresolve support utility: IPv6 addresses are now supported\n and the format of statistical output has changed. [Colm MacCarthaigh]", " *) Rewrite of ap_coreoutput_filter to do nonblocking writes [Brian Pane]", " *) Added new connection states for handler and write completion\n [Brian Pane]", " *) mod_cgid: Refuse to work on Solaris 10 due to OS bugs. PR 34264.\n [Justin Erenkrantz]", " *) Teach mod_ssl to use arbitrary OIDs in an SSLRequire directive,\n allowing string-valued client certificate attributes to be used for\n access control, as in: SSLRequire \"value\" in OID(\"1.3.6.1.4.1.18060.1\")\n [Martin Kraemer, David Reid]", " [Apache 2.3.0-dev includes those bug fixes and changes with the\n Apache 2.2.xx tree as documented, and except as noted, below.]", "Changes with Apache 2.2.x and later:", " *) http://svn.apache.org/viewvc/httpd/httpd/branches/2.2.x/CHANGES?view=markup", "Changes with Apache 2.0.x and later:", " *) http://svn.apache.org/viewvc/httpd/httpd/branches/2.0.x/CHANGES?view=markup" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 114, 1760], "buggy_code_start_loc": [11, 107, 68], "filenames": ["CHANGES", "STATUS", "modules/lua/mod_lua.c"], "fixing_code_end_loc": [17, 106, 1767], "fixing_code_start_loc": [12, 106, 69], "message": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:http_server:2.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "6FCD3C8C-9BF8-4F30-981A-593EEAEB9EDD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "046487A3-752B-4D0F-8984-96486B828EAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "89D2E052-51CD-4B57-A8B8-FAE51988D654", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "EAA27058-BACF-4F94-8E3C-7D38EC302EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "8FEAB0DF-04A9-4F99-8666-0BADC5D642B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E7D924D1-8A36-4C43-9E56-52814F9A6350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "39CDFECC-E26D-47E0-976F-6629040B3764", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "E3ECBCB1-0675-41F5-857B-438F36925F63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:-:*:*:*", "matchCriteriaId": "CB66DB75-2B16-4EBF-9B93-CE49D8086E41", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.10:*:*:*:*:*:*:*", "matchCriteriaId": "49A63F39-30BE-443F-AF10-6245587D3359", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:21:*:*:*:*:*:*:*", "matchCriteriaId": "56BDB5A0-0839-4A20-A003-B8CD56F48171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:*:*:*:*:*:*:*:*", "matchCriteriaId": "A70BB445-EF2B-4C9D-8502-FDD6A19F8C30", "versionEndExcluding": "12.1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "4725EA61-9BAB-4E72-9F92-ADE4624439CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0879FB1-58E2-4EC4-8111-044642E046BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "C7CF2929-4CBC-4B56-87AE-F45F53BD8DD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory."}, {"lang": "es", "value": "El m\u00f3dulo mod_lua.c en el m\u00f3dulo mod_lua en Apache HTTP Server 2.3.x y 2.4.x a trav\u00e9s de 2.4.10 no soporta la configuraci\u00f3n httpd en la cual el proveedor de autorizaci\u00f3n Lua se usa con argumentos diferentes dentro de contextos diferentes, lo que permite a atacantes remotos saltarse las restricciones de acceso en ciertas circunstancias aprovechando m\u00faltiples directivas requeridas, como se demuestra por una configuraci\u00f3n que especifica la autorizaci\u00f3n para un grupo para acceder a un directorio determinado, y una autorizaci\u00f3n para un segundo grupo para acceder a un segundo directorio."}], "evaluatorComment": null, "id": "CVE-2014-8109", "lastModified": "2023-02-13T00:42:40.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-29T23:59:00.053", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://advisories.mageia.org/MGASA-2015-0011.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Aug/msg00001.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Sep/msg00004.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2015-June/159352.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/28/5"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/cpujan2016-2367955.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/73040"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2523-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1174077"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://issues.apache.org/bugzilla/show_bug.cgi?id=57204"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/56c2e7cc9deb1c12a843d0dc251ea7fd3e7e80293cde02fcd65286ba%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/84a3714f0878781f6ed84473d1a503d2cc382277e100450209231830%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r76142b8c5119df2178be7c2dba88fde552eedeec37ea993dfce68d1d%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r83109088737656fa6307bd99ab40f8ff0269ae58d3f7272d7048494a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r9f93cf6dde308d42a9c807784e8102600d0397f5f834890708bf6920%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/ra7f6aeb28661fbf826969526585f16856abc4615877875f9d3b35ef4%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rb14daf9cc4e28d18cdc15d6a6ca74e565672fabf7ad89541071d008b%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rc998b18880df98bafaade071346690c2bc1444adaa1a1ea464b93f0a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rcc44594d4d6579b90deccd4536b5d31f099ef563df39b094be286b9e%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rd18c3c43602e66f9cdcf09f1de233804975b9572b0456cc582390b6f%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/re3d27b6250aa8548b8845d314bb8a350b3df326cacbbfdfe4d455234%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rf6449464fd8b7437704c55f88361b66f12d5b5f90bcce66af4be4ba9%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT205219"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT205031"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, "type": "CWE-863"}
296
Determine whether the {function_name} code is vulnerable or not.
[ "APACHE 2.4 STATUS: -*- mode: text; coding: utf-8 -*-\nLast modified at [$Date$]", "The current version of this file can be found at:", " * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x/STATUS", "Documentation status is maintained separately and can be found at:", " * docs/STATUS in this source tree, or\n * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x/docs/STATUS", "The current development branch of this software can be found at:", " * http://svn.apache.org/repos/asf/httpd/httpd/trunk", "Consult the following STATUS files for information on related projects:", " * http://svn.apache.org/repos/asf/apr/apr/trunk/STATUS\n * http://svn.apache.org/repos/asf/apr/apr/branches/1.4.x/STATUS\n * http://svn.apache.org/repos/asf/apr/apr-util/branches/1.4.x/STATUS\n * http://svn.apache.org/repos/asf/apr/apr/branches/1.5.x/STATUS\n * http://svn.apache.org/repos/asf/apr/apr-util/branches/1.5.x/STATUS", "Patches considered for backport are noted in their branches' STATUS:", " * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.0.x/STATUS\n * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.2.x/STATUS\n * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x/STATUS", "", "Release history:\n [NOTE that x.{odd}.z versions are strictly Alpha/Beta releases,\n while x.{even}.z versions are Stable/GA releases.]", " 2.4.11 : In development.\n 2.4.10 : Tagged on July 15, 2014. Released July 21, 2014\n 2.4.9 : Tagged on March 13, 2014. Released on March 17, 2014\n 2.4.8 : Tagged on March 11, 2014. Not released.\n 2.4.7 : Tagged on November 19, 2013. Released on Nov 25, 2013\n 2.4.6 : Tagged on July 15, 2013. Released July, 22, 2013\n 2.4.5 : Tagged on July 11, 2013, not released.\n 2.4.4 : Tagged on February 18, 2013. Released Feb 25, 2013\n 2.4.3 : Tagged on August 17, 2012. Released Aug 18, 2012\n 2.4.2 : Tagged on April 5, 2012. Released Apr 17, 2012.\n 2.4.1 : Tagged on February 13, 2012. Released Feb 21, 2012.\n 2.4.0 : Tagged on January 16, 2012, not released.\n 2.3.16 : Tagged on December 15, 2011.\n 2.3.15 : Tagged on November 8, 2011. Released Nov. 15, 2011.\n 2.3.14 : Tagged on August 1, 2011. Released Aug. 9, 2011.\n 2.3.13 : Tagged on June 28, 2011, not released.\n 2.3.12 : Tagged on May 11, 2011. Released May 23, 2011.\n 2.3.11 : Released as Beta on March 7, 2011.\n 2.3.10 : Tagged on December 13, 2010. Released Dec 21, 2010.\n 2.3.9 : Tagged on November 23, 2010, not released.\n 2.3.8 : Tagged on August 24, 2010.\n 2.3.7 : Tagged on August 19, 2010, not released.\n 2.3.6 : Released on June 21, 2010.\n 2.3.5 : Released on January 26, 2010.\n 2.3.4 : Released on December 8, 2009.\n 2.3.3 : Tagged on November 11, 2009, not released.\n 2.3.2 : Tagged on March 23, 2009, not released.\n 2.3.1 : Tagged on January 2, 2009, not released.\n 2.3.0 : Tagged on December 6, 2008, not released.", "Contributors looking for a mission:", " * Just do an egrep on \"TODO\" or \"XXX\" in the source.", " * Review the bug database at: http://issues.apache.org/bugzilla/", " * Review the \"PatchAvailable\" bugs in the bug database:", " https://issues.apache.org/bugzilla/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&product=Apache+httpd-2&keywords=PatchAvailable", " After testing, you can append a comment saying \"Reviewed and tested\".", " * Open bugs in the bug database.", " * See also the STATUS file in the docs/ directory, which lists documentation-specific TODO items.", "\nCURRENT RELEASE NOTES:", " * Forward binary compatibility is expected of Apache 2.4.x releases, such\n that no MMN major number changes will occur after 2.4.1. Such changes can\n only be made in the trunk.", " * All commits to branches/2.4.x must be reflected in SVN trunk,\n as well, if they apply. Logical progression is commit to trunk\n then merge into branches/2.4.x, as applicable.", " * Current exceptions for RTC for this branch:\n . mod_lua\n . documentation\n . non-Unix build\n . non-Unix, single-platform code", "RELEASE SHOWSTOPPERS:", "", "PATCHES ACCEPTED TO BACKPORT FROM TRUNK:\n [ start all new proposals below, under PATCHES PROPOSED. ]\n", " *) SECURITY: CVE-2014-8109 (cve.mitre.org)\n mod_lua: Fix handling of the Require line when a LuaAuthzProvider is\n used in multiple Require directives with different arguments.\n PR57204. \n trunk patch: http://svn.apache.org/r1642499\n 2.4.x patch: trunk works:\n +1 covener, ylavic, jim", "", "PATCHES PROPOSED TO BACKPORT FROM TRUNK:\n [ New proposals should be added at the end of the list ]", " * mod_proxy: Preserve original request headers even if they differ\n from the ones to be forwarded to the backend. PR 45387.\n trunk patch: http://svn.apache.org/r1588527\n 2.4.x patch: trunk works (modulo CHANGES)\n +1: ylavic, rjung", " * mod_proxy: Don't limit the size of the connectable Unix Domain Socket paths.\n [Graham Dumpleton, Christophe Jaillet, Yann Ylavic]\n trunk patch: http://svn.apache.org/r1598946\n http://svn.apache.org/r1602989\n 2.4.x patch: http://people.apache.org/~ylavic/httpd-2.4.x-ap_proxy_connect_uds.patch\n (modulo CHANGES/MMN)\n +1: ylavic, jim", " * mod_ssl, event: Ensure that the SSL close notify alert is flushed to the client.\n PR54998.\n trunk patch: http://svn.apache.org/r1601184\n http://svn.apache.org/r1601274\n http://svn.apache.org/r1601185\n 2.4.x patch: http://people.apache.org/~ylavic/httpd-2.4.x-SSL-shutdown.patch\n (modulo CHANGES/MMN)\n +1: ylavic, rjung", " * mod_proxy: Shutdown (eg. SSL close notify) the backend connection before closing.\n trunk patch: http://svn.apache.org/r1601291\n http://svn.apache.org/r1601630\n 2.4.x patch: http://people.apache.org/~ylavic/httpd-2.4.x-proxy-SSL-shutdown.patch\n (modulo CHANGES)\n note: depends on ap_shutdown_conn() from r1601185 above.\n +1: ylavic, rjung", " * mpm_winnt service.c: Normalize all error and status messages, clean up\n source formatting, and accept utf-8 service names/descriptions for i18n.\n trunk patches: http://svn.apache.org/r1611165\n http://svn.apache.org/r1611169\n http://svn.apache.org/r1611244\n 2.4.x patches: trunk works\n +1: wrowe, gsmith", " * mod_systemd: New module, for integration with systemd on Linux.\n trunk patch: http://svn.apache.org/r1393976\n http://svn.apache.org/r1393997\n http://svn.apache.org/r1484554\n http://svn.apache.org/r1528032\n http://svn.apache.org/r1528034\n http://svn.apache.org/r1614821\n http://svn.apache.org/r1618579\n http://svn.apache.org/r1618588\n 2.4.x patch: http://people.apache.org/~jkaluza/patches/mod_systemd/httpd-2.4.x-mod_systemd.patch\n +1: jkaluza", " * core: Add support for systemd socket activation.\n trunk patch: http://svn.apache.org/r1511033\n http://svn.apache.org/r1608686\n http://svn.apache.org/r1608694\n http://svn.apache.org/r1608703\n http://svn.apache.org/r1608721\n http://svn.apache.org/r1608744\n 2.4.x patch: http://people.apache.org/~jkaluza/patches/mod_systemd/httpd-2.4.x-socket-activation.patch\n +1: jkaluza", " * mod_buffer: Forward flushed input data immediately and avoid (unlikely)\n access to freed memory.\n trunk patch: http://svn.apache.org/r1632742\n http://svn.apache.org/r1634836 (CHANGES entry)\n 2.4.x patches: trunk works (modulo CHANGES).\n +1: ylavic", " * mod_cgi: Log CGI script stderr to ScriptLog, use APLOGNO for\n log_scripterror errors.\n trunk patch: http://svn.apache.org/r1626978\n 2.4.x patch: trunk works\n +1 jkaluza\n ylavic: shouldn't we also (still) log on ErrorLog, at least on 2.4.x?\n The log_script_err() line may somewhere be expected in error_log.\n The new AH* in script_log could also cause parsing issues, but I'm\n fine with this personnaly.", " * mod_proxy_fcgi: Ignore body data from backend for 304 responses. PR 57198.\n trunk patch: http://svn.apache.org/r1640495\n 2.4.x patch: trunk works\n +1 jkaluza, covener\n ylavic: Shouldn't we handle more cases here to ignore the body?\n Please see my comment on dev@ as a reply to commit e-mail.", " * mod_proxy: Add ap_proxy_define_match_worker() and use it for ProxyPassMatch\n and ProxyMatch section to distinguish between normal workers and workers\n with regex substitutions in the name. Implement handling of such workers\n in ap_proxy_get_worker(). Fixes the bug when regex workers were not\n matched and used for request. PR 43513.\n trunk patch: http://svn.apache.org/r1609680\n http://svn.apache.org/r1641381\n 2.4.x patch: trunk works\n +1: jkaluza, ylavic", " * mod_rewrite: use the context info API to alleviate the need to specify\n a RewriteBase in some situations\n trunk patch: http://svn.apache.org/r1642484\n 2.4.x patch: trunk works\n +1 covener", "OTHER PROPOSALS", " * A list of further possible backports can be found at: \n http://people.apache.org/~rjung/patches/possible-backports-httpd-trunk-2_4.txt\n If you want to propose one of those, please add them above.", "\nPATCHES/ISSUES THAT ARE BEING WORKED", "\nPATCHES/ISSUES THAT ARE STALLED", " * core: Stop the HTTP_IN filter from attempting to write error buckets\n to the output filters\n trunk patch: https://svn.apache.org/viewvc?view=revision&revision=1482522\n https://svn.apache.org/viewvc?view=revision&revision=1482918\n 2.4.x patch: /* working on it */\n +1: jim", " * mod_proxy: Ensure network errors detected by the proxy are returned as\n 504 Gateway Timout as opposed to 502 Bad Gateway\n trunk patch: https://svn.apache.org/viewvc?view=revision&revision=1480058\n 2.4.x patch: trunk patch works modulo CHANGES\n +1:\n -1: rpluem: This change is still disputed. See\n http://mail-archives.apache.org/mod_mbox/httpd-dev/201305.mbox/%3C1B16B9E3-87BA-4EEF-939C-7C7313B54714%40gbiv.com%3E", " * cross-compile: allow to provide CC_FOR_BUILD so that gen_test_char will be\n compiled by the build compiler instead of the host compiler.\n Also set CC_FOR_BUILD to 'cc' when cross-compilation is detected.\n Trunk patches: http://svn.apache.org/viewvc?view=revision&revision=1327907\n http://svn.apache.org/viewvc?view=revision&revision=1328390\n http://svn.apache.org/viewvc?view=revision&revision=1328714\n 2.4 patch: http://people.apache.org/~fuankg/diffs/httpd-2.4.x-cross_compile.diff\n fuankg: on hold until we agree for a better and more simple solution ...", " * mod_ssl: Add support for Next Protocol Negotiation.\n Trunk patch:\n http://svn.apache.org/viewvc?view=revision&revision=1332643\n 2.4.x patch:\n Trunk patch works.\n +1: ben\n sf says: Needs r1345599, too.\n And wrowe's comment about the 2.2 patch is also valid for 2.4:\n http://svn.apache.org/viewvc?view=revision&revision=1354823", " * Makefile.win: Added copying of .vbs / .wsf CGIs to Windows install target.\n Moved fixing of shebang to separate target so that it is\n no longer executed by default and all CGIs remain inactive.\n trunk patch: http://svn.apache.org/viewvc?view=revision&revision=1387984\n http://svn.apache.org/viewvc?view=revision&revision=1421203\n http://svn.apache.org/viewvc?view=revision&revision=1421591\n 2.4.x patch: http://people.apache.org/~fuankg/diffs/httpd-2.4.x-Makefile.win.diff\n +1 fuankg, gsmith\n -.8: trawick\n This commit is essentially deciding that an httpd install on\n Windows now has printenv/testcgi written in 2 more languages.\n To the extent that the usefulness is that it shows how to make scripts\n of these types executable by httpd, I believe that the documentation\n is the proper place to solve that. To the extent that the usefullness\n is to show how to implement a CGI in these particular languages, I believe\n that the httpd distribution and documentation in general is not the\n place for that. Historically these types of scripts have caused problems\n for downstream vendorsas well as newbies (and sometimes the intersection\n of those two groups) who don't understand that these are information leaks\n once they are enabled, and the subtlety of the way they are disabled (\"Apache\n messed up the first line; let me fix that\") contributes to that.\n fuankg notes: I've just added a big warning to all CGI scripts which should now\n make absolutely clear that these CGIs are for testing purpose only - so those\n who enable those scripts with inserting the right shebang should be 100% aware\n of any risks (this should cover your last point).\n jim: trawick, does the above address your concerns?\n trawick: to some extent (somebody reading the script gets an idea)\n Why isn't the configuration requirement documented instead\n of described indirectly in a sample?\n Why are these new samples added to the install without three\n votes? (I didn't veto it; put your name next to the two\n existing ones and I'll be satisified that enough people\n considered this addition as an appropriate solution for a\n real httpd usability problem.)\n wrowe: I'd agree with trawick, and suggest that these scripts can begin\n their life somewhere in the manual/ tree. This really seems like\n the place where /usr/share/httpd/examples/ would be useful, but\n there isn't an ordinary directory for that. Since we want none\n of the scripts to function 'out of the box', what about a new\n cgi-examples/ dir alongside cgi-bin/? Otherwise manual/cgi/examples\n might work?" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 114, 1760], "buggy_code_start_loc": [11, 107, 68], "filenames": ["CHANGES", "STATUS", "modules/lua/mod_lua.c"], "fixing_code_end_loc": [17, 106, 1767], "fixing_code_start_loc": [12, 106, 69], "message": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:http_server:2.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "6FCD3C8C-9BF8-4F30-981A-593EEAEB9EDD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "046487A3-752B-4D0F-8984-96486B828EAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "89D2E052-51CD-4B57-A8B8-FAE51988D654", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "EAA27058-BACF-4F94-8E3C-7D38EC302EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "8FEAB0DF-04A9-4F99-8666-0BADC5D642B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E7D924D1-8A36-4C43-9E56-52814F9A6350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "39CDFECC-E26D-47E0-976F-6629040B3764", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "E3ECBCB1-0675-41F5-857B-438F36925F63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:-:*:*:*", "matchCriteriaId": "CB66DB75-2B16-4EBF-9B93-CE49D8086E41", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.10:*:*:*:*:*:*:*", "matchCriteriaId": "49A63F39-30BE-443F-AF10-6245587D3359", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:21:*:*:*:*:*:*:*", "matchCriteriaId": "56BDB5A0-0839-4A20-A003-B8CD56F48171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:*:*:*:*:*:*:*:*", "matchCriteriaId": "A70BB445-EF2B-4C9D-8502-FDD6A19F8C30", "versionEndExcluding": "12.1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "4725EA61-9BAB-4E72-9F92-ADE4624439CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0879FB1-58E2-4EC4-8111-044642E046BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "C7CF2929-4CBC-4B56-87AE-F45F53BD8DD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory."}, {"lang": "es", "value": "El m\u00f3dulo mod_lua.c en el m\u00f3dulo mod_lua en Apache HTTP Server 2.3.x y 2.4.x a trav\u00e9s de 2.4.10 no soporta la configuraci\u00f3n httpd en la cual el proveedor de autorizaci\u00f3n Lua se usa con argumentos diferentes dentro de contextos diferentes, lo que permite a atacantes remotos saltarse las restricciones de acceso en ciertas circunstancias aprovechando m\u00faltiples directivas requeridas, como se demuestra por una configuraci\u00f3n que especifica la autorizaci\u00f3n para un grupo para acceder a un directorio determinado, y una autorizaci\u00f3n para un segundo grupo para acceder a un segundo directorio."}], "evaluatorComment": null, "id": "CVE-2014-8109", "lastModified": "2023-02-13T00:42:40.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-29T23:59:00.053", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://advisories.mageia.org/MGASA-2015-0011.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Aug/msg00001.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Sep/msg00004.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2015-June/159352.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/28/5"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/cpujan2016-2367955.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/73040"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2523-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1174077"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://issues.apache.org/bugzilla/show_bug.cgi?id=57204"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/56c2e7cc9deb1c12a843d0dc251ea7fd3e7e80293cde02fcd65286ba%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/84a3714f0878781f6ed84473d1a503d2cc382277e100450209231830%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r76142b8c5119df2178be7c2dba88fde552eedeec37ea993dfce68d1d%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r83109088737656fa6307bd99ab40f8ff0269ae58d3f7272d7048494a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r9f93cf6dde308d42a9c807784e8102600d0397f5f834890708bf6920%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/ra7f6aeb28661fbf826969526585f16856abc4615877875f9d3b35ef4%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rb14daf9cc4e28d18cdc15d6a6ca74e565672fabf7ad89541071d008b%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rc998b18880df98bafaade071346690c2bc1444adaa1a1ea464b93f0a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rcc44594d4d6579b90deccd4536b5d31f099ef563df39b094be286b9e%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rd18c3c43602e66f9cdcf09f1de233804975b9572b0456cc582390b6f%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/re3d27b6250aa8548b8845d314bb8a350b3df326cacbbfdfe4d455234%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rf6449464fd8b7437704c55f88361b66f12d5b5f90bcce66af4be4ba9%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT205219"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT205031"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, "type": "CWE-863"}
296
Determine whether the {function_name} code is vulnerable or not.
[ "APACHE 2.4 STATUS: -*- mode: text; coding: utf-8 -*-\nLast modified at [$Date$]", "The current version of this file can be found at:", " * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x/STATUS", "Documentation status is maintained separately and can be found at:", " * docs/STATUS in this source tree, or\n * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x/docs/STATUS", "The current development branch of this software can be found at:", " * http://svn.apache.org/repos/asf/httpd/httpd/trunk", "Consult the following STATUS files for information on related projects:", " * http://svn.apache.org/repos/asf/apr/apr/trunk/STATUS\n * http://svn.apache.org/repos/asf/apr/apr/branches/1.4.x/STATUS\n * http://svn.apache.org/repos/asf/apr/apr-util/branches/1.4.x/STATUS\n * http://svn.apache.org/repos/asf/apr/apr/branches/1.5.x/STATUS\n * http://svn.apache.org/repos/asf/apr/apr-util/branches/1.5.x/STATUS", "Patches considered for backport are noted in their branches' STATUS:", " * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.0.x/STATUS\n * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.2.x/STATUS\n * http://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x/STATUS", "", "Release history:\n [NOTE that x.{odd}.z versions are strictly Alpha/Beta releases,\n while x.{even}.z versions are Stable/GA releases.]", " 2.4.11 : In development.\n 2.4.10 : Tagged on July 15, 2014. Released July 21, 2014\n 2.4.9 : Tagged on March 13, 2014. Released on March 17, 2014\n 2.4.8 : Tagged on March 11, 2014. Not released.\n 2.4.7 : Tagged on November 19, 2013. Released on Nov 25, 2013\n 2.4.6 : Tagged on July 15, 2013. Released July, 22, 2013\n 2.4.5 : Tagged on July 11, 2013, not released.\n 2.4.4 : Tagged on February 18, 2013. Released Feb 25, 2013\n 2.4.3 : Tagged on August 17, 2012. Released Aug 18, 2012\n 2.4.2 : Tagged on April 5, 2012. Released Apr 17, 2012.\n 2.4.1 : Tagged on February 13, 2012. Released Feb 21, 2012.\n 2.4.0 : Tagged on January 16, 2012, not released.\n 2.3.16 : Tagged on December 15, 2011.\n 2.3.15 : Tagged on November 8, 2011. Released Nov. 15, 2011.\n 2.3.14 : Tagged on August 1, 2011. Released Aug. 9, 2011.\n 2.3.13 : Tagged on June 28, 2011, not released.\n 2.3.12 : Tagged on May 11, 2011. Released May 23, 2011.\n 2.3.11 : Released as Beta on March 7, 2011.\n 2.3.10 : Tagged on December 13, 2010. Released Dec 21, 2010.\n 2.3.9 : Tagged on November 23, 2010, not released.\n 2.3.8 : Tagged on August 24, 2010.\n 2.3.7 : Tagged on August 19, 2010, not released.\n 2.3.6 : Released on June 21, 2010.\n 2.3.5 : Released on January 26, 2010.\n 2.3.4 : Released on December 8, 2009.\n 2.3.3 : Tagged on November 11, 2009, not released.\n 2.3.2 : Tagged on March 23, 2009, not released.\n 2.3.1 : Tagged on January 2, 2009, not released.\n 2.3.0 : Tagged on December 6, 2008, not released.", "Contributors looking for a mission:", " * Just do an egrep on \"TODO\" or \"XXX\" in the source.", " * Review the bug database at: http://issues.apache.org/bugzilla/", " * Review the \"PatchAvailable\" bugs in the bug database:", " https://issues.apache.org/bugzilla/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&product=Apache+httpd-2&keywords=PatchAvailable", " After testing, you can append a comment saying \"Reviewed and tested\".", " * Open bugs in the bug database.", " * See also the STATUS file in the docs/ directory, which lists documentation-specific TODO items.", "\nCURRENT RELEASE NOTES:", " * Forward binary compatibility is expected of Apache 2.4.x releases, such\n that no MMN major number changes will occur after 2.4.1. Such changes can\n only be made in the trunk.", " * All commits to branches/2.4.x must be reflected in SVN trunk,\n as well, if they apply. Logical progression is commit to trunk\n then merge into branches/2.4.x, as applicable.", " * Current exceptions for RTC for this branch:\n . mod_lua\n . documentation\n . non-Unix build\n . non-Unix, single-platform code", "RELEASE SHOWSTOPPERS:", "", "PATCHES ACCEPTED TO BACKPORT FROM TRUNK:\n [ start all new proposals below, under PATCHES PROPOSED. ]\n", "", "", "PATCHES PROPOSED TO BACKPORT FROM TRUNK:\n [ New proposals should be added at the end of the list ]", " * mod_proxy: Preserve original request headers even if they differ\n from the ones to be forwarded to the backend. PR 45387.\n trunk patch: http://svn.apache.org/r1588527\n 2.4.x patch: trunk works (modulo CHANGES)\n +1: ylavic, rjung", " * mod_proxy: Don't limit the size of the connectable Unix Domain Socket paths.\n [Graham Dumpleton, Christophe Jaillet, Yann Ylavic]\n trunk patch: http://svn.apache.org/r1598946\n http://svn.apache.org/r1602989\n 2.4.x patch: http://people.apache.org/~ylavic/httpd-2.4.x-ap_proxy_connect_uds.patch\n (modulo CHANGES/MMN)\n +1: ylavic, jim", " * mod_ssl, event: Ensure that the SSL close notify alert is flushed to the client.\n PR54998.\n trunk patch: http://svn.apache.org/r1601184\n http://svn.apache.org/r1601274\n http://svn.apache.org/r1601185\n 2.4.x patch: http://people.apache.org/~ylavic/httpd-2.4.x-SSL-shutdown.patch\n (modulo CHANGES/MMN)\n +1: ylavic, rjung", " * mod_proxy: Shutdown (eg. SSL close notify) the backend connection before closing.\n trunk patch: http://svn.apache.org/r1601291\n http://svn.apache.org/r1601630\n 2.4.x patch: http://people.apache.org/~ylavic/httpd-2.4.x-proxy-SSL-shutdown.patch\n (modulo CHANGES)\n note: depends on ap_shutdown_conn() from r1601185 above.\n +1: ylavic, rjung", " * mpm_winnt service.c: Normalize all error and status messages, clean up\n source formatting, and accept utf-8 service names/descriptions for i18n.\n trunk patches: http://svn.apache.org/r1611165\n http://svn.apache.org/r1611169\n http://svn.apache.org/r1611244\n 2.4.x patches: trunk works\n +1: wrowe, gsmith", " * mod_systemd: New module, for integration with systemd on Linux.\n trunk patch: http://svn.apache.org/r1393976\n http://svn.apache.org/r1393997\n http://svn.apache.org/r1484554\n http://svn.apache.org/r1528032\n http://svn.apache.org/r1528034\n http://svn.apache.org/r1614821\n http://svn.apache.org/r1618579\n http://svn.apache.org/r1618588\n 2.4.x patch: http://people.apache.org/~jkaluza/patches/mod_systemd/httpd-2.4.x-mod_systemd.patch\n +1: jkaluza", " * core: Add support for systemd socket activation.\n trunk patch: http://svn.apache.org/r1511033\n http://svn.apache.org/r1608686\n http://svn.apache.org/r1608694\n http://svn.apache.org/r1608703\n http://svn.apache.org/r1608721\n http://svn.apache.org/r1608744\n 2.4.x patch: http://people.apache.org/~jkaluza/patches/mod_systemd/httpd-2.4.x-socket-activation.patch\n +1: jkaluza", " * mod_buffer: Forward flushed input data immediately and avoid (unlikely)\n access to freed memory.\n trunk patch: http://svn.apache.org/r1632742\n http://svn.apache.org/r1634836 (CHANGES entry)\n 2.4.x patches: trunk works (modulo CHANGES).\n +1: ylavic", " * mod_cgi: Log CGI script stderr to ScriptLog, use APLOGNO for\n log_scripterror errors.\n trunk patch: http://svn.apache.org/r1626978\n 2.4.x patch: trunk works\n +1 jkaluza\n ylavic: shouldn't we also (still) log on ErrorLog, at least on 2.4.x?\n The log_script_err() line may somewhere be expected in error_log.\n The new AH* in script_log could also cause parsing issues, but I'm\n fine with this personnaly.", " * mod_proxy_fcgi: Ignore body data from backend for 304 responses. PR 57198.\n trunk patch: http://svn.apache.org/r1640495\n 2.4.x patch: trunk works\n +1 jkaluza, covener\n ylavic: Shouldn't we handle more cases here to ignore the body?\n Please see my comment on dev@ as a reply to commit e-mail.", " * mod_proxy: Add ap_proxy_define_match_worker() and use it for ProxyPassMatch\n and ProxyMatch section to distinguish between normal workers and workers\n with regex substitutions in the name. Implement handling of such workers\n in ap_proxy_get_worker(). Fixes the bug when regex workers were not\n matched and used for request. PR 43513.\n trunk patch: http://svn.apache.org/r1609680\n http://svn.apache.org/r1641381\n 2.4.x patch: trunk works\n +1: jkaluza, ylavic", " * mod_rewrite: use the context info API to alleviate the need to specify\n a RewriteBase in some situations\n trunk patch: http://svn.apache.org/r1642484\n 2.4.x patch: trunk works\n +1 covener", "OTHER PROPOSALS", " * A list of further possible backports can be found at: \n http://people.apache.org/~rjung/patches/possible-backports-httpd-trunk-2_4.txt\n If you want to propose one of those, please add them above.", "\nPATCHES/ISSUES THAT ARE BEING WORKED", "\nPATCHES/ISSUES THAT ARE STALLED", " * core: Stop the HTTP_IN filter from attempting to write error buckets\n to the output filters\n trunk patch: https://svn.apache.org/viewvc?view=revision&revision=1482522\n https://svn.apache.org/viewvc?view=revision&revision=1482918\n 2.4.x patch: /* working on it */\n +1: jim", " * mod_proxy: Ensure network errors detected by the proxy are returned as\n 504 Gateway Timout as opposed to 502 Bad Gateway\n trunk patch: https://svn.apache.org/viewvc?view=revision&revision=1480058\n 2.4.x patch: trunk patch works modulo CHANGES\n +1:\n -1: rpluem: This change is still disputed. See\n http://mail-archives.apache.org/mod_mbox/httpd-dev/201305.mbox/%3C1B16B9E3-87BA-4EEF-939C-7C7313B54714%40gbiv.com%3E", " * cross-compile: allow to provide CC_FOR_BUILD so that gen_test_char will be\n compiled by the build compiler instead of the host compiler.\n Also set CC_FOR_BUILD to 'cc' when cross-compilation is detected.\n Trunk patches: http://svn.apache.org/viewvc?view=revision&revision=1327907\n http://svn.apache.org/viewvc?view=revision&revision=1328390\n http://svn.apache.org/viewvc?view=revision&revision=1328714\n 2.4 patch: http://people.apache.org/~fuankg/diffs/httpd-2.4.x-cross_compile.diff\n fuankg: on hold until we agree for a better and more simple solution ...", " * mod_ssl: Add support for Next Protocol Negotiation.\n Trunk patch:\n http://svn.apache.org/viewvc?view=revision&revision=1332643\n 2.4.x patch:\n Trunk patch works.\n +1: ben\n sf says: Needs r1345599, too.\n And wrowe's comment about the 2.2 patch is also valid for 2.4:\n http://svn.apache.org/viewvc?view=revision&revision=1354823", " * Makefile.win: Added copying of .vbs / .wsf CGIs to Windows install target.\n Moved fixing of shebang to separate target so that it is\n no longer executed by default and all CGIs remain inactive.\n trunk patch: http://svn.apache.org/viewvc?view=revision&revision=1387984\n http://svn.apache.org/viewvc?view=revision&revision=1421203\n http://svn.apache.org/viewvc?view=revision&revision=1421591\n 2.4.x patch: http://people.apache.org/~fuankg/diffs/httpd-2.4.x-Makefile.win.diff\n +1 fuankg, gsmith\n -.8: trawick\n This commit is essentially deciding that an httpd install on\n Windows now has printenv/testcgi written in 2 more languages.\n To the extent that the usefulness is that it shows how to make scripts\n of these types executable by httpd, I believe that the documentation\n is the proper place to solve that. To the extent that the usefullness\n is to show how to implement a CGI in these particular languages, I believe\n that the httpd distribution and documentation in general is not the\n place for that. Historically these types of scripts have caused problems\n for downstream vendorsas well as newbies (and sometimes the intersection\n of those two groups) who don't understand that these are information leaks\n once they are enabled, and the subtlety of the way they are disabled (\"Apache\n messed up the first line; let me fix that\") contributes to that.\n fuankg notes: I've just added a big warning to all CGI scripts which should now\n make absolutely clear that these CGIs are for testing purpose only - so those\n who enable those scripts with inserting the right shebang should be 100% aware\n of any risks (this should cover your last point).\n jim: trawick, does the above address your concerns?\n trawick: to some extent (somebody reading the script gets an idea)\n Why isn't the configuration requirement documented instead\n of described indirectly in a sample?\n Why are these new samples added to the install without three\n votes? (I didn't veto it; put your name next to the two\n existing ones and I'll be satisified that enough people\n considered this addition as an appropriate solution for a\n real httpd usability problem.)\n wrowe: I'd agree with trawick, and suggest that these scripts can begin\n their life somewhere in the manual/ tree. This really seems like\n the place where /usr/share/httpd/examples/ would be useful, but\n there isn't an ordinary directory for that. Since we want none\n of the scripts to function 'out of the box', what about a new\n cgi-examples/ dir alongside cgi-bin/? Otherwise manual/cgi/examples\n might work?" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 114, 1760], "buggy_code_start_loc": [11, 107, 68], "filenames": ["CHANGES", "STATUS", "modules/lua/mod_lua.c"], "fixing_code_end_loc": [17, 106, 1767], "fixing_code_start_loc": [12, 106, 69], "message": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:http_server:2.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "6FCD3C8C-9BF8-4F30-981A-593EEAEB9EDD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "046487A3-752B-4D0F-8984-96486B828EAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "89D2E052-51CD-4B57-A8B8-FAE51988D654", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "EAA27058-BACF-4F94-8E3C-7D38EC302EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "8FEAB0DF-04A9-4F99-8666-0BADC5D642B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E7D924D1-8A36-4C43-9E56-52814F9A6350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "39CDFECC-E26D-47E0-976F-6629040B3764", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "E3ECBCB1-0675-41F5-857B-438F36925F63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:-:*:*:*", "matchCriteriaId": "CB66DB75-2B16-4EBF-9B93-CE49D8086E41", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.10:*:*:*:*:*:*:*", "matchCriteriaId": "49A63F39-30BE-443F-AF10-6245587D3359", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:21:*:*:*:*:*:*:*", "matchCriteriaId": "56BDB5A0-0839-4A20-A003-B8CD56F48171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:*:*:*:*:*:*:*:*", "matchCriteriaId": "A70BB445-EF2B-4C9D-8502-FDD6A19F8C30", "versionEndExcluding": "12.1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "4725EA61-9BAB-4E72-9F92-ADE4624439CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0879FB1-58E2-4EC4-8111-044642E046BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "C7CF2929-4CBC-4B56-87AE-F45F53BD8DD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory."}, {"lang": "es", "value": "El m\u00f3dulo mod_lua.c en el m\u00f3dulo mod_lua en Apache HTTP Server 2.3.x y 2.4.x a trav\u00e9s de 2.4.10 no soporta la configuraci\u00f3n httpd en la cual el proveedor de autorizaci\u00f3n Lua se usa con argumentos diferentes dentro de contextos diferentes, lo que permite a atacantes remotos saltarse las restricciones de acceso en ciertas circunstancias aprovechando m\u00faltiples directivas requeridas, como se demuestra por una configuraci\u00f3n que especifica la autorizaci\u00f3n para un grupo para acceder a un directorio determinado, y una autorizaci\u00f3n para un segundo grupo para acceder a un segundo directorio."}], "evaluatorComment": null, "id": "CVE-2014-8109", "lastModified": "2023-02-13T00:42:40.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-29T23:59:00.053", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://advisories.mageia.org/MGASA-2015-0011.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Aug/msg00001.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Sep/msg00004.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2015-June/159352.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/28/5"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/cpujan2016-2367955.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/73040"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2523-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1174077"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://issues.apache.org/bugzilla/show_bug.cgi?id=57204"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/56c2e7cc9deb1c12a843d0dc251ea7fd3e7e80293cde02fcd65286ba%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/84a3714f0878781f6ed84473d1a503d2cc382277e100450209231830%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r76142b8c5119df2178be7c2dba88fde552eedeec37ea993dfce68d1d%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r83109088737656fa6307bd99ab40f8ff0269ae58d3f7272d7048494a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r9f93cf6dde308d42a9c807784e8102600d0397f5f834890708bf6920%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/ra7f6aeb28661fbf826969526585f16856abc4615877875f9d3b35ef4%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rb14daf9cc4e28d18cdc15d6a6ca74e565672fabf7ad89541071d008b%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rc998b18880df98bafaade071346690c2bc1444adaa1a1ea464b93f0a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rcc44594d4d6579b90deccd4536b5d31f099ef563df39b094be286b9e%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rd18c3c43602e66f9cdcf09f1de233804975b9572b0456cc582390b6f%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/re3d27b6250aa8548b8845d314bb8a350b3df326cacbbfdfe4d455234%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rf6449464fd8b7437704c55f88361b66f12d5b5f90bcce66af4be4ba9%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT205219"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT205031"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, "type": "CWE-863"}
296
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#include \"mod_lua.h\"\n#include <string.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <apr_thread_mutex.h>\n#include <apr_pools.h>\n#include \"lua_apr.h\"\n#include \"lua_config.h\"\n#include \"apr_optional.h\"\n#include \"mod_ssl.h\"\n#include \"mod_auth.h\"\n#include \"util_mutex.h\"", "\n#ifdef APR_HAS_THREADS\n#include \"apr_thread_proc.h\"\n#endif", "/* getpid for *NIX */\n#if APR_HAVE_SYS_TYPES_H\n#include <sys/types.h>\n#endif\n#if APR_HAVE_UNISTD_H\n#include <unistd.h>\n#endif", "/* getpid for Windows */\n#if APR_HAVE_PROCESS_H\n#include <process.h>\n#endif", "APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap_lua, AP_LUA, int, lua_open,\n (lua_State *L, apr_pool_t *p),\n (L, p), OK, DECLINED)", "APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap_lua, AP_LUA, int, lua_request,\n (lua_State *L, request_rec *r),\n (L, r), OK, DECLINED)\nstatic APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *lua_ssl_val = NULL;\nstatic APR_OPTIONAL_FN_TYPE(ssl_is_https) *lua_ssl_is_https = NULL;", "module AP_MODULE_DECLARE_DATA lua_module;", "#define AP_LUA_HOOK_FIRST (APR_HOOK_FIRST - 1)\n#define AP_LUA_HOOK_LAST (APR_HOOK_LAST + 1)", "typedef struct {\n const char *name;\n const char *file_name;\n const char *function_name;\n ap_lua_vm_spec *spec;", "", " apr_array_header_t *args;", "} lua_authz_provider_spec;", "\napr_hash_t *lua_authz_providers;", "typedef struct\n{\n apr_bucket_brigade *tmpBucket;\n lua_State *L;\n ap_lua_vm_spec *spec;\n int broken;\n} lua_filter_ctx;", "apr_global_mutex_t *lua_ivm_mutex;\napr_shm_t *lua_ivm_shm;\nchar *lua_ivm_shmfile;", "static apr_status_t shm_cleanup_wrapper(void *unused) {\n if (lua_ivm_shm) {\n return apr_shm_destroy(lua_ivm_shm);\n }\n return OK;\n}", "/**\n * error reporting if lua has an error.\n * Extracts the error from lua stack and prints\n */\nstatic void report_lua_error(lua_State *L, request_rec *r)\n{\n const char *lua_response;\n r->status = HTTP_INTERNAL_SERVER_ERROR;\n r->content_type = \"text/html\";\n ap_rputs(\"<h3>Error!</h3>\\n\", r);\n ap_rputs(\"<pre>\", r);\n lua_response = lua_tostring(L, -1);\n ap_rputs(ap_escape_html(r->pool, lua_response), r);\n ap_rputs(\"</pre>\\n\", r);", " ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, r->pool, APLOGNO(01471) \"Lua error: %s\",\n lua_response);\n}", "static void lua_open_callback(lua_State *L, apr_pool_t *p, void *ctx)\n{\n ap_lua_init(L, p);\n ap_lua_load_apache2_lmodule(L);\n ap_lua_load_request_lmodule(L, p);\n ap_lua_load_config_lmodule(L);\n}", "static int lua_open_hook(lua_State *L, apr_pool_t *p)\n{\n lua_open_callback(L, p, NULL);\n return OK;\n}", "static const char *scope_to_string(unsigned int scope)\n{\n switch (scope) {\n case AP_LUA_SCOPE_ONCE:\n case AP_LUA_SCOPE_UNSET:\n return \"once\";\n case AP_LUA_SCOPE_REQUEST:\n return \"request\";\n case AP_LUA_SCOPE_CONN:\n return \"conn\";\n#if APR_HAS_THREADS\n case AP_LUA_SCOPE_THREAD:\n return \"thread\";\n case AP_LUA_SCOPE_SERVER:\n return \"server\";\n#endif\n default:\n ap_assert(0);\n return 0;\n }\n}", "static void ap_lua_release_state(lua_State* L, ap_lua_vm_spec* spec, request_rec* r) {\n char *hash;\n apr_reslist_t* reslist = NULL;\n if (spec->scope == AP_LUA_SCOPE_SERVER) {\n ap_lua_server_spec* sspec = NULL;\n lua_settop(L, 0);\n lua_getfield(L, LUA_REGISTRYINDEX, \"Apache2.Lua.server_spec\");\n sspec = (ap_lua_server_spec*) lua_touserdata(L, 1);\n hash = apr_psprintf(r->pool, \"reslist:%s\", spec->file);\n if (apr_pool_userdata_get((void **)&reslist, hash,\n r->server->process->pool) == APR_SUCCESS) {\n AP_DEBUG_ASSERT(sspec != NULL);\n if (reslist != NULL) {\n apr_reslist_release(reslist, sspec);\n }\n }\n }\n}", "static ap_lua_vm_spec *create_vm_spec(apr_pool_t **lifecycle_pool,\n request_rec *r,\n const ap_lua_dir_cfg *cfg,\n const ap_lua_server_cfg *server_cfg,\n const char *filename,\n const char *bytecode,\n apr_size_t bytecode_len,\n const char *function,\n const char *what)\n{\n apr_pool_t *pool;\n ap_lua_vm_spec *spec = apr_pcalloc(r->pool, sizeof(ap_lua_vm_spec));", " spec->scope = cfg->vm_scope;\n spec->pool = r->pool;\n spec->package_paths = cfg->package_paths;\n spec->package_cpaths = cfg->package_cpaths;\n spec->cb = &lua_open_callback;\n spec->cb_arg = NULL;\n spec->bytecode = bytecode;\n spec->bytecode_len = bytecode_len;\n spec->codecache = (cfg->codecache == AP_LUA_CACHE_UNSET) ? AP_LUA_CACHE_STAT : cfg->codecache;\n spec->vm_min = cfg->vm_min ? cfg->vm_min : 1;\n spec->vm_max = cfg->vm_max ? cfg->vm_max : 1;\n \n if (filename) {\n char *file;\n apr_filepath_merge(&file, server_cfg->root_path,\n filename, APR_FILEPATH_NOTRELATIVE, r->pool);\n spec->file = file;\n }\n else {\n spec->file = r->filename;\n }\n ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, APLOGNO(02313)\n \"%s details: scope: %s, file: %s, func: %s\",\n what, scope_to_string(spec->scope), spec->file,\n function ? function : \"-\");", " switch (spec->scope) {\n case AP_LUA_SCOPE_ONCE:\n case AP_LUA_SCOPE_UNSET:\n apr_pool_create(&pool, r->pool);\n break;\n case AP_LUA_SCOPE_REQUEST:\n pool = r->pool;\n break;\n case AP_LUA_SCOPE_CONN:\n pool = r->connection->pool;\n break;\n#if APR_HAS_THREADS\n case AP_LUA_SCOPE_THREAD:\n pool = apr_thread_pool_get(r->connection->current_thread);\n break;\n case AP_LUA_SCOPE_SERVER:\n pool = r->server->process->pool;\n break;\n#endif\n default:\n ap_assert(0);\n }", " *lifecycle_pool = pool;\n return spec;\n}", "static const char* ap_lua_interpolate_string(apr_pool_t* pool, const char* string, const char** values)\n{\n char *stringBetween;\n const char* ret;\n int srclen,x,y;\n srclen = strlen(string);\n ret = \"\";\n y = 0;\n for (x=0; x < srclen; x++) {\n if (string[x] == '$' && x != srclen-1 && string[x+1] >= '0' && string[x+1] <= '9') {\n int v = *(string+x+1) - '0';\n if (x-y > 0) {\n stringBetween = apr_pstrndup(pool, string+y, x-y);\n }\n else {\n stringBetween = \"\";\n }\n ret = apr_pstrcat(pool, ret, stringBetween, values[v], NULL);\n y = ++x+1;\n }\n }\n \n if (x-y > 0 && y > 0) {\n stringBetween = apr_pstrndup(pool, string+y, x-y);\n ret = apr_pstrcat(pool, ret, stringBetween, NULL);\n }\n /* If no replacement was made, just return the original string */\n else if (y == 0) {\n return string;\n }\n return ret;\n}", "", "/**\n * \"main\"\n */\nstatic int lua_handler(request_rec *r)\n{\n int rc = OK;\n if (strcmp(r->handler, \"lua-script\")) {\n return DECLINED;\n }\n /* Decline the request if the script does not exist (or is a directory),\n * rather than just returning internal server error */\n if (\n (r->finfo.filetype == APR_NOFILE)\n || (r->finfo.filetype & APR_DIR)\n ) {\n return DECLINED;\n }\n ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, APLOGNO(01472)\n \"handling [%s] in mod_lua\", r->filename);", " /* XXX: This seems wrong because it may generate wrong headers for HEAD requests */\n if (!r->header_only) {\n lua_State *L;\n apr_pool_t *pool;\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n ap_lua_vm_spec *spec = create_vm_spec(&pool, r, cfg, NULL, NULL, NULL,\n 0, \"handle\", \"request handler\");", " L = ap_lua_get_lua_state(pool, spec, r);\n if (!L) {\n /* TODO annotate spec with failure reason */\n r->status = HTTP_INTERNAL_SERVER_ERROR;\n ap_rputs(\"Unable to compile VM, see logs\", r);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, APLOGNO(01474) \"got a vm!\");\n lua_getglobal(L, \"handle\");\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01475)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n \"handle\",\n spec->file);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n ap_lua_run_lua_request(L, r);\n if (lua_pcall(L, 1, 1, 0)) {\n report_lua_error(L, r);\n }\n if (lua_isnumber(L, -1)) {\n rc = lua_tointeger(L, -1);\n }\n ap_lua_release_state(L, spec, r);\n }\n return rc;\n}", "\n/* ------------------- Input/output content filters ------------------- */", "\nstatic apr_status_t lua_setup_filter_ctx(ap_filter_t* f, request_rec* r, lua_filter_ctx** c) {\n apr_pool_t *pool;\n ap_lua_vm_spec *spec;\n int n, rc;\n lua_State *L;\n lua_filter_ctx *ctx; \n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n \n ctx = apr_pcalloc(r->pool, sizeof(lua_filter_ctx));\n ctx->broken = 0;\n *c = ctx;\n /* Find the filter that was called.\n * XXX: If we were wired with mod_filter, the filter (mod_filters name)\n * and the provider (our underlying filters name) need to have matched.\n */\n for (n = 0; n < cfg->mapped_filters->nelts; n++) {\n ap_lua_filter_handler_spec *hook_spec =\n ((ap_lua_filter_handler_spec **) cfg->mapped_filters->elts)[n];", " if (hook_spec == NULL) {\n continue;\n }\n if (!strcasecmp(hook_spec->filter_name, f->frec->name)) {\n spec = create_vm_spec(&pool, r, cfg, server_cfg,\n hook_spec->file_name,\n NULL,\n 0,\n hook_spec->function_name,\n \"filter\");\n L = ap_lua_get_lua_state(pool, spec, r);\n if (L) {\n L = lua_newthread(L);\n }", " if (!L) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02328)\n \"lua: Failed to obtain lua interpreter for %s %s\",\n hook_spec->function_name, hook_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return APR_EGENERAL;\n }\n if (hook_spec->function_name != NULL) {\n lua_getglobal(L, hook_spec->function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02329)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n hook_spec->function_name,\n hook_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return APR_EGENERAL;\n }", " ap_lua_run_lua_request(L, r);\n }\n else {\n int t;\n ap_lua_run_lua_request(L, r);", " t = lua_gettop(L);\n lua_setglobal(L, \"r\");\n lua_settop(L, t);\n }\n ctx->L = L;\n ctx->spec = spec;\n \n /* If a Lua filter is interested in filtering a request, it must first do a yield, \n * otherwise we'll assume that it's not interested and pretend we didn't find it.\n */\n rc = lua_resume(L, 1);\n if (rc == LUA_YIELD) {\n if (f->frec->providers == NULL) { \n /* Not wired by mod_filter */\n apr_table_unset(r->headers_out, \"Content-Length\");\n apr_table_unset(r->headers_out, \"Content-MD5\");\n apr_table_unset(r->headers_out, \"ETAG\");\n }\n return OK;\n }\n else {\n ap_lua_release_state(L, spec, r);\n return APR_ENOENT;\n }\n }\n }\n return APR_ENOENT;\n}", "static apr_status_t lua_output_filter_handle(ap_filter_t *f, apr_bucket_brigade *pbbIn) {\n request_rec *r = f->r;\n int rc;\n lua_State *L;\n lua_filter_ctx* ctx;\n conn_rec *c = r->connection;\n apr_bucket *pbktIn;\n apr_status_t rv;\n \n /* Set up the initial filter context and acquire the function.\n * The corresponding Lua function should yield here.\n */\n if (!f->ctx) {\n rc = lua_setup_filter_ctx(f,r,&ctx);\n if (rc == APR_EGENERAL) {\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n if (rc == APR_ENOENT) {\n /* No filter entry found (or the script declined to filter), just pass on the buckets */\n ap_remove_output_filter(f);\n return ap_pass_brigade(f->next,pbbIn);\n }\n else { \n /* We've got a willing lua filter, setup and check for a prefix */\n size_t olen;\n apr_bucket *pbktOut;\n const char* output = lua_tolstring(ctx->L, 1, &olen);", " f->ctx = ctx;\n ctx->tmpBucket = apr_brigade_create(r->pool, c->bucket_alloc);", " if (olen > 0) { \n pbktOut = apr_bucket_heap_create(output, olen, NULL, c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktOut);\n rv = ap_pass_brigade(f->next, ctx->tmpBucket);\n apr_brigade_cleanup(ctx->tmpBucket);\n if (rv != APR_SUCCESS) {\n return rv;\n }\n }\n }\n }\n ctx = (lua_filter_ctx*) f->ctx;\n L = ctx->L;\n /* While the Lua function is still yielding, pass in buckets to the coroutine */\n if (!ctx->broken) {\n for (pbktIn = APR_BRIGADE_FIRST(pbbIn);\n pbktIn != APR_BRIGADE_SENTINEL(pbbIn);\n pbktIn = APR_BUCKET_NEXT(pbktIn))\n {\n const char *data;\n apr_size_t len;\n apr_bucket *pbktOut;", " /* read the bucket */\n apr_bucket_read(pbktIn,&data,&len,APR_BLOCK_READ);", " /* Push the bucket onto the Lua stack as a global var */\n lua_pushlstring(L, data, len);\n lua_setglobal(L, \"bucket\");\n \n /* If Lua yielded, it means we have something to pass on */\n if (lua_resume(L, 0) == LUA_YIELD) {\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n if (olen > 0) { \n pbktOut = apr_bucket_heap_create(output, olen, NULL,\n c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktOut);\n rv = ap_pass_brigade(f->next, ctx->tmpBucket);\n apr_brigade_cleanup(ctx->tmpBucket);\n if (rv != APR_SUCCESS) {\n return rv;\n }\n }\n }\n else {\n ctx->broken = 1;\n ap_lua_release_state(L, ctx->spec, r);\n ap_remove_output_filter(f);\n apr_brigade_cleanup(pbbIn);\n apr_brigade_cleanup(ctx->tmpBucket);\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02663)\n \"lua: Error while executing filter: %s\",\n lua_tostring(L, -1));\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n }\n /* If we've safely reached the end, do a final call to Lua to allow for any \n finishing moves by the script, such as appending a tail. */\n if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(pbbIn))) {\n apr_bucket *pbktEOS;\n lua_pushnil(L);\n lua_setglobal(L, \"bucket\");\n if (lua_resume(L, 0) == LUA_YIELD) {\n apr_bucket *pbktOut;\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n if (olen > 0) { \n pbktOut = apr_bucket_heap_create(output, olen, NULL,\n c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktOut);\n }\n }\n pbktEOS = apr_bucket_eos_create(c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktEOS);\n ap_lua_release_state(L, ctx->spec, r);\n rv = ap_pass_brigade(f->next, ctx->tmpBucket);\n apr_brigade_cleanup(ctx->tmpBucket);\n if (rv != APR_SUCCESS) {\n return rv;\n }\n }\n }\n /* Clean up */\n apr_brigade_cleanup(pbbIn);\n return APR_SUCCESS; \n}", "", "static apr_status_t lua_input_filter_handle(ap_filter_t *f,\n apr_bucket_brigade *pbbOut,\n ap_input_mode_t eMode,\n apr_read_type_e eBlock,\n apr_off_t nBytes) \n{\n request_rec *r = f->r;\n int rc, lastCall = 0;\n lua_State *L;\n lua_filter_ctx* ctx;\n conn_rec *c = r->connection;\n apr_status_t ret;\n \n /* Set up the initial filter context and acquire the function.\n * The corresponding Lua function should yield here.\n */\n if (!f->ctx) {\n rc = lua_setup_filter_ctx(f,r,&ctx);\n f->ctx = ctx;\n if (rc == APR_EGENERAL) {\n ctx->broken = 1;\n ap_remove_input_filter(f); \n return HTTP_INTERNAL_SERVER_ERROR;\n }\n if (rc == APR_ENOENT ) {\n ap_remove_input_filter(f);\n ctx->broken = 1;\n }\n if (rc == APR_SUCCESS) {\n ctx->tmpBucket = apr_brigade_create(r->pool, c->bucket_alloc);\n }\n }\n ctx = (lua_filter_ctx*) f->ctx;\n L = ctx->L;\n /* If the Lua script broke or denied serving the request, just pass the buckets through */\n if (ctx->broken) {\n return ap_get_brigade(f->next, pbbOut, eMode, eBlock, nBytes);\n }\n \n if (APR_BRIGADE_EMPTY(ctx->tmpBucket)) {\n ret = ap_get_brigade(f->next, ctx->tmpBucket, eMode, eBlock, nBytes);\n if (eMode == AP_MODE_EATCRLF || ret != APR_SUCCESS)\n return ret;\n }\n \n /* While the Lua function is still yielding, pass buckets to the coroutine */\n if (!ctx->broken) {\n lastCall = 0;\n while(!APR_BRIGADE_EMPTY(ctx->tmpBucket)) {\n apr_bucket *pbktIn = APR_BRIGADE_FIRST(ctx->tmpBucket);\n apr_bucket *pbktOut;\n const char *data;\n apr_size_t len;\n \n if (APR_BUCKET_IS_EOS(pbktIn)) {\n APR_BUCKET_REMOVE(pbktIn);\n break;\n }", " /* read the bucket */\n ret = apr_bucket_read(pbktIn, &data, &len, eBlock);\n if (ret != APR_SUCCESS)\n return ret;", " /* Push the bucket onto the Lua stack as a global var */\n lastCall++;\n lua_pushlstring(L, data, len);\n lua_setglobal(L, \"bucket\");\n \n /* If Lua yielded, it means we have something to pass on */\n if (lua_resume(L, 0) == LUA_YIELD) {\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n pbktOut = apr_bucket_heap_create(output, olen, 0, c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(pbbOut, pbktOut);\n apr_bucket_delete(pbktIn);\n return APR_SUCCESS;\n }\n else {\n ctx->broken = 1;\n ap_lua_release_state(L, ctx->spec, r);\n ap_remove_input_filter(f); \n apr_bucket_delete(pbktIn);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n }\n /* If we've safely reached the end, do a final call to Lua to allow for any \n finishing moves by the script, such as appending a tail. */\n if (lastCall == 0) {\n apr_bucket *pbktEOS = apr_bucket_eos_create(c->bucket_alloc);\n lua_pushnil(L);\n lua_setglobal(L, \"bucket\");\n if (lua_resume(L, 0) == LUA_YIELD) {\n apr_bucket *pbktOut;\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n pbktOut = apr_bucket_heap_create(output, olen, 0, c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(pbbOut, pbktOut);\n }\n APR_BRIGADE_INSERT_TAIL(pbbOut,pbktEOS);\n ap_lua_release_state(L, ctx->spec, r);\n }\n }\n return APR_SUCCESS;\n}", "\n/* ---------------- Configury stuff --------------- */", "/** harnesses for magic hooks **/", "static int lua_request_rec_hook_harness(request_rec *r, const char *name, int apr_hook_when)\n{\n int rc;\n apr_pool_t *pool;\n lua_State *L;\n ap_lua_vm_spec *spec;\n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n const char *key = apr_psprintf(r->pool, \"%s_%d\", name, apr_hook_when);\n apr_array_header_t *hook_specs = apr_hash_get(cfg->hooks, key,\n APR_HASH_KEY_STRING);\n if (hook_specs) {\n int i;\n for (i = 0; i < hook_specs->nelts; i++) {\n ap_lua_mapped_handler_spec *hook_spec =\n ((ap_lua_mapped_handler_spec **) hook_specs->elts)[i];", " if (hook_spec == NULL) {\n continue;\n }\n spec = create_vm_spec(&pool, r, cfg, server_cfg,\n hook_spec->file_name,\n hook_spec->bytecode,\n hook_spec->bytecode_len,\n hook_spec->function_name,\n \"request hook\");", " L = ap_lua_get_lua_state(pool, spec, r);", " if (!L) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01477)\n \"lua: Failed to obtain lua interpreter for entry function '%s' in %s\",\n hook_spec->function_name, hook_spec->file_name);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " if (hook_spec->function_name != NULL) {\n lua_getglobal(L, hook_spec->function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01478)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n hook_spec->function_name,\n hook_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " ap_lua_run_lua_request(L, r);\n }\n else {\n int t;\n ap_lua_run_lua_request(L, r);", " t = lua_gettop(L);\n lua_setglobal(L, \"r\");\n lua_settop(L, t);\n }", " if (lua_pcall(L, 1, 1, 0)) {\n report_lua_error(L, r);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n rc = DECLINED;\n if (lua_isnumber(L, -1)) {\n rc = lua_tointeger(L, -1);\n ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, \"Lua hook %s:%s for phase %s returned %d\", \n hook_spec->file_name, hook_spec->function_name, name, rc);\n }\n else { \n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, \"Lua hook %s:%s for phase %s did not return a numeric value\", \n hook_spec->file_name, hook_spec->function_name, name);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n if (rc != DECLINED) {\n ap_lua_release_state(L, spec, r);\n return rc;\n }\n ap_lua_release_state(L, spec, r);\n }\n }\n return DECLINED;\n}", "\n/* Fix for making sure that LuaMapHandler works when FallbackResource is set */\nstatic int lua_map_handler_fixups(request_rec *r)\n{\n /* If there is no handler set yet, this might be a LuaMapHandler request */\n if (r->handler == NULL) {\n int n = 0;\n ap_regmatch_t match[10];\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n for (n = 0; n < cfg->mapped_handlers->nelts; n++) {\n ap_lua_mapped_handler_spec *hook_spec =\n ((ap_lua_mapped_handler_spec **) cfg->mapped_handlers->elts)[n];", " if (hook_spec == NULL) {\n continue;\n }\n if (!ap_regexec(hook_spec->uri_pattern, r->uri, 10, match, 0)) {\n r->handler = apr_pstrdup(r->pool, \"lua-map-handler\");\n return OK;\n }\n }\n }\n return DECLINED;\n}", "\nstatic int lua_map_handler(request_rec *r)\n{\n int rc, n = 0;\n apr_pool_t *pool;\n lua_State *L;\n const char *filename, *function_name;\n const char *values[10];\n ap_lua_vm_spec *spec;\n ap_regmatch_t match[10];\n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n for (n = 0; n < cfg->mapped_handlers->nelts; n++) {\n ap_lua_mapped_handler_spec *hook_spec =\n ((ap_lua_mapped_handler_spec **) cfg->mapped_handlers->elts)[n];", " if (hook_spec == NULL) {\n continue;\n }\n if (!ap_regexec(hook_spec->uri_pattern, r->uri, 10, match, 0)) {\n int i;\n for (i=0 ; i < 10; i++) {\n if (match[i].rm_eo >= 0) {\n values[i] = apr_pstrndup(r->pool, r->uri+match[i].rm_so, match[i].rm_eo - match[i].rm_so);\n }\n else values[i] = \"\";\n }\n filename = ap_lua_interpolate_string(r->pool, hook_spec->file_name, values);\n function_name = ap_lua_interpolate_string(r->pool, hook_spec->function_name, values);\n spec = create_vm_spec(&pool, r, cfg, server_cfg,\n filename,\n hook_spec->bytecode,\n hook_spec->bytecode_len,\n function_name,\n \"mapped handler\");\n L = ap_lua_get_lua_state(pool, spec, r);", " if (!L) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02330)\n \"lua: Failed to obtain Lua interpreter for entry function '%s' in %s\",\n function_name, filename);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " if (function_name != NULL) {\n lua_getglobal(L, function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02331)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n function_name,\n filename);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " ap_lua_run_lua_request(L, r);\n }\n else {\n int t;\n ap_lua_run_lua_request(L, r);", " t = lua_gettop(L);\n lua_setglobal(L, \"r\");\n lua_settop(L, t);\n }", " if (lua_pcall(L, 1, 1, 0)) {\n report_lua_error(L, r);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n rc = DECLINED;\n if (lua_isnumber(L, -1)) {\n rc = lua_tointeger(L, -1);\n }\n else { \n ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(02483)\n \"lua: Lua handler %s in %s did not return a value, assuming apache2.OK\",\n function_name,\n filename);\n rc = OK;\n }\n ap_lua_release_state(L, spec, r);\n if (rc != DECLINED) {\n return rc;\n }\n }\n }\n return DECLINED;\n}", "\nstatic apr_size_t config_getstr(ap_configfile_t *cfg, char *buf,\n size_t bufsiz)\n{\n apr_size_t i = 0;", " if (cfg->getstr) {\n apr_status_t rc = (cfg->getstr) (buf, bufsiz, cfg->param);\n if (rc == APR_SUCCESS) {\n i = strlen(buf);\n if (i && buf[i - 1] == '\\n')\n ++cfg->line_number;\n }\n else {\n buf[0] = '\\0';\n i = 0;\n }\n }\n else {\n while (i < bufsiz) {\n char ch;\n apr_status_t rc = (cfg->getch) (&ch, cfg->param);\n if (rc != APR_SUCCESS)\n break;\n buf[i++] = ch;\n if (ch == '\\n') {\n ++cfg->line_number;\n break;\n }\n }\n }\n return i;\n}", "typedef struct cr_ctx\n{\n cmd_parms *cmd;\n ap_configfile_t *cfp;\n size_t startline;\n const char *endstr;\n char buf[HUGE_STRING_LEN];\n} cr_ctx;", "\n/* Okay, this deserves a little explaination -- in order for the errors that lua\n * generates to be 'accuarate', including line numbers, we basically inject\n * N line number new lines into the 'top' of the chunk reader.....\n *\n * be happy. this is cool.\n *\n */\nstatic const char *lf =\n \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n#define N_LF 32", "static const char *direct_chunkreader(lua_State *lvm, void *udata,\n size_t *plen)\n{\n const char *p;\n struct cr_ctx *ctx = udata;", " if (ctx->startline) {\n *plen = ctx->startline > N_LF ? N_LF : ctx->startline;\n ctx->startline -= *plen;\n return lf;\n }\n *plen = config_getstr(ctx->cfp, ctx->buf, HUGE_STRING_LEN);", " for (p = ctx->buf; isspace(*p); ++p);\n if (p[0] == '<' && p[1] == '/') {\n apr_size_t i = 0;\n while (i < strlen(ctx->endstr)) {\n if (tolower(p[i + 2]) != ctx->endstr[i])\n return ctx->buf;\n ++i;\n }\n *plen = 0;\n return NULL;\n }\n /*fprintf(stderr, \"buf read: %s\\n\", ctx->buf); */\n return ctx->buf;\n}", "static int ldump_writer(lua_State *L, const void *b, size_t size, void *B)\n{\n (void) L;\n luaL_addlstring((luaL_Buffer *) B, (const char *) b, size);\n return 0;\n}", "typedef struct hack_section_baton\n{\n const char *name;\n ap_lua_mapped_handler_spec *spec;\n int apr_hook_when;\n} hack_section_baton;", "/* You can be unhappy now.\n *\n * This is uncool.\n *\n * When you create a <Section handler in httpd, the only 'easy' way to create\n * a directory context is to parse the section, and convert it into a 'normal'\n * Configureation option, and then collapse the entire section, in memory,\n * back into the parent section -- from which you can then get the new directive\n * invoked.... anyways. evil. Rici taught me how to do this hack :-)\n */\nstatic const char *hack_section_handler(cmd_parms *cmd, void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n ap_directive_t *directive = cmd->directive;\n hack_section_baton *baton = directive->data;\n const char *key = apr_psprintf(cmd->pool, \"%s_%d\", baton->name, baton->apr_hook_when);", " apr_array_header_t *hook_specs = apr_hash_get(cfg->hooks, key,\n APR_HASH_KEY_STRING);\n if (!hook_specs) {\n hook_specs = apr_array_make(cmd->pool, 2,\n sizeof(ap_lua_mapped_handler_spec *));\n apr_hash_set(cfg->hooks, key,\n APR_HASH_KEY_STRING, hook_specs);\n }", " baton->spec->scope = cfg->vm_scope;", " *(ap_lua_mapped_handler_spec **) apr_array_push(hook_specs) = baton->spec;", " return NULL;\n}", "static const char *register_named_block_function_hook(const char *name,\n cmd_parms *cmd,\n void *mconfig,\n const char *line)\n{\n const char *function = NULL;\n ap_lua_mapped_handler_spec *spec;\n int when = APR_HOOK_MIDDLE;\n const char *endp = ap_strrchr_c(line, '>');", " if (endp == NULL) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive missing closing '>'\", NULL);\n }", " line = apr_pstrndup(cmd->temp_pool, line, endp - line);", " if (line[0]) { \n const char *word;\n word = ap_getword_conf(cmd->temp_pool, &line);\n if (*word) {\n function = apr_pstrdup(cmd->pool, word);\n }\n word = ap_getword_conf(cmd->temp_pool, &line);\n if (*word) {\n if (!strcasecmp(\"early\", word)) { \n when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(\"late\", word)) {\n when = AP_LUA_HOOK_LAST;\n }\n else { \n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> 2nd argument must be 'early' or 'late'\", NULL);\n }\n }\n }", " spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));", " {\n cr_ctx ctx;\n lua_State *lvm;\n char *tmp;\n int rv;\n ap_directive_t **current;\n hack_section_baton *baton;", " spec->file_name = apr_psprintf(cmd->pool, \"%s:%u\",\n cmd->config_file->name,\n cmd->config_file->line_number);\n if (function) {\n spec->function_name = (char *) function;\n }\n else {\n function = NULL;\n }", " ctx.cmd = cmd;\n tmp = apr_pstrdup(cmd->pool, cmd->err_directive->directive + 1);\n ap_str_tolower(tmp);\n ctx.endstr = tmp;\n ctx.cfp = cmd->config_file;\n ctx.startline = cmd->config_file->line_number;", " /* This lua State is used only to compile the input strings -> bytecode, so we don't need anything extra. */\n lvm = luaL_newstate();", " lua_settop(lvm, 0);", " rv = lua_load(lvm, direct_chunkreader, &ctx, spec->file_name);", " if (rv != 0) {\n const char *errstr = apr_pstrcat(cmd->pool, \"Lua Error:\",\n lua_tostring(lvm, -1), NULL);\n lua_close(lvm);\n return errstr;\n }\n else {\n luaL_Buffer b;\n luaL_buffinit(lvm, &b);\n lua_dump(lvm, ldump_writer, &b);\n luaL_pushresult(&b);\n spec->bytecode_len = lua_strlen(lvm, -1);\n spec->bytecode = apr_pstrmemdup(cmd->pool, lua_tostring(lvm, -1),\n spec->bytecode_len);\n lua_close(lvm);\n }", " current = mconfig;", " /* Here, we have to replace our current config node for the next pass */\n if (!*current) {\n *current = apr_pcalloc(cmd->pool, sizeof(**current));\n }", " baton = apr_pcalloc(cmd->pool, sizeof(hack_section_baton));\n baton->name = name;\n baton->spec = spec;\n baton->apr_hook_when = when;", " (*current)->filename = cmd->config_file->name;\n (*current)->line_num = cmd->config_file->line_number;\n (*current)->directive = apr_pstrdup(cmd->pool, \"Lua_____ByteCodeHack\");\n (*current)->args = NULL;\n (*current)->data = baton;\n }", " return NULL;\n}", "static const char *register_named_file_function_hook(const char *name,\n cmd_parms *cmd,\n void *_cfg,\n const char *file,\n const char *function,\n int apr_hook_when)\n{\n ap_lua_mapped_handler_spec *spec;\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n const char *key = apr_psprintf(cmd->pool, \"%s_%d\", name, apr_hook_when);\n apr_array_header_t *hook_specs = apr_hash_get(cfg->hooks, key,\n APR_HASH_KEY_STRING);", " if (!hook_specs) {\n hook_specs = apr_array_make(cmd->pool, 2,\n sizeof(ap_lua_mapped_handler_spec *));\n apr_hash_set(cfg->hooks, key, APR_HASH_KEY_STRING, hook_specs);\n }", " spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));\n spec->file_name = apr_pstrdup(cmd->pool, file);\n spec->function_name = apr_pstrdup(cmd->pool, function);\n spec->scope = cfg->vm_scope;", " *(ap_lua_mapped_handler_spec **) apr_array_push(hook_specs) = spec;\n return NULL;\n}\nstatic const char *register_mapped_file_function_hook(const char *pattern,\n cmd_parms *cmd,\n void *_cfg,\n const char *file,\n const char *function)\n{\n ap_lua_mapped_handler_spec *spec;\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n ap_regex_t *regex = apr_pcalloc(cmd->pool, sizeof(ap_regex_t));\n if (ap_regcomp(regex, pattern,0)) {\n return \"Invalid regex pattern!\";\n }", " spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));\n spec->file_name = apr_pstrdup(cmd->pool, file);\n spec->function_name = apr_pstrdup(cmd->pool, function);\n spec->scope = cfg->vm_scope;\n spec->uri_pattern = regex;", " *(ap_lua_mapped_handler_spec **) apr_array_push(cfg->mapped_handlers) = spec;\n return NULL;\n}\nstatic const char *register_filter_function_hook(const char *filter,\n cmd_parms *cmd,\n void *_cfg,\n const char *file,\n const char *function,\n int direction)\n{\n ap_lua_filter_handler_spec *spec;\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n \n spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_filter_handler_spec));\n spec->file_name = apr_pstrdup(cmd->pool, file);\n spec->function_name = apr_pstrdup(cmd->pool, function);\n spec->filter_name = filter;", " *(ap_lua_filter_handler_spec **) apr_array_push(cfg->mapped_filters) = spec;\n /* TODO: Make it work on other types than just AP_FTYPE_RESOURCE? */\n if (direction == AP_LUA_FILTER_OUTPUT) {\n spec->direction = AP_LUA_FILTER_OUTPUT;\n ap_register_output_filter_protocol(filter, lua_output_filter_handle, NULL, AP_FTYPE_RESOURCE,\n AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH);\n }\n else {\n spec->direction = AP_LUA_FILTER_INPUT;\n ap_register_input_filter(filter, lua_input_filter_handle, NULL, AP_FTYPE_RESOURCE);\n }\n return NULL;\n}\n/* disabled (see reference below)\nstatic int lua_check_user_id_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"check_user_id\", AP_LUA_HOOK_FIRST);\n}\n*/\nstatic int lua_check_user_id_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"check_user_id\", APR_HOOK_MIDDLE);\n}\n/* disabled (see reference below)\nstatic int lua_check_user_id_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"check_user_id\", AP_LUA_HOOK_LAST);\n}\n*/", "static int lua_translate_name_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"translate_name\", AP_LUA_HOOK_FIRST);\n}\nstatic int lua_translate_name_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"translate_name\", APR_HOOK_MIDDLE);\n}\nstatic int lua_translate_name_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"translate_name\", AP_LUA_HOOK_LAST);\n}", "static int lua_fixup_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"fixups\", APR_HOOK_MIDDLE);\n}", "static int lua_map_to_storage_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"map_to_storage\", APR_HOOK_MIDDLE);\n}", "static int lua_type_checker_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"type_checker\", APR_HOOK_MIDDLE);\n}", "static int lua_access_checker_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"access_checker\", AP_LUA_HOOK_FIRST);\n}\nstatic int lua_access_checker_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"access_checker\", APR_HOOK_MIDDLE);\n}\nstatic int lua_access_checker_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"access_checker\", AP_LUA_HOOK_LAST);\n}", "static int lua_auth_checker_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"auth_checker\", AP_LUA_HOOK_FIRST);\n}\nstatic int lua_auth_checker_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"auth_checker\", APR_HOOK_MIDDLE);\n}\nstatic int lua_auth_checker_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"auth_checker\", AP_LUA_HOOK_LAST);\n}\nstatic void lua_insert_filter_harness(request_rec *r)\n{\n /* ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, \"LuaHookInsertFilter not yet implemented\"); */\n}", "static int lua_log_transaction_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"log_transaction\", APR_HOOK_FIRST);\n}", "static int lua_quick_harness(request_rec *r, int lookup)\n{\n if (lookup) {\n return DECLINED;\n }\n return lua_request_rec_hook_harness(r, \"quick\", APR_HOOK_MIDDLE);\n}", "static const char *register_translate_name_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n int apr_hook_when = APR_HOOK_MIDDLE;\n if (err) {\n return err;\n }\n \n if (when) { \n if (!strcasecmp(when, \"early\")) { \n apr_hook_when = AP_LUA_HOOK_FIRST;\n } \n else if (!strcasecmp(when, \"late\")) { \n apr_hook_when = AP_LUA_HOOK_LAST;\n } \n else { \n return \"Third argument must be 'early' or 'late'\";\n }\n }", " return register_named_file_function_hook(\"translate_name\", cmd, _cfg,\n file, function, apr_hook_when);\n}", "static const char *register_translate_name_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"translate_name\", cmd, _cfg,\n line);\n}", "\nstatic const char *register_fixups_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"fixups\", cmd, _cfg, file,\n function, APR_HOOK_MIDDLE);\n}\nstatic const char *register_fixups_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"fixups\", cmd, _cfg, line);\n}", "static const char *register_map_to_storage_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"map_to_storage\", cmd, _cfg,\n file, function, APR_HOOK_MIDDLE);\n}", "static const char *register_log_transaction_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"log_transaction\", cmd, _cfg,\n file, function, APR_HOOK_FIRST);\n}", "static const char *register_map_to_storage_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"map_to_storage\", cmd, _cfg,\n line);\n}", "\nstatic const char *register_check_user_id_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n int apr_hook_when = APR_HOOK_MIDDLE;\n/* XXX: This does not currently work!!\n if (when) {\n if (!strcasecmp(when, \"early\")) {\n apr_hook_when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(when, \"late\")) {\n apr_hook_when = AP_LUA_HOOK_LAST;\n }\n else {\n return \"Third argument must be 'early' or 'late'\";\n }\n }\n*/\n return register_named_file_function_hook(\"check_user_id\", cmd, _cfg, file,\n function, apr_hook_when);\n}\nstatic const char *register_check_user_id_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"check_user_id\", cmd, _cfg,\n line);\n}", "static const char *register_type_checker_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"type_checker\", cmd, _cfg, file,\n function, APR_HOOK_MIDDLE);\n}\nstatic const char *register_type_checker_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"type_checker\", cmd, _cfg,\n line);\n}", "static const char *register_access_checker_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n int apr_hook_when = APR_HOOK_MIDDLE;", " if (when) {\n if (!strcasecmp(when, \"early\")) {\n apr_hook_when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(when, \"late\")) {\n apr_hook_when = AP_LUA_HOOK_LAST;\n }\n else {\n return \"Third argument must be 'early' or 'late'\";\n }\n }", " return register_named_file_function_hook(\"access_checker\", cmd, _cfg,\n file, function, apr_hook_when);\n}\nstatic const char *register_access_checker_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{", " return register_named_block_function_hook(\"access_checker\", cmd, _cfg,\n line);\n}", "static const char *register_auth_checker_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n int apr_hook_when = APR_HOOK_MIDDLE;", " if (when) {\n if (!strcasecmp(when, \"early\")) {\n apr_hook_when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(when, \"late\")) {\n apr_hook_when = AP_LUA_HOOK_LAST;\n }\n else {\n return \"Third argument must be 'early' or 'late'\";\n }\n }", " return register_named_file_function_hook(\"auth_checker\", cmd, _cfg, file,\n function, apr_hook_when);\n}\nstatic const char *register_auth_checker_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"auth_checker\", cmd, _cfg,\n line);\n}", "static const char *register_insert_filter_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return \"LuaHookInsertFilter not yet implemented\";\n}", "static const char *register_quick_hook(cmd_parms *cmd, void *_cfg,\n const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n return register_named_file_function_hook(\"quick\", cmd, _cfg, file,\n function, APR_HOOK_MIDDLE);\n}\nstatic const char *register_map_handler(cmd_parms *cmd, void *_cfg,\n const char* match, const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n if (!function) function = \"handle\";\n return register_mapped_file_function_hook(match, cmd, _cfg, file,\n function);\n}\nstatic const char *register_output_filter(cmd_parms *cmd, void *_cfg,\n const char* filter, const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n if (!function) function = \"handle\";\n return register_filter_function_hook(filter, cmd, _cfg, file,\n function, AP_LUA_FILTER_OUTPUT);\n}\nstatic const char *register_input_filter(cmd_parms *cmd, void *_cfg,\n const char* filter, const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n if (!function) function = \"handle\";\n return register_filter_function_hook(filter, cmd, _cfg, file,\n function, AP_LUA_FILTER_INPUT);\n}\nstatic const char *register_quick_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"quick\", cmd, _cfg,\n line);\n}", "", "static const char *register_package_helper(cmd_parms *cmd, \n const char *arg,\n apr_array_header_t *dir_array)\n{\n apr_status_t rv;", " ap_lua_server_cfg *server_cfg =\n ap_get_module_config(cmd->server->module_config, &lua_module);", " char *fixed_filename;\n rv = apr_filepath_merge(&fixed_filename, \n server_cfg->root_path, \n arg,\n APR_FILEPATH_NOTRELATIVE, \n cmd->pool);", " if (rv != APR_SUCCESS) {\n return apr_psprintf(cmd->pool,\n \"Unable to build full path to file, %s\", arg);\n }", " *(const char **) apr_array_push(dir_array) = fixed_filename;\n return NULL;\n}", "\n/**\n * Called for config directive which looks like\n * LuaPackagePath /lua/package/path/mapped/thing/like/this/?.lua\n */\nstatic const char *register_package_dir(cmd_parms *cmd, void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;", " return register_package_helper(cmd, arg, cfg->package_paths);\n}", "/**\n * Called for config directive which looks like\n * LuaPackageCPath /lua/package/path/mapped/thing/like/this/?.so\n */\nstatic const char *register_package_cdir(cmd_parms *cmd, \n void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;", " return register_package_helper(cmd, arg, cfg->package_cpaths);\n}", "static const char *register_lua_inherit(cmd_parms *cmd, \n void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n \n if (strcasecmp(\"none\", arg) == 0) {\n cfg->inherit = AP_LUA_INHERIT_NONE;\n }\n else if (strcasecmp(\"parent-first\", arg) == 0) {\n cfg->inherit = AP_LUA_INHERIT_PARENT_FIRST;\n }\n else if (strcasecmp(\"parent-last\", arg) == 0) {\n cfg->inherit = AP_LUA_INHERIT_PARENT_LAST;\n }\n else { \n return apr_psprintf(cmd->pool,\n \"LuaInherit type of '%s' not recognized, valid \"\n \"options are 'none', 'parent-first', and 'parent-last'\", \n arg);\n }\n return NULL;\n}\nstatic const char *register_lua_codecache(cmd_parms *cmd, \n void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n \n if (strcasecmp(\"never\", arg) == 0) {\n cfg->codecache = AP_LUA_CACHE_NEVER;\n }\n else if (strcasecmp(\"stat\", arg) == 0) {\n cfg->codecache = AP_LUA_CACHE_STAT;\n }\n else if (strcasecmp(\"forever\", arg) == 0) {\n cfg->codecache = AP_LUA_CACHE_FOREVER;\n }\n else { \n return apr_psprintf(cmd->pool,\n \"LuaCodeCache type of '%s' not recognized, valid \"\n \"options are 'never', 'stat', and 'forever'\", \n arg);\n }\n return NULL;\n}\nstatic const char *register_lua_scope(cmd_parms *cmd, \n void *_cfg,\n const char *scope, \n const char *min,\n const char *max)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n if (strcmp(\"once\", scope) == 0) {\n cfg->vm_scope = AP_LUA_SCOPE_ONCE;\n }\n else if (strcmp(\"request\", scope) == 0) {\n cfg->vm_scope = AP_LUA_SCOPE_REQUEST;\n }\n else if (strcmp(\"conn\", scope) == 0) {\n cfg->vm_scope = AP_LUA_SCOPE_CONN;\n }\n else if (strcmp(\"thread\", scope) == 0) {\n#if !APR_HAS_THREADS\n return apr_psprintf(cmd->pool,\n \"Scope type of '%s' cannot be used because this \"\n \"server does not have threading support \"\n \"(APR_HAS_THREADS)\" \n scope);\n#endif\n cfg->vm_scope = AP_LUA_SCOPE_THREAD;\n }\n else if (strcmp(\"server\", scope) == 0) {\n unsigned int vmin, vmax;\n#if !APR_HAS_THREADS\n return apr_psprintf(cmd->pool,\n \"Scope type of '%s' cannot be used because this \"\n \"server does not have threading support \"\n \"(APR_HAS_THREADS)\" \n scope);\n#endif\n cfg->vm_scope = AP_LUA_SCOPE_SERVER;\n vmin = min ? atoi(min) : 1;\n vmax = max ? atoi(max) : 1;\n if (vmin == 0) {\n vmin = 1;\n }\n if (vmax < vmin) {\n vmax = vmin;\n }\n cfg->vm_min = vmin;\n cfg->vm_max = vmax;\n }\n else {\n return apr_psprintf(cmd->pool,\n \"Invalid value for LuaScope, '%s', acceptable \"\n \"values are: 'once', 'request', 'conn'\"\n#if APR_HAS_THREADS\n \", 'thread', 'server'\"\n#endif\n ,scope);\n }", " return NULL;\n}", "", "static const char *register_lua_root(cmd_parms *cmd, void *_cfg,\n const char *root)\n{\n /* ap_lua_dir_cfg* cfg = (ap_lua_dir_cfg*)_cfg; */\n ap_lua_server_cfg *cfg = ap_get_module_config(cmd->server->module_config,\n &lua_module);", " cfg->root_path = root;\n return NULL;\n}", "const char *ap_lua_ssl_val(apr_pool_t *p, server_rec *s, conn_rec *c,\n request_rec *r, const char *var)\n{\n if (lua_ssl_val) { \n return (const char *)lua_ssl_val(p, s, c, r, (char *)var);\n }\n return NULL;\n}", "int ap_lua_ssl_is_https(conn_rec *c)\n{\n return lua_ssl_is_https ? lua_ssl_is_https(c) : 0;\n}", "/*******************************/", "static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line,\n const void **parsed_require_line)\n{\n const char *provider_name;\n lua_authz_provider_spec *spec;", "", "\n apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE,\n cmd->temp_pool);\n ap_assert(provider_name != NULL);", " spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING);\n ap_assert(spec != NULL);", "", "\n if (require_line && *require_line) {\n const char *arg;", " spec->args = apr_array_make(cmd->pool, 2, sizeof(const char *));", " while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) {", " APR_ARRAY_PUSH(spec->args, const char *) = arg;\n }\n }", " *parsed_require_line = spec;", " return NULL;\n}", "static authz_status lua_authz_check(request_rec *r, const char *require_line,\n const void *parsed_require_line)\n{\n apr_pool_t *pool;\n ap_lua_vm_spec *spec;\n lua_State *L;\n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);", " const lua_authz_provider_spec *prov_spec = parsed_require_line;", " int result;\n int nargs = 0;", " spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name,\n NULL, 0, prov_spec->function_name, \"authz provider\");", " L = ap_lua_get_lua_state(pool, spec, r);\n if (L == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314)\n \"Unable to compile VM for authz provider %s\", prov_spec->name);\n return AUTHZ_GENERAL_ERROR;\n }\n lua_getglobal(L, prov_spec->function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319)\n \"Unable to find entry function '%s' in %s (not a valid function)\",\n prov_spec->function_name, prov_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }\n ap_lua_run_lua_request(L, r);", " if (prov_spec->args) {", " int i;", " if (!lua_checkstack(L, prov_spec->args->nelts)) {", " ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315)\n \"Error: authz provider %s: too many arguments\", prov_spec->name);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }", " for (i = 0; i < prov_spec->args->nelts; i++) {\n const char *arg = APR_ARRAY_IDX(prov_spec->args, i, const char *);", " lua_pushstring(L, arg);\n }", " nargs = prov_spec->args->nelts;", " }\n if (lua_pcall(L, 1 + nargs, 1, 0)) {\n const char *err = lua_tostring(L, -1);\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316)\n \"Error executing authz provider %s: %s\", prov_spec->name, err);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }\n if (!lua_isnumber(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317)\n \"Error: authz provider %s did not return integer\", prov_spec->name);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }\n result = lua_tointeger(L, -1);\n ap_lua_release_state(L, spec, r);\n switch (result) {\n case AUTHZ_DENIED:\n case AUTHZ_GRANTED:\n case AUTHZ_NEUTRAL:\n case AUTHZ_GENERAL_ERROR:\n case AUTHZ_DENIED_NO_USER:\n return result;\n default:\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318)\n \"Error: authz provider %s: invalid return value %d\",\n prov_spec->name, result);\n }\n return AUTHZ_GENERAL_ERROR;\n}", "static const authz_provider lua_authz_provider =\n{\n &lua_authz_check,\n &lua_authz_parse,\n};", "static const char *register_authz_provider(cmd_parms *cmd, void *_cfg,\n const char *name, const char *file,\n const char *function)\n{\n lua_authz_provider_spec *spec;\n const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);\n if (err)\n return err;", " spec = apr_pcalloc(cmd->pool, sizeof(*spec));\n spec->name = name;\n spec->file_name = file;\n spec->function_name = function;", " apr_hash_set(lua_authz_providers, name, APR_HASH_KEY_STRING, spec);\n ap_register_auth_provider(cmd->pool, AUTHZ_PROVIDER_GROUP, name,\n AUTHZ_PROVIDER_VERSION,\n &lua_authz_provider,\n AP_AUTH_INTERNAL_PER_CONF);\n return NULL;\n}", "\ncommand_rec lua_commands[] = {", " AP_INIT_TAKE1(\"LuaRoot\", register_lua_root, NULL, OR_ALL,\n \"Specify the base path for resolving relative paths for mod_lua directives\"),", " AP_INIT_TAKE1(\"LuaPackagePath\", register_package_dir, NULL, OR_ALL,\n \"Add a directory to lua's package.path\"),", " AP_INIT_TAKE1(\"LuaPackageCPath\", register_package_cdir, NULL, OR_ALL,\n \"Add a directory to lua's package.cpath\"),", " AP_INIT_TAKE3(\"LuaAuthzProvider\", register_authz_provider, NULL, RSRC_CONF|EXEC_ON_READ,\n \"Provide an authorization provider\"),", " AP_INIT_TAKE23(\"LuaHookTranslateName\", register_translate_name_hook, NULL,\n OR_ALL,\n \"Provide a hook for the translate name phase of request processing\"),", " AP_INIT_RAW_ARGS(\"<LuaHookTranslateName\", register_translate_name_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the translate name phase of request processing\"),", " AP_INIT_TAKE2(\"LuaHookFixups\", register_fixups_hook, NULL, OR_ALL,\n \"Provide a hook for the fixups phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookFixups\", register_fixups_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a inline hook for the fixups phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE2(\"LuaHookMapToStorage\", register_map_to_storage_hook, NULL,\n OR_ALL,\n \"Provide a hook for the map_to_storage phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookMapToStorage\", register_map_to_storage_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the map_to_storage phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE23(\"LuaHookCheckUserID\", register_check_user_id_hook, NULL,\n OR_ALL,\n \"Provide a hook for the check_user_id phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookCheckUserID\", register_check_user_id_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the check_user_id phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE2(\"LuaHookTypeChecker\", register_type_checker_hook, NULL,\n OR_ALL,\n \"Provide a hook for the type_checker phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookTypeChecker\", register_type_checker_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the type_checker phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE23(\"LuaHookAccessChecker\", register_access_checker_hook, NULL,\n OR_ALL,\n \"Provide a hook for the access_checker phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookAccessChecker\", register_access_checker_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the access_checker phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE23(\"LuaHookAuthChecker\", register_auth_checker_hook, NULL,\n OR_ALL,\n \"Provide a hook for the auth_checker phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookAuthChecker\", register_auth_checker_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the auth_checker phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE2(\"LuaHookInsertFilter\", register_insert_filter_hook, NULL,\n OR_ALL,\n \"Provide a hook for the insert_filter phase of request processing\"),\n \n AP_INIT_TAKE2(\"LuaHookLog\", register_log_transaction_hook, NULL,\n OR_ALL,\n \"Provide a hook for the logging phase of request processing\"),", " AP_INIT_TAKE123(\"LuaScope\", register_lua_scope, NULL, OR_ALL,\n \"One of once, request, conn, server -- default is once\"),", " AP_INIT_TAKE1(\"LuaInherit\", register_lua_inherit, NULL, OR_ALL,\n \"Controls how Lua scripts in parent contexts are merged with the current \" \n \" context: none|parent-last|parent-first (default: parent-first) \"),\n \n AP_INIT_TAKE1(\"LuaCodeCache\", register_lua_codecache, NULL, OR_ALL,\n \"Controls the behavior of the in-memory code cache \" \n \" context: stat|forever|never (default: stat) \"),", " AP_INIT_TAKE2(\"LuaQuickHandler\", register_quick_hook, NULL, OR_ALL,\n \"Provide a hook for the quick handler of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaQuickHandler\", register_quick_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the quick handler of request processing\"),\n AP_INIT_RAW_ARGS(\"Lua_____ByteCodeHack\", hack_section_handler, NULL,\n OR_ALL,\n \"(internal) Byte code handler\"),\n AP_INIT_TAKE23(\"LuaMapHandler\", register_map_handler, NULL, OR_ALL,\n \"Maps a path to a lua handler\"),\n AP_INIT_TAKE3(\"LuaOutputFilter\", register_output_filter, NULL, OR_ALL,\n \"Registers a Lua function as an output filter\"),\n AP_INIT_TAKE3(\"LuaInputFilter\", register_input_filter, NULL, OR_ALL,\n \"Registers a Lua function as an input filter\"),\n {NULL}\n};", "\nstatic void *create_dir_config(apr_pool_t *p, char *dir)\n{\n ap_lua_dir_cfg *cfg = apr_pcalloc(p, sizeof(ap_lua_dir_cfg));\n cfg->package_paths = apr_array_make(p, 2, sizeof(char *));\n cfg->package_cpaths = apr_array_make(p, 2, sizeof(char *));\n cfg->mapped_handlers =\n apr_array_make(p, 1, sizeof(ap_lua_mapped_handler_spec *));\n cfg->mapped_filters =\n apr_array_make(p, 1, sizeof(ap_lua_filter_handler_spec *));\n cfg->pool = p;\n cfg->hooks = apr_hash_make(p);\n cfg->dir = apr_pstrdup(p, dir);\n cfg->vm_scope = AP_LUA_SCOPE_UNSET;\n cfg->codecache = AP_LUA_CACHE_UNSET;\n cfg->vm_min = 0;\n cfg->vm_max = 0;", " return cfg;\n}", "static int create_request_config(request_rec *r)\n{\n ap_lua_request_cfg *cfg = apr_palloc(r->pool, sizeof(ap_lua_request_cfg));\n cfg->mapped_request_details = NULL;\n cfg->request_scoped_vms = apr_hash_make(r->pool);\n ap_set_module_config(r->request_config, &lua_module, cfg);\n return OK;\n}", "static void *create_server_config(apr_pool_t *p, server_rec *s)\n{", " ap_lua_server_cfg *cfg = apr_pcalloc(p, sizeof(ap_lua_server_cfg));\n cfg->vm_reslists = apr_hash_make(p);\n apr_thread_rwlock_create(&cfg->vm_reslists_lock, p);\n cfg->root_path = NULL;", " return cfg;\n}", "static int lua_request_hook(lua_State *L, request_rec *r)\n{\n ap_lua_push_request(L, r);\n return OK;\n}", "static int lua_pre_config(apr_pool_t *pconf, apr_pool_t *plog,\n apr_pool_t *ptemp)\n{\n ap_mutex_register(pconf, \"lua-ivm-shm\", NULL, APR_LOCK_DEFAULT, 0);\n return OK;\n}", "static int lua_post_config(apr_pool_t *pconf, apr_pool_t *plog,\n apr_pool_t *ptemp, server_rec *s)\n{\n apr_pool_t **pool;\n const char *tempdir;\n apr_status_t rs;", " lua_ssl_val = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);\n lua_ssl_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);\n \n if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)\n return OK;", " /* Create ivm mutex */\n rs = ap_global_mutex_create(&lua_ivm_mutex, NULL, \"lua-ivm-shm\", NULL,\n s, pconf, 0);\n if (APR_SUCCESS != rs) {\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " /* Create shared memory space */\n rs = apr_temp_dir_get(&tempdir, pconf);\n if (rs != APR_SUCCESS) {\n ap_log_error(APLOG_MARK, APLOG_ERR, rs, s, APLOGNO(02664)\n \"mod_lua IVM: Failed to find temporary directory\");\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n lua_ivm_shmfile = apr_psprintf(pconf, \"%s/httpd_lua_shm.%ld\", tempdir,\n (long int)getpid());\n rs = apr_shm_create(&lua_ivm_shm, sizeof(apr_pool_t**),\n (const char *) lua_ivm_shmfile, pconf);\n if (rs != APR_SUCCESS) {\n ap_log_error(APLOG_MARK, APLOG_ERR, rs, s, APLOGNO(02665)\n \"mod_lua: Failed to create shared memory segment on file %s\",\n lua_ivm_shmfile);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n pool = (apr_pool_t **)apr_shm_baseaddr_get(lua_ivm_shm);\n apr_pool_create(pool, pconf);\n apr_pool_cleanup_register(pconf, NULL, shm_cleanup_wrapper,\n apr_pool_cleanup_null);\n return OK;\n}\nstatic void *overlay_hook_specs(apr_pool_t *p,\n const void *key,\n apr_ssize_t klen,\n const void *overlay_val,\n const void *base_val,\n const void *data)\n{\n const apr_array_header_t *overlay_info = (const apr_array_header_t*)overlay_val;\n const apr_array_header_t *base_info = (const apr_array_header_t*)base_val;\n return apr_array_append(p, base_info, overlay_info);\n}", "static void *merge_dir_config(apr_pool_t *p, void *basev, void *overridesv)\n{\n ap_lua_dir_cfg *a, *base, *overrides;", " a = (ap_lua_dir_cfg *)apr_pcalloc(p, sizeof(ap_lua_dir_cfg));\n base = (ap_lua_dir_cfg*)basev;\n overrides = (ap_lua_dir_cfg*)overridesv;", " a->pool = overrides->pool;\n a->dir = apr_pstrdup(p, overrides->dir);", " a->vm_scope = (overrides->vm_scope == AP_LUA_SCOPE_UNSET) ? base->vm_scope: overrides->vm_scope;\n a->inherit = (overrides->inherit == AP_LUA_INHERIT_UNSET) ? base->inherit : overrides->inherit;\n a->codecache = (overrides->codecache == AP_LUA_CACHE_UNSET) ? base->codecache : overrides->codecache;\n \n a->vm_min = (overrides->vm_min == 0) ? base->vm_min : overrides->vm_min;\n a->vm_max = (overrides->vm_max == 0) ? base->vm_max : overrides->vm_max;", " if (a->inherit == AP_LUA_INHERIT_UNSET || a->inherit == AP_LUA_INHERIT_PARENT_FIRST) { \n a->package_paths = apr_array_append(p, base->package_paths, overrides->package_paths);\n a->package_cpaths = apr_array_append(p, base->package_cpaths, overrides->package_cpaths);\n a->mapped_handlers = apr_array_append(p, base->mapped_handlers, overrides->mapped_handlers);\n a->mapped_filters = apr_array_append(p, base->mapped_filters, overrides->mapped_filters);\n a->hooks = apr_hash_merge(p, overrides->hooks, base->hooks, overlay_hook_specs, NULL);\n }\n else if (a->inherit == AP_LUA_INHERIT_PARENT_LAST) { \n a->package_paths = apr_array_append(p, overrides->package_paths, base->package_paths);\n a->package_cpaths = apr_array_append(p, overrides->package_cpaths, base->package_cpaths);\n a->mapped_handlers = apr_array_append(p, overrides->mapped_handlers, base->mapped_handlers);\n a->mapped_filters = apr_array_append(p, overrides->mapped_filters, base->mapped_filters);\n a->hooks = apr_hash_merge(p, base->hooks, overrides->hooks, overlay_hook_specs, NULL);\n }\n else { \n a->package_paths = overrides->package_paths;\n a->package_cpaths = overrides->package_cpaths;\n a->mapped_handlers= overrides->mapped_handlers;\n a->mapped_filters= overrides->mapped_filters;\n a->hooks= overrides->hooks;\n }", " return a;\n}", "static void lua_register_hooks(apr_pool_t *p)\n{\n /* ap_register_output_filter(\"luahood\", luahood, NULL, AP_FTYPE_RESOURCE); */\n ap_hook_handler(lua_handler, NULL, NULL, APR_HOOK_MIDDLE);\n ap_hook_create_request(create_request_config, NULL, NULL,\n APR_HOOK_MIDDLE);", " /* http_request.h hooks */\n ap_hook_translate_name(lua_translate_name_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n ap_hook_translate_name(lua_translate_name_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_translate_name(lua_translate_name_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);", " ap_hook_fixups(lua_fixup_harness, NULL, NULL, APR_HOOK_MIDDLE);\n ap_hook_map_to_storage(lua_map_to_storage_harness, NULL, NULL,\n APR_HOOK_MIDDLE);", "/* XXX: Does not work :( \n * ap_hook_check_user_id(lua_check_user_id_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n */\n ap_hook_check_user_id(lua_check_user_id_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n/* XXX: Does not work :(\n * ap_hook_check_user_id(lua_check_user_id_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);\n*/\n ap_hook_type_checker(lua_type_checker_harness, NULL, NULL,\n APR_HOOK_MIDDLE);", " ap_hook_access_checker(lua_access_checker_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n ap_hook_access_checker(lua_access_checker_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_access_checker(lua_access_checker_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);\n ap_hook_auth_checker(lua_auth_checker_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n ap_hook_auth_checker(lua_auth_checker_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_auth_checker(lua_auth_checker_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);", " ap_hook_insert_filter(lua_insert_filter_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_quick_handler(lua_quick_harness, NULL, NULL, APR_HOOK_FIRST);", " ap_hook_post_config(lua_post_config, NULL, NULL, APR_HOOK_MIDDLE);\n ap_hook_pre_config(lua_pre_config, NULL, NULL, APR_HOOK_MIDDLE);", " APR_OPTIONAL_HOOK(ap_lua, lua_open, lua_open_hook, NULL, NULL,\n APR_HOOK_REALLY_FIRST);", " APR_OPTIONAL_HOOK(ap_lua, lua_request, lua_request_hook, NULL, NULL,\n APR_HOOK_REALLY_FIRST);\n ap_hook_handler(lua_map_handler, NULL, NULL, AP_LUA_HOOK_FIRST);\n \n /* Hook this right before FallbackResource kicks in */\n ap_hook_fixups(lua_map_handler_fixups, NULL, NULL, AP_LUA_HOOK_LAST-2);\n#if APR_HAS_THREADS\n ap_hook_child_init(ap_lua_init_mutex, NULL, NULL, APR_HOOK_MIDDLE);\n#endif\n /* providers */\n lua_authz_providers = apr_hash_make(p);\n \n /* Logging catcher */\n ap_hook_log_transaction(lua_log_transaction_harness,NULL,NULL,\n APR_HOOK_FIRST);\n}", "AP_DECLARE_MODULE(lua) = {\n STANDARD20_MODULE_STUFF,\n create_dir_config, /* create per-dir config structures */\n merge_dir_config, /* merge per-dir config structures */\n create_server_config, /* create per-server config structures */\n NULL, /* merge per-server config structures */\n lua_commands, /* table of config file commands */\n lua_register_hooks /* register hooks */\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 114, 1760], "buggy_code_start_loc": [11, 107, 68], "filenames": ["CHANGES", "STATUS", "modules/lua/mod_lua.c"], "fixing_code_end_loc": [17, 106, 1767], "fixing_code_start_loc": [12, 106, 69], "message": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:http_server:2.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "6FCD3C8C-9BF8-4F30-981A-593EEAEB9EDD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "046487A3-752B-4D0F-8984-96486B828EAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "89D2E052-51CD-4B57-A8B8-FAE51988D654", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "EAA27058-BACF-4F94-8E3C-7D38EC302EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "8FEAB0DF-04A9-4F99-8666-0BADC5D642B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E7D924D1-8A36-4C43-9E56-52814F9A6350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "39CDFECC-E26D-47E0-976F-6629040B3764", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "E3ECBCB1-0675-41F5-857B-438F36925F63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:-:*:*:*", "matchCriteriaId": "CB66DB75-2B16-4EBF-9B93-CE49D8086E41", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.10:*:*:*:*:*:*:*", "matchCriteriaId": "49A63F39-30BE-443F-AF10-6245587D3359", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:21:*:*:*:*:*:*:*", "matchCriteriaId": "56BDB5A0-0839-4A20-A003-B8CD56F48171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:*:*:*:*:*:*:*:*", "matchCriteriaId": "A70BB445-EF2B-4C9D-8502-FDD6A19F8C30", "versionEndExcluding": "12.1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "4725EA61-9BAB-4E72-9F92-ADE4624439CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0879FB1-58E2-4EC4-8111-044642E046BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "C7CF2929-4CBC-4B56-87AE-F45F53BD8DD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory."}, {"lang": "es", "value": "El m\u00f3dulo mod_lua.c en el m\u00f3dulo mod_lua en Apache HTTP Server 2.3.x y 2.4.x a trav\u00e9s de 2.4.10 no soporta la configuraci\u00f3n httpd en la cual el proveedor de autorizaci\u00f3n Lua se usa con argumentos diferentes dentro de contextos diferentes, lo que permite a atacantes remotos saltarse las restricciones de acceso en ciertas circunstancias aprovechando m\u00faltiples directivas requeridas, como se demuestra por una configuraci\u00f3n que especifica la autorizaci\u00f3n para un grupo para acceder a un directorio determinado, y una autorizaci\u00f3n para un segundo grupo para acceder a un segundo directorio."}], "evaluatorComment": null, "id": "CVE-2014-8109", "lastModified": "2023-02-13T00:42:40.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-29T23:59:00.053", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://advisories.mageia.org/MGASA-2015-0011.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Aug/msg00001.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Sep/msg00004.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2015-June/159352.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/28/5"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/cpujan2016-2367955.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/73040"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2523-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1174077"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://issues.apache.org/bugzilla/show_bug.cgi?id=57204"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/56c2e7cc9deb1c12a843d0dc251ea7fd3e7e80293cde02fcd65286ba%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/84a3714f0878781f6ed84473d1a503d2cc382277e100450209231830%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r76142b8c5119df2178be7c2dba88fde552eedeec37ea993dfce68d1d%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r83109088737656fa6307bd99ab40f8ff0269ae58d3f7272d7048494a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r9f93cf6dde308d42a9c807784e8102600d0397f5f834890708bf6920%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/ra7f6aeb28661fbf826969526585f16856abc4615877875f9d3b35ef4%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rb14daf9cc4e28d18cdc15d6a6ca74e565672fabf7ad89541071d008b%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rc998b18880df98bafaade071346690c2bc1444adaa1a1ea464b93f0a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rcc44594d4d6579b90deccd4536b5d31f099ef563df39b094be286b9e%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rd18c3c43602e66f9cdcf09f1de233804975b9572b0456cc582390b6f%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/re3d27b6250aa8548b8845d314bb8a350b3df326cacbbfdfe4d455234%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rf6449464fd8b7437704c55f88361b66f12d5b5f90bcce66af4be4ba9%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT205219"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT205031"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, "type": "CWE-863"}
296
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#include \"mod_lua.h\"\n#include <string.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <apr_thread_mutex.h>\n#include <apr_pools.h>\n#include \"lua_apr.h\"\n#include \"lua_config.h\"\n#include \"apr_optional.h\"\n#include \"mod_ssl.h\"\n#include \"mod_auth.h\"\n#include \"util_mutex.h\"", "\n#ifdef APR_HAS_THREADS\n#include \"apr_thread_proc.h\"\n#endif", "/* getpid for *NIX */\n#if APR_HAVE_SYS_TYPES_H\n#include <sys/types.h>\n#endif\n#if APR_HAVE_UNISTD_H\n#include <unistd.h>\n#endif", "/* getpid for Windows */\n#if APR_HAVE_PROCESS_H\n#include <process.h>\n#endif", "APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap_lua, AP_LUA, int, lua_open,\n (lua_State *L, apr_pool_t *p),\n (L, p), OK, DECLINED)", "APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap_lua, AP_LUA, int, lua_request,\n (lua_State *L, request_rec *r),\n (L, r), OK, DECLINED)\nstatic APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *lua_ssl_val = NULL;\nstatic APR_OPTIONAL_FN_TYPE(ssl_is_https) *lua_ssl_is_https = NULL;", "module AP_MODULE_DECLARE_DATA lua_module;", "#define AP_LUA_HOOK_FIRST (APR_HOOK_FIRST - 1)\n#define AP_LUA_HOOK_LAST (APR_HOOK_LAST + 1)", "typedef struct {\n const char *name;\n const char *file_name;\n const char *function_name;\n ap_lua_vm_spec *spec;", "} lua_authz_provider_spec;", "typedef struct {\n lua_authz_provider_spec *spec;", " apr_array_header_t *args;", "} lua_authz_provider_func;", "\napr_hash_t *lua_authz_providers;", "typedef struct\n{\n apr_bucket_brigade *tmpBucket;\n lua_State *L;\n ap_lua_vm_spec *spec;\n int broken;\n} lua_filter_ctx;", "apr_global_mutex_t *lua_ivm_mutex;\napr_shm_t *lua_ivm_shm;\nchar *lua_ivm_shmfile;", "static apr_status_t shm_cleanup_wrapper(void *unused) {\n if (lua_ivm_shm) {\n return apr_shm_destroy(lua_ivm_shm);\n }\n return OK;\n}", "/**\n * error reporting if lua has an error.\n * Extracts the error from lua stack and prints\n */\nstatic void report_lua_error(lua_State *L, request_rec *r)\n{\n const char *lua_response;\n r->status = HTTP_INTERNAL_SERVER_ERROR;\n r->content_type = \"text/html\";\n ap_rputs(\"<h3>Error!</h3>\\n\", r);\n ap_rputs(\"<pre>\", r);\n lua_response = lua_tostring(L, -1);\n ap_rputs(ap_escape_html(r->pool, lua_response), r);\n ap_rputs(\"</pre>\\n\", r);", " ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, r->pool, APLOGNO(01471) \"Lua error: %s\",\n lua_response);\n}", "static void lua_open_callback(lua_State *L, apr_pool_t *p, void *ctx)\n{\n ap_lua_init(L, p);\n ap_lua_load_apache2_lmodule(L);\n ap_lua_load_request_lmodule(L, p);\n ap_lua_load_config_lmodule(L);\n}", "static int lua_open_hook(lua_State *L, apr_pool_t *p)\n{\n lua_open_callback(L, p, NULL);\n return OK;\n}", "static const char *scope_to_string(unsigned int scope)\n{\n switch (scope) {\n case AP_LUA_SCOPE_ONCE:\n case AP_LUA_SCOPE_UNSET:\n return \"once\";\n case AP_LUA_SCOPE_REQUEST:\n return \"request\";\n case AP_LUA_SCOPE_CONN:\n return \"conn\";\n#if APR_HAS_THREADS\n case AP_LUA_SCOPE_THREAD:\n return \"thread\";\n case AP_LUA_SCOPE_SERVER:\n return \"server\";\n#endif\n default:\n ap_assert(0);\n return 0;\n }\n}", "static void ap_lua_release_state(lua_State* L, ap_lua_vm_spec* spec, request_rec* r) {\n char *hash;\n apr_reslist_t* reslist = NULL;\n if (spec->scope == AP_LUA_SCOPE_SERVER) {\n ap_lua_server_spec* sspec = NULL;\n lua_settop(L, 0);\n lua_getfield(L, LUA_REGISTRYINDEX, \"Apache2.Lua.server_spec\");\n sspec = (ap_lua_server_spec*) lua_touserdata(L, 1);\n hash = apr_psprintf(r->pool, \"reslist:%s\", spec->file);\n if (apr_pool_userdata_get((void **)&reslist, hash,\n r->server->process->pool) == APR_SUCCESS) {\n AP_DEBUG_ASSERT(sspec != NULL);\n if (reslist != NULL) {\n apr_reslist_release(reslist, sspec);\n }\n }\n }\n}", "static ap_lua_vm_spec *create_vm_spec(apr_pool_t **lifecycle_pool,\n request_rec *r,\n const ap_lua_dir_cfg *cfg,\n const ap_lua_server_cfg *server_cfg,\n const char *filename,\n const char *bytecode,\n apr_size_t bytecode_len,\n const char *function,\n const char *what)\n{\n apr_pool_t *pool;\n ap_lua_vm_spec *spec = apr_pcalloc(r->pool, sizeof(ap_lua_vm_spec));", " spec->scope = cfg->vm_scope;\n spec->pool = r->pool;\n spec->package_paths = cfg->package_paths;\n spec->package_cpaths = cfg->package_cpaths;\n spec->cb = &lua_open_callback;\n spec->cb_arg = NULL;\n spec->bytecode = bytecode;\n spec->bytecode_len = bytecode_len;\n spec->codecache = (cfg->codecache == AP_LUA_CACHE_UNSET) ? AP_LUA_CACHE_STAT : cfg->codecache;\n spec->vm_min = cfg->vm_min ? cfg->vm_min : 1;\n spec->vm_max = cfg->vm_max ? cfg->vm_max : 1;\n \n if (filename) {\n char *file;\n apr_filepath_merge(&file, server_cfg->root_path,\n filename, APR_FILEPATH_NOTRELATIVE, r->pool);\n spec->file = file;\n }\n else {\n spec->file = r->filename;\n }\n ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, APLOGNO(02313)\n \"%s details: scope: %s, file: %s, func: %s\",\n what, scope_to_string(spec->scope), spec->file,\n function ? function : \"-\");", " switch (spec->scope) {\n case AP_LUA_SCOPE_ONCE:\n case AP_LUA_SCOPE_UNSET:\n apr_pool_create(&pool, r->pool);\n break;\n case AP_LUA_SCOPE_REQUEST:\n pool = r->pool;\n break;\n case AP_LUA_SCOPE_CONN:\n pool = r->connection->pool;\n break;\n#if APR_HAS_THREADS\n case AP_LUA_SCOPE_THREAD:\n pool = apr_thread_pool_get(r->connection->current_thread);\n break;\n case AP_LUA_SCOPE_SERVER:\n pool = r->server->process->pool;\n break;\n#endif\n default:\n ap_assert(0);\n }", " *lifecycle_pool = pool;\n return spec;\n}", "static const char* ap_lua_interpolate_string(apr_pool_t* pool, const char* string, const char** values)\n{\n char *stringBetween;\n const char* ret;\n int srclen,x,y;\n srclen = strlen(string);\n ret = \"\";\n y = 0;\n for (x=0; x < srclen; x++) {\n if (string[x] == '$' && x != srclen-1 && string[x+1] >= '0' && string[x+1] <= '9') {\n int v = *(string+x+1) - '0';\n if (x-y > 0) {\n stringBetween = apr_pstrndup(pool, string+y, x-y);\n }\n else {\n stringBetween = \"\";\n }\n ret = apr_pstrcat(pool, ret, stringBetween, values[v], NULL);\n y = ++x+1;\n }\n }\n \n if (x-y > 0 && y > 0) {\n stringBetween = apr_pstrndup(pool, string+y, x-y);\n ret = apr_pstrcat(pool, ret, stringBetween, NULL);\n }\n /* If no replacement was made, just return the original string */\n else if (y == 0) {\n return string;\n }\n return ret;\n}", "", "/**\n * \"main\"\n */\nstatic int lua_handler(request_rec *r)\n{\n int rc = OK;\n if (strcmp(r->handler, \"lua-script\")) {\n return DECLINED;\n }\n /* Decline the request if the script does not exist (or is a directory),\n * rather than just returning internal server error */\n if (\n (r->finfo.filetype == APR_NOFILE)\n || (r->finfo.filetype & APR_DIR)\n ) {\n return DECLINED;\n }\n ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, APLOGNO(01472)\n \"handling [%s] in mod_lua\", r->filename);", " /* XXX: This seems wrong because it may generate wrong headers for HEAD requests */\n if (!r->header_only) {\n lua_State *L;\n apr_pool_t *pool;\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n ap_lua_vm_spec *spec = create_vm_spec(&pool, r, cfg, NULL, NULL, NULL,\n 0, \"handle\", \"request handler\");", " L = ap_lua_get_lua_state(pool, spec, r);\n if (!L) {\n /* TODO annotate spec with failure reason */\n r->status = HTTP_INTERNAL_SERVER_ERROR;\n ap_rputs(\"Unable to compile VM, see logs\", r);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, APLOGNO(01474) \"got a vm!\");\n lua_getglobal(L, \"handle\");\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01475)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n \"handle\",\n spec->file);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n ap_lua_run_lua_request(L, r);\n if (lua_pcall(L, 1, 1, 0)) {\n report_lua_error(L, r);\n }\n if (lua_isnumber(L, -1)) {\n rc = lua_tointeger(L, -1);\n }\n ap_lua_release_state(L, spec, r);\n }\n return rc;\n}", "\n/* ------------------- Input/output content filters ------------------- */", "\nstatic apr_status_t lua_setup_filter_ctx(ap_filter_t* f, request_rec* r, lua_filter_ctx** c) {\n apr_pool_t *pool;\n ap_lua_vm_spec *spec;\n int n, rc;\n lua_State *L;\n lua_filter_ctx *ctx; \n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n \n ctx = apr_pcalloc(r->pool, sizeof(lua_filter_ctx));\n ctx->broken = 0;\n *c = ctx;\n /* Find the filter that was called.\n * XXX: If we were wired with mod_filter, the filter (mod_filters name)\n * and the provider (our underlying filters name) need to have matched.\n */\n for (n = 0; n < cfg->mapped_filters->nelts; n++) {\n ap_lua_filter_handler_spec *hook_spec =\n ((ap_lua_filter_handler_spec **) cfg->mapped_filters->elts)[n];", " if (hook_spec == NULL) {\n continue;\n }\n if (!strcasecmp(hook_spec->filter_name, f->frec->name)) {\n spec = create_vm_spec(&pool, r, cfg, server_cfg,\n hook_spec->file_name,\n NULL,\n 0,\n hook_spec->function_name,\n \"filter\");\n L = ap_lua_get_lua_state(pool, spec, r);\n if (L) {\n L = lua_newthread(L);\n }", " if (!L) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02328)\n \"lua: Failed to obtain lua interpreter for %s %s\",\n hook_spec->function_name, hook_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return APR_EGENERAL;\n }\n if (hook_spec->function_name != NULL) {\n lua_getglobal(L, hook_spec->function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02329)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n hook_spec->function_name,\n hook_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return APR_EGENERAL;\n }", " ap_lua_run_lua_request(L, r);\n }\n else {\n int t;\n ap_lua_run_lua_request(L, r);", " t = lua_gettop(L);\n lua_setglobal(L, \"r\");\n lua_settop(L, t);\n }\n ctx->L = L;\n ctx->spec = spec;\n \n /* If a Lua filter is interested in filtering a request, it must first do a yield, \n * otherwise we'll assume that it's not interested and pretend we didn't find it.\n */\n rc = lua_resume(L, 1);\n if (rc == LUA_YIELD) {\n if (f->frec->providers == NULL) { \n /* Not wired by mod_filter */\n apr_table_unset(r->headers_out, \"Content-Length\");\n apr_table_unset(r->headers_out, \"Content-MD5\");\n apr_table_unset(r->headers_out, \"ETAG\");\n }\n return OK;\n }\n else {\n ap_lua_release_state(L, spec, r);\n return APR_ENOENT;\n }\n }\n }\n return APR_ENOENT;\n}", "static apr_status_t lua_output_filter_handle(ap_filter_t *f, apr_bucket_brigade *pbbIn) {\n request_rec *r = f->r;\n int rc;\n lua_State *L;\n lua_filter_ctx* ctx;\n conn_rec *c = r->connection;\n apr_bucket *pbktIn;\n apr_status_t rv;\n \n /* Set up the initial filter context and acquire the function.\n * The corresponding Lua function should yield here.\n */\n if (!f->ctx) {\n rc = lua_setup_filter_ctx(f,r,&ctx);\n if (rc == APR_EGENERAL) {\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n if (rc == APR_ENOENT) {\n /* No filter entry found (or the script declined to filter), just pass on the buckets */\n ap_remove_output_filter(f);\n return ap_pass_brigade(f->next,pbbIn);\n }\n else { \n /* We've got a willing lua filter, setup and check for a prefix */\n size_t olen;\n apr_bucket *pbktOut;\n const char* output = lua_tolstring(ctx->L, 1, &olen);", " f->ctx = ctx;\n ctx->tmpBucket = apr_brigade_create(r->pool, c->bucket_alloc);", " if (olen > 0) { \n pbktOut = apr_bucket_heap_create(output, olen, NULL, c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktOut);\n rv = ap_pass_brigade(f->next, ctx->tmpBucket);\n apr_brigade_cleanup(ctx->tmpBucket);\n if (rv != APR_SUCCESS) {\n return rv;\n }\n }\n }\n }\n ctx = (lua_filter_ctx*) f->ctx;\n L = ctx->L;\n /* While the Lua function is still yielding, pass in buckets to the coroutine */\n if (!ctx->broken) {\n for (pbktIn = APR_BRIGADE_FIRST(pbbIn);\n pbktIn != APR_BRIGADE_SENTINEL(pbbIn);\n pbktIn = APR_BUCKET_NEXT(pbktIn))\n {\n const char *data;\n apr_size_t len;\n apr_bucket *pbktOut;", " /* read the bucket */\n apr_bucket_read(pbktIn,&data,&len,APR_BLOCK_READ);", " /* Push the bucket onto the Lua stack as a global var */\n lua_pushlstring(L, data, len);\n lua_setglobal(L, \"bucket\");\n \n /* If Lua yielded, it means we have something to pass on */\n if (lua_resume(L, 0) == LUA_YIELD) {\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n if (olen > 0) { \n pbktOut = apr_bucket_heap_create(output, olen, NULL,\n c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktOut);\n rv = ap_pass_brigade(f->next, ctx->tmpBucket);\n apr_brigade_cleanup(ctx->tmpBucket);\n if (rv != APR_SUCCESS) {\n return rv;\n }\n }\n }\n else {\n ctx->broken = 1;\n ap_lua_release_state(L, ctx->spec, r);\n ap_remove_output_filter(f);\n apr_brigade_cleanup(pbbIn);\n apr_brigade_cleanup(ctx->tmpBucket);\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02663)\n \"lua: Error while executing filter: %s\",\n lua_tostring(L, -1));\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n }\n /* If we've safely reached the end, do a final call to Lua to allow for any \n finishing moves by the script, such as appending a tail. */\n if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(pbbIn))) {\n apr_bucket *pbktEOS;\n lua_pushnil(L);\n lua_setglobal(L, \"bucket\");\n if (lua_resume(L, 0) == LUA_YIELD) {\n apr_bucket *pbktOut;\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n if (olen > 0) { \n pbktOut = apr_bucket_heap_create(output, olen, NULL,\n c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktOut);\n }\n }\n pbktEOS = apr_bucket_eos_create(c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(ctx->tmpBucket, pbktEOS);\n ap_lua_release_state(L, ctx->spec, r);\n rv = ap_pass_brigade(f->next, ctx->tmpBucket);\n apr_brigade_cleanup(ctx->tmpBucket);\n if (rv != APR_SUCCESS) {\n return rv;\n }\n }\n }\n /* Clean up */\n apr_brigade_cleanup(pbbIn);\n return APR_SUCCESS; \n}", "", "static apr_status_t lua_input_filter_handle(ap_filter_t *f,\n apr_bucket_brigade *pbbOut,\n ap_input_mode_t eMode,\n apr_read_type_e eBlock,\n apr_off_t nBytes) \n{\n request_rec *r = f->r;\n int rc, lastCall = 0;\n lua_State *L;\n lua_filter_ctx* ctx;\n conn_rec *c = r->connection;\n apr_status_t ret;\n \n /* Set up the initial filter context and acquire the function.\n * The corresponding Lua function should yield here.\n */\n if (!f->ctx) {\n rc = lua_setup_filter_ctx(f,r,&ctx);\n f->ctx = ctx;\n if (rc == APR_EGENERAL) {\n ctx->broken = 1;\n ap_remove_input_filter(f); \n return HTTP_INTERNAL_SERVER_ERROR;\n }\n if (rc == APR_ENOENT ) {\n ap_remove_input_filter(f);\n ctx->broken = 1;\n }\n if (rc == APR_SUCCESS) {\n ctx->tmpBucket = apr_brigade_create(r->pool, c->bucket_alloc);\n }\n }\n ctx = (lua_filter_ctx*) f->ctx;\n L = ctx->L;\n /* If the Lua script broke or denied serving the request, just pass the buckets through */\n if (ctx->broken) {\n return ap_get_brigade(f->next, pbbOut, eMode, eBlock, nBytes);\n }\n \n if (APR_BRIGADE_EMPTY(ctx->tmpBucket)) {\n ret = ap_get_brigade(f->next, ctx->tmpBucket, eMode, eBlock, nBytes);\n if (eMode == AP_MODE_EATCRLF || ret != APR_SUCCESS)\n return ret;\n }\n \n /* While the Lua function is still yielding, pass buckets to the coroutine */\n if (!ctx->broken) {\n lastCall = 0;\n while(!APR_BRIGADE_EMPTY(ctx->tmpBucket)) {\n apr_bucket *pbktIn = APR_BRIGADE_FIRST(ctx->tmpBucket);\n apr_bucket *pbktOut;\n const char *data;\n apr_size_t len;\n \n if (APR_BUCKET_IS_EOS(pbktIn)) {\n APR_BUCKET_REMOVE(pbktIn);\n break;\n }", " /* read the bucket */\n ret = apr_bucket_read(pbktIn, &data, &len, eBlock);\n if (ret != APR_SUCCESS)\n return ret;", " /* Push the bucket onto the Lua stack as a global var */\n lastCall++;\n lua_pushlstring(L, data, len);\n lua_setglobal(L, \"bucket\");\n \n /* If Lua yielded, it means we have something to pass on */\n if (lua_resume(L, 0) == LUA_YIELD) {\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n pbktOut = apr_bucket_heap_create(output, olen, 0, c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(pbbOut, pbktOut);\n apr_bucket_delete(pbktIn);\n return APR_SUCCESS;\n }\n else {\n ctx->broken = 1;\n ap_lua_release_state(L, ctx->spec, r);\n ap_remove_input_filter(f); \n apr_bucket_delete(pbktIn);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n }\n /* If we've safely reached the end, do a final call to Lua to allow for any \n finishing moves by the script, such as appending a tail. */\n if (lastCall == 0) {\n apr_bucket *pbktEOS = apr_bucket_eos_create(c->bucket_alloc);\n lua_pushnil(L);\n lua_setglobal(L, \"bucket\");\n if (lua_resume(L, 0) == LUA_YIELD) {\n apr_bucket *pbktOut;\n size_t olen;\n const char* output = lua_tolstring(L, 1, &olen);\n pbktOut = apr_bucket_heap_create(output, olen, 0, c->bucket_alloc);\n APR_BRIGADE_INSERT_TAIL(pbbOut, pbktOut);\n }\n APR_BRIGADE_INSERT_TAIL(pbbOut,pbktEOS);\n ap_lua_release_state(L, ctx->spec, r);\n }\n }\n return APR_SUCCESS;\n}", "\n/* ---------------- Configury stuff --------------- */", "/** harnesses for magic hooks **/", "static int lua_request_rec_hook_harness(request_rec *r, const char *name, int apr_hook_when)\n{\n int rc;\n apr_pool_t *pool;\n lua_State *L;\n ap_lua_vm_spec *spec;\n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n const char *key = apr_psprintf(r->pool, \"%s_%d\", name, apr_hook_when);\n apr_array_header_t *hook_specs = apr_hash_get(cfg->hooks, key,\n APR_HASH_KEY_STRING);\n if (hook_specs) {\n int i;\n for (i = 0; i < hook_specs->nelts; i++) {\n ap_lua_mapped_handler_spec *hook_spec =\n ((ap_lua_mapped_handler_spec **) hook_specs->elts)[i];", " if (hook_spec == NULL) {\n continue;\n }\n spec = create_vm_spec(&pool, r, cfg, server_cfg,\n hook_spec->file_name,\n hook_spec->bytecode,\n hook_spec->bytecode_len,\n hook_spec->function_name,\n \"request hook\");", " L = ap_lua_get_lua_state(pool, spec, r);", " if (!L) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01477)\n \"lua: Failed to obtain lua interpreter for entry function '%s' in %s\",\n hook_spec->function_name, hook_spec->file_name);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " if (hook_spec->function_name != NULL) {\n lua_getglobal(L, hook_spec->function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01478)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n hook_spec->function_name,\n hook_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " ap_lua_run_lua_request(L, r);\n }\n else {\n int t;\n ap_lua_run_lua_request(L, r);", " t = lua_gettop(L);\n lua_setglobal(L, \"r\");\n lua_settop(L, t);\n }", " if (lua_pcall(L, 1, 1, 0)) {\n report_lua_error(L, r);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n rc = DECLINED;\n if (lua_isnumber(L, -1)) {\n rc = lua_tointeger(L, -1);\n ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, \"Lua hook %s:%s for phase %s returned %d\", \n hook_spec->file_name, hook_spec->function_name, name, rc);\n }\n else { \n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, \"Lua hook %s:%s for phase %s did not return a numeric value\", \n hook_spec->file_name, hook_spec->function_name, name);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n if (rc != DECLINED) {\n ap_lua_release_state(L, spec, r);\n return rc;\n }\n ap_lua_release_state(L, spec, r);\n }\n }\n return DECLINED;\n}", "\n/* Fix for making sure that LuaMapHandler works when FallbackResource is set */\nstatic int lua_map_handler_fixups(request_rec *r)\n{\n /* If there is no handler set yet, this might be a LuaMapHandler request */\n if (r->handler == NULL) {\n int n = 0;\n ap_regmatch_t match[10];\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n for (n = 0; n < cfg->mapped_handlers->nelts; n++) {\n ap_lua_mapped_handler_spec *hook_spec =\n ((ap_lua_mapped_handler_spec **) cfg->mapped_handlers->elts)[n];", " if (hook_spec == NULL) {\n continue;\n }\n if (!ap_regexec(hook_spec->uri_pattern, r->uri, 10, match, 0)) {\n r->handler = apr_pstrdup(r->pool, \"lua-map-handler\");\n return OK;\n }\n }\n }\n return DECLINED;\n}", "\nstatic int lua_map_handler(request_rec *r)\n{\n int rc, n = 0;\n apr_pool_t *pool;\n lua_State *L;\n const char *filename, *function_name;\n const char *values[10];\n ap_lua_vm_spec *spec;\n ap_regmatch_t match[10];\n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);\n for (n = 0; n < cfg->mapped_handlers->nelts; n++) {\n ap_lua_mapped_handler_spec *hook_spec =\n ((ap_lua_mapped_handler_spec **) cfg->mapped_handlers->elts)[n];", " if (hook_spec == NULL) {\n continue;\n }\n if (!ap_regexec(hook_spec->uri_pattern, r->uri, 10, match, 0)) {\n int i;\n for (i=0 ; i < 10; i++) {\n if (match[i].rm_eo >= 0) {\n values[i] = apr_pstrndup(r->pool, r->uri+match[i].rm_so, match[i].rm_eo - match[i].rm_so);\n }\n else values[i] = \"\";\n }\n filename = ap_lua_interpolate_string(r->pool, hook_spec->file_name, values);\n function_name = ap_lua_interpolate_string(r->pool, hook_spec->function_name, values);\n spec = create_vm_spec(&pool, r, cfg, server_cfg,\n filename,\n hook_spec->bytecode,\n hook_spec->bytecode_len,\n function_name,\n \"mapped handler\");\n L = ap_lua_get_lua_state(pool, spec, r);", " if (!L) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02330)\n \"lua: Failed to obtain Lua interpreter for entry function '%s' in %s\",\n function_name, filename);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " if (function_name != NULL) {\n lua_getglobal(L, function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02331)\n \"lua: Unable to find entry function '%s' in %s (not a valid function)\",\n function_name,\n filename);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " ap_lua_run_lua_request(L, r);\n }\n else {\n int t;\n ap_lua_run_lua_request(L, r);", " t = lua_gettop(L);\n lua_setglobal(L, \"r\");\n lua_settop(L, t);\n }", " if (lua_pcall(L, 1, 1, 0)) {\n report_lua_error(L, r);\n ap_lua_release_state(L, spec, r);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n rc = DECLINED;\n if (lua_isnumber(L, -1)) {\n rc = lua_tointeger(L, -1);\n }\n else { \n ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(02483)\n \"lua: Lua handler %s in %s did not return a value, assuming apache2.OK\",\n function_name,\n filename);\n rc = OK;\n }\n ap_lua_release_state(L, spec, r);\n if (rc != DECLINED) {\n return rc;\n }\n }\n }\n return DECLINED;\n}", "\nstatic apr_size_t config_getstr(ap_configfile_t *cfg, char *buf,\n size_t bufsiz)\n{\n apr_size_t i = 0;", " if (cfg->getstr) {\n apr_status_t rc = (cfg->getstr) (buf, bufsiz, cfg->param);\n if (rc == APR_SUCCESS) {\n i = strlen(buf);\n if (i && buf[i - 1] == '\\n')\n ++cfg->line_number;\n }\n else {\n buf[0] = '\\0';\n i = 0;\n }\n }\n else {\n while (i < bufsiz) {\n char ch;\n apr_status_t rc = (cfg->getch) (&ch, cfg->param);\n if (rc != APR_SUCCESS)\n break;\n buf[i++] = ch;\n if (ch == '\\n') {\n ++cfg->line_number;\n break;\n }\n }\n }\n return i;\n}", "typedef struct cr_ctx\n{\n cmd_parms *cmd;\n ap_configfile_t *cfp;\n size_t startline;\n const char *endstr;\n char buf[HUGE_STRING_LEN];\n} cr_ctx;", "\n/* Okay, this deserves a little explaination -- in order for the errors that lua\n * generates to be 'accuarate', including line numbers, we basically inject\n * N line number new lines into the 'top' of the chunk reader.....\n *\n * be happy. this is cool.\n *\n */\nstatic const char *lf =\n \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n#define N_LF 32", "static const char *direct_chunkreader(lua_State *lvm, void *udata,\n size_t *plen)\n{\n const char *p;\n struct cr_ctx *ctx = udata;", " if (ctx->startline) {\n *plen = ctx->startline > N_LF ? N_LF : ctx->startline;\n ctx->startline -= *plen;\n return lf;\n }\n *plen = config_getstr(ctx->cfp, ctx->buf, HUGE_STRING_LEN);", " for (p = ctx->buf; isspace(*p); ++p);\n if (p[0] == '<' && p[1] == '/') {\n apr_size_t i = 0;\n while (i < strlen(ctx->endstr)) {\n if (tolower(p[i + 2]) != ctx->endstr[i])\n return ctx->buf;\n ++i;\n }\n *plen = 0;\n return NULL;\n }\n /*fprintf(stderr, \"buf read: %s\\n\", ctx->buf); */\n return ctx->buf;\n}", "static int ldump_writer(lua_State *L, const void *b, size_t size, void *B)\n{\n (void) L;\n luaL_addlstring((luaL_Buffer *) B, (const char *) b, size);\n return 0;\n}", "typedef struct hack_section_baton\n{\n const char *name;\n ap_lua_mapped_handler_spec *spec;\n int apr_hook_when;\n} hack_section_baton;", "/* You can be unhappy now.\n *\n * This is uncool.\n *\n * When you create a <Section handler in httpd, the only 'easy' way to create\n * a directory context is to parse the section, and convert it into a 'normal'\n * Configureation option, and then collapse the entire section, in memory,\n * back into the parent section -- from which you can then get the new directive\n * invoked.... anyways. evil. Rici taught me how to do this hack :-)\n */\nstatic const char *hack_section_handler(cmd_parms *cmd, void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n ap_directive_t *directive = cmd->directive;\n hack_section_baton *baton = directive->data;\n const char *key = apr_psprintf(cmd->pool, \"%s_%d\", baton->name, baton->apr_hook_when);", " apr_array_header_t *hook_specs = apr_hash_get(cfg->hooks, key,\n APR_HASH_KEY_STRING);\n if (!hook_specs) {\n hook_specs = apr_array_make(cmd->pool, 2,\n sizeof(ap_lua_mapped_handler_spec *));\n apr_hash_set(cfg->hooks, key,\n APR_HASH_KEY_STRING, hook_specs);\n }", " baton->spec->scope = cfg->vm_scope;", " *(ap_lua_mapped_handler_spec **) apr_array_push(hook_specs) = baton->spec;", " return NULL;\n}", "static const char *register_named_block_function_hook(const char *name,\n cmd_parms *cmd,\n void *mconfig,\n const char *line)\n{\n const char *function = NULL;\n ap_lua_mapped_handler_spec *spec;\n int when = APR_HOOK_MIDDLE;\n const char *endp = ap_strrchr_c(line, '>');", " if (endp == NULL) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive missing closing '>'\", NULL);\n }", " line = apr_pstrndup(cmd->temp_pool, line, endp - line);", " if (line[0]) { \n const char *word;\n word = ap_getword_conf(cmd->temp_pool, &line);\n if (*word) {\n function = apr_pstrdup(cmd->pool, word);\n }\n word = ap_getword_conf(cmd->temp_pool, &line);\n if (*word) {\n if (!strcasecmp(\"early\", word)) { \n when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(\"late\", word)) {\n when = AP_LUA_HOOK_LAST;\n }\n else { \n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> 2nd argument must be 'early' or 'late'\", NULL);\n }\n }\n }", " spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));", " {\n cr_ctx ctx;\n lua_State *lvm;\n char *tmp;\n int rv;\n ap_directive_t **current;\n hack_section_baton *baton;", " spec->file_name = apr_psprintf(cmd->pool, \"%s:%u\",\n cmd->config_file->name,\n cmd->config_file->line_number);\n if (function) {\n spec->function_name = (char *) function;\n }\n else {\n function = NULL;\n }", " ctx.cmd = cmd;\n tmp = apr_pstrdup(cmd->pool, cmd->err_directive->directive + 1);\n ap_str_tolower(tmp);\n ctx.endstr = tmp;\n ctx.cfp = cmd->config_file;\n ctx.startline = cmd->config_file->line_number;", " /* This lua State is used only to compile the input strings -> bytecode, so we don't need anything extra. */\n lvm = luaL_newstate();", " lua_settop(lvm, 0);", " rv = lua_load(lvm, direct_chunkreader, &ctx, spec->file_name);", " if (rv != 0) {\n const char *errstr = apr_pstrcat(cmd->pool, \"Lua Error:\",\n lua_tostring(lvm, -1), NULL);\n lua_close(lvm);\n return errstr;\n }\n else {\n luaL_Buffer b;\n luaL_buffinit(lvm, &b);\n lua_dump(lvm, ldump_writer, &b);\n luaL_pushresult(&b);\n spec->bytecode_len = lua_strlen(lvm, -1);\n spec->bytecode = apr_pstrmemdup(cmd->pool, lua_tostring(lvm, -1),\n spec->bytecode_len);\n lua_close(lvm);\n }", " current = mconfig;", " /* Here, we have to replace our current config node for the next pass */\n if (!*current) {\n *current = apr_pcalloc(cmd->pool, sizeof(**current));\n }", " baton = apr_pcalloc(cmd->pool, sizeof(hack_section_baton));\n baton->name = name;\n baton->spec = spec;\n baton->apr_hook_when = when;", " (*current)->filename = cmd->config_file->name;\n (*current)->line_num = cmd->config_file->line_number;\n (*current)->directive = apr_pstrdup(cmd->pool, \"Lua_____ByteCodeHack\");\n (*current)->args = NULL;\n (*current)->data = baton;\n }", " return NULL;\n}", "static const char *register_named_file_function_hook(const char *name,\n cmd_parms *cmd,\n void *_cfg,\n const char *file,\n const char *function,\n int apr_hook_when)\n{\n ap_lua_mapped_handler_spec *spec;\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n const char *key = apr_psprintf(cmd->pool, \"%s_%d\", name, apr_hook_when);\n apr_array_header_t *hook_specs = apr_hash_get(cfg->hooks, key,\n APR_HASH_KEY_STRING);", " if (!hook_specs) {\n hook_specs = apr_array_make(cmd->pool, 2,\n sizeof(ap_lua_mapped_handler_spec *));\n apr_hash_set(cfg->hooks, key, APR_HASH_KEY_STRING, hook_specs);\n }", " spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));\n spec->file_name = apr_pstrdup(cmd->pool, file);\n spec->function_name = apr_pstrdup(cmd->pool, function);\n spec->scope = cfg->vm_scope;", " *(ap_lua_mapped_handler_spec **) apr_array_push(hook_specs) = spec;\n return NULL;\n}\nstatic const char *register_mapped_file_function_hook(const char *pattern,\n cmd_parms *cmd,\n void *_cfg,\n const char *file,\n const char *function)\n{\n ap_lua_mapped_handler_spec *spec;\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n ap_regex_t *regex = apr_pcalloc(cmd->pool, sizeof(ap_regex_t));\n if (ap_regcomp(regex, pattern,0)) {\n return \"Invalid regex pattern!\";\n }", " spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));\n spec->file_name = apr_pstrdup(cmd->pool, file);\n spec->function_name = apr_pstrdup(cmd->pool, function);\n spec->scope = cfg->vm_scope;\n spec->uri_pattern = regex;", " *(ap_lua_mapped_handler_spec **) apr_array_push(cfg->mapped_handlers) = spec;\n return NULL;\n}\nstatic const char *register_filter_function_hook(const char *filter,\n cmd_parms *cmd,\n void *_cfg,\n const char *file,\n const char *function,\n int direction)\n{\n ap_lua_filter_handler_spec *spec;\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n \n spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_filter_handler_spec));\n spec->file_name = apr_pstrdup(cmd->pool, file);\n spec->function_name = apr_pstrdup(cmd->pool, function);\n spec->filter_name = filter;", " *(ap_lua_filter_handler_spec **) apr_array_push(cfg->mapped_filters) = spec;\n /* TODO: Make it work on other types than just AP_FTYPE_RESOURCE? */\n if (direction == AP_LUA_FILTER_OUTPUT) {\n spec->direction = AP_LUA_FILTER_OUTPUT;\n ap_register_output_filter_protocol(filter, lua_output_filter_handle, NULL, AP_FTYPE_RESOURCE,\n AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH);\n }\n else {\n spec->direction = AP_LUA_FILTER_INPUT;\n ap_register_input_filter(filter, lua_input_filter_handle, NULL, AP_FTYPE_RESOURCE);\n }\n return NULL;\n}\n/* disabled (see reference below)\nstatic int lua_check_user_id_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"check_user_id\", AP_LUA_HOOK_FIRST);\n}\n*/\nstatic int lua_check_user_id_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"check_user_id\", APR_HOOK_MIDDLE);\n}\n/* disabled (see reference below)\nstatic int lua_check_user_id_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"check_user_id\", AP_LUA_HOOK_LAST);\n}\n*/", "static int lua_translate_name_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"translate_name\", AP_LUA_HOOK_FIRST);\n}\nstatic int lua_translate_name_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"translate_name\", APR_HOOK_MIDDLE);\n}\nstatic int lua_translate_name_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"translate_name\", AP_LUA_HOOK_LAST);\n}", "static int lua_fixup_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"fixups\", APR_HOOK_MIDDLE);\n}", "static int lua_map_to_storage_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"map_to_storage\", APR_HOOK_MIDDLE);\n}", "static int lua_type_checker_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"type_checker\", APR_HOOK_MIDDLE);\n}", "static int lua_access_checker_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"access_checker\", AP_LUA_HOOK_FIRST);\n}\nstatic int lua_access_checker_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"access_checker\", APR_HOOK_MIDDLE);\n}\nstatic int lua_access_checker_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"access_checker\", AP_LUA_HOOK_LAST);\n}", "static int lua_auth_checker_harness_first(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"auth_checker\", AP_LUA_HOOK_FIRST);\n}\nstatic int lua_auth_checker_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"auth_checker\", APR_HOOK_MIDDLE);\n}\nstatic int lua_auth_checker_harness_last(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"auth_checker\", AP_LUA_HOOK_LAST);\n}\nstatic void lua_insert_filter_harness(request_rec *r)\n{\n /* ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, \"LuaHookInsertFilter not yet implemented\"); */\n}", "static int lua_log_transaction_harness(request_rec *r)\n{\n return lua_request_rec_hook_harness(r, \"log_transaction\", APR_HOOK_FIRST);\n}", "static int lua_quick_harness(request_rec *r, int lookup)\n{\n if (lookup) {\n return DECLINED;\n }\n return lua_request_rec_hook_harness(r, \"quick\", APR_HOOK_MIDDLE);\n}", "static const char *register_translate_name_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n int apr_hook_when = APR_HOOK_MIDDLE;\n if (err) {\n return err;\n }\n \n if (when) { \n if (!strcasecmp(when, \"early\")) { \n apr_hook_when = AP_LUA_HOOK_FIRST;\n } \n else if (!strcasecmp(when, \"late\")) { \n apr_hook_when = AP_LUA_HOOK_LAST;\n } \n else { \n return \"Third argument must be 'early' or 'late'\";\n }\n }", " return register_named_file_function_hook(\"translate_name\", cmd, _cfg,\n file, function, apr_hook_when);\n}", "static const char *register_translate_name_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"translate_name\", cmd, _cfg,\n line);\n}", "\nstatic const char *register_fixups_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"fixups\", cmd, _cfg, file,\n function, APR_HOOK_MIDDLE);\n}\nstatic const char *register_fixups_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"fixups\", cmd, _cfg, line);\n}", "static const char *register_map_to_storage_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"map_to_storage\", cmd, _cfg,\n file, function, APR_HOOK_MIDDLE);\n}", "static const char *register_log_transaction_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"log_transaction\", cmd, _cfg,\n file, function, APR_HOOK_FIRST);\n}", "static const char *register_map_to_storage_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"map_to_storage\", cmd, _cfg,\n line);\n}", "\nstatic const char *register_check_user_id_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n int apr_hook_when = APR_HOOK_MIDDLE;\n/* XXX: This does not currently work!!\n if (when) {\n if (!strcasecmp(when, \"early\")) {\n apr_hook_when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(when, \"late\")) {\n apr_hook_when = AP_LUA_HOOK_LAST;\n }\n else {\n return \"Third argument must be 'early' or 'late'\";\n }\n }\n*/\n return register_named_file_function_hook(\"check_user_id\", cmd, _cfg, file,\n function, apr_hook_when);\n}\nstatic const char *register_check_user_id_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"check_user_id\", cmd, _cfg,\n line);\n}", "static const char *register_type_checker_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return register_named_file_function_hook(\"type_checker\", cmd, _cfg, file,\n function, APR_HOOK_MIDDLE);\n}\nstatic const char *register_type_checker_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"type_checker\", cmd, _cfg,\n line);\n}", "static const char *register_access_checker_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n int apr_hook_when = APR_HOOK_MIDDLE;", " if (when) {\n if (!strcasecmp(when, \"early\")) {\n apr_hook_when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(when, \"late\")) {\n apr_hook_when = AP_LUA_HOOK_LAST;\n }\n else {\n return \"Third argument must be 'early' or 'late'\";\n }\n }", " return register_named_file_function_hook(\"access_checker\", cmd, _cfg,\n file, function, apr_hook_when);\n}\nstatic const char *register_access_checker_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{", " return register_named_block_function_hook(\"access_checker\", cmd, _cfg,\n line);\n}", "static const char *register_auth_checker_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function,\n const char *when)\n{\n int apr_hook_when = APR_HOOK_MIDDLE;", " if (when) {\n if (!strcasecmp(when, \"early\")) {\n apr_hook_when = AP_LUA_HOOK_FIRST;\n }\n else if (!strcasecmp(when, \"late\")) {\n apr_hook_when = AP_LUA_HOOK_LAST;\n }\n else {\n return \"Third argument must be 'early' or 'late'\";\n }\n }", " return register_named_file_function_hook(\"auth_checker\", cmd, _cfg, file,\n function, apr_hook_when);\n}\nstatic const char *register_auth_checker_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"auth_checker\", cmd, _cfg,\n line);\n}", "static const char *register_insert_filter_hook(cmd_parms *cmd, void *_cfg,\n const char *file,\n const char *function)\n{\n return \"LuaHookInsertFilter not yet implemented\";\n}", "static const char *register_quick_hook(cmd_parms *cmd, void *_cfg,\n const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n return register_named_file_function_hook(\"quick\", cmd, _cfg, file,\n function, APR_HOOK_MIDDLE);\n}\nstatic const char *register_map_handler(cmd_parms *cmd, void *_cfg,\n const char* match, const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n if (!function) function = \"handle\";\n return register_mapped_file_function_hook(match, cmd, _cfg, file,\n function);\n}\nstatic const char *register_output_filter(cmd_parms *cmd, void *_cfg,\n const char* filter, const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n if (!function) function = \"handle\";\n return register_filter_function_hook(filter, cmd, _cfg, file,\n function, AP_LUA_FILTER_OUTPUT);\n}\nstatic const char *register_input_filter(cmd_parms *cmd, void *_cfg,\n const char* filter, const char *file, const char *function)\n{\n const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|\n NOT_IN_HTACCESS);\n if (err) {\n return err;\n }\n if (!function) function = \"handle\";\n return register_filter_function_hook(filter, cmd, _cfg, file,\n function, AP_LUA_FILTER_INPUT);\n}\nstatic const char *register_quick_block(cmd_parms *cmd, void *_cfg,\n const char *line)\n{\n return register_named_block_function_hook(\"quick\", cmd, _cfg,\n line);\n}", "", "static const char *register_package_helper(cmd_parms *cmd, \n const char *arg,\n apr_array_header_t *dir_array)\n{\n apr_status_t rv;", " ap_lua_server_cfg *server_cfg =\n ap_get_module_config(cmd->server->module_config, &lua_module);", " char *fixed_filename;\n rv = apr_filepath_merge(&fixed_filename, \n server_cfg->root_path, \n arg,\n APR_FILEPATH_NOTRELATIVE, \n cmd->pool);", " if (rv != APR_SUCCESS) {\n return apr_psprintf(cmd->pool,\n \"Unable to build full path to file, %s\", arg);\n }", " *(const char **) apr_array_push(dir_array) = fixed_filename;\n return NULL;\n}", "\n/**\n * Called for config directive which looks like\n * LuaPackagePath /lua/package/path/mapped/thing/like/this/?.lua\n */\nstatic const char *register_package_dir(cmd_parms *cmd, void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;", " return register_package_helper(cmd, arg, cfg->package_paths);\n}", "/**\n * Called for config directive which looks like\n * LuaPackageCPath /lua/package/path/mapped/thing/like/this/?.so\n */\nstatic const char *register_package_cdir(cmd_parms *cmd, \n void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;", " return register_package_helper(cmd, arg, cfg->package_cpaths);\n}", "static const char *register_lua_inherit(cmd_parms *cmd, \n void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n \n if (strcasecmp(\"none\", arg) == 0) {\n cfg->inherit = AP_LUA_INHERIT_NONE;\n }\n else if (strcasecmp(\"parent-first\", arg) == 0) {\n cfg->inherit = AP_LUA_INHERIT_PARENT_FIRST;\n }\n else if (strcasecmp(\"parent-last\", arg) == 0) {\n cfg->inherit = AP_LUA_INHERIT_PARENT_LAST;\n }\n else { \n return apr_psprintf(cmd->pool,\n \"LuaInherit type of '%s' not recognized, valid \"\n \"options are 'none', 'parent-first', and 'parent-last'\", \n arg);\n }\n return NULL;\n}\nstatic const char *register_lua_codecache(cmd_parms *cmd, \n void *_cfg,\n const char *arg)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n \n if (strcasecmp(\"never\", arg) == 0) {\n cfg->codecache = AP_LUA_CACHE_NEVER;\n }\n else if (strcasecmp(\"stat\", arg) == 0) {\n cfg->codecache = AP_LUA_CACHE_STAT;\n }\n else if (strcasecmp(\"forever\", arg) == 0) {\n cfg->codecache = AP_LUA_CACHE_FOREVER;\n }\n else { \n return apr_psprintf(cmd->pool,\n \"LuaCodeCache type of '%s' not recognized, valid \"\n \"options are 'never', 'stat', and 'forever'\", \n arg);\n }\n return NULL;\n}\nstatic const char *register_lua_scope(cmd_parms *cmd, \n void *_cfg,\n const char *scope, \n const char *min,\n const char *max)\n{\n ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;\n if (strcmp(\"once\", scope) == 0) {\n cfg->vm_scope = AP_LUA_SCOPE_ONCE;\n }\n else if (strcmp(\"request\", scope) == 0) {\n cfg->vm_scope = AP_LUA_SCOPE_REQUEST;\n }\n else if (strcmp(\"conn\", scope) == 0) {\n cfg->vm_scope = AP_LUA_SCOPE_CONN;\n }\n else if (strcmp(\"thread\", scope) == 0) {\n#if !APR_HAS_THREADS\n return apr_psprintf(cmd->pool,\n \"Scope type of '%s' cannot be used because this \"\n \"server does not have threading support \"\n \"(APR_HAS_THREADS)\" \n scope);\n#endif\n cfg->vm_scope = AP_LUA_SCOPE_THREAD;\n }\n else if (strcmp(\"server\", scope) == 0) {\n unsigned int vmin, vmax;\n#if !APR_HAS_THREADS\n return apr_psprintf(cmd->pool,\n \"Scope type of '%s' cannot be used because this \"\n \"server does not have threading support \"\n \"(APR_HAS_THREADS)\" \n scope);\n#endif\n cfg->vm_scope = AP_LUA_SCOPE_SERVER;\n vmin = min ? atoi(min) : 1;\n vmax = max ? atoi(max) : 1;\n if (vmin == 0) {\n vmin = 1;\n }\n if (vmax < vmin) {\n vmax = vmin;\n }\n cfg->vm_min = vmin;\n cfg->vm_max = vmax;\n }\n else {\n return apr_psprintf(cmd->pool,\n \"Invalid value for LuaScope, '%s', acceptable \"\n \"values are: 'once', 'request', 'conn'\"\n#if APR_HAS_THREADS\n \", 'thread', 'server'\"\n#endif\n ,scope);\n }", " return NULL;\n}", "", "static const char *register_lua_root(cmd_parms *cmd, void *_cfg,\n const char *root)\n{\n /* ap_lua_dir_cfg* cfg = (ap_lua_dir_cfg*)_cfg; */\n ap_lua_server_cfg *cfg = ap_get_module_config(cmd->server->module_config,\n &lua_module);", " cfg->root_path = root;\n return NULL;\n}", "const char *ap_lua_ssl_val(apr_pool_t *p, server_rec *s, conn_rec *c,\n request_rec *r, const char *var)\n{\n if (lua_ssl_val) { \n return (const char *)lua_ssl_val(p, s, c, r, (char *)var);\n }\n return NULL;\n}", "int ap_lua_ssl_is_https(conn_rec *c)\n{\n return lua_ssl_is_https ? lua_ssl_is_https(c) : 0;\n}", "/*******************************/", "static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line,\n const void **parsed_require_line)\n{\n const char *provider_name;\n lua_authz_provider_spec *spec;", " lua_authz_provider_func *func = apr_pcalloc(cmd->pool, sizeof(lua_authz_provider_func));", "\n apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE,\n cmd->temp_pool);\n ap_assert(provider_name != NULL);", " spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING);\n ap_assert(spec != NULL);", " func->spec = spec;", "\n if (require_line && *require_line) {\n const char *arg;", " func->args = apr_array_make(cmd->pool, 2, sizeof(const char *));", " while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) {", " APR_ARRAY_PUSH(func->args, const char *) = arg;\n }\n }", " *parsed_require_line = func;", " return NULL;\n}", "static authz_status lua_authz_check(request_rec *r, const char *require_line,\n const void *parsed_require_line)\n{\n apr_pool_t *pool;\n ap_lua_vm_spec *spec;\n lua_State *L;\n ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,\n &lua_module);\n const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,\n &lua_module);", " const lua_authz_provider_func *prov_func = parsed_require_line;\n const lua_authz_provider_spec *prov_spec = prov_func->spec;", " int result;\n int nargs = 0;", " spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name,\n NULL, 0, prov_spec->function_name, \"authz provider\");", " L = ap_lua_get_lua_state(pool, spec, r);\n if (L == NULL) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314)\n \"Unable to compile VM for authz provider %s\", prov_spec->name);\n return AUTHZ_GENERAL_ERROR;\n }\n lua_getglobal(L, prov_spec->function_name);\n if (!lua_isfunction(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319)\n \"Unable to find entry function '%s' in %s (not a valid function)\",\n prov_spec->function_name, prov_spec->file_name);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }\n ap_lua_run_lua_request(L, r);", " if (prov_func->args) {", " int i;", " if (!lua_checkstack(L, prov_func->args->nelts)) {", " ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315)\n \"Error: authz provider %s: too many arguments\", prov_spec->name);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }", " for (i = 0; i < prov_func->args->nelts; i++) {\n const char *arg = APR_ARRAY_IDX(prov_func->args, i, const char *);", " lua_pushstring(L, arg);\n }", " nargs = prov_func->args->nelts;", " }\n if (lua_pcall(L, 1 + nargs, 1, 0)) {\n const char *err = lua_tostring(L, -1);\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316)\n \"Error executing authz provider %s: %s\", prov_spec->name, err);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }\n if (!lua_isnumber(L, -1)) {\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317)\n \"Error: authz provider %s did not return integer\", prov_spec->name);\n ap_lua_release_state(L, spec, r);\n return AUTHZ_GENERAL_ERROR;\n }\n result = lua_tointeger(L, -1);\n ap_lua_release_state(L, spec, r);\n switch (result) {\n case AUTHZ_DENIED:\n case AUTHZ_GRANTED:\n case AUTHZ_NEUTRAL:\n case AUTHZ_GENERAL_ERROR:\n case AUTHZ_DENIED_NO_USER:\n return result;\n default:\n ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318)\n \"Error: authz provider %s: invalid return value %d\",\n prov_spec->name, result);\n }\n return AUTHZ_GENERAL_ERROR;\n}", "static const authz_provider lua_authz_provider =\n{\n &lua_authz_check,\n &lua_authz_parse,\n};", "static const char *register_authz_provider(cmd_parms *cmd, void *_cfg,\n const char *name, const char *file,\n const char *function)\n{\n lua_authz_provider_spec *spec;\n const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);\n if (err)\n return err;", " spec = apr_pcalloc(cmd->pool, sizeof(*spec));\n spec->name = name;\n spec->file_name = file;\n spec->function_name = function;", " apr_hash_set(lua_authz_providers, name, APR_HASH_KEY_STRING, spec);\n ap_register_auth_provider(cmd->pool, AUTHZ_PROVIDER_GROUP, name,\n AUTHZ_PROVIDER_VERSION,\n &lua_authz_provider,\n AP_AUTH_INTERNAL_PER_CONF);\n return NULL;\n}", "\ncommand_rec lua_commands[] = {", " AP_INIT_TAKE1(\"LuaRoot\", register_lua_root, NULL, OR_ALL,\n \"Specify the base path for resolving relative paths for mod_lua directives\"),", " AP_INIT_TAKE1(\"LuaPackagePath\", register_package_dir, NULL, OR_ALL,\n \"Add a directory to lua's package.path\"),", " AP_INIT_TAKE1(\"LuaPackageCPath\", register_package_cdir, NULL, OR_ALL,\n \"Add a directory to lua's package.cpath\"),", " AP_INIT_TAKE3(\"LuaAuthzProvider\", register_authz_provider, NULL, RSRC_CONF|EXEC_ON_READ,\n \"Provide an authorization provider\"),", " AP_INIT_TAKE23(\"LuaHookTranslateName\", register_translate_name_hook, NULL,\n OR_ALL,\n \"Provide a hook for the translate name phase of request processing\"),", " AP_INIT_RAW_ARGS(\"<LuaHookTranslateName\", register_translate_name_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the translate name phase of request processing\"),", " AP_INIT_TAKE2(\"LuaHookFixups\", register_fixups_hook, NULL, OR_ALL,\n \"Provide a hook for the fixups phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookFixups\", register_fixups_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a inline hook for the fixups phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE2(\"LuaHookMapToStorage\", register_map_to_storage_hook, NULL,\n OR_ALL,\n \"Provide a hook for the map_to_storage phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookMapToStorage\", register_map_to_storage_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the map_to_storage phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE23(\"LuaHookCheckUserID\", register_check_user_id_hook, NULL,\n OR_ALL,\n \"Provide a hook for the check_user_id phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookCheckUserID\", register_check_user_id_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the check_user_id phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE2(\"LuaHookTypeChecker\", register_type_checker_hook, NULL,\n OR_ALL,\n \"Provide a hook for the type_checker phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookTypeChecker\", register_type_checker_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the type_checker phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE23(\"LuaHookAccessChecker\", register_access_checker_hook, NULL,\n OR_ALL,\n \"Provide a hook for the access_checker phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookAccessChecker\", register_access_checker_block,\n NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the access_checker phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE23(\"LuaHookAuthChecker\", register_auth_checker_hook, NULL,\n OR_ALL,\n \"Provide a hook for the auth_checker phase of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaHookAuthChecker\", register_auth_checker_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the auth_checker phase of request processing\"),", " /* todo: test */\n AP_INIT_TAKE2(\"LuaHookInsertFilter\", register_insert_filter_hook, NULL,\n OR_ALL,\n \"Provide a hook for the insert_filter phase of request processing\"),\n \n AP_INIT_TAKE2(\"LuaHookLog\", register_log_transaction_hook, NULL,\n OR_ALL,\n \"Provide a hook for the logging phase of request processing\"),", " AP_INIT_TAKE123(\"LuaScope\", register_lua_scope, NULL, OR_ALL,\n \"One of once, request, conn, server -- default is once\"),", " AP_INIT_TAKE1(\"LuaInherit\", register_lua_inherit, NULL, OR_ALL,\n \"Controls how Lua scripts in parent contexts are merged with the current \" \n \" context: none|parent-last|parent-first (default: parent-first) \"),\n \n AP_INIT_TAKE1(\"LuaCodeCache\", register_lua_codecache, NULL, OR_ALL,\n \"Controls the behavior of the in-memory code cache \" \n \" context: stat|forever|never (default: stat) \"),", " AP_INIT_TAKE2(\"LuaQuickHandler\", register_quick_hook, NULL, OR_ALL,\n \"Provide a hook for the quick handler of request processing\"),\n AP_INIT_RAW_ARGS(\"<LuaQuickHandler\", register_quick_block, NULL,\n EXEC_ON_READ | OR_ALL,\n \"Provide a hook for the quick handler of request processing\"),\n AP_INIT_RAW_ARGS(\"Lua_____ByteCodeHack\", hack_section_handler, NULL,\n OR_ALL,\n \"(internal) Byte code handler\"),\n AP_INIT_TAKE23(\"LuaMapHandler\", register_map_handler, NULL, OR_ALL,\n \"Maps a path to a lua handler\"),\n AP_INIT_TAKE3(\"LuaOutputFilter\", register_output_filter, NULL, OR_ALL,\n \"Registers a Lua function as an output filter\"),\n AP_INIT_TAKE3(\"LuaInputFilter\", register_input_filter, NULL, OR_ALL,\n \"Registers a Lua function as an input filter\"),\n {NULL}\n};", "\nstatic void *create_dir_config(apr_pool_t *p, char *dir)\n{\n ap_lua_dir_cfg *cfg = apr_pcalloc(p, sizeof(ap_lua_dir_cfg));\n cfg->package_paths = apr_array_make(p, 2, sizeof(char *));\n cfg->package_cpaths = apr_array_make(p, 2, sizeof(char *));\n cfg->mapped_handlers =\n apr_array_make(p, 1, sizeof(ap_lua_mapped_handler_spec *));\n cfg->mapped_filters =\n apr_array_make(p, 1, sizeof(ap_lua_filter_handler_spec *));\n cfg->pool = p;\n cfg->hooks = apr_hash_make(p);\n cfg->dir = apr_pstrdup(p, dir);\n cfg->vm_scope = AP_LUA_SCOPE_UNSET;\n cfg->codecache = AP_LUA_CACHE_UNSET;\n cfg->vm_min = 0;\n cfg->vm_max = 0;", " return cfg;\n}", "static int create_request_config(request_rec *r)\n{\n ap_lua_request_cfg *cfg = apr_palloc(r->pool, sizeof(ap_lua_request_cfg));\n cfg->mapped_request_details = NULL;\n cfg->request_scoped_vms = apr_hash_make(r->pool);\n ap_set_module_config(r->request_config, &lua_module, cfg);\n return OK;\n}", "static void *create_server_config(apr_pool_t *p, server_rec *s)\n{", " ap_lua_server_cfg *cfg = apr_pcalloc(p, sizeof(ap_lua_server_cfg));\n cfg->vm_reslists = apr_hash_make(p);\n apr_thread_rwlock_create(&cfg->vm_reslists_lock, p);\n cfg->root_path = NULL;", " return cfg;\n}", "static int lua_request_hook(lua_State *L, request_rec *r)\n{\n ap_lua_push_request(L, r);\n return OK;\n}", "static int lua_pre_config(apr_pool_t *pconf, apr_pool_t *plog,\n apr_pool_t *ptemp)\n{\n ap_mutex_register(pconf, \"lua-ivm-shm\", NULL, APR_LOCK_DEFAULT, 0);\n return OK;\n}", "static int lua_post_config(apr_pool_t *pconf, apr_pool_t *plog,\n apr_pool_t *ptemp, server_rec *s)\n{\n apr_pool_t **pool;\n const char *tempdir;\n apr_status_t rs;", " lua_ssl_val = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);\n lua_ssl_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);\n \n if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)\n return OK;", " /* Create ivm mutex */\n rs = ap_global_mutex_create(&lua_ivm_mutex, NULL, \"lua-ivm-shm\", NULL,\n s, pconf, 0);\n if (APR_SUCCESS != rs) {\n return HTTP_INTERNAL_SERVER_ERROR;\n }", " /* Create shared memory space */\n rs = apr_temp_dir_get(&tempdir, pconf);\n if (rs != APR_SUCCESS) {\n ap_log_error(APLOG_MARK, APLOG_ERR, rs, s, APLOGNO(02664)\n \"mod_lua IVM: Failed to find temporary directory\");\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n lua_ivm_shmfile = apr_psprintf(pconf, \"%s/httpd_lua_shm.%ld\", tempdir,\n (long int)getpid());\n rs = apr_shm_create(&lua_ivm_shm, sizeof(apr_pool_t**),\n (const char *) lua_ivm_shmfile, pconf);\n if (rs != APR_SUCCESS) {\n ap_log_error(APLOG_MARK, APLOG_ERR, rs, s, APLOGNO(02665)\n \"mod_lua: Failed to create shared memory segment on file %s\",\n lua_ivm_shmfile);\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n pool = (apr_pool_t **)apr_shm_baseaddr_get(lua_ivm_shm);\n apr_pool_create(pool, pconf);\n apr_pool_cleanup_register(pconf, NULL, shm_cleanup_wrapper,\n apr_pool_cleanup_null);\n return OK;\n}\nstatic void *overlay_hook_specs(apr_pool_t *p,\n const void *key,\n apr_ssize_t klen,\n const void *overlay_val,\n const void *base_val,\n const void *data)\n{\n const apr_array_header_t *overlay_info = (const apr_array_header_t*)overlay_val;\n const apr_array_header_t *base_info = (const apr_array_header_t*)base_val;\n return apr_array_append(p, base_info, overlay_info);\n}", "static void *merge_dir_config(apr_pool_t *p, void *basev, void *overridesv)\n{\n ap_lua_dir_cfg *a, *base, *overrides;", " a = (ap_lua_dir_cfg *)apr_pcalloc(p, sizeof(ap_lua_dir_cfg));\n base = (ap_lua_dir_cfg*)basev;\n overrides = (ap_lua_dir_cfg*)overridesv;", " a->pool = overrides->pool;\n a->dir = apr_pstrdup(p, overrides->dir);", " a->vm_scope = (overrides->vm_scope == AP_LUA_SCOPE_UNSET) ? base->vm_scope: overrides->vm_scope;\n a->inherit = (overrides->inherit == AP_LUA_INHERIT_UNSET) ? base->inherit : overrides->inherit;\n a->codecache = (overrides->codecache == AP_LUA_CACHE_UNSET) ? base->codecache : overrides->codecache;\n \n a->vm_min = (overrides->vm_min == 0) ? base->vm_min : overrides->vm_min;\n a->vm_max = (overrides->vm_max == 0) ? base->vm_max : overrides->vm_max;", " if (a->inherit == AP_LUA_INHERIT_UNSET || a->inherit == AP_LUA_INHERIT_PARENT_FIRST) { \n a->package_paths = apr_array_append(p, base->package_paths, overrides->package_paths);\n a->package_cpaths = apr_array_append(p, base->package_cpaths, overrides->package_cpaths);\n a->mapped_handlers = apr_array_append(p, base->mapped_handlers, overrides->mapped_handlers);\n a->mapped_filters = apr_array_append(p, base->mapped_filters, overrides->mapped_filters);\n a->hooks = apr_hash_merge(p, overrides->hooks, base->hooks, overlay_hook_specs, NULL);\n }\n else if (a->inherit == AP_LUA_INHERIT_PARENT_LAST) { \n a->package_paths = apr_array_append(p, overrides->package_paths, base->package_paths);\n a->package_cpaths = apr_array_append(p, overrides->package_cpaths, base->package_cpaths);\n a->mapped_handlers = apr_array_append(p, overrides->mapped_handlers, base->mapped_handlers);\n a->mapped_filters = apr_array_append(p, overrides->mapped_filters, base->mapped_filters);\n a->hooks = apr_hash_merge(p, base->hooks, overrides->hooks, overlay_hook_specs, NULL);\n }\n else { \n a->package_paths = overrides->package_paths;\n a->package_cpaths = overrides->package_cpaths;\n a->mapped_handlers= overrides->mapped_handlers;\n a->mapped_filters= overrides->mapped_filters;\n a->hooks= overrides->hooks;\n }", " return a;\n}", "static void lua_register_hooks(apr_pool_t *p)\n{\n /* ap_register_output_filter(\"luahood\", luahood, NULL, AP_FTYPE_RESOURCE); */\n ap_hook_handler(lua_handler, NULL, NULL, APR_HOOK_MIDDLE);\n ap_hook_create_request(create_request_config, NULL, NULL,\n APR_HOOK_MIDDLE);", " /* http_request.h hooks */\n ap_hook_translate_name(lua_translate_name_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n ap_hook_translate_name(lua_translate_name_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_translate_name(lua_translate_name_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);", " ap_hook_fixups(lua_fixup_harness, NULL, NULL, APR_HOOK_MIDDLE);\n ap_hook_map_to_storage(lua_map_to_storage_harness, NULL, NULL,\n APR_HOOK_MIDDLE);", "/* XXX: Does not work :( \n * ap_hook_check_user_id(lua_check_user_id_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n */\n ap_hook_check_user_id(lua_check_user_id_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n/* XXX: Does not work :(\n * ap_hook_check_user_id(lua_check_user_id_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);\n*/\n ap_hook_type_checker(lua_type_checker_harness, NULL, NULL,\n APR_HOOK_MIDDLE);", " ap_hook_access_checker(lua_access_checker_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n ap_hook_access_checker(lua_access_checker_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_access_checker(lua_access_checker_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);\n ap_hook_auth_checker(lua_auth_checker_harness_first, NULL, NULL,\n AP_LUA_HOOK_FIRST);\n ap_hook_auth_checker(lua_auth_checker_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_auth_checker(lua_auth_checker_harness_last, NULL, NULL,\n AP_LUA_HOOK_LAST);", " ap_hook_insert_filter(lua_insert_filter_harness, NULL, NULL,\n APR_HOOK_MIDDLE);\n ap_hook_quick_handler(lua_quick_harness, NULL, NULL, APR_HOOK_FIRST);", " ap_hook_post_config(lua_post_config, NULL, NULL, APR_HOOK_MIDDLE);\n ap_hook_pre_config(lua_pre_config, NULL, NULL, APR_HOOK_MIDDLE);", " APR_OPTIONAL_HOOK(ap_lua, lua_open, lua_open_hook, NULL, NULL,\n APR_HOOK_REALLY_FIRST);", " APR_OPTIONAL_HOOK(ap_lua, lua_request, lua_request_hook, NULL, NULL,\n APR_HOOK_REALLY_FIRST);\n ap_hook_handler(lua_map_handler, NULL, NULL, AP_LUA_HOOK_FIRST);\n \n /* Hook this right before FallbackResource kicks in */\n ap_hook_fixups(lua_map_handler_fixups, NULL, NULL, AP_LUA_HOOK_LAST-2);\n#if APR_HAS_THREADS\n ap_hook_child_init(ap_lua_init_mutex, NULL, NULL, APR_HOOK_MIDDLE);\n#endif\n /* providers */\n lua_authz_providers = apr_hash_make(p);\n \n /* Logging catcher */\n ap_hook_log_transaction(lua_log_transaction_harness,NULL,NULL,\n APR_HOOK_FIRST);\n}", "AP_DECLARE_MODULE(lua) = {\n STANDARD20_MODULE_STUFF,\n create_dir_config, /* create per-dir config structures */\n merge_dir_config, /* merge per-dir config structures */\n create_server_config, /* create per-server config structures */\n NULL, /* merge per-server config structures */\n lua_commands, /* table of config file commands */\n lua_register_hooks /* register hooks */\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [11, 114, 1760], "buggy_code_start_loc": [11, 107, 68], "filenames": ["CHANGES", "STATUS", "modules/lua/mod_lua.c"], "fixing_code_end_loc": [17, 106, 1767], "fixing_code_start_loc": [12, 106, 69], "message": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:http_server:2.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "6FCD3C8C-9BF8-4F30-981A-593EEAEB9EDD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "046487A3-752B-4D0F-8984-96486B828EAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "89D2E052-51CD-4B57-A8B8-FAE51988D654", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "EAA27058-BACF-4F94-8E3C-7D38EC302EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "8FEAB0DF-04A9-4F99-8666-0BADC5D642B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E7D924D1-8A36-4C43-9E56-52814F9A6350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.9:*:*:*:*:*:*:*", "matchCriteriaId": "39CDFECC-E26D-47E0-976F-6629040B3764", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:apache:http_server:2.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "E3ECBCB1-0675-41F5-857B-438F36925F63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:10.04:*:*:*:-:*:*:*", "matchCriteriaId": "01EDA41C-6B2E-49AF-B503-EB3882265C11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:-:*:*:*", "matchCriteriaId": "CB66DB75-2B16-4EBF-9B93-CE49D8086E41", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.10:*:*:*:*:*:*:*", "matchCriteriaId": "49A63F39-30BE-443F-AF10-6245587D3359", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:21:*:*:*:*:*:*:*", "matchCriteriaId": "56BDB5A0-0839-4A20-A003-B8CD56F48171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:*:*:*:*:*:*:*:*", "matchCriteriaId": "A70BB445-EF2B-4C9D-8502-FDD6A19F8C30", "versionEndExcluding": "12.1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "4725EA61-9BAB-4E72-9F92-ADE4624439CC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "D0879FB1-58E2-4EC4-8111-044642E046BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_ops_center:12.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "C7CF2929-4CBC-4B56-87AE-F45F53BD8DD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mod_lua.c in the mod_lua module in the Apache HTTP Server 2.3.x and 2.4.x through 2.4.10 does not support an httpd configuration in which the same Lua authorization provider is used with different arguments within different contexts, which allows remote attackers to bypass intended access restrictions in opportunistic circumstances by leveraging multiple Require directives, as demonstrated by a configuration that specifies authorization for one group to access a certain directory, and authorization for a second group to access a second directory."}, {"lang": "es", "value": "El m\u00f3dulo mod_lua.c en el m\u00f3dulo mod_lua en Apache HTTP Server 2.3.x y 2.4.x a trav\u00e9s de 2.4.10 no soporta la configuraci\u00f3n httpd en la cual el proveedor de autorizaci\u00f3n Lua se usa con argumentos diferentes dentro de contextos diferentes, lo que permite a atacantes remotos saltarse las restricciones de acceso en ciertas circunstancias aprovechando m\u00faltiples directivas requeridas, como se demuestra por una configuraci\u00f3n que especifica la autorizaci\u00f3n para un grupo para acceder a un directorio determinado, y una autorizaci\u00f3n para un segundo grupo para acceder a un segundo directorio."}], "evaluatorComment": null, "id": "CVE-2014-8109", "lastModified": "2023-02-13T00:42:40.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-29T23:59:00.053", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://advisories.mageia.org/MGASA-2015-0011.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Aug/msg00001.html"}, {"source": "secalert@redhat.com", "tags": ["Broken Link", "Mailing List"], "url": "http://lists.apple.com/archives/security-announce/2015/Sep/msg00004.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.fedoraproject.org/pipermail/package-announce/2015-June/159352.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/28/5"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.oracle.com/technetwork/topics/security/cpujan2016-2367955.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/73040"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2523-1"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1174077"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://issues.apache.org/bugzilla/show_bug.cgi?id=57204"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/56c2e7cc9deb1c12a843d0dc251ea7fd3e7e80293cde02fcd65286ba%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/84a3714f0878781f6ed84473d1a503d2cc382277e100450209231830%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r76142b8c5119df2178be7c2dba88fde552eedeec37ea993dfce68d1d%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r83109088737656fa6307bd99ab40f8ff0269ae58d3f7272d7048494a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/r9f93cf6dde308d42a9c807784e8102600d0397f5f834890708bf6920%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/ra7f6aeb28661fbf826969526585f16856abc4615877875f9d3b35ef4%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rb14daf9cc4e28d18cdc15d6a6ca74e565672fabf7ad89541071d008b%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rc998b18880df98bafaade071346690c2bc1444adaa1a1ea464b93f0a%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rcc44594d4d6579b90deccd4536b5d31f099ef563df39b094be286b9e%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rd18c3c43602e66f9cdcf09f1de233804975b9572b0456cc582390b6f%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/re3d27b6250aa8548b8845d314bb8a350b3df326cacbbfdfe4d455234%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.apache.org/thread.html/rf6449464fd8b7437704c55f88361b66f12d5b5f90bcce66af4be4ba9%40%3Ccvs.httpd.apache.org%3E"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/HT205219"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT205031"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/apache/httpd/commit/3f1693d558d0758f829c8b53993f1749ddf6ffcb"}, "type": "CWE-863"}
296
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2008-2015, Dave Benson and the protobuf-c authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */", "/*! \\file\n * Support library for `protoc-c` generated code.\n *\n * This file implements the public API used by the code generated\n * by `protoc-c`.\n *\n * \\authors Dave Benson and the protobuf-c authors\n *\n * \\copyright 2008-2014. Licensed under the terms of the [BSD-2-Clause] license.\n */", "/**\n * \\todo 64-BIT OPTIMIZATION: certain implementations use 32-bit math\n * even on 64-bit platforms (uint64_size, uint64_pack, parse_uint64).\n *\n * \\todo Use size_t consistently.\n */", "#include <stdlib.h>\t/* for malloc, free */\n#include <string.h>\t/* for strcmp, strlen, memcpy, memmove, memset */", "#include \"protobuf-c.h\"", "#define TRUE\t\t\t\t1\n#define FALSE\t\t\t\t0", "#define PROTOBUF_C__ASSERT_NOT_REACHED() assert(0)", "/* Workaround for Microsoft compilers. */\n#ifdef _MSC_VER\n# define inline __inline\n#endif", "/**\n * \\defgroup internal Internal functions and macros\n *\n * These are not exported by the library but are useful to developers working\n * on `libprotobuf-c` itself.\n */", "/**\n * \\defgroup macros Utility macros for manipulating structures\n *\n * Macros and constants used to manipulate the base \"classes\" generated by\n * `protobuf-c`. They also define limits and check correctness.\n *\n * \\ingroup internal\n * @{\n */", "/** The maximum length of a 64-bit integer in varint encoding. */\n#define MAX_UINT64_ENCODED_SIZE\t\t10", "#ifndef PROTOBUF_C_UNPACK_ERROR\n# define PROTOBUF_C_UNPACK_ERROR(...)\n#endif", "#if !defined(_WIN32) || !defined(PROTOBUF_C_USE_SHARED_LIB)\nconst char protobuf_c_empty_string[] = \"\";\n#endif", "/**\n * Internal `ProtobufCMessage` manipulation macro.\n *\n * Base macro for manipulating a `ProtobufCMessage`. Used by STRUCT_MEMBER() and\n * STRUCT_MEMBER_PTR().\n */\n#define STRUCT_MEMBER_P(struct_p, struct_offset) \\\n ((void *) ((uint8_t *) (struct_p) + (struct_offset)))", "/**\n * Return field in a `ProtobufCMessage` based on offset.\n *\n * Take a pointer to a `ProtobufCMessage` and find the field at the offset.\n * Cast it to the passed type.\n */\n#define STRUCT_MEMBER(member_type, struct_p, struct_offset) \\\n (*(member_type *) STRUCT_MEMBER_P((struct_p), (struct_offset)))", "/**\n * Return field in a `ProtobufCMessage` based on offset.\n *\n * Take a pointer to a `ProtobufCMessage` and find the field at the offset. Cast\n * it to a pointer to the passed type.\n */\n#define STRUCT_MEMBER_PTR(member_type, struct_p, struct_offset) \\\n ((member_type *) STRUCT_MEMBER_P((struct_p), (struct_offset)))", "/* Assertions for magic numbers. */", "#define ASSERT_IS_ENUM_DESCRIPTOR(desc) \\\n\tassert((desc)->magic == PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC)", "#define ASSERT_IS_MESSAGE_DESCRIPTOR(desc) \\\n\tassert((desc)->magic == PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC)", "#define ASSERT_IS_MESSAGE(message) \\\n\tASSERT_IS_MESSAGE_DESCRIPTOR((message)->descriptor)", "#define ASSERT_IS_SERVICE_DESCRIPTOR(desc) \\\n\tassert((desc)->magic == PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC)", "/**@}*/", "/* --- version --- */", "const char *\nprotobuf_c_version(void)\n{\n\treturn PROTOBUF_C_VERSION;\n}", "uint32_t\nprotobuf_c_version_number(void)\n{\n\treturn PROTOBUF_C_VERSION_NUMBER;\n}", "/* --- allocator --- */", "static void *\nsystem_alloc(void *allocator_data, size_t size)\n{\n\t(void)allocator_data;\n\treturn malloc(size);\n}", "static void\nsystem_free(void *allocator_data, void *data)\n{\n\t(void)allocator_data;\n\tfree(data);\n}", "static inline void *\ndo_alloc(ProtobufCAllocator *allocator, size_t size)\n{\n\treturn allocator->alloc(allocator->allocator_data, size);\n}", "static inline void\ndo_free(ProtobufCAllocator *allocator, void *data)\n{\n\tif (data != NULL)\n\t\tallocator->free(allocator->allocator_data, data);\n}", "/*\n * This allocator uses the system's malloc() and free(). It is the default\n * allocator used if NULL is passed as the ProtobufCAllocator to an exported\n * function.\n */\nstatic ProtobufCAllocator protobuf_c__allocator = {\n\t.alloc = &system_alloc,\n\t.free = &system_free,\n\t.allocator_data = NULL,\n};", "/* === buffer-simple === */", "void\nprotobuf_c_buffer_simple_append(ProtobufCBuffer *buffer,\n\t\t\t\tsize_t len, const uint8_t *data)\n{\n\tProtobufCBufferSimple *simp = (ProtobufCBufferSimple *) buffer;\n\tsize_t new_len = simp->len + len;", "\tif (new_len > simp->alloced) {\n\t\tProtobufCAllocator *allocator = simp->allocator;\n\t\tsize_t new_alloced = simp->alloced * 2;\n\t\tuint8_t *new_data;", "\t\tif (allocator == NULL)\n\t\t\tallocator = &protobuf_c__allocator;\n\t\twhile (new_alloced < new_len)\n\t\t\tnew_alloced += new_alloced;\n\t\tnew_data = do_alloc(allocator, new_alloced);\n\t\tif (!new_data)\n\t\t\treturn;\n\t\tmemcpy(new_data, simp->data, simp->len);\n\t\tif (simp->must_free_data)\n\t\t\tdo_free(allocator, simp->data);\n\t\telse\n\t\t\tsimp->must_free_data = TRUE;\n\t\tsimp->data = new_data;\n\t\tsimp->alloced = new_alloced;\n\t}\n\tmemcpy(simp->data + simp->len, data, len);\n\tsimp->len = new_len;\n}", "/**\n * \\defgroup packedsz protobuf_c_message_get_packed_size() implementation\n *\n * Routines mainly used by protobuf_c_message_get_packed_size().\n *\n * \\ingroup internal\n * @{\n */", "/**\n * Return the number of bytes required to store the tag for the field. Includes\n * 3 bits for the wire-type, and a single bit that denotes the end-of-tag.\n *\n * \\param number\n * Field tag to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nget_tag_size(uint32_t number)\n{\n\tif (number < (1UL << 4)) {\n\t\treturn 1;\n\t} else if (number < (1UL << 11)) {\n\t\treturn 2;\n\t} else if (number < (1UL << 18)) {\n\t\treturn 3;\n\t} else if (number < (1UL << 25)) {\n\t\treturn 4;\n\t} else {\n\t\treturn 5;\n\t}\n}", "/**\n * Return the number of bytes required to store a variable-length unsigned\n * 32-bit integer in base-128 varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nuint32_size(uint32_t v)\n{\n\tif (v < (1UL << 7)) {\n\t\treturn 1;\n\t} else if (v < (1UL << 14)) {\n\t\treturn 2;\n\t} else if (v < (1UL << 21)) {\n\t\treturn 3;\n\t} else if (v < (1UL << 28)) {\n\t\treturn 4;\n\t} else {\n\t\treturn 5;\n\t}\n}", "/**\n * Return the number of bytes required to store a variable-length signed 32-bit\n * integer in base-128 varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nint32_size(int32_t v)\n{\n\tif (v < 0) {\n\t\treturn 10;\n\t} else if (v < (1L << 7)) {\n\t\treturn 1;\n\t} else if (v < (1L << 14)) {\n\t\treturn 2;\n\t} else if (v < (1L << 21)) {\n\t\treturn 3;\n\t} else if (v < (1L << 28)) {\n\t\treturn 4;\n\t} else {\n\t\treturn 5;\n\t}\n}", "/**\n * Return the ZigZag-encoded 32-bit unsigned integer form of a 32-bit signed\n * integer.\n *\n * \\param v\n * Value to encode.\n * \\return\n * ZigZag encoded integer.\n */\nstatic inline uint32_t\nzigzag32(int32_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn ((uint32_t)v << 1) ^ -((uint32_t)v >> 31);\n}", "/**\n * Return the number of bytes required to store a signed 32-bit integer,\n * converted to an unsigned 32-bit integer with ZigZag encoding, using base-128\n * varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nsint32_size(int32_t v)\n{\n\treturn uint32_size(zigzag32(v));\n}", "/**\n * Return the number of bytes required to store a 64-bit unsigned integer in\n * base-128 varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nuint64_size(uint64_t v)\n{\n\tuint32_t upper_v = (uint32_t) (v >> 32);", "\tif (upper_v == 0) {\n\t\treturn uint32_size((uint32_t) v);\n\t} else if (upper_v < (1UL << 3)) {\n\t\treturn 5;\n\t} else if (upper_v < (1UL << 10)) {\n\t\treturn 6;\n\t} else if (upper_v < (1UL << 17)) {\n\t\treturn 7;\n\t} else if (upper_v < (1UL << 24)) {\n\t\treturn 8;\n\t} else if (upper_v < (1UL << 31)) {\n\t\treturn 9;\n\t} else {\n\t\treturn 10;\n\t}\n}", "/**\n * Return the ZigZag-encoded 64-bit unsigned integer form of a 64-bit signed\n * integer.\n *\n * \\param v\n * Value to encode.\n * \\return\n * ZigZag encoded integer.\n */\nstatic inline uint64_t\nzigzag64(int64_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn ((uint64_t)v << 1) ^ -((uint64_t)v >> 63);\n}", "/**\n * Return the number of bytes required to store a signed 64-bit integer,\n * converted to an unsigned 64-bit integer with ZigZag encoding, using base-128\n * varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nsint64_size(int64_t v)\n{\n\treturn uint64_size(zigzag64(v));\n}", "/**\n * Calculate the serialized size of a single required message field, including\n * the space needed by the preceding tag.\n *\n * \\param field\n * Field descriptor for member.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nrequired_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t const void *member)\n{\n\tsize_t rv = get_tag_size(field->id);", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\treturn rv + sint32_size(*(const int32_t *) member);\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\treturn rv + int32_size(*(const int32_t *) member);\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\treturn rv + uint32_size(*(const uint32_t *) member);\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\treturn rv + sint64_size(*(const int64_t *) member);\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\treturn rv + uint64_size(*(const uint64_t *) member);\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\treturn rv + 4;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\treturn rv + 8;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\treturn rv + 1;\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\treturn rv + 4;\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\treturn rv + 8;\n\tcase PROTOBUF_C_TYPE_STRING: {\n\t\tconst char *str = *(char * const *) member;\n\t\tsize_t len = str ? strlen(str) : 0;\n\t\treturn rv + uint32_size(len) + len;\n\t}\n\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\tsize_t len = ((const ProtobufCBinaryData *) member)->len;\n\t\treturn rv + uint32_size(len) + len;\n\t}\n\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\tconst ProtobufCMessage *msg = *(ProtobufCMessage * const *) member;\n\t\tsize_t subrv = msg ? protobuf_c_message_get_packed_size(msg) : 0;\n\t\treturn rv + uint32_size(subrv) + subrv;\n\t}\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Calculate the serialized size of a single oneof message field, including\n * the space needed by the preceding tag. Returns 0 if the oneof field isn't\n * selected or is not set.\n *\n * \\param field\n * Field descriptor for member.\n * \\param oneof_case\n * Enum value that selects the field in the oneof.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\noneof_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t uint32_t oneof_case,\n\t\t\t const void *member)\n{\n\tif (oneof_case != field->id) {\n\t\treturn 0;\n\t}\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t}\n\treturn required_field_get_packed_size(field, member);\n}", "/**\n * Calculate the serialized size of a single optional message field, including\n * the space needed by the preceding tag. Returns 0 if the optional field isn't\n * set.\n *\n * \\param field\n * Field descriptor for member.\n * \\param has\n * True if the field exists, false if not.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\noptional_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t const protobuf_c_boolean has,\n\t\t\t const void *member)\n{\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t} else {\n\t\tif (!has)\n\t\t\treturn 0;\n\t}\n\treturn required_field_get_packed_size(field, member);\n}", "static protobuf_c_boolean\nfield_is_zeroish(const ProtobufCFieldDescriptor *field,\n\t\t const void *member)\n{\n\tprotobuf_c_boolean ret = FALSE;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tret = (0 == *(const protobuf_c_boolean *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_SINT32:\n\tcase PROTOBUF_C_TYPE_INT32:\n\tcase PROTOBUF_C_TYPE_UINT32:\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\tret = (0 == *(const uint32_t *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\tret = (0 == *(const uint64_t *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tret = (0 == *(const float *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tret = (0 == *(const double *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_STRING:\n\t\tret = (NULL == *(const char * const *) member) ||\n\t\t ('\\0' == **(const char * const *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BYTES:\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\tret = (NULL == *(const void * const *) member);\n\t\tbreak;\n\tdefault:\n\t\tret = TRUE;\n\t\tbreak;\n\t}", "\treturn ret;\n}", "/**\n * Calculate the serialized size of a single unlabeled message field, including\n * the space needed by the preceding tag. Returns 0 if the field isn't set or\n * if it is set to a \"zeroish\" value (null pointer or 0 for numerical values).\n * Unlabeled fields are supported only in proto3.\n *\n * \\param field\n * Field descriptor for member.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nunlabeled_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t\tconst void *member)\n{\n\tif (field_is_zeroish(field, member))\n\t\treturn 0;\n\treturn required_field_get_packed_size(field, member);\n}", "/**\n * Calculate the serialized size of repeated message fields, which may consist\n * of any number of values (including 0). Includes the space needed by the\n * preceding tags (as needed).\n *\n * \\param field\n * Field descriptor for member.\n * \\param count\n * Number of repeated field members.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nrepeated_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t size_t count, const void *member)\n{\n\tsize_t header_size;\n\tsize_t rv = 0;\n\tunsigned i;\n\tvoid *array = *(void * const *) member;", "\tif (count == 0)\n\t\treturn 0;\n\theader_size = get_tag_size(field->id);\n\tif (0 == (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED))\n\t\theader_size *= count;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint32_size(((int32_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += int32_size(((int32_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint32_size(((uint32_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint64_size(((int64_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint64_size(((uint64_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\trv += 4 * count;\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\trv += 8 * count;\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\trv += count;\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_STRING:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tsize_t len = strlen(((char **) array)[i]);\n\t\t\trv += uint32_size(len) + len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BYTES:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tsize_t len = ((ProtobufCBinaryData *) array)[i].len;\n\t\t\trv += uint32_size(len) + len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tsize_t len = protobuf_c_message_get_packed_size(\n\t\t\t\t((ProtobufCMessage **) array)[i]);\n\t\t\trv += uint32_size(len) + len;\n\t\t}\n\t\tbreak;\n\t}", "\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED))\n\t\theader_size += uint32_size(rv);\n\treturn header_size + rv;\n}", "/**\n * Calculate the serialized size of an unknown field, i.e. one that is passed\n * through mostly uninterpreted. This is required for forward compatibility if\n * new fields are added to the message descriptor.\n *\n * \\param field\n * Unknown field type.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nunknown_field_get_packed_size(const ProtobufCMessageUnknownField *field)\n{\n\treturn get_tag_size(field->tag) + field->len;\n}", "/**@}*/", "/*\n * Calculate the serialized size of the message.\n */\nsize_t protobuf_c_message_get_packed_size(const ProtobufCMessage *message)\n{\n\tunsigned i;\n\tsize_t rv = 0;", "\tASSERT_IS_MESSAGE(message);\n\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *field =\n\t\t\tmessage->descriptor->fields + i;\n\t\tconst void *member =\n\t\t\t((const char *) message) + field->offset;\n\t\tconst void *qmember =\n\t\t\t((const char *) message) + field->quantifier_offset;", "\t\tif (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\trv += required_field_get_packed_size(field, member);\n\t\t} else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t field->label == PROTOBUF_C_LABEL_NONE) &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {\n\t\t\trv += oneof_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\t*(const uint32_t *) qmember,\n\t\t\t\tmember\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {\n\t\t\trv += optional_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\t*(protobuf_c_boolean *) qmember,\n\t\t\t\tmember\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_NONE) {\n\t\t\trv += unlabeled_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\tmember\n\t\t\t);\n\t\t} else {\n\t\t\trv += repeated_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\t*(const size_t *) qmember,\n\t\t\t\tmember\n\t\t\t);\n\t\t}\n\t}\n\tfor (i = 0; i < message->n_unknown_fields; i++)\n\t\trv += unknown_field_get_packed_size(&message->unknown_fields[i]);\n\treturn rv;\n}", "/**\n * \\defgroup pack protobuf_c_message_pack() implementation\n *\n * Routines mainly used by protobuf_c_message_pack().\n *\n * \\ingroup internal\n * @{\n */", "/**\n * Pack an unsigned 32-bit integer in base-128 varint encoding and return the\n * number of bytes written, which must be 5 or less.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nuint32_pack(uint32_t value, uint8_t *out)\n{\n\tunsigned rv = 0;", "\tif (value >= 0x80) {\n\t\tout[rv++] = value | 0x80;\n\t\tvalue >>= 7;\n\t\tif (value >= 0x80) {\n\t\t\tout[rv++] = value | 0x80;\n\t\t\tvalue >>= 7;\n\t\t\tif (value >= 0x80) {\n\t\t\t\tout[rv++] = value | 0x80;\n\t\t\t\tvalue >>= 7;\n\t\t\t\tif (value >= 0x80) {\n\t\t\t\t\tout[rv++] = value | 0x80;\n\t\t\t\t\tvalue >>= 7;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/* assert: value<128 */\n\tout[rv++] = value;\n\treturn rv;\n}", "/**\n * Pack a signed 32-bit integer and return the number of bytes written,\n * passed as unsigned to avoid implementation-specific behavior.\n * Negative numbers are encoded as two's complement 64-bit integers.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nint32_pack(uint32_t value, uint8_t *out)\n{\n\tif ((int32_t)value < 0) {\n\t\tout[0] = value | 0x80;\n\t\tout[1] = (value >> 7) | 0x80;\n\t\tout[2] = (value >> 14) | 0x80;\n\t\tout[3] = (value >> 21) | 0x80;\n\t\tout[4] = (value >> 28) | 0xf0;\n\t\tout[5] = out[6] = out[7] = out[8] = 0xff;\n\t\tout[9] = 0x01;\n\t\treturn 10;\n\t} else {\n\t\treturn uint32_pack(value, out);\n\t}\n}", "/**\n * Pack a signed 32-bit integer using ZigZag encoding and return the number of\n * bytes written.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nsint32_pack(int32_t value, uint8_t *out)\n{\n\treturn uint32_pack(zigzag32(value), out);\n}", "/**\n * Pack a 64-bit unsigned integer using base-128 varint encoding and return the\n * number of bytes written.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\nuint64_pack(uint64_t value, uint8_t *out)\n{\n\tuint32_t hi = (uint32_t) (value >> 32);\n\tuint32_t lo = (uint32_t) value;\n\tunsigned rv;", "\tif (hi == 0)\n\t\treturn uint32_pack((uint32_t) lo, out);\n\tout[0] = (lo) | 0x80;\n\tout[1] = (lo >> 7) | 0x80;\n\tout[2] = (lo >> 14) | 0x80;\n\tout[3] = (lo >> 21) | 0x80;\n\tif (hi < 8) {\n\t\tout[4] = (hi << 4) | (lo >> 28);\n\t\treturn 5;\n\t} else {\n\t\tout[4] = ((hi & 7) << 4) | (lo >> 28) | 0x80;\n\t\thi >>= 3;\n\t}\n\trv = 5;\n\twhile (hi >= 128) {\n\t\tout[rv++] = hi | 0x80;\n\t\thi >>= 7;\n\t}\n\tout[rv++] = hi;\n\treturn rv;\n}", "/**\n * Pack a 64-bit signed integer in ZigZag encoding and return the number of\n * bytes written.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nsint64_pack(int64_t value, uint8_t *out)\n{\n\treturn uint64_pack(zigzag64(value), out);\n}", "/**\n * Pack a 32-bit quantity in little-endian byte order. Used for protobuf wire\n * types fixed32, sfixed32, float. Similar to \"htole32\".\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nfixed32_pack(uint32_t value, void *out)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, &value, 4);\n#else\n\tuint8_t *buf = out;", "\tbuf[0] = value;\n\tbuf[1] = value >> 8;\n\tbuf[2] = value >> 16;\n\tbuf[3] = value >> 24;\n#endif\n\treturn 4;\n}", "/**\n * Pack a 64-bit quantity in little-endian byte order. Used for protobuf wire\n * types fixed64, sfixed64, double. Similar to \"htole64\".\n *\n * \\todo The big-endian impl is really only good for 32-bit machines, a 64-bit\n * version would be appreciated, plus a way to decide to use 64-bit math where\n * convenient.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nfixed64_pack(uint64_t value, void *out)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, &value, 8);\n#else\n\tfixed32_pack(value, out);\n\tfixed32_pack(value >> 32, ((char *) out) + 4);\n#endif\n\treturn 8;\n}", "/**\n * Pack a boolean value as an integer and return the number of bytes written.\n *\n * \\todo Perhaps on some platforms *out = !!value would be a better impl, b/c\n * that is idiomatic C++ in some STL implementations.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nboolean_pack(protobuf_c_boolean value, uint8_t *out)\n{\n\t*out = value ? TRUE : FALSE;\n\treturn 1;\n}", "/**\n * Pack a NUL-terminated C string and return the number of bytes written. The\n * output includes a length delimiter.\n *\n * The NULL pointer is treated as an empty string. This isn't really necessary,\n * but it allows people to leave required strings blank. (See Issue #13 in the\n * bug tracker for a little more explanation).\n *\n * \\param str\n * String to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nstring_pack(const char *str, uint8_t *out)\n{\n\tif (str == NULL) {\n\t\tout[0] = 0;\n\t\treturn 1;\n\t} else {\n\t\tsize_t len = strlen(str);\n\t\tsize_t rv = uint32_pack(len, out);\n\t\tmemcpy(out + rv, str, len);\n\t\treturn rv + len;\n\t}\n}", "/**\n * Pack a ProtobufCBinaryData and return the number of bytes written. The output\n * includes a length delimiter.\n *\n * \\param bd\n * ProtobufCBinaryData to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nbinary_data_pack(const ProtobufCBinaryData *bd, uint8_t *out)\n{\n\tsize_t len = bd->len;\n\tsize_t rv = uint32_pack(len, out);\n\tmemcpy(out + rv, bd->data, len);\n\treturn rv + len;\n}", "/**\n * Pack a ProtobufCMessage and return the number of bytes written. The output\n * includes a length delimiter.\n *\n * \\param message\n * ProtobufCMessage object to pack.\n * \\param[out] out\n * Packed message.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nprefixed_message_pack(const ProtobufCMessage *message, uint8_t *out)\n{\n\tif (message == NULL) {\n\t\tout[0] = 0;\n\t\treturn 1;\n\t} else {\n\t\tsize_t rv = protobuf_c_message_pack(message, out + 1);\n\t\tuint32_t rv_packed_size = uint32_size(rv);\n\t\tif (rv_packed_size != 1)\n\t\t\tmemmove(out + rv_packed_size, out + 1, rv);\n\t\treturn uint32_pack(rv, out) + rv;\n\t}\n}", "/**\n * Pack a field tag.\n *\n * Wire-type will be added in required_field_pack().\n *\n * \\todo Just call uint64_pack on 64-bit platforms.\n *\n * \\param id\n * Tag value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\ntag_pack(uint32_t id, uint8_t *out)\n{\n\tif (id < (1UL << (32 - 3)))\n\t\treturn uint32_pack(id << 3, out);\n\telse\n\t\treturn uint64_pack(((uint64_t) id) << 3, out);\n}", "/**\n * Pack a required field and return the number of bytes written.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\nrequired_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t const void *member, uint8_t *out)\n{\n\tsize_t rv = tag_pack(field->id, out);", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + sint32_pack(*(const int32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + int32_pack(*(const int32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + uint32_pack(*(const uint32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + sint64_pack(*(const int64_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + uint64_pack(*(const uint64_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_32BIT;\n\t\treturn rv + fixed32_pack(*(const uint32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_64BIT;\n\t\treturn rv + fixed64_pack(*(const uint64_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + boolean_pack(*(const protobuf_c_boolean *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_STRING:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\treturn rv + string_pack(*(char *const *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_BYTES:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\treturn rv + binary_data_pack((const ProtobufCBinaryData *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\treturn rv + prefixed_message_pack(*(ProtobufCMessage * const *) member, out + rv);\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Pack a oneof field and return the number of bytes written. Only packs the\n * field that is selected by the case enum.\n *\n * \\param field\n * Field descriptor.\n * \\param oneof_case\n * Enum value that selects the field in the oneof.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\noneof_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t uint32_t oneof_case,\n\t\t const void *member, uint8_t *out)\n{\n\tif (oneof_case != field->id) {\n\t\treturn 0;\n\t}\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack(field, member, out);\n}", "/**\n * Pack an optional field and return the number of bytes written.\n *\n * \\param field\n * Field descriptor.\n * \\param has\n * Whether the field is set.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\noptional_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t const protobuf_c_boolean has,\n\t\t const void *member, uint8_t *out)\n{\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t} else {\n\t\tif (!has)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack(field, member, out);\n}", "/**\n * Pack an unlabeled field and return the number of bytes written.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\nunlabeled_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t const void *member, uint8_t *out)\n{\n\tif (field_is_zeroish(field, member))\n\t\treturn 0;\n\treturn required_field_pack(field, member, out);\n}", "/**\n * Given a field type, return the in-memory size.\n *\n * \\todo Implement as a table lookup.\n *\n * \\param type\n * Field type.\n * \\return\n * Size of the field.\n */\nstatic inline size_t\nsizeof_elt_in_repeated_array(ProtobufCType type)\n{\n\tswitch (type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\tcase PROTOBUF_C_TYPE_INT32:\n\tcase PROTOBUF_C_TYPE_UINT32:\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\tcase PROTOBUF_C_TYPE_ENUM:\n\t\treturn 4;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\treturn 8;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\treturn sizeof(protobuf_c_boolean);\n\tcase PROTOBUF_C_TYPE_STRING:\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\treturn sizeof(void *);\n\tcase PROTOBUF_C_TYPE_BYTES:\n\t\treturn sizeof(ProtobufCBinaryData);\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Pack an array of 32-bit quantities.\n *\n * \\param[out] out\n * Destination.\n * \\param[in] in\n * Source.\n * \\param[in] n\n * Number of elements in the source array.\n */\nstatic void\ncopy_to_little_endian_32(void *out, const void *in, const unsigned n)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, in, n * 4);\n#else\n\tunsigned i;\n\tconst uint32_t *ini = in;\n\tfor (i = 0; i < n; i++)\n\t\tfixed32_pack(ini[i], (uint32_t *) out + i);\n#endif\n}", "/**\n * Pack an array of 64-bit quantities.\n *\n * \\param[out] out\n * Destination.\n * \\param[in] in\n * Source.\n * \\param[in] n\n * Number of elements in the source array.\n */\nstatic void\ncopy_to_little_endian_64(void *out, const void *in, const unsigned n)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, in, n * 8);\n#else\n\tunsigned i;\n\tconst uint64_t *ini = in;\n\tfor (i = 0; i < n; i++)\n\t\tfixed64_pack(ini[i], (uint64_t *) out + i);\n#endif\n}", "/**\n * Get the minimum number of bytes required to pack a field value of a\n * particular type.\n *\n * \\param type\n * Field type.\n * \\return\n * Number of bytes.\n */\nstatic unsigned\nget_type_min_size(ProtobufCType type)\n{\n\tif (type == PROTOBUF_C_TYPE_SFIXED32 ||\n\t type == PROTOBUF_C_TYPE_FIXED32 ||\n\t type == PROTOBUF_C_TYPE_FLOAT)\n\t{\n\t\treturn 4;\n\t}\n\tif (type == PROTOBUF_C_TYPE_SFIXED64 ||\n\t type == PROTOBUF_C_TYPE_FIXED64 ||\n\t type == PROTOBUF_C_TYPE_DOUBLE)\n\t{\n\t\treturn 8;\n\t}\n\treturn 1;\n}", "/**\n * Packs the elements of a repeated field and returns the serialised field and\n * its length.\n *\n * \\param field\n * Field descriptor.\n * \\param count\n * Number of elements in the repeated field array.\n * \\param member\n * Pointer to the elements for this repeated field.\n * \\param[out] out\n * Serialised representation of the repeated field.\n * \\return\n * Number of bytes serialised to `out`.\n */\nstatic size_t\nrepeated_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t size_t count, const void *member, uint8_t *out)\n{\n\tvoid *array = *(void * const *) member;\n\tunsigned i;", "\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) {\n\t\tunsigned header_len;\n\t\tunsigned len_start;\n\t\tunsigned min_length;\n\t\tunsigned payload_len;\n\t\tunsigned length_size_min;\n\t\tunsigned actual_length_size;\n\t\tuint8_t *payload_at;", "\t\tif (count == 0)\n\t\t\treturn 0;\n\t\theader_len = tag_pack(field->id, out);\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\tlen_start = header_len;\n\t\tmin_length = get_type_min_size(field->type) * count;\n\t\tlength_size_min = uint32_size(min_length);\n\t\theader_len += length_size_min;\n\t\tpayload_at = out + header_len;", "\t\tswitch (field->type) {\n\t\tcase PROTOBUF_C_TYPE_SFIXED32:\n\t\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\t\tcopy_to_little_endian_32(payload_at, array, count);\n\t\t\tpayload_at += count * 4;\n\t\t\tbreak;\n\t\tcase PROTOBUF_C_TYPE_SFIXED64:\n\t\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\t\tcopy_to_little_endian_64(payload_at, array, count);\n\t\t\tpayload_at += count * 8;\n\t\t\tbreak;\n\t\tcase PROTOBUF_C_TYPE_ENUM:\n\t\tcase PROTOBUF_C_TYPE_INT32: {\n\t\t\tconst int32_t *arr = (const int32_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += int32_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_SINT32: {\n\t\t\tconst int32_t *arr = (const int32_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += sint32_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_SINT64: {\n\t\t\tconst int64_t *arr = (const int64_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += sint64_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_UINT32: {\n\t\t\tconst uint32_t *arr = (const uint32_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += uint32_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_INT64:\n\t\tcase PROTOBUF_C_TYPE_UINT64: {\n\t\t\tconst uint64_t *arr = (const uint64_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += uint64_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_BOOL: {\n\t\t\tconst protobuf_c_boolean *arr = (const protobuf_c_boolean *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += boolean_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t\t}", "\t\tpayload_len = payload_at - (out + header_len);\n\t\tactual_length_size = uint32_size(payload_len);\n\t\tif (length_size_min != actual_length_size) {\n\t\t\tassert(actual_length_size == length_size_min + 1);\n\t\t\tmemmove(out + header_len + 1, out + header_len,\n\t\t\t\tpayload_len);\n\t\t\theader_len++;\n\t\t}\n\t\tuint32_pack(payload_len, out + len_start);\n\t\treturn header_len + payload_len;\n\t} else {\n\t\t/* not \"packed\" cased */\n\t\t/* CONSIDER: optimize this case a bit (by putting the loop inside the switch) */\n\t\tsize_t rv = 0;\n\t\tunsigned siz = sizeof_elt_in_repeated_array(field->type);", "\t\tfor (i = 0; i < count; i++) {\n\t\t\trv += required_field_pack(field, array, out + rv);\n\t\t\tarray = (char *)array + siz;\n\t\t}\n\t\treturn rv;\n\t}\n}", "static size_t\nunknown_field_pack(const ProtobufCMessageUnknownField *field, uint8_t *out)\n{\n\tsize_t rv = tag_pack(field->tag, out);\n\tout[0] |= field->wire_type;\n\tmemcpy(out + rv, field->data, field->len);\n\treturn rv + field->len;\n}", "/**@}*/", "size_t\nprotobuf_c_message_pack(const ProtobufCMessage *message, uint8_t *out)\n{\n\tunsigned i;\n\tsize_t rv = 0;", "\tASSERT_IS_MESSAGE(message);\n\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *field =\n\t\t\tmessage->descriptor->fields + i;\n\t\tconst void *member = ((const char *) message) + field->offset;", "\t\t/*\n\t\t * It doesn't hurt to compute qmember (a pointer to the\n\t\t * quantifier field of the structure), but the pointer is only\n\t\t * valid if the field is:\n\t\t * - a repeated field, or\n\t\t * - a field that is part of a oneof\n\t\t * - an optional field that isn't a pointer type\n\t\t * (Meaning: not a message or a string).\n\t\t */\n\t\tconst void *qmember =\n\t\t\t((const char *) message) + field->quantifier_offset;", "\t\tif (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\trv += required_field_pack(field, member, out + rv);\n\t\t} else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t field->label == PROTOBUF_C_LABEL_NONE) &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {\n\t\t\trv += oneof_field_pack(\n\t\t\t\tfield,\n\t\t\t\t*(const uint32_t *) qmember,\n\t\t\t\tmember,\n\t\t\t\tout + rv\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {\n\t\t\trv += optional_field_pack(\n\t\t\t\tfield,\n\t\t\t\t*(const protobuf_c_boolean *) qmember,\n\t\t\t\tmember,\n\t\t\t\tout + rv\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_NONE) {\n\t\t\trv += unlabeled_field_pack(field, member, out + rv);\n\t\t} else {\n\t\t\trv += repeated_field_pack(field, *(const size_t *) qmember,\n\t\t\t\tmember, out + rv);\n\t\t}\n\t}\n\tfor (i = 0; i < message->n_unknown_fields; i++)\n\t\trv += unknown_field_pack(&message->unknown_fields[i], out + rv);\n\treturn rv;\n}", "/**\n * \\defgroup packbuf protobuf_c_message_pack_to_buffer() implementation\n *\n * Routines mainly used by protobuf_c_message_pack_to_buffer().\n *\n * \\ingroup internal\n * @{\n */", "/**\n * Pack a required field to a virtual buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes packed.\n */\nstatic size_t\nrequired_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tsize_t rv;\n\tuint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2];", "\trv = tag_pack(field->id, scratch);\n\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += sint32_pack(*(const int32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += int32_pack(*(const int32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += uint32_pack(*(const uint32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += sint64_pack(*(const int64_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += uint64_pack(*(const uint64_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_32BIT;\n\t\trv += fixed32_pack(*(const uint32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_64BIT;\n\t\trv += fixed64_pack(*(const uint64_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += boolean_pack(*(const protobuf_c_boolean *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_STRING: {\n\t\tconst char *str = *(char *const *) member;\n\t\tsize_t sublen = str ? strlen(str) : 0;", "\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\trv += uint32_pack(sublen, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbuffer->append(buffer, sublen, (const uint8_t *) str);\n\t\trv += sublen;\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\tconst ProtobufCBinaryData *bd = ((const ProtobufCBinaryData *) member);\n\t\tsize_t sublen = bd->len;", "\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\trv += uint32_pack(sublen, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbuffer->append(buffer, sublen, bd->data);\n\t\trv += sublen;\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\tconst ProtobufCMessage *msg = *(ProtobufCMessage * const *) member;\n\t\t\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\tif (msg == NULL) {\n\t\t\trv += uint32_pack(0, scratch + rv);\n\t\t\tbuffer->append(buffer, rv, scratch);\n\t\t} else {\n\t\t\tsize_t sublen = protobuf_c_message_get_packed_size(msg);\n\t\t\trv += uint32_pack(sublen, scratch + rv);\n\t\t\tbuffer->append(buffer, rv, scratch);\n\t\t\tprotobuf_c_message_pack_to_buffer(msg, buffer);\n\t\t\trv += sublen;\n\t\t}\n\t\tbreak;\n\t}\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\treturn rv;\n}", "/**\n * Pack a oneof field to a buffer. Only packs the field that is selected by the case enum.\n *\n * \\param field\n * Field descriptor.\n * \\param oneof_case\n * Enum value that selects the field in the oneof.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes serialised to `buffer`.\n */\nstatic size_t\noneof_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t uint32_t oneof_case,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tif (oneof_case != field->id) {\n\t\treturn 0;\n\t}\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void *const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack_to_buffer(field, member, buffer);\n}", "/**\n * Pack an optional field to a buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param has\n * Whether the field is set.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes serialised to `buffer`.\n */\nstatic size_t\noptional_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t const protobuf_c_boolean has,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void *const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t} else {\n\t\tif (!has)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack_to_buffer(field, member, buffer);\n}", "/**\n * Pack an unlabeled field to a buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes serialised to `buffer`.\n */\nstatic size_t\nunlabeled_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tif (field_is_zeroish(field, member))\n\t\treturn 0;\n\treturn required_field_pack_to_buffer(field, member, buffer);\n}", "/**\n * Get the packed size of an array of same field type.\n *\n * \\param field\n * Field descriptor.\n * \\param count\n * Number of elements of this type.\n * \\param array\n * The elements to get the size of.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nget_packed_payload_length(const ProtobufCFieldDescriptor *field,\n\t\t\t unsigned count, const void *array)\n{\n\tunsigned rv = 0;\n\tunsigned i;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\treturn count * 4;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\treturn count * 8;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32: {\n\t\tconst int32_t *arr = (const int32_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += int32_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_SINT32: {\n\t\tconst int32_t *arr = (const int32_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint32_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_UINT32: {\n\t\tconst uint32_t *arr = (const uint32_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint32_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_SINT64: {\n\t\tconst int64_t *arr = (const int64_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint64_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64: {\n\t\tconst uint64_t *arr = (const uint64_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint64_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\treturn count;\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\treturn rv;\n}", "/**\n * Pack an array of same field type to a virtual buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param count\n * Number of elements of this type.\n * \\param array\n * The elements to get the size of.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes packed.\n */\nstatic size_t\npack_buffer_packed_payload(const ProtobufCFieldDescriptor *field,\n\t\t\t unsigned count, const void *array,\n\t\t\t ProtobufCBuffer *buffer)\n{\n\tuint8_t scratch[16];\n\tsize_t rv = 0;\n\tunsigned i;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n#if !defined(WORDS_BIGENDIAN)\n\t\trv = count * 4;\n\t\tgoto no_packing_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = fixed32_pack(((uint32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n#if !defined(WORDS_BIGENDIAN)\n\t\trv = count * 8;\n\t\tgoto no_packing_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = fixed64_pack(((uint64_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = int32_pack(((int32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = sint32_pack(((int32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = uint32_pack(((uint32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = sint64_pack(((int64_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = uint64_pack(((uint64_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = boolean_pack(((protobuf_c_boolean *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\treturn count;\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\treturn rv;", "#if !defined(WORDS_BIGENDIAN)\nno_packing_needed:\n\tbuffer->append(buffer, rv, array);\n\treturn rv;\n#endif\n}", "static size_t\nrepeated_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t unsigned count, const void *member,\n\t\t\t ProtobufCBuffer *buffer)\n{\n\tchar *array = *(char * const *) member;", "\tif (count == 0)\n\t\treturn 0;\n\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) {\n\t\tuint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2];\n\t\tsize_t rv = tag_pack(field->id, scratch);\n\t\tsize_t payload_len = get_packed_payload_length(field, count, array);\n\t\tsize_t tmp;", "\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\trv += uint32_pack(payload_len, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\ttmp = pack_buffer_packed_payload(field, count, array, buffer);\n\t\tassert(tmp == payload_len);\n\t\treturn rv + payload_len;\n\t} else {\n\t\tsize_t siz;\n\t\tunsigned i;\n\t\t/* CONSIDER: optimize this case a bit (by putting the loop inside the switch) */\n\t\tunsigned rv = 0;", "\t\tsiz = sizeof_elt_in_repeated_array(field->type);\n\t\tfor (i = 0; i < count; i++) {\n\t\t\trv += required_field_pack_to_buffer(field, array, buffer);\n\t\t\tarray += siz;\n\t\t}\n\t\treturn rv;\n\t}\n}", "static size_t\nunknown_field_pack_to_buffer(const ProtobufCMessageUnknownField *field,\n\t\t\t ProtobufCBuffer *buffer)\n{\n\tuint8_t header[MAX_UINT64_ENCODED_SIZE];\n\tsize_t rv = tag_pack(field->tag, header);", "\theader[0] |= field->wire_type;\n\tbuffer->append(buffer, rv, header);\n\tbuffer->append(buffer, field->len, field->data);\n\treturn rv + field->len;\n}", "/**@}*/", "size_t\nprotobuf_c_message_pack_to_buffer(const ProtobufCMessage *message,\n\t\t\t\t ProtobufCBuffer *buffer)\n{\n\tunsigned i;\n\tsize_t rv = 0;", "\tASSERT_IS_MESSAGE(message);\n\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *field =\n\t\t\tmessage->descriptor->fields + i;\n\t\tconst void *member =\n\t\t\t((const char *) message) + field->offset;\n\t\tconst void *qmember =\n\t\t\t((const char *) message) + field->quantifier_offset;", "\t\tif (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\trv += required_field_pack_to_buffer(field, member, buffer);\n\t\t} else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t field->label == PROTOBUF_C_LABEL_NONE) &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {\n\t\t\trv += oneof_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\t*(const uint32_t *) qmember,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {\n\t\t\trv += optional_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\t*(const protobuf_c_boolean *) qmember,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_NONE) {\n\t\t\trv += unlabeled_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t} else {\n\t\t\trv += repeated_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\t*(const size_t *) qmember,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t}\n\t}\n\tfor (i = 0; i < message->n_unknown_fields; i++)\n\t\trv += unknown_field_pack_to_buffer(&message->unknown_fields[i], buffer);", "\treturn rv;\n}", "/**\n * \\defgroup unpack unpacking implementation\n *\n * Routines mainly used by the unpacking functions.\n *\n * \\ingroup internal\n * @{\n */", "static inline int\nint_range_lookup(unsigned n_ranges, const ProtobufCIntRange *ranges, int value)\n{\n\tunsigned n;\n\tunsigned start;", "\tif (n_ranges == 0)\n\t\treturn -1;\n\tstart = 0;\n\tn = n_ranges;\n\twhile (n > 1) {\n\t\tunsigned mid = start + n / 2;", "\t\tif (value < ranges[mid].start_value) {\n\t\t\tn = mid - start;\n\t\t} else if (value >= ranges[mid].start_value +\n\t\t\t (int) (ranges[mid + 1].orig_index -\n\t\t\t\t ranges[mid].orig_index))\n\t\t{\n\t\t\tunsigned new_start = mid + 1;\n\t\t\tn = start + n - new_start;\n\t\t\tstart = new_start;\n\t\t} else\n\t\t\treturn (value - ranges[mid].start_value) +\n\t\t\t ranges[mid].orig_index;\n\t}\n\tif (n > 0) {\n\t\tunsigned start_orig_index = ranges[start].orig_index;\n\t\tunsigned range_size =\n\t\t\tranges[start + 1].orig_index - start_orig_index;", "\t\tif (ranges[start].start_value <= value &&\n\t\t value < (int) (ranges[start].start_value + range_size))\n\t\t{\n\t\t\treturn (value - ranges[start].start_value) +\n\t\t\t start_orig_index;\n\t\t}\n\t}\n\treturn -1;\n}", "static size_t\nparse_tag_and_wiretype(size_t len,\n\t\t const uint8_t *data,\n\t\t uint32_t *tag_out,\n\t\t uint8_t *wiretype_out)\n{\n\tunsigned max_rv = len > 5 ? 5 : len;\n\tuint32_t tag = (data[0] & 0x7f) >> 3;\n\tunsigned shift = 4;\n\tunsigned rv;", "\t/* 0 is not a valid tag value */\n\tif ((data[0] & 0xf8) == 0) {\n\t\treturn 0;\n\t}", "\t*wiretype_out = data[0] & 7;\n\tif ((data[0] & 0x80) == 0) {\n\t\t*tag_out = tag;\n\t\treturn 1;\n\t}\n\tfor (rv = 1; rv < max_rv; rv++) {\n\t\tif (data[rv] & 0x80) {\n\t\t\ttag |= (data[rv] & 0x7f) << shift;\n\t\t\tshift += 7;\n\t\t} else {\n\t\t\ttag |= data[rv] << shift;\n\t\t\t*tag_out = tag;\n\t\t\treturn rv + 1;\n\t\t}\n\t}\n\treturn 0; /* error: bad header */\n}", "/* sizeof(ScannedMember) must be <= (1UL<<BOUND_SIZEOF_SCANNED_MEMBER_LOG2) */\n#define BOUND_SIZEOF_SCANNED_MEMBER_LOG2 5\ntypedef struct ScannedMember ScannedMember;\n/** Field as it's being read. */\nstruct ScannedMember {\n\tuint32_t tag; /**< Field tag. */\n\tuint8_t wire_type; /**< Field type. */\n\tuint8_t length_prefix_len; /**< Prefix length. */\n\tconst ProtobufCFieldDescriptor *field; /**< Field descriptor. */\n\tsize_t len; /**< Field length. */\n\tconst uint8_t *data; /**< Pointer to field data. */\n};", "static inline size_t\nscan_length_prefixed_data(size_t len, const uint8_t *data,\n\t\t\t size_t *prefix_len_out)\n{\n\tunsigned hdr_max = len < 5 ? len : 5;\n\tunsigned hdr_len;\n\tsize_t val = 0;\n\tunsigned i;\n\tunsigned shift = 0;", "\tfor (i = 0; i < hdr_max; i++) {\n\t\tval |= ((size_t)data[i] & 0x7f) << shift;\n\t\tshift += 7;\n\t\tif ((data[i] & 0x80) == 0)\n\t\t\tbreak;\n\t}\n\tif (i == hdr_max) {\n\t\tPROTOBUF_C_UNPACK_ERROR(\"error parsing length for length-prefixed data\");\n\t\treturn 0;\n\t}\n\thdr_len = i + 1;\n\t*prefix_len_out = hdr_len;\n\tif (val > INT_MAX) {\n\t\t// Protobuf messages should always be less than 2 GiB in size.\n\t\t// We also want to return early here so that hdr_len + val does\n\t\t// not overflow on 32-bit systems.\n\t\tPROTOBUF_C_UNPACK_ERROR(\"length prefix of %lu is too large\",\n\t\t\t(unsigned long int)val);\n\t\treturn 0;\n\t}\n\tif (hdr_len + val > len) {\n\t\tPROTOBUF_C_UNPACK_ERROR(\"data too short after length-prefix of %lu\",\n\t\t\t(unsigned long int)val);\n\t\treturn 0;\n\t}\n\treturn hdr_len + val;\n}", "static size_t\nmax_b128_numbers(size_t len, const uint8_t *data)\n{\n\tsize_t rv = 0;\n\twhile (len--)\n\t\tif ((*data++ & 0x80) == 0)\n\t\t\t++rv;\n\treturn rv;\n}", "/**@}*/", "/**\n * Merge earlier message into a latter message.\n *\n * For numeric types and strings, if the same value appears multiple\n * times, the parser accepts the last value it sees. For embedded\n * message fields, the parser merges multiple instances of the same\n * field. That is, all singular scalar fields in the latter instance\n * replace those in the former, singular embedded messages are merged,\n * and repeated fields are concatenated.\n *\n * The earlier message should be freed after calling this function, as\n * some of its fields may have been reused and changed to their default\n * values during the merge.\n */\nstatic protobuf_c_boolean\nmerge_messages(ProtobufCMessage *earlier_msg,\n\t ProtobufCMessage *latter_msg,\n\t ProtobufCAllocator *allocator)\n{\n\tunsigned i;\n\tconst ProtobufCFieldDescriptor *fields =\n\t\tlatter_msg->descriptor->fields;\n\tfor (i = 0; i < latter_msg->descriptor->n_fields; i++) {\n\t\tif (fields[i].label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t *n_earlier =\n\t\t\t\tSTRUCT_MEMBER_PTR(size_t, earlier_msg,\n\t\t\t\t\t\t fields[i].quantifier_offset);\n\t\t\tuint8_t **p_earlier =\n\t\t\t\tSTRUCT_MEMBER_PTR(uint8_t *, earlier_msg,\n\t\t\t\t\t\t fields[i].offset);\n\t\t\tsize_t *n_latter =\n\t\t\t\tSTRUCT_MEMBER_PTR(size_t, latter_msg,\n\t\t\t\t\t\t fields[i].quantifier_offset);\n\t\t\tuint8_t **p_latter =\n\t\t\t\tSTRUCT_MEMBER_PTR(uint8_t *, latter_msg,\n\t\t\t\t\t\t fields[i].offset);", "\t\t\tif (*n_earlier > 0) {\n\t\t\t\tif (*n_latter > 0) {\n\t\t\t\t\t/* Concatenate the repeated field */\n\t\t\t\t\tsize_t el_size =\n\t\t\t\t\t\tsizeof_elt_in_repeated_array(fields[i].type);\n\t\t\t\t\tuint8_t *new_field;", "\t\t\t\t\tnew_field = do_alloc(allocator,\n\t\t\t\t\t\t(*n_earlier + *n_latter) * el_size);\n\t\t\t\t\tif (!new_field)\n\t\t\t\t\t\treturn FALSE;", "\t\t\t\t\tmemcpy(new_field, *p_earlier,\n\t\t\t\t\t *n_earlier * el_size);\n\t\t\t\t\tmemcpy(new_field +\n\t\t\t\t\t *n_earlier * el_size,\n\t\t\t\t\t *p_latter,\n\t\t\t\t\t *n_latter * el_size);", "\t\t\t\t\tdo_free(allocator, *p_latter);\n\t\t\t\t\tdo_free(allocator, *p_earlier);\n\t\t\t\t\t*p_latter = new_field;\n\t\t\t\t\t*n_latter = *n_earlier + *n_latter;\n\t\t\t\t} else {\n\t\t\t\t\t/* Zero copy the repeated field from the earlier message */\n\t\t\t\t\t*n_latter = *n_earlier;\n\t\t\t\t\t*p_latter = *p_earlier;\n\t\t\t\t}\n\t\t\t\t/* Make sure the field does not get double freed */\n\t\t\t\t*n_earlier = 0;\n\t\t\t\t*p_earlier = 0;\n\t\t\t}\n\t\t} else if (fields[i].label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t fields[i].label == PROTOBUF_C_LABEL_NONE) {\n\t\t\tconst ProtobufCFieldDescriptor *field;\n\t\t\tuint32_t *earlier_case_p = STRUCT_MEMBER_PTR(uint32_t,\n\t\t\t\t\t\t\t\t earlier_msg,\n\t\t\t\t\t\t\t\t fields[i].\n\t\t\t\t\t\t\t\t quantifier_offset);\n\t\t\tuint32_t *latter_case_p = STRUCT_MEMBER_PTR(uint32_t,\n\t\t\t\t\t\t\t\t latter_msg,\n\t\t\t\t\t\t\t\t fields[i].\n\t\t\t\t\t\t\t\t quantifier_offset);\n\t\t\tprotobuf_c_boolean need_to_merge = FALSE;\n\t\t\tvoid *earlier_elem;\n\t\t\tvoid *latter_elem;\n\t\t\tconst void *def_val;", "\t\t\tif (fields[i].flags & PROTOBUF_C_FIELD_FLAG_ONEOF) {\n\t\t\t\tif (*latter_case_p == 0) {\n\t\t\t\t\t/* lookup correct oneof field */\n\t\t\t\t\tint field_index =\n\t\t\t\t\t\tint_range_lookup(\n\t\t\t\t\t\t\tlatter_msg->descriptor\n\t\t\t\t\t\t\t->n_field_ranges,\n\t\t\t\t\t\t\tlatter_msg->descriptor\n\t\t\t\t\t\t\t->field_ranges,\n\t\t\t\t\t\t\t*earlier_case_p);\n\t\t\t\t\tif (field_index < 0)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\tfield = latter_msg->descriptor->fields +\n\t\t\t\t\t\tfield_index;\n\t\t\t\t} else {\n\t\t\t\t\t/* Oneof is present in the latter message, move on */\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfield = &fields[i];\n\t\t\t}", "\t\t\tearlier_elem = STRUCT_MEMBER_P(earlier_msg, field->offset);\n\t\t\tlatter_elem = STRUCT_MEMBER_P(latter_msg, field->offset);\n\t\t\tdef_val = field->default_value;", "\t\t\tswitch (field->type) {\n\t\t\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\t\t\tProtobufCMessage *em = *(ProtobufCMessage **) earlier_elem;\n\t\t\t\tProtobufCMessage *lm = *(ProtobufCMessage **) latter_elem;\n\t\t\t\tif (em != NULL) {\n\t\t\t\t\tif (lm != NULL) {\n\t\t\t\t\t\tif (!merge_messages(em, lm, allocator))\n\t\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t\t/* Already merged */\n\t\t\t\t\t\tneed_to_merge = FALSE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* Zero copy the message */\n\t\t\t\t\t\tneed_to_merge = TRUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\t\t\tuint8_t *e_data =\n\t\t\t\t\t((ProtobufCBinaryData *) earlier_elem)->data;\n\t\t\t\tuint8_t *l_data =\n\t\t\t\t\t((ProtobufCBinaryData *) latter_elem)->data;\n\t\t\t\tconst ProtobufCBinaryData *d_bd =\n\t\t\t\t\t(ProtobufCBinaryData *) def_val;", "\t\t\t\tneed_to_merge =\n\t\t\t\t\t(e_data != NULL &&\n\t\t\t\t\t (d_bd == NULL ||\n\t\t\t\t\t e_data != d_bd->data)) &&\n\t\t\t\t\t(l_data == NULL ||\n\t\t\t\t\t (d_bd != NULL &&\n\t\t\t\t\t l_data == d_bd->data));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase PROTOBUF_C_TYPE_STRING: {\n\t\t\t\tchar *e_str = *(char **) earlier_elem;\n\t\t\t\tchar *l_str = *(char **) latter_elem;\n\t\t\t\tconst char *d_str = def_val;", "\t\t\t\tneed_to_merge = e_str != d_str && l_str == d_str;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t/* Could be has field or case enum, the logic is\n\t\t\t\t * equivalent, since 0 (FALSE) means not set for\n\t\t\t\t * oneof */\n\t\t\t\tneed_to_merge = (*earlier_case_p != 0) &&\n\t\t\t\t\t\t(*latter_case_p == 0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t}", "\t\t\tif (need_to_merge) {\n\t\t\t\tsize_t el_size =\n\t\t\t\t\tsizeof_elt_in_repeated_array(field->type);\n\t\t\t\tmemcpy(latter_elem, earlier_elem, el_size);\n\t\t\t\t/*\n\t\t\t\t * Reset the element from the old message to 0\n\t\t\t\t * to make sure earlier message deallocation\n\t\t\t\t * doesn't corrupt zero-copied data in the new\n\t\t\t\t * message, earlier message will be freed after\n\t\t\t\t * this function is called anyway\n\t\t\t\t */\n\t\t\t\tmemset(earlier_elem, 0, el_size);", "\t\t\t\tif (field->quantifier_offset != 0) {\n\t\t\t\t\t/* Set the has field or the case enum,\n\t\t\t\t\t * if applicable */\n\t\t\t\t\t*latter_case_p = *earlier_case_p;\n\t\t\t\t\t*earlier_case_p = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn TRUE;\n}", "/**\n * Count packed elements.\n *\n * Given a raw slab of packed-repeated values, determine the number of\n * elements. This function detects certain kinds of errors but not\n * others; the remaining error checking is done by\n * parse_packed_repeated_member().\n */\nstatic protobuf_c_boolean\ncount_packed_elements(ProtobufCType type,\n\t\t size_t len, const uint8_t *data, size_t *count_out)\n{\n\tswitch (type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tif (len % 4 != 0) {\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"length must be a multiple of 4 for fixed-length 32-bit types\");\n\t\t\treturn FALSE;\n\t\t}\n\t\t*count_out = len / 4;\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tif (len % 8 != 0) {\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"length must be a multiple of 8 for fixed-length 64-bit types\");\n\t\t\treturn FALSE;\n\t\t}\n\t\t*count_out = len / 8;\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\tcase PROTOBUF_C_TYPE_SINT32:\n\tcase PROTOBUF_C_TYPE_UINT32:\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_SINT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\t*count_out = max_b128_numbers(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\t*count_out = len;\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_STRING:\n\tcase PROTOBUF_C_TYPE_BYTES:\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\tdefault:\n\t\tPROTOBUF_C_UNPACK_ERROR(\"bad protobuf-c type %u for packed-repeated\", type);\n\t\treturn FALSE;\n\t}\n}", "static inline uint32_t\nparse_uint32(unsigned len, const uint8_t *data)\n{\n\tuint32_t rv = data[0] & 0x7f;\n\tif (len > 1) {\n\t\trv |= ((uint32_t) (data[1] & 0x7f) << 7);\n\t\tif (len > 2) {\n\t\t\trv |= ((uint32_t) (data[2] & 0x7f) << 14);\n\t\t\tif (len > 3) {\n\t\t\t\trv |= ((uint32_t) (data[3] & 0x7f) << 21);\n\t\t\t\tif (len > 4)\n\t\t\t\t\trv |= ((uint32_t) (data[4]) << 28);\n\t\t\t}\n\t\t}\n\t}\n\treturn rv;\n}", "static inline uint32_t\nparse_int32(unsigned len, const uint8_t *data)\n{\n\treturn parse_uint32(len, data);\n}", "static inline int32_t\nunzigzag32(uint32_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn (int32_t)((v >> 1) ^ -(v & 1));\n}", "static inline uint32_t\nparse_fixed_uint32(const uint8_t *data)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tuint32_t t;\n\tmemcpy(&t, data, 4);\n\treturn t;\n#else\n\treturn data[0] |\n\t\t((uint32_t) (data[1]) << 8) |\n\t\t((uint32_t) (data[2]) << 16) |\n\t\t((uint32_t) (data[3]) << 24);\n#endif\n}", "static uint64_t\nparse_uint64(unsigned len, const uint8_t *data)\n{\n\tunsigned shift, i;\n\tuint64_t rv;", "\tif (len < 5)\n\t\treturn parse_uint32(len, data);\n\trv = ((uint64_t) (data[0] & 0x7f)) |\n\t\t((uint64_t) (data[1] & 0x7f) << 7) |\n\t\t((uint64_t) (data[2] & 0x7f) << 14) |\n\t\t((uint64_t) (data[3] & 0x7f) << 21);\n\tshift = 28;\n\tfor (i = 4; i < len; i++) {\n\t\trv |= (((uint64_t) (data[i] & 0x7f)) << shift);\n\t\tshift += 7;\n\t}\n\treturn rv;\n}", "static inline int64_t\nunzigzag64(uint64_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn (int64_t)((v >> 1) ^ -(v & 1));\n}", "static inline uint64_t\nparse_fixed_uint64(const uint8_t *data)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tuint64_t t;\n\tmemcpy(&t, data, 8);\n\treturn t;\n#else\n\treturn (uint64_t) parse_fixed_uint32(data) |\n\t\t(((uint64_t) parse_fixed_uint32(data + 4)) << 32);\n#endif\n}", "static protobuf_c_boolean\nparse_boolean(unsigned len, const uint8_t *data)\n{\n\tunsigned i;\n\tfor (i = 0; i < len; i++)\n\t\tif (data[i] & 0x7f)\n\t\t\treturn TRUE;\n\treturn FALSE;\n}", "static protobuf_c_boolean\nparse_required_member(ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCAllocator *allocator,\n\t\t protobuf_c_boolean maybe_clear)\n{\n\tunsigned len = scanned_member->len;\n\tconst uint8_t *data = scanned_member->data;\n\tuint8_t wire_type = scanned_member->wire_type;", "\tswitch (scanned_member->field->type) {\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(int32_t *) member = parse_int32(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(uint32_t *) member = parse_uint32(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(int32_t *) member = unzigzag32(parse_uint32(len, data));\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_32BIT)\n\t\t\treturn FALSE;\n\t\t*(uint32_t *) member = parse_fixed_uint32(data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(uint64_t *) member = parse_uint64(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(int64_t *) member = unzigzag64(parse_uint64(len, data));\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_64BIT)\n\t\t\treturn FALSE;\n\t\t*(uint64_t *) member = parse_fixed_uint64(data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\t*(protobuf_c_boolean *) member = parse_boolean(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_STRING: {\n\t\tchar **pstr = member;\n\t\tunsigned pref_len = scanned_member->length_prefix_len;", "\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED)\n\t\t\treturn FALSE;", "\t\tif (maybe_clear && *pstr != NULL) {\n\t\t\tconst char *def = scanned_member->field->default_value;\n\t\t\tif (*pstr != NULL && *pstr != def)\n\t\t\t\tdo_free(allocator, *pstr);\n\t\t}\n\t\t*pstr = do_alloc(allocator, len - pref_len + 1);\n\t\tif (*pstr == NULL)\n\t\t\treturn FALSE;\n\t\tmemcpy(*pstr, data + pref_len, len - pref_len);\n\t\t(*pstr)[len - pref_len] = 0;\n\t\treturn TRUE;\n\t}\n\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\tProtobufCBinaryData *bd = member;\n\t\tconst ProtobufCBinaryData *def_bd;\n\t\tunsigned pref_len = scanned_member->length_prefix_len;", "\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED)\n\t\t\treturn FALSE;", "\t\tdef_bd = scanned_member->field->default_value;\n\t\tif (maybe_clear &&\n\t\t bd->data != NULL &&\n\t\t (def_bd == NULL || bd->data != def_bd->data))\n\t\t{\n\t\t\tdo_free(allocator, bd->data);\n\t\t}\n\t\tif (len > pref_len) {\n\t\t\tbd->data = do_alloc(allocator, len - pref_len);\n\t\t\tif (bd->data == NULL)\n\t\t\t\treturn FALSE;\n\t\t\tmemcpy(bd->data, data + pref_len, len - pref_len);\n\t\t} else {\n\t\t\tbd->data = NULL;\n\t\t}\n\t\tbd->len = len - pref_len;\n\t\treturn TRUE;\n\t}\n\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\tProtobufCMessage **pmessage = member;\n\t\tProtobufCMessage *subm;\n\t\tconst ProtobufCMessage *def_mess;\n\t\tprotobuf_c_boolean merge_successful = TRUE;\n\t\tunsigned pref_len = scanned_member->length_prefix_len;", "\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED)\n\t\t\treturn FALSE;", "\t\tdef_mess = scanned_member->field->default_value;", "\t\tsubm = protobuf_c_message_unpack(scanned_member->field->descriptor,\n\t\t\t\t\t\t allocator,\n\t\t\t\t\t\t len - pref_len,\n\t\t\t\t\t\t data + pref_len);", "\n\t\tif (maybe_clear &&\n\t\t *pmessage != NULL &&\n\t\t *pmessage != def_mess)\n\t\t{\n\t\t\tif (subm != NULL)\n\t\t\t\tmerge_successful = merge_messages(*pmessage, subm, allocator);\n\t\t\t/* Delete the previous message */\n\t\t\tprotobuf_c_message_free_unpacked(*pmessage, allocator);\n\t\t}\n\t\t*pmessage = subm;\n\t\tif (subm == NULL || !merge_successful)\n\t\t\treturn FALSE;\n\t\treturn TRUE;\n\t}\n\t}\n\treturn FALSE;\n}", "static protobuf_c_boolean\nparse_oneof_member (ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCMessage *message,\n\t\t ProtobufCAllocator *allocator)\n{\n\tuint32_t *oneof_case = STRUCT_MEMBER_PTR(uint32_t, message,\n\t\t\t\t\t scanned_member->field->quantifier_offset);", "\t/* If we have already parsed a member of this oneof, free it. */\n\tif (*oneof_case != 0) {\n\t\tconst ProtobufCFieldDescriptor *old_field;\n\t\tsize_t el_size;\n\t\t/* lookup field */\n\t\tint field_index =\n\t\t\tint_range_lookup(message->descriptor->n_field_ranges,\n\t\t\t\t\t message->descriptor->field_ranges,\n\t\t\t\t\t *oneof_case);\n\t\tif (field_index < 0)\n\t\t\treturn FALSE;\n\t\told_field = message->descriptor->fields + field_index;\n\t\tel_size = sizeof_elt_in_repeated_array(old_field->type);", "\t\tswitch (old_field->type) {\n\t case PROTOBUF_C_TYPE_STRING: {\n\t\t\tchar **pstr = member;\n\t\t\tconst char *def = old_field->default_value;\n\t\t\tif (*pstr != NULL && *pstr != def)\n\t\t\t\tdo_free(allocator, *pstr);\n\t\t\tbreak;\n\t }\n\t\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\t\tProtobufCBinaryData *bd = member;\n\t\t\tconst ProtobufCBinaryData *def_bd = old_field->default_value;\n\t\t\tif (bd->data != NULL &&\n\t\t\t (def_bd == NULL || bd->data != def_bd->data))\n\t\t\t{\n\t\t\t\tdo_free(allocator, bd->data);\n\t\t\t}\n\t\t\tbreak;\n\t }\n\t\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\t\tProtobufCMessage **pmessage = member;\n\t\t\tconst ProtobufCMessage *def_mess = old_field->default_value;\n\t\t\tif (*pmessage != NULL && *pmessage != def_mess)\n\t\t\t\tprotobuf_c_message_free_unpacked(*pmessage, allocator);\n\t\t\tbreak;\n\t }\n\t\tdefault:\n\t\t\tbreak;\n\t\t}", "\t\tmemset (member, 0, el_size);\n\t}\n\tif (!parse_required_member (scanned_member, member, allocator, TRUE))\n\t\treturn FALSE;", "\t*oneof_case = scanned_member->tag;\n\treturn TRUE;\n}", "\nstatic protobuf_c_boolean\nparse_optional_member(ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCMessage *message,\n\t\t ProtobufCAllocator *allocator)\n{\n\tif (!parse_required_member(scanned_member, member, allocator, TRUE))\n\t\treturn FALSE;\n\tif (scanned_member->field->quantifier_offset != 0)\n\t\tSTRUCT_MEMBER(protobuf_c_boolean,\n\t\t\t message,\n\t\t\t scanned_member->field->quantifier_offset) = TRUE;\n\treturn TRUE;\n}", "static protobuf_c_boolean\nparse_repeated_member(ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCMessage *message,\n\t\t ProtobufCAllocator *allocator)\n{\n\tconst ProtobufCFieldDescriptor *field = scanned_member->field;\n\tsize_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);\n\tsize_t siz = sizeof_elt_in_repeated_array(field->type);\n\tchar *array = *(char **) member;", "\tif (!parse_required_member(scanned_member, array + siz * (*p_n),\n\t\t\t\t allocator, FALSE))\n\t{\n\t\treturn FALSE;\n\t}\n\t*p_n += 1;\n\treturn TRUE;\n}", "static unsigned\nscan_varint(unsigned len, const uint8_t *data)\n{\n\tunsigned i;\n\tif (len > 10)\n\t\tlen = 10;\n\tfor (i = 0; i < len; i++)\n\t\tif ((data[i] & 0x80) == 0)\n\t\t\tbreak;\n\tif (i == len)\n\t\treturn 0;\n\treturn i + 1;\n}", "static protobuf_c_boolean\nparse_packed_repeated_member(ScannedMember *scanned_member,\n\t\t\t void *member,\n\t\t\t ProtobufCMessage *message)\n{\n\tconst ProtobufCFieldDescriptor *field = scanned_member->field;\n\tsize_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);\n\tsize_t siz = sizeof_elt_in_repeated_array(field->type);\n\tvoid *array = *(char **) member + siz * (*p_n);\n\tconst uint8_t *at = scanned_member->data + scanned_member->length_prefix_len;\n\tsize_t rem = scanned_member->len - scanned_member->length_prefix_len;\n\tsize_t count = 0;\n#if defined(WORDS_BIGENDIAN)\n\tunsigned i;\n#endif", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tcount = (scanned_member->len - scanned_member->length_prefix_len) / 4;\n#if !defined(WORDS_BIGENDIAN)\n\t\tgoto no_unpacking_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\t((uint32_t *) array)[i] = parse_fixed_uint32(at);\n\t\t\tat += 4;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tcount = (scanned_member->len - scanned_member->length_prefix_len) / 8;\n#if !defined(WORDS_BIGENDIAN)\n\t\tgoto no_unpacking_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\t((uint64_t *) array)[i] = parse_fixed_uint64(at);\n\t\t\tat += 8;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated int32 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int32_t *) array)[count++] = parse_int32(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated sint32 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int32_t *) array)[count++] = unzigzag32(parse_uint32(s, at));\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated enum or uint32 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((uint32_t *) array)[count++] = parse_uint32(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;", "\tcase PROTOBUF_C_TYPE_SINT64:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated sint64 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int64_t *) array)[count++] = unzigzag64(parse_uint64(s, at));\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated int64/uint64 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int64_t *) array)[count++] = parse_uint64(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated boolean value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((protobuf_c_boolean *) array)[count++] = parse_boolean(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\t*p_n += count;\n\treturn TRUE;", "#if !defined(WORDS_BIGENDIAN)\nno_unpacking_needed:\n\tmemcpy(array, at, count * siz);\n\t*p_n += count;\n\treturn TRUE;\n#endif\n}", "static protobuf_c_boolean\nis_packable_type(ProtobufCType type)\n{\n\treturn\n\t\ttype != PROTOBUF_C_TYPE_STRING &&\n\t\ttype != PROTOBUF_C_TYPE_BYTES &&\n\t\ttype != PROTOBUF_C_TYPE_MESSAGE;\n}", "static protobuf_c_boolean\nparse_member(ScannedMember *scanned_member,\n\t ProtobufCMessage *message,\n\t ProtobufCAllocator *allocator)\n{\n\tconst ProtobufCFieldDescriptor *field = scanned_member->field;\n\tvoid *member;", "\tif (field == NULL) {\n\t\tProtobufCMessageUnknownField *ufield =\n\t\t\tmessage->unknown_fields +\n\t\t\t(message->n_unknown_fields++);\n\t\tufield->tag = scanned_member->tag;\n\t\tufield->wire_type = scanned_member->wire_type;\n\t\tufield->len = scanned_member->len;\n\t\tufield->data = do_alloc(allocator, scanned_member->len);\n\t\tif (ufield->data == NULL)\n\t\t\treturn FALSE;\n\t\tmemcpy(ufield->data, scanned_member->data, ufield->len);\n\t\treturn TRUE;\n\t}\n\tmember = (char *) message + field->offset;\n\tswitch (field->label) {\n\tcase PROTOBUF_C_LABEL_REQUIRED:\n\t\treturn parse_required_member(scanned_member, member,\n\t\t\t\t\t allocator, TRUE);\n\tcase PROTOBUF_C_LABEL_OPTIONAL:\n\tcase PROTOBUF_C_LABEL_NONE:\n\t\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF)) {\n\t\t\treturn parse_oneof_member(scanned_member, member,\n\t\t\t\t\t\t message, allocator);\n\t\t} else {\n\t\t\treturn parse_optional_member(scanned_member, member,\n\t\t\t\t\t\t message, allocator);\n\t\t}\n\tcase PROTOBUF_C_LABEL_REPEATED:\n\t\tif (scanned_member->wire_type ==\n\t\t PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&\n\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||\n\t\t is_packable_type(field->type)))\n\t\t{\n\t\t\treturn parse_packed_repeated_member(scanned_member,\n\t\t\t\t\t\t\t member, message);\n\t\t} else {\n\t\t\treturn parse_repeated_member(scanned_member,\n\t\t\t\t\t\t member, message,\n\t\t\t\t\t\t allocator);\n\t\t}\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Initialise messages generated by old code.\n *\n * This function is used if desc->message_init == NULL (which occurs\n * for old code, and which would be useful to support allocating\n * descriptors dynamically).\n */\nstatic void\nmessage_init_generic(const ProtobufCMessageDescriptor *desc,\n\t\t ProtobufCMessage *message)\n{\n\tunsigned i;", "\tmemset(message, 0, desc->sizeof_message);\n\tmessage->descriptor = desc;\n\tfor (i = 0; i < desc->n_fields; i++) {\n\t\tif (desc->fields[i].default_value != NULL &&\n\t\t desc->fields[i].label != PROTOBUF_C_LABEL_REPEATED)\n\t\t{\n\t\t\tvoid *field =\n\t\t\t\tSTRUCT_MEMBER_P(message, desc->fields[i].offset);\n\t\t\tconst void *dv = desc->fields[i].default_value;", "\t\t\tswitch (desc->fields[i].type) {\n\t\t\tcase PROTOBUF_C_TYPE_INT32:\n\t\t\tcase PROTOBUF_C_TYPE_SINT32:\n\t\t\tcase PROTOBUF_C_TYPE_SFIXED32:\n\t\t\tcase PROTOBUF_C_TYPE_UINT32:\n\t\t\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\t\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\t\tcase PROTOBUF_C_TYPE_ENUM:\n\t\t\t\tmemcpy(field, dv, 4);\n\t\t\t\tbreak;\n\t\t\tcase PROTOBUF_C_TYPE_INT64:\n\t\t\tcase PROTOBUF_C_TYPE_SINT64:\n\t\t\tcase PROTOBUF_C_TYPE_SFIXED64:\n\t\t\tcase PROTOBUF_C_TYPE_UINT64:\n\t\t\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\t\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\t\t\tmemcpy(field, dv, 8);\n\t\t\t\tbreak;\n\t\t\tcase PROTOBUF_C_TYPE_BOOL:\n\t\t\t\tmemcpy(field, dv, sizeof(protobuf_c_boolean));\n\t\t\t\tbreak;\n\t\t\tcase PROTOBUF_C_TYPE_BYTES:\n\t\t\t\tmemcpy(field, dv, sizeof(ProtobufCBinaryData));\n\t\t\t\tbreak;", "\t\t\tcase PROTOBUF_C_TYPE_STRING:\n\t\t\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\t\t\t/*\n\t\t\t\t * The next line essentially implements a cast\n\t\t\t\t * from const, which is totally unavoidable.\n\t\t\t\t */\n\t\t\t\t*(const void **) field = dv;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}", "/**@}*/", "/*\n * ScannedMember slabs (an unpacking implementation detail). Before doing real\n * unpacking, we first scan through the elements to see how many there are (for\n * repeated fields), and which field to use (for non-repeated fields given\n * twice).\n *\n * In order to avoid allocations for small messages, we keep a stack-allocated\n * slab of ScannedMembers of size FIRST_SCANNED_MEMBER_SLAB_SIZE (16). After we\n * fill that up, we allocate each slab twice as large as the previous one.\n */\n#define FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2 4", "/*\n * The number of slabs, including the stack-allocated ones; choose the number so\n * that we would overflow if we needed a slab larger than provided.\n */\n#define MAX_SCANNED_MEMBER_SLAB\t\t\t\\\n (sizeof(unsigned int)*8 - 1\t\t\t\\\n - BOUND_SIZEOF_SCANNED_MEMBER_LOG2\t\t\\\n - FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2)", "#define REQUIRED_FIELD_BITMAP_SET(index)\t\\\n\t(required_fields_bitmap[(index)/8] |= (1UL<<((index)%8)))", "#define REQUIRED_FIELD_BITMAP_IS_SET(index)\t\\\n\t(required_fields_bitmap[(index)/8] & (1UL<<((index)%8)))", "ProtobufCMessage *\nprotobuf_c_message_unpack(const ProtobufCMessageDescriptor *desc,\n\t\t\t ProtobufCAllocator *allocator,\n\t\t\t size_t len, const uint8_t *data)\n{\n\tProtobufCMessage *rv;\n\tsize_t rem = len;\n\tconst uint8_t *at = data;\n\tconst ProtobufCFieldDescriptor *last_field = desc->fields + 0;\n\tScannedMember first_member_slab[1UL <<\n\t\t\t\t\tFIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2];", "\t/*\n\t * scanned_member_slabs[i] is an array of arrays of ScannedMember.\n\t * The first slab (scanned_member_slabs[0] is just a pointer to\n\t * first_member_slab), above. All subsequent slabs will be allocated\n\t * using the allocator.\n\t */\n\tScannedMember *scanned_member_slabs[MAX_SCANNED_MEMBER_SLAB + 1];\n\tunsigned which_slab = 0; /* the slab we are currently populating */\n\tunsigned in_slab_index = 0; /* number of members in the slab */\n\tsize_t n_unknown = 0;\n\tunsigned f;\n\tunsigned j;\n\tunsigned i_slab;\n\tunsigned last_field_index = 0;\n\tunsigned required_fields_bitmap_len;\n\tunsigned char required_fields_bitmap_stack[16];\n\tunsigned char *required_fields_bitmap = required_fields_bitmap_stack;\n\tprotobuf_c_boolean required_fields_bitmap_alloced = FALSE;", "\tASSERT_IS_MESSAGE_DESCRIPTOR(desc);", "\tif (allocator == NULL)\n\t\tallocator = &protobuf_c__allocator;", "\trv = do_alloc(allocator, desc->sizeof_message);\n\tif (!rv)\n\t\treturn (NULL);\n\tscanned_member_slabs[0] = first_member_slab;", "\trequired_fields_bitmap_len = (desc->n_fields + 7) / 8;\n\tif (required_fields_bitmap_len > sizeof(required_fields_bitmap_stack)) {\n\t\trequired_fields_bitmap = do_alloc(allocator, required_fields_bitmap_len);\n\t\tif (!required_fields_bitmap) {\n\t\t\tdo_free(allocator, rv);\n\t\t\treturn (NULL);\n\t\t}\n\t\trequired_fields_bitmap_alloced = TRUE;\n\t}\n\tmemset(required_fields_bitmap, 0, required_fields_bitmap_len);", "\t/*\n\t * Generated code always defines \"message_init\". However, we provide a\n\t * fallback for (1) users of old protobuf-c generated-code that do not\n\t * provide the function, and (2) descriptors constructed from some other\n\t * source (most likely, direct construction from the .proto file).\n\t */\n\tif (desc->message_init != NULL)\n\t\tprotobuf_c_message_init(desc, rv);\n\telse\n\t\tmessage_init_generic(desc, rv);", "\twhile (rem > 0) {\n\t\tuint32_t tag;\n\t\tuint8_t wire_type;\n\t\tsize_t used = parse_tag_and_wiretype(rem, at, &tag, &wire_type);\n\t\tconst ProtobufCFieldDescriptor *field;\n\t\tScannedMember tmp;", "\t\tif (used == 0) {\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"error parsing tag/wiretype at offset %u\",\n\t\t\t\t\t\t(unsigned) (at - data));\n\t\t\tgoto error_cleanup_during_scan;\n\t\t}\n\t\t/*\n\t\t * \\todo Consider optimizing for field[1].id == tag, if field[1]\n\t\t * exists!\n\t\t */\n\t\tif (last_field == NULL || last_field->id != tag) {\n\t\t\t/* lookup field */\n\t\t\tint field_index =\n\t\t\t int_range_lookup(desc->n_field_ranges,\n\t\t\t\t\t desc->field_ranges,\n\t\t\t\t\t tag);\n\t\t\tif (field_index < 0) {\n\t\t\t\tfield = NULL;\n\t\t\t\tn_unknown++;\n\t\t\t} else {\n\t\t\t\tfield = desc->fields + field_index;\n\t\t\t\tlast_field = field;\n\t\t\t\tlast_field_index = field_index;\n\t\t\t}\n\t\t} else {\n\t\t\tfield = last_field;\n\t\t}", "\t\tif (field != NULL && field->label == PROTOBUF_C_LABEL_REQUIRED)\n\t\t\tREQUIRED_FIELD_BITMAP_SET(last_field_index);", "\t\tat += used;\n\t\trem -= used;\n\t\ttmp.tag = tag;\n\t\ttmp.wire_type = wire_type;\n\t\ttmp.field = field;\n\t\ttmp.data = at;\n\t\ttmp.length_prefix_len = 0;", "\t\tswitch (wire_type) {\n\t\tcase PROTOBUF_C_WIRE_TYPE_VARINT: {\n\t\t\tunsigned max_len = rem < 10 ? rem : 10;\n\t\t\tunsigned i;", "\t\t\tfor (i = 0; i < max_len; i++)\n\t\t\t\tif ((at[i] & 0x80) == 0)\n\t\t\t\t\tbreak;\n\t\t\tif (i == max_len) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"unterminated varint at offset %u\",\n\t\t\t\t\t\t\t(unsigned) (at - data));\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.len = i + 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_WIRE_TYPE_64BIT:\n\t\t\tif (rem < 8) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"too short after 64bit wiretype at offset %u\",\n\t\t\t\t\t\t\t(unsigned) (at - data));\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.len = 8;\n\t\t\tbreak;\n\t\tcase PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED: {\n\t\t\tsize_t pref_len;", "\t\t\ttmp.len = scan_length_prefixed_data(rem, at, &pref_len);\n\t\t\tif (tmp.len == 0) {\n\t\t\t\t/* NOTE: scan_length_prefixed_data calls UNPACK_ERROR */\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.length_prefix_len = pref_len;\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_WIRE_TYPE_32BIT:\n\t\t\tif (rem < 4) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"too short after 32bit wiretype at offset %u\",\n\t\t\t\t\t (unsigned) (at - data));\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.len = 4;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"unsupported tag %u at offset %u\",\n\t\t\t\t\t\twire_type, (unsigned) (at - data));\n\t\t\tgoto error_cleanup_during_scan;\n\t\t}", "\t\tif (in_slab_index == (1UL <<\n\t\t\t(which_slab + FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2)))\n\t\t{\n\t\t\tsize_t size;", "\t\t\tin_slab_index = 0;\n\t\t\tif (which_slab == MAX_SCANNED_MEMBER_SLAB) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"too many fields\");\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\twhich_slab++;\n\t\t\tsize = sizeof(ScannedMember)\n\t\t\t\t<< (which_slab + FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2);\n\t\t\tscanned_member_slabs[which_slab] = do_alloc(allocator, size);\n\t\t\tif (scanned_member_slabs[which_slab] == NULL)\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t}\n\t\tscanned_member_slabs[which_slab][in_slab_index++] = tmp;", "\t\tif (field != NULL && field->label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t *n = STRUCT_MEMBER_PTR(size_t, rv,\n\t\t\t\t\t\t field->quantifier_offset);\n\t\t\tif (wire_type == PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||\n\t\t\t is_packable_type(field->type)))\n\t\t\t{\n\t\t\t\tsize_t count;\n\t\t\t\tif (!count_packed_elements(field->type,\n\t\t\t\t\t\t\t tmp.len -\n\t\t\t\t\t\t\t tmp.length_prefix_len,\n\t\t\t\t\t\t\t tmp.data +\n\t\t\t\t\t\t\t tmp.length_prefix_len,\n\t\t\t\t\t\t\t &count))\n\t\t\t\t{\n\t\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"counting packed elements\");\n\t\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t\t}\n\t\t\t\t*n += count;\n\t\t\t} else {\n\t\t\t\t*n += 1;\n\t\t\t}\n\t\t}", "\t\tat += tmp.len;\n\t\trem -= tmp.len;\n\t}", "\t/* allocate space for repeated fields, also check that all required fields have been set */\n\tfor (f = 0; f < desc->n_fields; f++) {\n\t\tconst ProtobufCFieldDescriptor *field = desc->fields + f;\n\t\tif (field->label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t siz =\n\t\t\t sizeof_elt_in_repeated_array(field->type);\n\t\t\tsize_t *n_ptr =\n\t\t\t STRUCT_MEMBER_PTR(size_t, rv,\n\t\t\t\t\t field->quantifier_offset);\n\t\t\tif (*n_ptr != 0) {\n\t\t\t\tunsigned n = *n_ptr;\n\t\t\t\tvoid *a;\n\t\t\t\t*n_ptr = 0;\n\t\t\t\tassert(rv->descriptor != NULL);\n#define CLEAR_REMAINING_N_PTRS() \\\n for(f++;f < desc->n_fields; f++) \\\n { \\\n field = desc->fields + f; \\\n if (field->label == PROTOBUF_C_LABEL_REPEATED) \\\n STRUCT_MEMBER (size_t, rv, field->quantifier_offset) = 0; \\\n }\n\t\t\t\ta = do_alloc(allocator, siz * n);\n\t\t\t\tif (!a) {\n\t\t\t\t\tCLEAR_REMAINING_N_PTRS();\n\t\t\t\t\tgoto error_cleanup;\n\t\t\t\t}\n\t\t\t\tSTRUCT_MEMBER(void *, rv, field->offset) = a;\n\t\t\t}\n\t\t} else if (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\tif (field->default_value == NULL &&\n\t\t\t !REQUIRED_FIELD_BITMAP_IS_SET(f))\n\t\t\t{\n\t\t\t\tCLEAR_REMAINING_N_PTRS();\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"message '%s': missing required field '%s'\",\n\t\t\t\t\t\t\tdesc->name, field->name);\n\t\t\t\tgoto error_cleanup;\n\t\t\t}\n\t\t}\n\t}\n#undef CLEAR_REMAINING_N_PTRS", "\t/* allocate space for unknown fields */\n\tif (n_unknown) {\n\t\trv->unknown_fields = do_alloc(allocator,\n\t\t\t\t\t n_unknown * sizeof(ProtobufCMessageUnknownField));\n\t\tif (rv->unknown_fields == NULL)\n\t\t\tgoto error_cleanup;\n\t}", "\t/* do real parsing */\n\tfor (i_slab = 0; i_slab <= which_slab; i_slab++) {\n\t\tunsigned max = (i_slab == which_slab) ?\n\t\t\tin_slab_index : (1UL << (i_slab + 4));\n\t\tScannedMember *slab = scanned_member_slabs[i_slab];", "\t\tfor (j = 0; j < max; j++) {\n\t\t\tif (!parse_member(slab + j, rv, allocator)) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"error parsing member %s of %s\",\n\t\t\t\t\t\t\tslab->field ? slab->field->name : \"*unknown-field*\",\n\t\t\t\t\tdesc->name);\n\t\t\t\tgoto error_cleanup;\n\t\t\t}\n\t\t}\n\t}", "\t/* cleanup */\n\tfor (j = 1; j <= which_slab; j++)\n\t\tdo_free(allocator, scanned_member_slabs[j]);\n\tif (required_fields_bitmap_alloced)\n\t\tdo_free(allocator, required_fields_bitmap);\n\treturn rv;", "error_cleanup:\n\tprotobuf_c_message_free_unpacked(rv, allocator);\n\tfor (j = 1; j <= which_slab; j++)\n\t\tdo_free(allocator, scanned_member_slabs[j]);\n\tif (required_fields_bitmap_alloced)\n\t\tdo_free(allocator, required_fields_bitmap);\n\treturn NULL;", "error_cleanup_during_scan:\n\tdo_free(allocator, rv);\n\tfor (j = 1; j <= which_slab; j++)\n\t\tdo_free(allocator, scanned_member_slabs[j]);\n\tif (required_fields_bitmap_alloced)\n\t\tdo_free(allocator, required_fields_bitmap);\n\treturn NULL;\n}", "void\nprotobuf_c_message_free_unpacked(ProtobufCMessage *message,\n\t\t\t\t ProtobufCAllocator *allocator)\n{\n\tconst ProtobufCMessageDescriptor *desc;\n\tunsigned f;", "\tif (message == NULL)\n\t\treturn;", "\tdesc = message->descriptor;", "\tASSERT_IS_MESSAGE(message);", "\tif (allocator == NULL)\n\t\tallocator = &protobuf_c__allocator;\n\tmessage->descriptor = NULL;\n\tfor (f = 0; f < desc->n_fields; f++) {\n\t\tif (0 != (desc->fields[f].flags & PROTOBUF_C_FIELD_FLAG_ONEOF) &&\n\t\t desc->fields[f].id !=\n\t\t STRUCT_MEMBER(uint32_t, message, desc->fields[f].quantifier_offset))\n\t\t{\n\t\t\t/* This is not the selected oneof, skip it */\n\t\t\tcontinue;\n\t\t}", "\t\tif (desc->fields[f].label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t n = STRUCT_MEMBER(size_t,\n\t\t\t\t\t\t message,\n\t\t\t\t\t\t desc->fields[f].quantifier_offset);\n\t\t\tvoid *arr = STRUCT_MEMBER(void *,\n\t\t\t\t\t\t message,\n\t\t\t\t\t\t desc->fields[f].offset);", "\t\t\tif (arr != NULL) {\n\t\t\t\tif (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {\n\t\t\t\t\tunsigned i;\n\t\t\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\t\t\tdo_free(allocator, ((char **) arr)[i]);\n\t\t\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\t\t\tunsigned i;\n\t\t\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\t\t\tdo_free(allocator, ((ProtobufCBinaryData *) arr)[i].data);\n\t\t\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\t\t\tunsigned i;\n\t\t\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\t\t\tprotobuf_c_message_free_unpacked(\n\t\t\t\t\t\t\t((ProtobufCMessage **) arr)[i],\n\t\t\t\t\t\t\tallocator\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tdo_free(allocator, arr);\n\t\t\t}\n\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {\n\t\t\tchar *str = STRUCT_MEMBER(char *, message,\n\t\t\t\t\t\t desc->fields[f].offset);", "\t\t\tif (str && str != desc->fields[f].default_value)\n\t\t\t\tdo_free(allocator, str);\n\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\tvoid *data = STRUCT_MEMBER(ProtobufCBinaryData, message,\n\t\t\t\t\t\t desc->fields[f].offset).data;\n\t\t\tconst ProtobufCBinaryData *default_bd;", "\t\t\tdefault_bd = desc->fields[f].default_value;\n\t\t\tif (data != NULL &&\n\t\t\t (default_bd == NULL ||\n\t\t\t default_bd->data != data))\n\t\t\t{\n\t\t\t\tdo_free(allocator, data);\n\t\t\t}\n\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\tProtobufCMessage *sm;", "\t\t\tsm = STRUCT_MEMBER(ProtobufCMessage *, message,\n\t\t\t\t\t desc->fields[f].offset);\n\t\t\tif (sm && sm != desc->fields[f].default_value)\n\t\t\t\tprotobuf_c_message_free_unpacked(sm, allocator);\n\t\t}\n\t}", "\tfor (f = 0; f < message->n_unknown_fields; f++)\n\t\tdo_free(allocator, message->unknown_fields[f].data);\n\tif (message->unknown_fields != NULL)\n\t\tdo_free(allocator, message->unknown_fields);", "\tdo_free(allocator, message);\n}", "void\nprotobuf_c_message_init(const ProtobufCMessageDescriptor * descriptor,\n\t\t\tvoid *message)\n{\n\tdescriptor->message_init((ProtobufCMessage *) (message));\n}", "protobuf_c_boolean\nprotobuf_c_message_check(const ProtobufCMessage *message)\n{\n\tunsigned i;", "\tif (!message ||\n\t !message->descriptor ||\n\t message->descriptor->magic != PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC)\n\t{\n\t\treturn FALSE;\n\t}", "\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *f = message->descriptor->fields + i;\n\t\tProtobufCType type = f->type;\n\t\tProtobufCLabel label = f->label;\n\t\tvoid *field = STRUCT_MEMBER_P (message, f->offset);", "\t\tif (f->flags & PROTOBUF_C_FIELD_FLAG_ONEOF) {\n\t\t\tconst uint32_t *oneof_case = STRUCT_MEMBER_P (message, f->quantifier_offset);\n\t\t\tif (f->id != *oneof_case) {\n\t\t\t\tcontinue; //Do not check if it is an unpopulated oneof member.\n\t\t\t}\n\t\t}", "\t\tif (label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t *quantity = STRUCT_MEMBER_P (message, f->quantifier_offset);", "\t\t\tif (*quantity > 0 && *(void **) field == NULL) {\n\t\t\t\treturn FALSE;\n\t\t\t}", "\t\t\tif (type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\t\tProtobufCMessage **submessage = *(ProtobufCMessage ***) field;\n\t\t\t\tunsigned j;\n\t\t\t\tfor (j = 0; j < *quantity; j++) {\n\t\t\t\t\tif (!protobuf_c_message_check(submessage[j]))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t} else if (type == PROTOBUF_C_TYPE_STRING) {\n\t\t\t\tchar **string = *(char ***) field;\n\t\t\t\tunsigned j;\n\t\t\t\tfor (j = 0; j < *quantity; j++) {\n\t\t\t\t\tif (!string[j])\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t} else if (type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\t\tProtobufCBinaryData *bd = *(ProtobufCBinaryData **) field;\n\t\t\t\tunsigned j;\n\t\t\t\tfor (j = 0; j < *quantity; j++) {\n\t\t\t\t\tif (bd[j].len > 0 && bd[j].data == NULL)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}", "\t\t} else { /* PROTOBUF_C_LABEL_REQUIRED or PROTOBUF_C_LABEL_OPTIONAL */", "\t\t\tif (type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\t\tProtobufCMessage *submessage = *(ProtobufCMessage **) field;\n\t\t\t\tif (label == PROTOBUF_C_LABEL_REQUIRED || submessage != NULL) {\n\t\t\t\t\tif (!protobuf_c_message_check(submessage))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t} else if (type == PROTOBUF_C_TYPE_STRING) {\n\t\t\t\tchar *string = *(char **) field;\n\t\t\t\tif (label == PROTOBUF_C_LABEL_REQUIRED && string == NULL)\n\t\t\t\t\treturn FALSE;\n\t\t\t} else if (type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\t\tprotobuf_c_boolean *has = STRUCT_MEMBER_P (message, f->quantifier_offset);\n\t\t\t\tProtobufCBinaryData *bd = field;\n\t\t\t\tif (label == PROTOBUF_C_LABEL_REQUIRED || *has == TRUE) {\n\t\t\t\t\tif (bd->len > 0 && bd->data == NULL)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\treturn TRUE;\n}", "/* === services === */", "typedef void (*GenericHandler) (void *service,\n\t\t\t\tconst ProtobufCMessage *input,\n\t\t\t\tProtobufCClosure closure,\n\t\t\t\tvoid *closure_data);\nvoid\nprotobuf_c_service_invoke_internal(ProtobufCService *service,\n\t\t\t\t unsigned method_index,\n\t\t\t\t const ProtobufCMessage *input,\n\t\t\t\t ProtobufCClosure closure,\n\t\t\t\t void *closure_data)\n{\n\tGenericHandler *handlers;\n\tGenericHandler handler;", "\t/*\n\t * Verify that method_index is within range. If this fails, you are\n\t * likely invoking a newly added method on an old service. (Although\n\t * other memory corruption bugs can cause this assertion too.)\n\t */\n\tassert(method_index < service->descriptor->n_methods);", "\t/*\n\t * Get the array of virtual methods (which are enumerated by the\n\t * generated code).\n\t */\n\thandlers = (GenericHandler *) (service + 1);", "\t/*\n\t * Get our method and invoke it.\n\t * \\todo Seems like handler == NULL is a situation that needs handling.\n\t */\n\thandler = handlers[method_index];\n\t(*handler)(service, input, closure, closure_data);\n}", "void\nprotobuf_c_service_generated_init(ProtobufCService *service,\n\t\t\t\t const ProtobufCServiceDescriptor *descriptor,\n\t\t\t\t ProtobufCServiceDestroy destroy)\n{\n\tASSERT_IS_SERVICE_DESCRIPTOR(descriptor);\n\tservice->descriptor = descriptor;\n\tservice->destroy = destroy;\n\tservice->invoke = protobuf_c_service_invoke_internal;\n\tmemset(service + 1, 0, descriptor->n_methods * sizeof(GenericHandler));\n}", "void protobuf_c_service_destroy(ProtobufCService *service)\n{\n\tservice->destroy(service);\n}", "/* --- querying the descriptors --- */", "const ProtobufCEnumValue *\nprotobuf_c_enum_descriptor_get_value_by_name(const ProtobufCEnumDescriptor *desc,\n\t\t\t\t\t const char *name)\n{\n\tunsigned start = 0;\n\tunsigned count;", "\tif (desc == NULL || desc->values_by_name == NULL)\n\t\treturn NULL;", "\tcount = desc->n_value_names;", "\twhile (count > 1) {\n\t\tunsigned mid = start + count / 2;\n\t\tint rv = strcmp(desc->values_by_name[mid].name, name);\n\t\tif (rv == 0)\n\t\t\treturn desc->values + desc->values_by_name[mid].index;\n\t\telse if (rv < 0) {\n\t\t\tcount = start + count - (mid + 1);\n\t\t\tstart = mid + 1;\n\t\t} else\n\t\t\tcount = mid - start;\n\t}\n\tif (count == 0)\n\t\treturn NULL;\n\tif (strcmp(desc->values_by_name[start].name, name) == 0)\n\t\treturn desc->values + desc->values_by_name[start].index;\n\treturn NULL;\n}", "const ProtobufCEnumValue *\nprotobuf_c_enum_descriptor_get_value(const ProtobufCEnumDescriptor *desc,\n\t\t\t\t int value)\n{\n\tint rv = int_range_lookup(desc->n_value_ranges, desc->value_ranges, value);\n\tif (rv < 0)\n\t\treturn NULL;\n\treturn desc->values + rv;\n}", "const ProtobufCFieldDescriptor *\nprotobuf_c_message_descriptor_get_field_by_name(const ProtobufCMessageDescriptor *desc,\n\t\t\t\t\t\tconst char *name)\n{\n\tunsigned start = 0;\n\tunsigned count;\n\tconst ProtobufCFieldDescriptor *field;", "\tif (desc == NULL || desc->fields_sorted_by_name == NULL)\n\t\treturn NULL;", "\tcount = desc->n_fields;", "\twhile (count > 1) {\n\t\tunsigned mid = start + count / 2;\n\t\tint rv;\n\t\tfield = desc->fields + desc->fields_sorted_by_name[mid];\n\t\trv = strcmp(field->name, name);\n\t\tif (rv == 0)\n\t\t\treturn field;\n\t\telse if (rv < 0) {\n\t\t\tcount = start + count - (mid + 1);\n\t\t\tstart = mid + 1;\n\t\t} else\n\t\t\tcount = mid - start;\n\t}\n\tif (count == 0)\n\t\treturn NULL;\n\tfield = desc->fields + desc->fields_sorted_by_name[start];\n\tif (strcmp(field->name, name) == 0)\n\t\treturn field;\n\treturn NULL;\n}", "const ProtobufCFieldDescriptor *\nprotobuf_c_message_descriptor_get_field(const ProtobufCMessageDescriptor *desc,\n\t\t\t\t\tunsigned value)\n{\n\tint rv = int_range_lookup(desc->n_field_ranges,desc->field_ranges, value);\n\tif (rv < 0)\n\t\treturn NULL;\n\treturn desc->fields + rv;\n}", "const ProtobufCMethodDescriptor *\nprotobuf_c_service_descriptor_get_method_by_name(const ProtobufCServiceDescriptor *desc,\n\t\t\t\t\t\t const char *name)\n{\n\tunsigned start = 0;\n\tunsigned count;", "\tif (desc == NULL || desc->method_indices_by_name == NULL)\n\t\treturn NULL;", "\tcount = desc->n_methods;", "\twhile (count > 1) {\n\t\tunsigned mid = start + count / 2;\n\t\tunsigned mid_index = desc->method_indices_by_name[mid];\n\t\tconst char *mid_name = desc->methods[mid_index].name;\n\t\tint rv = strcmp(mid_name, name);", "\t\tif (rv == 0)\n\t\t\treturn desc->methods + desc->method_indices_by_name[mid];\n\t\tif (rv < 0) {\n\t\t\tcount = start + count - (mid + 1);\n\t\t\tstart = mid + 1;\n\t\t} else {\n\t\t\tcount = mid - start;\n\t\t}\n\t}\n\tif (count == 0)\n\t\treturn NULL;\n\tif (strcmp(desc->methods[desc->method_indices_by_name[start]].name, name) == 0)\n\t\treturn desc->methods + desc->method_indices_by_name[start];\n\treturn NULL;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2610], "buggy_code_start_loc": [2606], "filenames": ["protobuf-c/protobuf-c.c"], "fixing_code_end_loc": [2613], "fixing_code_start_loc": [2606], "message": "protobuf-c before 1.4.1 has an unsigned integer overflow in parse_required_member.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:protobuf-c_project:protobuf-c:*:*:*:*:*:*:*:*", "matchCriteriaId": "036DA1F5-7D0A-427C-B29F-90FA388EBB1E", "versionEndExcluding": "1.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "protobuf-c before 1.4.1 has an unsigned integer overflow in parse_required_member."}], "evaluatorComment": null, "id": "CVE-2022-48468", "lastModified": "2023-04-29T07:15:07.207", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-13T21:15:07.077", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/protobuf-c/protobuf-c/commit/ec3d900001a13ccdaa8aef996b34c61159c76217"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/protobuf-c/protobuf-c/issues/499"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/protobuf-c/protobuf-c/pull/513"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes"], "url": "https://github.com/protobuf-c/protobuf-c/releases/tag/v1.4.1"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/EI4JZSHJXW7WOOTAQSV5SUCC5GE2GC2B/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/UGLZZYPOLI733DPETL444E3GY5KSS6LG/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/VNUEZZEPR2F6M67ANXLOPJX6AQL3TK4P/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/protobuf-c/protobuf-c/commit/ec3d900001a13ccdaa8aef996b34c61159c76217"}, "type": "CWE-190"}
297
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2008-2015, Dave Benson and the protobuf-c authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */", "/*! \\file\n * Support library for `protoc-c` generated code.\n *\n * This file implements the public API used by the code generated\n * by `protoc-c`.\n *\n * \\authors Dave Benson and the protobuf-c authors\n *\n * \\copyright 2008-2014. Licensed under the terms of the [BSD-2-Clause] license.\n */", "/**\n * \\todo 64-BIT OPTIMIZATION: certain implementations use 32-bit math\n * even on 64-bit platforms (uint64_size, uint64_pack, parse_uint64).\n *\n * \\todo Use size_t consistently.\n */", "#include <stdlib.h>\t/* for malloc, free */\n#include <string.h>\t/* for strcmp, strlen, memcpy, memmove, memset */", "#include \"protobuf-c.h\"", "#define TRUE\t\t\t\t1\n#define FALSE\t\t\t\t0", "#define PROTOBUF_C__ASSERT_NOT_REACHED() assert(0)", "/* Workaround for Microsoft compilers. */\n#ifdef _MSC_VER\n# define inline __inline\n#endif", "/**\n * \\defgroup internal Internal functions and macros\n *\n * These are not exported by the library but are useful to developers working\n * on `libprotobuf-c` itself.\n */", "/**\n * \\defgroup macros Utility macros for manipulating structures\n *\n * Macros and constants used to manipulate the base \"classes\" generated by\n * `protobuf-c`. They also define limits and check correctness.\n *\n * \\ingroup internal\n * @{\n */", "/** The maximum length of a 64-bit integer in varint encoding. */\n#define MAX_UINT64_ENCODED_SIZE\t\t10", "#ifndef PROTOBUF_C_UNPACK_ERROR\n# define PROTOBUF_C_UNPACK_ERROR(...)\n#endif", "#if !defined(_WIN32) || !defined(PROTOBUF_C_USE_SHARED_LIB)\nconst char protobuf_c_empty_string[] = \"\";\n#endif", "/**\n * Internal `ProtobufCMessage` manipulation macro.\n *\n * Base macro for manipulating a `ProtobufCMessage`. Used by STRUCT_MEMBER() and\n * STRUCT_MEMBER_PTR().\n */\n#define STRUCT_MEMBER_P(struct_p, struct_offset) \\\n ((void *) ((uint8_t *) (struct_p) + (struct_offset)))", "/**\n * Return field in a `ProtobufCMessage` based on offset.\n *\n * Take a pointer to a `ProtobufCMessage` and find the field at the offset.\n * Cast it to the passed type.\n */\n#define STRUCT_MEMBER(member_type, struct_p, struct_offset) \\\n (*(member_type *) STRUCT_MEMBER_P((struct_p), (struct_offset)))", "/**\n * Return field in a `ProtobufCMessage` based on offset.\n *\n * Take a pointer to a `ProtobufCMessage` and find the field at the offset. Cast\n * it to a pointer to the passed type.\n */\n#define STRUCT_MEMBER_PTR(member_type, struct_p, struct_offset) \\\n ((member_type *) STRUCT_MEMBER_P((struct_p), (struct_offset)))", "/* Assertions for magic numbers. */", "#define ASSERT_IS_ENUM_DESCRIPTOR(desc) \\\n\tassert((desc)->magic == PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC)", "#define ASSERT_IS_MESSAGE_DESCRIPTOR(desc) \\\n\tassert((desc)->magic == PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC)", "#define ASSERT_IS_MESSAGE(message) \\\n\tASSERT_IS_MESSAGE_DESCRIPTOR((message)->descriptor)", "#define ASSERT_IS_SERVICE_DESCRIPTOR(desc) \\\n\tassert((desc)->magic == PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC)", "/**@}*/", "/* --- version --- */", "const char *\nprotobuf_c_version(void)\n{\n\treturn PROTOBUF_C_VERSION;\n}", "uint32_t\nprotobuf_c_version_number(void)\n{\n\treturn PROTOBUF_C_VERSION_NUMBER;\n}", "/* --- allocator --- */", "static void *\nsystem_alloc(void *allocator_data, size_t size)\n{\n\t(void)allocator_data;\n\treturn malloc(size);\n}", "static void\nsystem_free(void *allocator_data, void *data)\n{\n\t(void)allocator_data;\n\tfree(data);\n}", "static inline void *\ndo_alloc(ProtobufCAllocator *allocator, size_t size)\n{\n\treturn allocator->alloc(allocator->allocator_data, size);\n}", "static inline void\ndo_free(ProtobufCAllocator *allocator, void *data)\n{\n\tif (data != NULL)\n\t\tallocator->free(allocator->allocator_data, data);\n}", "/*\n * This allocator uses the system's malloc() and free(). It is the default\n * allocator used if NULL is passed as the ProtobufCAllocator to an exported\n * function.\n */\nstatic ProtobufCAllocator protobuf_c__allocator = {\n\t.alloc = &system_alloc,\n\t.free = &system_free,\n\t.allocator_data = NULL,\n};", "/* === buffer-simple === */", "void\nprotobuf_c_buffer_simple_append(ProtobufCBuffer *buffer,\n\t\t\t\tsize_t len, const uint8_t *data)\n{\n\tProtobufCBufferSimple *simp = (ProtobufCBufferSimple *) buffer;\n\tsize_t new_len = simp->len + len;", "\tif (new_len > simp->alloced) {\n\t\tProtobufCAllocator *allocator = simp->allocator;\n\t\tsize_t new_alloced = simp->alloced * 2;\n\t\tuint8_t *new_data;", "\t\tif (allocator == NULL)\n\t\t\tallocator = &protobuf_c__allocator;\n\t\twhile (new_alloced < new_len)\n\t\t\tnew_alloced += new_alloced;\n\t\tnew_data = do_alloc(allocator, new_alloced);\n\t\tif (!new_data)\n\t\t\treturn;\n\t\tmemcpy(new_data, simp->data, simp->len);\n\t\tif (simp->must_free_data)\n\t\t\tdo_free(allocator, simp->data);\n\t\telse\n\t\t\tsimp->must_free_data = TRUE;\n\t\tsimp->data = new_data;\n\t\tsimp->alloced = new_alloced;\n\t}\n\tmemcpy(simp->data + simp->len, data, len);\n\tsimp->len = new_len;\n}", "/**\n * \\defgroup packedsz protobuf_c_message_get_packed_size() implementation\n *\n * Routines mainly used by protobuf_c_message_get_packed_size().\n *\n * \\ingroup internal\n * @{\n */", "/**\n * Return the number of bytes required to store the tag for the field. Includes\n * 3 bits for the wire-type, and a single bit that denotes the end-of-tag.\n *\n * \\param number\n * Field tag to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nget_tag_size(uint32_t number)\n{\n\tif (number < (1UL << 4)) {\n\t\treturn 1;\n\t} else if (number < (1UL << 11)) {\n\t\treturn 2;\n\t} else if (number < (1UL << 18)) {\n\t\treturn 3;\n\t} else if (number < (1UL << 25)) {\n\t\treturn 4;\n\t} else {\n\t\treturn 5;\n\t}\n}", "/**\n * Return the number of bytes required to store a variable-length unsigned\n * 32-bit integer in base-128 varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nuint32_size(uint32_t v)\n{\n\tif (v < (1UL << 7)) {\n\t\treturn 1;\n\t} else if (v < (1UL << 14)) {\n\t\treturn 2;\n\t} else if (v < (1UL << 21)) {\n\t\treturn 3;\n\t} else if (v < (1UL << 28)) {\n\t\treturn 4;\n\t} else {\n\t\treturn 5;\n\t}\n}", "/**\n * Return the number of bytes required to store a variable-length signed 32-bit\n * integer in base-128 varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nint32_size(int32_t v)\n{\n\tif (v < 0) {\n\t\treturn 10;\n\t} else if (v < (1L << 7)) {\n\t\treturn 1;\n\t} else if (v < (1L << 14)) {\n\t\treturn 2;\n\t} else if (v < (1L << 21)) {\n\t\treturn 3;\n\t} else if (v < (1L << 28)) {\n\t\treturn 4;\n\t} else {\n\t\treturn 5;\n\t}\n}", "/**\n * Return the ZigZag-encoded 32-bit unsigned integer form of a 32-bit signed\n * integer.\n *\n * \\param v\n * Value to encode.\n * \\return\n * ZigZag encoded integer.\n */\nstatic inline uint32_t\nzigzag32(int32_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn ((uint32_t)v << 1) ^ -((uint32_t)v >> 31);\n}", "/**\n * Return the number of bytes required to store a signed 32-bit integer,\n * converted to an unsigned 32-bit integer with ZigZag encoding, using base-128\n * varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nsint32_size(int32_t v)\n{\n\treturn uint32_size(zigzag32(v));\n}", "/**\n * Return the number of bytes required to store a 64-bit unsigned integer in\n * base-128 varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nuint64_size(uint64_t v)\n{\n\tuint32_t upper_v = (uint32_t) (v >> 32);", "\tif (upper_v == 0) {\n\t\treturn uint32_size((uint32_t) v);\n\t} else if (upper_v < (1UL << 3)) {\n\t\treturn 5;\n\t} else if (upper_v < (1UL << 10)) {\n\t\treturn 6;\n\t} else if (upper_v < (1UL << 17)) {\n\t\treturn 7;\n\t} else if (upper_v < (1UL << 24)) {\n\t\treturn 8;\n\t} else if (upper_v < (1UL << 31)) {\n\t\treturn 9;\n\t} else {\n\t\treturn 10;\n\t}\n}", "/**\n * Return the ZigZag-encoded 64-bit unsigned integer form of a 64-bit signed\n * integer.\n *\n * \\param v\n * Value to encode.\n * \\return\n * ZigZag encoded integer.\n */\nstatic inline uint64_t\nzigzag64(int64_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn ((uint64_t)v << 1) ^ -((uint64_t)v >> 63);\n}", "/**\n * Return the number of bytes required to store a signed 64-bit integer,\n * converted to an unsigned 64-bit integer with ZigZag encoding, using base-128\n * varint encoding.\n *\n * \\param v\n * Value to encode.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nsint64_size(int64_t v)\n{\n\treturn uint64_size(zigzag64(v));\n}", "/**\n * Calculate the serialized size of a single required message field, including\n * the space needed by the preceding tag.\n *\n * \\param field\n * Field descriptor for member.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nrequired_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t const void *member)\n{\n\tsize_t rv = get_tag_size(field->id);", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\treturn rv + sint32_size(*(const int32_t *) member);\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\treturn rv + int32_size(*(const int32_t *) member);\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\treturn rv + uint32_size(*(const uint32_t *) member);\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\treturn rv + sint64_size(*(const int64_t *) member);\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\treturn rv + uint64_size(*(const uint64_t *) member);\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\treturn rv + 4;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\treturn rv + 8;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\treturn rv + 1;\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\treturn rv + 4;\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\treturn rv + 8;\n\tcase PROTOBUF_C_TYPE_STRING: {\n\t\tconst char *str = *(char * const *) member;\n\t\tsize_t len = str ? strlen(str) : 0;\n\t\treturn rv + uint32_size(len) + len;\n\t}\n\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\tsize_t len = ((const ProtobufCBinaryData *) member)->len;\n\t\treturn rv + uint32_size(len) + len;\n\t}\n\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\tconst ProtobufCMessage *msg = *(ProtobufCMessage * const *) member;\n\t\tsize_t subrv = msg ? protobuf_c_message_get_packed_size(msg) : 0;\n\t\treturn rv + uint32_size(subrv) + subrv;\n\t}\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Calculate the serialized size of a single oneof message field, including\n * the space needed by the preceding tag. Returns 0 if the oneof field isn't\n * selected or is not set.\n *\n * \\param field\n * Field descriptor for member.\n * \\param oneof_case\n * Enum value that selects the field in the oneof.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\noneof_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t uint32_t oneof_case,\n\t\t\t const void *member)\n{\n\tif (oneof_case != field->id) {\n\t\treturn 0;\n\t}\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t}\n\treturn required_field_get_packed_size(field, member);\n}", "/**\n * Calculate the serialized size of a single optional message field, including\n * the space needed by the preceding tag. Returns 0 if the optional field isn't\n * set.\n *\n * \\param field\n * Field descriptor for member.\n * \\param has\n * True if the field exists, false if not.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\noptional_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t const protobuf_c_boolean has,\n\t\t\t const void *member)\n{\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t} else {\n\t\tif (!has)\n\t\t\treturn 0;\n\t}\n\treturn required_field_get_packed_size(field, member);\n}", "static protobuf_c_boolean\nfield_is_zeroish(const ProtobufCFieldDescriptor *field,\n\t\t const void *member)\n{\n\tprotobuf_c_boolean ret = FALSE;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tret = (0 == *(const protobuf_c_boolean *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_SINT32:\n\tcase PROTOBUF_C_TYPE_INT32:\n\tcase PROTOBUF_C_TYPE_UINT32:\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\tret = (0 == *(const uint32_t *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\tret = (0 == *(const uint64_t *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tret = (0 == *(const float *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tret = (0 == *(const double *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_STRING:\n\t\tret = (NULL == *(const char * const *) member) ||\n\t\t ('\\0' == **(const char * const *) member);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BYTES:\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\tret = (NULL == *(const void * const *) member);\n\t\tbreak;\n\tdefault:\n\t\tret = TRUE;\n\t\tbreak;\n\t}", "\treturn ret;\n}", "/**\n * Calculate the serialized size of a single unlabeled message field, including\n * the space needed by the preceding tag. Returns 0 if the field isn't set or\n * if it is set to a \"zeroish\" value (null pointer or 0 for numerical values).\n * Unlabeled fields are supported only in proto3.\n *\n * \\param field\n * Field descriptor for member.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nunlabeled_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t\tconst void *member)\n{\n\tif (field_is_zeroish(field, member))\n\t\treturn 0;\n\treturn required_field_get_packed_size(field, member);\n}", "/**\n * Calculate the serialized size of repeated message fields, which may consist\n * of any number of values (including 0). Includes the space needed by the\n * preceding tags (as needed).\n *\n * \\param field\n * Field descriptor for member.\n * \\param count\n * Number of repeated field members.\n * \\param member\n * Field to encode.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nrepeated_field_get_packed_size(const ProtobufCFieldDescriptor *field,\n\t\t\t size_t count, const void *member)\n{\n\tsize_t header_size;\n\tsize_t rv = 0;\n\tunsigned i;\n\tvoid *array = *(void * const *) member;", "\tif (count == 0)\n\t\treturn 0;\n\theader_size = get_tag_size(field->id);\n\tif (0 == (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED))\n\t\theader_size *= count;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint32_size(((int32_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += int32_size(((int32_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint32_size(((uint32_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint64_size(((int64_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint64_size(((uint64_t *) array)[i]);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\trv += 4 * count;\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\trv += 8 * count;\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\trv += count;\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_STRING:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tsize_t len = strlen(((char **) array)[i]);\n\t\t\trv += uint32_size(len) + len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BYTES:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tsize_t len = ((ProtobufCBinaryData *) array)[i].len;\n\t\t\trv += uint32_size(len) + len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tsize_t len = protobuf_c_message_get_packed_size(\n\t\t\t\t((ProtobufCMessage **) array)[i]);\n\t\t\trv += uint32_size(len) + len;\n\t\t}\n\t\tbreak;\n\t}", "\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED))\n\t\theader_size += uint32_size(rv);\n\treturn header_size + rv;\n}", "/**\n * Calculate the serialized size of an unknown field, i.e. one that is passed\n * through mostly uninterpreted. This is required for forward compatibility if\n * new fields are added to the message descriptor.\n *\n * \\param field\n * Unknown field type.\n * \\return\n * Number of bytes required.\n */\nstatic inline size_t\nunknown_field_get_packed_size(const ProtobufCMessageUnknownField *field)\n{\n\treturn get_tag_size(field->tag) + field->len;\n}", "/**@}*/", "/*\n * Calculate the serialized size of the message.\n */\nsize_t protobuf_c_message_get_packed_size(const ProtobufCMessage *message)\n{\n\tunsigned i;\n\tsize_t rv = 0;", "\tASSERT_IS_MESSAGE(message);\n\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *field =\n\t\t\tmessage->descriptor->fields + i;\n\t\tconst void *member =\n\t\t\t((const char *) message) + field->offset;\n\t\tconst void *qmember =\n\t\t\t((const char *) message) + field->quantifier_offset;", "\t\tif (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\trv += required_field_get_packed_size(field, member);\n\t\t} else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t field->label == PROTOBUF_C_LABEL_NONE) &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {\n\t\t\trv += oneof_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\t*(const uint32_t *) qmember,\n\t\t\t\tmember\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {\n\t\t\trv += optional_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\t*(protobuf_c_boolean *) qmember,\n\t\t\t\tmember\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_NONE) {\n\t\t\trv += unlabeled_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\tmember\n\t\t\t);\n\t\t} else {\n\t\t\trv += repeated_field_get_packed_size(\n\t\t\t\tfield,\n\t\t\t\t*(const size_t *) qmember,\n\t\t\t\tmember\n\t\t\t);\n\t\t}\n\t}\n\tfor (i = 0; i < message->n_unknown_fields; i++)\n\t\trv += unknown_field_get_packed_size(&message->unknown_fields[i]);\n\treturn rv;\n}", "/**\n * \\defgroup pack protobuf_c_message_pack() implementation\n *\n * Routines mainly used by protobuf_c_message_pack().\n *\n * \\ingroup internal\n * @{\n */", "/**\n * Pack an unsigned 32-bit integer in base-128 varint encoding and return the\n * number of bytes written, which must be 5 or less.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nuint32_pack(uint32_t value, uint8_t *out)\n{\n\tunsigned rv = 0;", "\tif (value >= 0x80) {\n\t\tout[rv++] = value | 0x80;\n\t\tvalue >>= 7;\n\t\tif (value >= 0x80) {\n\t\t\tout[rv++] = value | 0x80;\n\t\t\tvalue >>= 7;\n\t\t\tif (value >= 0x80) {\n\t\t\t\tout[rv++] = value | 0x80;\n\t\t\t\tvalue >>= 7;\n\t\t\t\tif (value >= 0x80) {\n\t\t\t\t\tout[rv++] = value | 0x80;\n\t\t\t\t\tvalue >>= 7;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/* assert: value<128 */\n\tout[rv++] = value;\n\treturn rv;\n}", "/**\n * Pack a signed 32-bit integer and return the number of bytes written,\n * passed as unsigned to avoid implementation-specific behavior.\n * Negative numbers are encoded as two's complement 64-bit integers.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nint32_pack(uint32_t value, uint8_t *out)\n{\n\tif ((int32_t)value < 0) {\n\t\tout[0] = value | 0x80;\n\t\tout[1] = (value >> 7) | 0x80;\n\t\tout[2] = (value >> 14) | 0x80;\n\t\tout[3] = (value >> 21) | 0x80;\n\t\tout[4] = (value >> 28) | 0xf0;\n\t\tout[5] = out[6] = out[7] = out[8] = 0xff;\n\t\tout[9] = 0x01;\n\t\treturn 10;\n\t} else {\n\t\treturn uint32_pack(value, out);\n\t}\n}", "/**\n * Pack a signed 32-bit integer using ZigZag encoding and return the number of\n * bytes written.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nsint32_pack(int32_t value, uint8_t *out)\n{\n\treturn uint32_pack(zigzag32(value), out);\n}", "/**\n * Pack a 64-bit unsigned integer using base-128 varint encoding and return the\n * number of bytes written.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\nuint64_pack(uint64_t value, uint8_t *out)\n{\n\tuint32_t hi = (uint32_t) (value >> 32);\n\tuint32_t lo = (uint32_t) value;\n\tunsigned rv;", "\tif (hi == 0)\n\t\treturn uint32_pack((uint32_t) lo, out);\n\tout[0] = (lo) | 0x80;\n\tout[1] = (lo >> 7) | 0x80;\n\tout[2] = (lo >> 14) | 0x80;\n\tout[3] = (lo >> 21) | 0x80;\n\tif (hi < 8) {\n\t\tout[4] = (hi << 4) | (lo >> 28);\n\t\treturn 5;\n\t} else {\n\t\tout[4] = ((hi & 7) << 4) | (lo >> 28) | 0x80;\n\t\thi >>= 3;\n\t}\n\trv = 5;\n\twhile (hi >= 128) {\n\t\tout[rv++] = hi | 0x80;\n\t\thi >>= 7;\n\t}\n\tout[rv++] = hi;\n\treturn rv;\n}", "/**\n * Pack a 64-bit signed integer in ZigZag encoding and return the number of\n * bytes written.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nsint64_pack(int64_t value, uint8_t *out)\n{\n\treturn uint64_pack(zigzag64(value), out);\n}", "/**\n * Pack a 32-bit quantity in little-endian byte order. Used for protobuf wire\n * types fixed32, sfixed32, float. Similar to \"htole32\".\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nfixed32_pack(uint32_t value, void *out)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, &value, 4);\n#else\n\tuint8_t *buf = out;", "\tbuf[0] = value;\n\tbuf[1] = value >> 8;\n\tbuf[2] = value >> 16;\n\tbuf[3] = value >> 24;\n#endif\n\treturn 4;\n}", "/**\n * Pack a 64-bit quantity in little-endian byte order. Used for protobuf wire\n * types fixed64, sfixed64, double. Similar to \"htole64\".\n *\n * \\todo The big-endian impl is really only good for 32-bit machines, a 64-bit\n * version would be appreciated, plus a way to decide to use 64-bit math where\n * convenient.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nfixed64_pack(uint64_t value, void *out)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, &value, 8);\n#else\n\tfixed32_pack(value, out);\n\tfixed32_pack(value >> 32, ((char *) out) + 4);\n#endif\n\treturn 8;\n}", "/**\n * Pack a boolean value as an integer and return the number of bytes written.\n *\n * \\todo Perhaps on some platforms *out = !!value would be a better impl, b/c\n * that is idiomatic C++ in some STL implementations.\n *\n * \\param value\n * Value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nboolean_pack(protobuf_c_boolean value, uint8_t *out)\n{\n\t*out = value ? TRUE : FALSE;\n\treturn 1;\n}", "/**\n * Pack a NUL-terminated C string and return the number of bytes written. The\n * output includes a length delimiter.\n *\n * The NULL pointer is treated as an empty string. This isn't really necessary,\n * but it allows people to leave required strings blank. (See Issue #13 in the\n * bug tracker for a little more explanation).\n *\n * \\param str\n * String to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nstring_pack(const char *str, uint8_t *out)\n{\n\tif (str == NULL) {\n\t\tout[0] = 0;\n\t\treturn 1;\n\t} else {\n\t\tsize_t len = strlen(str);\n\t\tsize_t rv = uint32_pack(len, out);\n\t\tmemcpy(out + rv, str, len);\n\t\treturn rv + len;\n\t}\n}", "/**\n * Pack a ProtobufCBinaryData and return the number of bytes written. The output\n * includes a length delimiter.\n *\n * \\param bd\n * ProtobufCBinaryData to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nbinary_data_pack(const ProtobufCBinaryData *bd, uint8_t *out)\n{\n\tsize_t len = bd->len;\n\tsize_t rv = uint32_pack(len, out);\n\tmemcpy(out + rv, bd->data, len);\n\treturn rv + len;\n}", "/**\n * Pack a ProtobufCMessage and return the number of bytes written. The output\n * includes a length delimiter.\n *\n * \\param message\n * ProtobufCMessage object to pack.\n * \\param[out] out\n * Packed message.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic inline size_t\nprefixed_message_pack(const ProtobufCMessage *message, uint8_t *out)\n{\n\tif (message == NULL) {\n\t\tout[0] = 0;\n\t\treturn 1;\n\t} else {\n\t\tsize_t rv = protobuf_c_message_pack(message, out + 1);\n\t\tuint32_t rv_packed_size = uint32_size(rv);\n\t\tif (rv_packed_size != 1)\n\t\t\tmemmove(out + rv_packed_size, out + 1, rv);\n\t\treturn uint32_pack(rv, out) + rv;\n\t}\n}", "/**\n * Pack a field tag.\n *\n * Wire-type will be added in required_field_pack().\n *\n * \\todo Just call uint64_pack on 64-bit platforms.\n *\n * \\param id\n * Tag value to encode.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\ntag_pack(uint32_t id, uint8_t *out)\n{\n\tif (id < (1UL << (32 - 3)))\n\t\treturn uint32_pack(id << 3, out);\n\telse\n\t\treturn uint64_pack(((uint64_t) id) << 3, out);\n}", "/**\n * Pack a required field and return the number of bytes written.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\nrequired_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t const void *member, uint8_t *out)\n{\n\tsize_t rv = tag_pack(field->id, out);", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + sint32_pack(*(const int32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + int32_pack(*(const int32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + uint32_pack(*(const uint32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + sint64_pack(*(const int64_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + uint64_pack(*(const uint64_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_32BIT;\n\t\treturn rv + fixed32_pack(*(const uint32_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_64BIT;\n\t\treturn rv + fixed64_pack(*(const uint64_t *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\treturn rv + boolean_pack(*(const protobuf_c_boolean *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_STRING:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\treturn rv + string_pack(*(char *const *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_BYTES:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\treturn rv + binary_data_pack((const ProtobufCBinaryData *) member, out + rv);\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\treturn rv + prefixed_message_pack(*(ProtobufCMessage * const *) member, out + rv);\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Pack a oneof field and return the number of bytes written. Only packs the\n * field that is selected by the case enum.\n *\n * \\param field\n * Field descriptor.\n * \\param oneof_case\n * Enum value that selects the field in the oneof.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\noneof_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t uint32_t oneof_case,\n\t\t const void *member, uint8_t *out)\n{\n\tif (oneof_case != field->id) {\n\t\treturn 0;\n\t}\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack(field, member, out);\n}", "/**\n * Pack an optional field and return the number of bytes written.\n *\n * \\param field\n * Field descriptor.\n * \\param has\n * Whether the field is set.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\noptional_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t const protobuf_c_boolean has,\n\t\t const void *member, uint8_t *out)\n{\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void * const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t} else {\n\t\tif (!has)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack(field, member, out);\n}", "/**\n * Pack an unlabeled field and return the number of bytes written.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The field member.\n * \\param[out] out\n * Packed value.\n * \\return\n * Number of bytes written to `out`.\n */\nstatic size_t\nunlabeled_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t const void *member, uint8_t *out)\n{\n\tif (field_is_zeroish(field, member))\n\t\treturn 0;\n\treturn required_field_pack(field, member, out);\n}", "/**\n * Given a field type, return the in-memory size.\n *\n * \\todo Implement as a table lookup.\n *\n * \\param type\n * Field type.\n * \\return\n * Size of the field.\n */\nstatic inline size_t\nsizeof_elt_in_repeated_array(ProtobufCType type)\n{\n\tswitch (type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\tcase PROTOBUF_C_TYPE_INT32:\n\tcase PROTOBUF_C_TYPE_UINT32:\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\tcase PROTOBUF_C_TYPE_ENUM:\n\t\treturn 4;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\treturn 8;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\treturn sizeof(protobuf_c_boolean);\n\tcase PROTOBUF_C_TYPE_STRING:\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\treturn sizeof(void *);\n\tcase PROTOBUF_C_TYPE_BYTES:\n\t\treturn sizeof(ProtobufCBinaryData);\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Pack an array of 32-bit quantities.\n *\n * \\param[out] out\n * Destination.\n * \\param[in] in\n * Source.\n * \\param[in] n\n * Number of elements in the source array.\n */\nstatic void\ncopy_to_little_endian_32(void *out, const void *in, const unsigned n)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, in, n * 4);\n#else\n\tunsigned i;\n\tconst uint32_t *ini = in;\n\tfor (i = 0; i < n; i++)\n\t\tfixed32_pack(ini[i], (uint32_t *) out + i);\n#endif\n}", "/**\n * Pack an array of 64-bit quantities.\n *\n * \\param[out] out\n * Destination.\n * \\param[in] in\n * Source.\n * \\param[in] n\n * Number of elements in the source array.\n */\nstatic void\ncopy_to_little_endian_64(void *out, const void *in, const unsigned n)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tmemcpy(out, in, n * 8);\n#else\n\tunsigned i;\n\tconst uint64_t *ini = in;\n\tfor (i = 0; i < n; i++)\n\t\tfixed64_pack(ini[i], (uint64_t *) out + i);\n#endif\n}", "/**\n * Get the minimum number of bytes required to pack a field value of a\n * particular type.\n *\n * \\param type\n * Field type.\n * \\return\n * Number of bytes.\n */\nstatic unsigned\nget_type_min_size(ProtobufCType type)\n{\n\tif (type == PROTOBUF_C_TYPE_SFIXED32 ||\n\t type == PROTOBUF_C_TYPE_FIXED32 ||\n\t type == PROTOBUF_C_TYPE_FLOAT)\n\t{\n\t\treturn 4;\n\t}\n\tif (type == PROTOBUF_C_TYPE_SFIXED64 ||\n\t type == PROTOBUF_C_TYPE_FIXED64 ||\n\t type == PROTOBUF_C_TYPE_DOUBLE)\n\t{\n\t\treturn 8;\n\t}\n\treturn 1;\n}", "/**\n * Packs the elements of a repeated field and returns the serialised field and\n * its length.\n *\n * \\param field\n * Field descriptor.\n * \\param count\n * Number of elements in the repeated field array.\n * \\param member\n * Pointer to the elements for this repeated field.\n * \\param[out] out\n * Serialised representation of the repeated field.\n * \\return\n * Number of bytes serialised to `out`.\n */\nstatic size_t\nrepeated_field_pack(const ProtobufCFieldDescriptor *field,\n\t\t size_t count, const void *member, uint8_t *out)\n{\n\tvoid *array = *(void * const *) member;\n\tunsigned i;", "\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) {\n\t\tunsigned header_len;\n\t\tunsigned len_start;\n\t\tunsigned min_length;\n\t\tunsigned payload_len;\n\t\tunsigned length_size_min;\n\t\tunsigned actual_length_size;\n\t\tuint8_t *payload_at;", "\t\tif (count == 0)\n\t\t\treturn 0;\n\t\theader_len = tag_pack(field->id, out);\n\t\tout[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\tlen_start = header_len;\n\t\tmin_length = get_type_min_size(field->type) * count;\n\t\tlength_size_min = uint32_size(min_length);\n\t\theader_len += length_size_min;\n\t\tpayload_at = out + header_len;", "\t\tswitch (field->type) {\n\t\tcase PROTOBUF_C_TYPE_SFIXED32:\n\t\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\t\tcopy_to_little_endian_32(payload_at, array, count);\n\t\t\tpayload_at += count * 4;\n\t\t\tbreak;\n\t\tcase PROTOBUF_C_TYPE_SFIXED64:\n\t\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\t\tcopy_to_little_endian_64(payload_at, array, count);\n\t\t\tpayload_at += count * 8;\n\t\t\tbreak;\n\t\tcase PROTOBUF_C_TYPE_ENUM:\n\t\tcase PROTOBUF_C_TYPE_INT32: {\n\t\t\tconst int32_t *arr = (const int32_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += int32_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_SINT32: {\n\t\t\tconst int32_t *arr = (const int32_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += sint32_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_SINT64: {\n\t\t\tconst int64_t *arr = (const int64_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += sint64_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_UINT32: {\n\t\t\tconst uint32_t *arr = (const uint32_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += uint32_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_INT64:\n\t\tcase PROTOBUF_C_TYPE_UINT64: {\n\t\t\tconst uint64_t *arr = (const uint64_t *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += uint64_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_TYPE_BOOL: {\n\t\t\tconst protobuf_c_boolean *arr = (const protobuf_c_boolean *) array;\n\t\t\tfor (i = 0; i < count; i++)\n\t\t\t\tpayload_at += boolean_pack(arr[i], payload_at);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t\t}", "\t\tpayload_len = payload_at - (out + header_len);\n\t\tactual_length_size = uint32_size(payload_len);\n\t\tif (length_size_min != actual_length_size) {\n\t\t\tassert(actual_length_size == length_size_min + 1);\n\t\t\tmemmove(out + header_len + 1, out + header_len,\n\t\t\t\tpayload_len);\n\t\t\theader_len++;\n\t\t}\n\t\tuint32_pack(payload_len, out + len_start);\n\t\treturn header_len + payload_len;\n\t} else {\n\t\t/* not \"packed\" cased */\n\t\t/* CONSIDER: optimize this case a bit (by putting the loop inside the switch) */\n\t\tsize_t rv = 0;\n\t\tunsigned siz = sizeof_elt_in_repeated_array(field->type);", "\t\tfor (i = 0; i < count; i++) {\n\t\t\trv += required_field_pack(field, array, out + rv);\n\t\t\tarray = (char *)array + siz;\n\t\t}\n\t\treturn rv;\n\t}\n}", "static size_t\nunknown_field_pack(const ProtobufCMessageUnknownField *field, uint8_t *out)\n{\n\tsize_t rv = tag_pack(field->tag, out);\n\tout[0] |= field->wire_type;\n\tmemcpy(out + rv, field->data, field->len);\n\treturn rv + field->len;\n}", "/**@}*/", "size_t\nprotobuf_c_message_pack(const ProtobufCMessage *message, uint8_t *out)\n{\n\tunsigned i;\n\tsize_t rv = 0;", "\tASSERT_IS_MESSAGE(message);\n\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *field =\n\t\t\tmessage->descriptor->fields + i;\n\t\tconst void *member = ((const char *) message) + field->offset;", "\t\t/*\n\t\t * It doesn't hurt to compute qmember (a pointer to the\n\t\t * quantifier field of the structure), but the pointer is only\n\t\t * valid if the field is:\n\t\t * - a repeated field, or\n\t\t * - a field that is part of a oneof\n\t\t * - an optional field that isn't a pointer type\n\t\t * (Meaning: not a message or a string).\n\t\t */\n\t\tconst void *qmember =\n\t\t\t((const char *) message) + field->quantifier_offset;", "\t\tif (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\trv += required_field_pack(field, member, out + rv);\n\t\t} else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t field->label == PROTOBUF_C_LABEL_NONE) &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {\n\t\t\trv += oneof_field_pack(\n\t\t\t\tfield,\n\t\t\t\t*(const uint32_t *) qmember,\n\t\t\t\tmember,\n\t\t\t\tout + rv\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {\n\t\t\trv += optional_field_pack(\n\t\t\t\tfield,\n\t\t\t\t*(const protobuf_c_boolean *) qmember,\n\t\t\t\tmember,\n\t\t\t\tout + rv\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_NONE) {\n\t\t\trv += unlabeled_field_pack(field, member, out + rv);\n\t\t} else {\n\t\t\trv += repeated_field_pack(field, *(const size_t *) qmember,\n\t\t\t\tmember, out + rv);\n\t\t}\n\t}\n\tfor (i = 0; i < message->n_unknown_fields; i++)\n\t\trv += unknown_field_pack(&message->unknown_fields[i], out + rv);\n\treturn rv;\n}", "/**\n * \\defgroup packbuf protobuf_c_message_pack_to_buffer() implementation\n *\n * Routines mainly used by protobuf_c_message_pack_to_buffer().\n *\n * \\ingroup internal\n * @{\n */", "/**\n * Pack a required field to a virtual buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes packed.\n */\nstatic size_t\nrequired_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tsize_t rv;\n\tuint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2];", "\trv = tag_pack(field->id, scratch);\n\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += sint32_pack(*(const int32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += int32_pack(*(const int32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += uint32_pack(*(const uint32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += sint64_pack(*(const int64_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += uint64_pack(*(const uint64_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_32BIT;\n\t\trv += fixed32_pack(*(const uint32_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_64BIT;\n\t\trv += fixed64_pack(*(const uint64_t *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;\n\t\trv += boolean_pack(*(const protobuf_c_boolean *) member, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_STRING: {\n\t\tconst char *str = *(char *const *) member;\n\t\tsize_t sublen = str ? strlen(str) : 0;", "\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\trv += uint32_pack(sublen, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbuffer->append(buffer, sublen, (const uint8_t *) str);\n\t\trv += sublen;\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\tconst ProtobufCBinaryData *bd = ((const ProtobufCBinaryData *) member);\n\t\tsize_t sublen = bd->len;", "\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\trv += uint32_pack(sublen, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\tbuffer->append(buffer, sublen, bd->data);\n\t\trv += sublen;\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\tconst ProtobufCMessage *msg = *(ProtobufCMessage * const *) member;\n\t\t\n\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\tif (msg == NULL) {\n\t\t\trv += uint32_pack(0, scratch + rv);\n\t\t\tbuffer->append(buffer, rv, scratch);\n\t\t} else {\n\t\t\tsize_t sublen = protobuf_c_message_get_packed_size(msg);\n\t\t\trv += uint32_pack(sublen, scratch + rv);\n\t\t\tbuffer->append(buffer, rv, scratch);\n\t\t\tprotobuf_c_message_pack_to_buffer(msg, buffer);\n\t\t\trv += sublen;\n\t\t}\n\t\tbreak;\n\t}\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\treturn rv;\n}", "/**\n * Pack a oneof field to a buffer. Only packs the field that is selected by the case enum.\n *\n * \\param field\n * Field descriptor.\n * \\param oneof_case\n * Enum value that selects the field in the oneof.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes serialised to `buffer`.\n */\nstatic size_t\noneof_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t uint32_t oneof_case,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tif (oneof_case != field->id) {\n\t\treturn 0;\n\t}\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void *const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack_to_buffer(field, member, buffer);\n}", "/**\n * Pack an optional field to a buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param has\n * Whether the field is set.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes serialised to `buffer`.\n */\nstatic size_t\noptional_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t const protobuf_c_boolean has,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tif (field->type == PROTOBUF_C_TYPE_MESSAGE ||\n\t field->type == PROTOBUF_C_TYPE_STRING)\n\t{\n\t\tconst void *ptr = *(const void *const *) member;\n\t\tif (ptr == NULL || ptr == field->default_value)\n\t\t\treturn 0;\n\t} else {\n\t\tif (!has)\n\t\t\treturn 0;\n\t}\n\treturn required_field_pack_to_buffer(field, member, buffer);\n}", "/**\n * Pack an unlabeled field to a buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param member\n * The element to be packed.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes serialised to `buffer`.\n */\nstatic size_t\nunlabeled_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t const void *member, ProtobufCBuffer *buffer)\n{\n\tif (field_is_zeroish(field, member))\n\t\treturn 0;\n\treturn required_field_pack_to_buffer(field, member, buffer);\n}", "/**\n * Get the packed size of an array of same field type.\n *\n * \\param field\n * Field descriptor.\n * \\param count\n * Number of elements of this type.\n * \\param array\n * The elements to get the size of.\n * \\return\n * Number of bytes required.\n */\nstatic size_t\nget_packed_payload_length(const ProtobufCFieldDescriptor *field,\n\t\t\t unsigned count, const void *array)\n{\n\tunsigned rv = 0;\n\tunsigned i;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\treturn count * 4;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\treturn count * 8;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32: {\n\t\tconst int32_t *arr = (const int32_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += int32_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_SINT32: {\n\t\tconst int32_t *arr = (const int32_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint32_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_UINT32: {\n\t\tconst uint32_t *arr = (const uint32_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint32_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_SINT64: {\n\t\tconst int64_t *arr = (const int64_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += sint64_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64: {\n\t\tconst uint64_t *arr = (const uint64_t *) array;\n\t\tfor (i = 0; i < count; i++)\n\t\t\trv += uint64_size(arr[i]);\n\t\tbreak;\n\t}\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\treturn count;\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\treturn rv;\n}", "/**\n * Pack an array of same field type to a virtual buffer.\n *\n * \\param field\n * Field descriptor.\n * \\param count\n * Number of elements of this type.\n * \\param array\n * The elements to get the size of.\n * \\param[out] buffer\n * Virtual buffer to append data to.\n * \\return\n * Number of bytes packed.\n */\nstatic size_t\npack_buffer_packed_payload(const ProtobufCFieldDescriptor *field,\n\t\t\t unsigned count, const void *array,\n\t\t\t ProtobufCBuffer *buffer)\n{\n\tuint8_t scratch[16];\n\tsize_t rv = 0;\n\tunsigned i;", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n#if !defined(WORDS_BIGENDIAN)\n\t\trv = count * 4;\n\t\tgoto no_packing_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = fixed32_pack(((uint32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n#if !defined(WORDS_BIGENDIAN)\n\t\trv = count * 8;\n\t\tgoto no_packing_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = fixed64_pack(((uint64_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = int32_pack(((int32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = sint32_pack(((int32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = uint32_pack(((uint32_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = sint64_pack(((int64_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = uint64_pack(((uint64_t *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\tfor (i = 0; i < count; i++) {\n\t\t\tunsigned len = boolean_pack(((protobuf_c_boolean *) array)[i], scratch);\n\t\t\tbuffer->append(buffer, len, scratch);\n\t\t\trv += len;\n\t\t}\n\t\treturn count;\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\treturn rv;", "#if !defined(WORDS_BIGENDIAN)\nno_packing_needed:\n\tbuffer->append(buffer, rv, array);\n\treturn rv;\n#endif\n}", "static size_t\nrepeated_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,\n\t\t\t unsigned count, const void *member,\n\t\t\t ProtobufCBuffer *buffer)\n{\n\tchar *array = *(char * const *) member;", "\tif (count == 0)\n\t\treturn 0;\n\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) {\n\t\tuint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2];\n\t\tsize_t rv = tag_pack(field->id, scratch);\n\t\tsize_t payload_len = get_packed_payload_length(field, count, array);\n\t\tsize_t tmp;", "\t\tscratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;\n\t\trv += uint32_pack(payload_len, scratch + rv);\n\t\tbuffer->append(buffer, rv, scratch);\n\t\ttmp = pack_buffer_packed_payload(field, count, array, buffer);\n\t\tassert(tmp == payload_len);\n\t\treturn rv + payload_len;\n\t} else {\n\t\tsize_t siz;\n\t\tunsigned i;\n\t\t/* CONSIDER: optimize this case a bit (by putting the loop inside the switch) */\n\t\tunsigned rv = 0;", "\t\tsiz = sizeof_elt_in_repeated_array(field->type);\n\t\tfor (i = 0; i < count; i++) {\n\t\t\trv += required_field_pack_to_buffer(field, array, buffer);\n\t\t\tarray += siz;\n\t\t}\n\t\treturn rv;\n\t}\n}", "static size_t\nunknown_field_pack_to_buffer(const ProtobufCMessageUnknownField *field,\n\t\t\t ProtobufCBuffer *buffer)\n{\n\tuint8_t header[MAX_UINT64_ENCODED_SIZE];\n\tsize_t rv = tag_pack(field->tag, header);", "\theader[0] |= field->wire_type;\n\tbuffer->append(buffer, rv, header);\n\tbuffer->append(buffer, field->len, field->data);\n\treturn rv + field->len;\n}", "/**@}*/", "size_t\nprotobuf_c_message_pack_to_buffer(const ProtobufCMessage *message,\n\t\t\t\t ProtobufCBuffer *buffer)\n{\n\tunsigned i;\n\tsize_t rv = 0;", "\tASSERT_IS_MESSAGE(message);\n\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *field =\n\t\t\tmessage->descriptor->fields + i;\n\t\tconst void *member =\n\t\t\t((const char *) message) + field->offset;\n\t\tconst void *qmember =\n\t\t\t((const char *) message) + field->quantifier_offset;", "\t\tif (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\trv += required_field_pack_to_buffer(field, member, buffer);\n\t\t} else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t field->label == PROTOBUF_C_LABEL_NONE) &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {\n\t\t\trv += oneof_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\t*(const uint32_t *) qmember,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {\n\t\t\trv += optional_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\t*(const protobuf_c_boolean *) qmember,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t} else if (field->label == PROTOBUF_C_LABEL_NONE) {\n\t\t\trv += unlabeled_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t} else {\n\t\t\trv += repeated_field_pack_to_buffer(\n\t\t\t\tfield,\n\t\t\t\t*(const size_t *) qmember,\n\t\t\t\tmember,\n\t\t\t\tbuffer\n\t\t\t);\n\t\t}\n\t}\n\tfor (i = 0; i < message->n_unknown_fields; i++)\n\t\trv += unknown_field_pack_to_buffer(&message->unknown_fields[i], buffer);", "\treturn rv;\n}", "/**\n * \\defgroup unpack unpacking implementation\n *\n * Routines mainly used by the unpacking functions.\n *\n * \\ingroup internal\n * @{\n */", "static inline int\nint_range_lookup(unsigned n_ranges, const ProtobufCIntRange *ranges, int value)\n{\n\tunsigned n;\n\tunsigned start;", "\tif (n_ranges == 0)\n\t\treturn -1;\n\tstart = 0;\n\tn = n_ranges;\n\twhile (n > 1) {\n\t\tunsigned mid = start + n / 2;", "\t\tif (value < ranges[mid].start_value) {\n\t\t\tn = mid - start;\n\t\t} else if (value >= ranges[mid].start_value +\n\t\t\t (int) (ranges[mid + 1].orig_index -\n\t\t\t\t ranges[mid].orig_index))\n\t\t{\n\t\t\tunsigned new_start = mid + 1;\n\t\t\tn = start + n - new_start;\n\t\t\tstart = new_start;\n\t\t} else\n\t\t\treturn (value - ranges[mid].start_value) +\n\t\t\t ranges[mid].orig_index;\n\t}\n\tif (n > 0) {\n\t\tunsigned start_orig_index = ranges[start].orig_index;\n\t\tunsigned range_size =\n\t\t\tranges[start + 1].orig_index - start_orig_index;", "\t\tif (ranges[start].start_value <= value &&\n\t\t value < (int) (ranges[start].start_value + range_size))\n\t\t{\n\t\t\treturn (value - ranges[start].start_value) +\n\t\t\t start_orig_index;\n\t\t}\n\t}\n\treturn -1;\n}", "static size_t\nparse_tag_and_wiretype(size_t len,\n\t\t const uint8_t *data,\n\t\t uint32_t *tag_out,\n\t\t uint8_t *wiretype_out)\n{\n\tunsigned max_rv = len > 5 ? 5 : len;\n\tuint32_t tag = (data[0] & 0x7f) >> 3;\n\tunsigned shift = 4;\n\tunsigned rv;", "\t/* 0 is not a valid tag value */\n\tif ((data[0] & 0xf8) == 0) {\n\t\treturn 0;\n\t}", "\t*wiretype_out = data[0] & 7;\n\tif ((data[0] & 0x80) == 0) {\n\t\t*tag_out = tag;\n\t\treturn 1;\n\t}\n\tfor (rv = 1; rv < max_rv; rv++) {\n\t\tif (data[rv] & 0x80) {\n\t\t\ttag |= (data[rv] & 0x7f) << shift;\n\t\t\tshift += 7;\n\t\t} else {\n\t\t\ttag |= data[rv] << shift;\n\t\t\t*tag_out = tag;\n\t\t\treturn rv + 1;\n\t\t}\n\t}\n\treturn 0; /* error: bad header */\n}", "/* sizeof(ScannedMember) must be <= (1UL<<BOUND_SIZEOF_SCANNED_MEMBER_LOG2) */\n#define BOUND_SIZEOF_SCANNED_MEMBER_LOG2 5\ntypedef struct ScannedMember ScannedMember;\n/** Field as it's being read. */\nstruct ScannedMember {\n\tuint32_t tag; /**< Field tag. */\n\tuint8_t wire_type; /**< Field type. */\n\tuint8_t length_prefix_len; /**< Prefix length. */\n\tconst ProtobufCFieldDescriptor *field; /**< Field descriptor. */\n\tsize_t len; /**< Field length. */\n\tconst uint8_t *data; /**< Pointer to field data. */\n};", "static inline size_t\nscan_length_prefixed_data(size_t len, const uint8_t *data,\n\t\t\t size_t *prefix_len_out)\n{\n\tunsigned hdr_max = len < 5 ? len : 5;\n\tunsigned hdr_len;\n\tsize_t val = 0;\n\tunsigned i;\n\tunsigned shift = 0;", "\tfor (i = 0; i < hdr_max; i++) {\n\t\tval |= ((size_t)data[i] & 0x7f) << shift;\n\t\tshift += 7;\n\t\tif ((data[i] & 0x80) == 0)\n\t\t\tbreak;\n\t}\n\tif (i == hdr_max) {\n\t\tPROTOBUF_C_UNPACK_ERROR(\"error parsing length for length-prefixed data\");\n\t\treturn 0;\n\t}\n\thdr_len = i + 1;\n\t*prefix_len_out = hdr_len;\n\tif (val > INT_MAX) {\n\t\t// Protobuf messages should always be less than 2 GiB in size.\n\t\t// We also want to return early here so that hdr_len + val does\n\t\t// not overflow on 32-bit systems.\n\t\tPROTOBUF_C_UNPACK_ERROR(\"length prefix of %lu is too large\",\n\t\t\t(unsigned long int)val);\n\t\treturn 0;\n\t}\n\tif (hdr_len + val > len) {\n\t\tPROTOBUF_C_UNPACK_ERROR(\"data too short after length-prefix of %lu\",\n\t\t\t(unsigned long int)val);\n\t\treturn 0;\n\t}\n\treturn hdr_len + val;\n}", "static size_t\nmax_b128_numbers(size_t len, const uint8_t *data)\n{\n\tsize_t rv = 0;\n\twhile (len--)\n\t\tif ((*data++ & 0x80) == 0)\n\t\t\t++rv;\n\treturn rv;\n}", "/**@}*/", "/**\n * Merge earlier message into a latter message.\n *\n * For numeric types and strings, if the same value appears multiple\n * times, the parser accepts the last value it sees. For embedded\n * message fields, the parser merges multiple instances of the same\n * field. That is, all singular scalar fields in the latter instance\n * replace those in the former, singular embedded messages are merged,\n * and repeated fields are concatenated.\n *\n * The earlier message should be freed after calling this function, as\n * some of its fields may have been reused and changed to their default\n * values during the merge.\n */\nstatic protobuf_c_boolean\nmerge_messages(ProtobufCMessage *earlier_msg,\n\t ProtobufCMessage *latter_msg,\n\t ProtobufCAllocator *allocator)\n{\n\tunsigned i;\n\tconst ProtobufCFieldDescriptor *fields =\n\t\tlatter_msg->descriptor->fields;\n\tfor (i = 0; i < latter_msg->descriptor->n_fields; i++) {\n\t\tif (fields[i].label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t *n_earlier =\n\t\t\t\tSTRUCT_MEMBER_PTR(size_t, earlier_msg,\n\t\t\t\t\t\t fields[i].quantifier_offset);\n\t\t\tuint8_t **p_earlier =\n\t\t\t\tSTRUCT_MEMBER_PTR(uint8_t *, earlier_msg,\n\t\t\t\t\t\t fields[i].offset);\n\t\t\tsize_t *n_latter =\n\t\t\t\tSTRUCT_MEMBER_PTR(size_t, latter_msg,\n\t\t\t\t\t\t fields[i].quantifier_offset);\n\t\t\tuint8_t **p_latter =\n\t\t\t\tSTRUCT_MEMBER_PTR(uint8_t *, latter_msg,\n\t\t\t\t\t\t fields[i].offset);", "\t\t\tif (*n_earlier > 0) {\n\t\t\t\tif (*n_latter > 0) {\n\t\t\t\t\t/* Concatenate the repeated field */\n\t\t\t\t\tsize_t el_size =\n\t\t\t\t\t\tsizeof_elt_in_repeated_array(fields[i].type);\n\t\t\t\t\tuint8_t *new_field;", "\t\t\t\t\tnew_field = do_alloc(allocator,\n\t\t\t\t\t\t(*n_earlier + *n_latter) * el_size);\n\t\t\t\t\tif (!new_field)\n\t\t\t\t\t\treturn FALSE;", "\t\t\t\t\tmemcpy(new_field, *p_earlier,\n\t\t\t\t\t *n_earlier * el_size);\n\t\t\t\t\tmemcpy(new_field +\n\t\t\t\t\t *n_earlier * el_size,\n\t\t\t\t\t *p_latter,\n\t\t\t\t\t *n_latter * el_size);", "\t\t\t\t\tdo_free(allocator, *p_latter);\n\t\t\t\t\tdo_free(allocator, *p_earlier);\n\t\t\t\t\t*p_latter = new_field;\n\t\t\t\t\t*n_latter = *n_earlier + *n_latter;\n\t\t\t\t} else {\n\t\t\t\t\t/* Zero copy the repeated field from the earlier message */\n\t\t\t\t\t*n_latter = *n_earlier;\n\t\t\t\t\t*p_latter = *p_earlier;\n\t\t\t\t}\n\t\t\t\t/* Make sure the field does not get double freed */\n\t\t\t\t*n_earlier = 0;\n\t\t\t\t*p_earlier = 0;\n\t\t\t}\n\t\t} else if (fields[i].label == PROTOBUF_C_LABEL_OPTIONAL ||\n\t\t\t fields[i].label == PROTOBUF_C_LABEL_NONE) {\n\t\t\tconst ProtobufCFieldDescriptor *field;\n\t\t\tuint32_t *earlier_case_p = STRUCT_MEMBER_PTR(uint32_t,\n\t\t\t\t\t\t\t\t earlier_msg,\n\t\t\t\t\t\t\t\t fields[i].\n\t\t\t\t\t\t\t\t quantifier_offset);\n\t\t\tuint32_t *latter_case_p = STRUCT_MEMBER_PTR(uint32_t,\n\t\t\t\t\t\t\t\t latter_msg,\n\t\t\t\t\t\t\t\t fields[i].\n\t\t\t\t\t\t\t\t quantifier_offset);\n\t\t\tprotobuf_c_boolean need_to_merge = FALSE;\n\t\t\tvoid *earlier_elem;\n\t\t\tvoid *latter_elem;\n\t\t\tconst void *def_val;", "\t\t\tif (fields[i].flags & PROTOBUF_C_FIELD_FLAG_ONEOF) {\n\t\t\t\tif (*latter_case_p == 0) {\n\t\t\t\t\t/* lookup correct oneof field */\n\t\t\t\t\tint field_index =\n\t\t\t\t\t\tint_range_lookup(\n\t\t\t\t\t\t\tlatter_msg->descriptor\n\t\t\t\t\t\t\t->n_field_ranges,\n\t\t\t\t\t\t\tlatter_msg->descriptor\n\t\t\t\t\t\t\t->field_ranges,\n\t\t\t\t\t\t\t*earlier_case_p);\n\t\t\t\t\tif (field_index < 0)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\tfield = latter_msg->descriptor->fields +\n\t\t\t\t\t\tfield_index;\n\t\t\t\t} else {\n\t\t\t\t\t/* Oneof is present in the latter message, move on */\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfield = &fields[i];\n\t\t\t}", "\t\t\tearlier_elem = STRUCT_MEMBER_P(earlier_msg, field->offset);\n\t\t\tlatter_elem = STRUCT_MEMBER_P(latter_msg, field->offset);\n\t\t\tdef_val = field->default_value;", "\t\t\tswitch (field->type) {\n\t\t\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\t\t\tProtobufCMessage *em = *(ProtobufCMessage **) earlier_elem;\n\t\t\t\tProtobufCMessage *lm = *(ProtobufCMessage **) latter_elem;\n\t\t\t\tif (em != NULL) {\n\t\t\t\t\tif (lm != NULL) {\n\t\t\t\t\t\tif (!merge_messages(em, lm, allocator))\n\t\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\t\t/* Already merged */\n\t\t\t\t\t\tneed_to_merge = FALSE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* Zero copy the message */\n\t\t\t\t\t\tneed_to_merge = TRUE;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\t\t\tuint8_t *e_data =\n\t\t\t\t\t((ProtobufCBinaryData *) earlier_elem)->data;\n\t\t\t\tuint8_t *l_data =\n\t\t\t\t\t((ProtobufCBinaryData *) latter_elem)->data;\n\t\t\t\tconst ProtobufCBinaryData *d_bd =\n\t\t\t\t\t(ProtobufCBinaryData *) def_val;", "\t\t\t\tneed_to_merge =\n\t\t\t\t\t(e_data != NULL &&\n\t\t\t\t\t (d_bd == NULL ||\n\t\t\t\t\t e_data != d_bd->data)) &&\n\t\t\t\t\t(l_data == NULL ||\n\t\t\t\t\t (d_bd != NULL &&\n\t\t\t\t\t l_data == d_bd->data));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase PROTOBUF_C_TYPE_STRING: {\n\t\t\t\tchar *e_str = *(char **) earlier_elem;\n\t\t\t\tchar *l_str = *(char **) latter_elem;\n\t\t\t\tconst char *d_str = def_val;", "\t\t\t\tneed_to_merge = e_str != d_str && l_str == d_str;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t/* Could be has field or case enum, the logic is\n\t\t\t\t * equivalent, since 0 (FALSE) means not set for\n\t\t\t\t * oneof */\n\t\t\t\tneed_to_merge = (*earlier_case_p != 0) &&\n\t\t\t\t\t\t(*latter_case_p == 0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t}", "\t\t\tif (need_to_merge) {\n\t\t\t\tsize_t el_size =\n\t\t\t\t\tsizeof_elt_in_repeated_array(field->type);\n\t\t\t\tmemcpy(latter_elem, earlier_elem, el_size);\n\t\t\t\t/*\n\t\t\t\t * Reset the element from the old message to 0\n\t\t\t\t * to make sure earlier message deallocation\n\t\t\t\t * doesn't corrupt zero-copied data in the new\n\t\t\t\t * message, earlier message will be freed after\n\t\t\t\t * this function is called anyway\n\t\t\t\t */\n\t\t\t\tmemset(earlier_elem, 0, el_size);", "\t\t\t\tif (field->quantifier_offset != 0) {\n\t\t\t\t\t/* Set the has field or the case enum,\n\t\t\t\t\t * if applicable */\n\t\t\t\t\t*latter_case_p = *earlier_case_p;\n\t\t\t\t\t*earlier_case_p = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn TRUE;\n}", "/**\n * Count packed elements.\n *\n * Given a raw slab of packed-repeated values, determine the number of\n * elements. This function detects certain kinds of errors but not\n * others; the remaining error checking is done by\n * parse_packed_repeated_member().\n */\nstatic protobuf_c_boolean\ncount_packed_elements(ProtobufCType type,\n\t\t size_t len, const uint8_t *data, size_t *count_out)\n{\n\tswitch (type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tif (len % 4 != 0) {\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"length must be a multiple of 4 for fixed-length 32-bit types\");\n\t\t\treturn FALSE;\n\t\t}\n\t\t*count_out = len / 4;\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tif (len % 8 != 0) {\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"length must be a multiple of 8 for fixed-length 64-bit types\");\n\t\t\treturn FALSE;\n\t\t}\n\t\t*count_out = len / 8;\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\tcase PROTOBUF_C_TYPE_SINT32:\n\tcase PROTOBUF_C_TYPE_UINT32:\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_SINT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\t*count_out = max_b128_numbers(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\t*count_out = len;\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_STRING:\n\tcase PROTOBUF_C_TYPE_BYTES:\n\tcase PROTOBUF_C_TYPE_MESSAGE:\n\tdefault:\n\t\tPROTOBUF_C_UNPACK_ERROR(\"bad protobuf-c type %u for packed-repeated\", type);\n\t\treturn FALSE;\n\t}\n}", "static inline uint32_t\nparse_uint32(unsigned len, const uint8_t *data)\n{\n\tuint32_t rv = data[0] & 0x7f;\n\tif (len > 1) {\n\t\trv |= ((uint32_t) (data[1] & 0x7f) << 7);\n\t\tif (len > 2) {\n\t\t\trv |= ((uint32_t) (data[2] & 0x7f) << 14);\n\t\t\tif (len > 3) {\n\t\t\t\trv |= ((uint32_t) (data[3] & 0x7f) << 21);\n\t\t\t\tif (len > 4)\n\t\t\t\t\trv |= ((uint32_t) (data[4]) << 28);\n\t\t\t}\n\t\t}\n\t}\n\treturn rv;\n}", "static inline uint32_t\nparse_int32(unsigned len, const uint8_t *data)\n{\n\treturn parse_uint32(len, data);\n}", "static inline int32_t\nunzigzag32(uint32_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn (int32_t)((v >> 1) ^ -(v & 1));\n}", "static inline uint32_t\nparse_fixed_uint32(const uint8_t *data)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tuint32_t t;\n\tmemcpy(&t, data, 4);\n\treturn t;\n#else\n\treturn data[0] |\n\t\t((uint32_t) (data[1]) << 8) |\n\t\t((uint32_t) (data[2]) << 16) |\n\t\t((uint32_t) (data[3]) << 24);\n#endif\n}", "static uint64_t\nparse_uint64(unsigned len, const uint8_t *data)\n{\n\tunsigned shift, i;\n\tuint64_t rv;", "\tif (len < 5)\n\t\treturn parse_uint32(len, data);\n\trv = ((uint64_t) (data[0] & 0x7f)) |\n\t\t((uint64_t) (data[1] & 0x7f) << 7) |\n\t\t((uint64_t) (data[2] & 0x7f) << 14) |\n\t\t((uint64_t) (data[3] & 0x7f) << 21);\n\tshift = 28;\n\tfor (i = 4; i < len; i++) {\n\t\trv |= (((uint64_t) (data[i] & 0x7f)) << shift);\n\t\tshift += 7;\n\t}\n\treturn rv;\n}", "static inline int64_t\nunzigzag64(uint64_t v)\n{\n\t// Note: Using unsigned types prevents undefined behavior\n\treturn (int64_t)((v >> 1) ^ -(v & 1));\n}", "static inline uint64_t\nparse_fixed_uint64(const uint8_t *data)\n{\n#if !defined(WORDS_BIGENDIAN)\n\tuint64_t t;\n\tmemcpy(&t, data, 8);\n\treturn t;\n#else\n\treturn (uint64_t) parse_fixed_uint32(data) |\n\t\t(((uint64_t) parse_fixed_uint32(data + 4)) << 32);\n#endif\n}", "static protobuf_c_boolean\nparse_boolean(unsigned len, const uint8_t *data)\n{\n\tunsigned i;\n\tfor (i = 0; i < len; i++)\n\t\tif (data[i] & 0x7f)\n\t\t\treturn TRUE;\n\treturn FALSE;\n}", "static protobuf_c_boolean\nparse_required_member(ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCAllocator *allocator,\n\t\t protobuf_c_boolean maybe_clear)\n{\n\tunsigned len = scanned_member->len;\n\tconst uint8_t *data = scanned_member->data;\n\tuint8_t wire_type = scanned_member->wire_type;", "\tswitch (scanned_member->field->type) {\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(int32_t *) member = parse_int32(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(uint32_t *) member = parse_uint32(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(int32_t *) member = unzigzag32(parse_uint32(len, data));\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_32BIT)\n\t\t\treturn FALSE;\n\t\t*(uint32_t *) member = parse_fixed_uint32(data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(uint64_t *) member = parse_uint64(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SINT64:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT)\n\t\t\treturn FALSE;\n\t\t*(int64_t *) member = unzigzag64(parse_uint64(len, data));\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_64BIT)\n\t\t\treturn FALSE;\n\t\t*(uint64_t *) member = parse_fixed_uint64(data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\t*(protobuf_c_boolean *) member = parse_boolean(len, data);\n\t\treturn TRUE;\n\tcase PROTOBUF_C_TYPE_STRING: {\n\t\tchar **pstr = member;\n\t\tunsigned pref_len = scanned_member->length_prefix_len;", "\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED)\n\t\t\treturn FALSE;", "\t\tif (maybe_clear && *pstr != NULL) {\n\t\t\tconst char *def = scanned_member->field->default_value;\n\t\t\tif (*pstr != NULL && *pstr != def)\n\t\t\t\tdo_free(allocator, *pstr);\n\t\t}\n\t\t*pstr = do_alloc(allocator, len - pref_len + 1);\n\t\tif (*pstr == NULL)\n\t\t\treturn FALSE;\n\t\tmemcpy(*pstr, data + pref_len, len - pref_len);\n\t\t(*pstr)[len - pref_len] = 0;\n\t\treturn TRUE;\n\t}\n\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\tProtobufCBinaryData *bd = member;\n\t\tconst ProtobufCBinaryData *def_bd;\n\t\tunsigned pref_len = scanned_member->length_prefix_len;", "\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED)\n\t\t\treturn FALSE;", "\t\tdef_bd = scanned_member->field->default_value;\n\t\tif (maybe_clear &&\n\t\t bd->data != NULL &&\n\t\t (def_bd == NULL || bd->data != def_bd->data))\n\t\t{\n\t\t\tdo_free(allocator, bd->data);\n\t\t}\n\t\tif (len > pref_len) {\n\t\t\tbd->data = do_alloc(allocator, len - pref_len);\n\t\t\tif (bd->data == NULL)\n\t\t\t\treturn FALSE;\n\t\t\tmemcpy(bd->data, data + pref_len, len - pref_len);\n\t\t} else {\n\t\t\tbd->data = NULL;\n\t\t}\n\t\tbd->len = len - pref_len;\n\t\treturn TRUE;\n\t}\n\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\tProtobufCMessage **pmessage = member;\n\t\tProtobufCMessage *subm;\n\t\tconst ProtobufCMessage *def_mess;\n\t\tprotobuf_c_boolean merge_successful = TRUE;\n\t\tunsigned pref_len = scanned_member->length_prefix_len;", "\t\tif (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED)\n\t\t\treturn FALSE;", "\t\tdef_mess = scanned_member->field->default_value;", "\t\tif (len >= pref_len)\n\t\t\tsubm = protobuf_c_message_unpack(scanned_member->field->descriptor,\n\t\t\t\t\t\t\t allocator,\n\t\t\t\t\t\t\t len - pref_len,\n\t\t\t\t\t\t\t data + pref_len);\n\t\telse\n\t\t\tsubm = NULL;", "\n\t\tif (maybe_clear &&\n\t\t *pmessage != NULL &&\n\t\t *pmessage != def_mess)\n\t\t{\n\t\t\tif (subm != NULL)\n\t\t\t\tmerge_successful = merge_messages(*pmessage, subm, allocator);\n\t\t\t/* Delete the previous message */\n\t\t\tprotobuf_c_message_free_unpacked(*pmessage, allocator);\n\t\t}\n\t\t*pmessage = subm;\n\t\tif (subm == NULL || !merge_successful)\n\t\t\treturn FALSE;\n\t\treturn TRUE;\n\t}\n\t}\n\treturn FALSE;\n}", "static protobuf_c_boolean\nparse_oneof_member (ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCMessage *message,\n\t\t ProtobufCAllocator *allocator)\n{\n\tuint32_t *oneof_case = STRUCT_MEMBER_PTR(uint32_t, message,\n\t\t\t\t\t scanned_member->field->quantifier_offset);", "\t/* If we have already parsed a member of this oneof, free it. */\n\tif (*oneof_case != 0) {\n\t\tconst ProtobufCFieldDescriptor *old_field;\n\t\tsize_t el_size;\n\t\t/* lookup field */\n\t\tint field_index =\n\t\t\tint_range_lookup(message->descriptor->n_field_ranges,\n\t\t\t\t\t message->descriptor->field_ranges,\n\t\t\t\t\t *oneof_case);\n\t\tif (field_index < 0)\n\t\t\treturn FALSE;\n\t\told_field = message->descriptor->fields + field_index;\n\t\tel_size = sizeof_elt_in_repeated_array(old_field->type);", "\t\tswitch (old_field->type) {\n\t case PROTOBUF_C_TYPE_STRING: {\n\t\t\tchar **pstr = member;\n\t\t\tconst char *def = old_field->default_value;\n\t\t\tif (*pstr != NULL && *pstr != def)\n\t\t\t\tdo_free(allocator, *pstr);\n\t\t\tbreak;\n\t }\n\t\tcase PROTOBUF_C_TYPE_BYTES: {\n\t\t\tProtobufCBinaryData *bd = member;\n\t\t\tconst ProtobufCBinaryData *def_bd = old_field->default_value;\n\t\t\tif (bd->data != NULL &&\n\t\t\t (def_bd == NULL || bd->data != def_bd->data))\n\t\t\t{\n\t\t\t\tdo_free(allocator, bd->data);\n\t\t\t}\n\t\t\tbreak;\n\t }\n\t\tcase PROTOBUF_C_TYPE_MESSAGE: {\n\t\t\tProtobufCMessage **pmessage = member;\n\t\t\tconst ProtobufCMessage *def_mess = old_field->default_value;\n\t\t\tif (*pmessage != NULL && *pmessage != def_mess)\n\t\t\t\tprotobuf_c_message_free_unpacked(*pmessage, allocator);\n\t\t\tbreak;\n\t }\n\t\tdefault:\n\t\t\tbreak;\n\t\t}", "\t\tmemset (member, 0, el_size);\n\t}\n\tif (!parse_required_member (scanned_member, member, allocator, TRUE))\n\t\treturn FALSE;", "\t*oneof_case = scanned_member->tag;\n\treturn TRUE;\n}", "\nstatic protobuf_c_boolean\nparse_optional_member(ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCMessage *message,\n\t\t ProtobufCAllocator *allocator)\n{\n\tif (!parse_required_member(scanned_member, member, allocator, TRUE))\n\t\treturn FALSE;\n\tif (scanned_member->field->quantifier_offset != 0)\n\t\tSTRUCT_MEMBER(protobuf_c_boolean,\n\t\t\t message,\n\t\t\t scanned_member->field->quantifier_offset) = TRUE;\n\treturn TRUE;\n}", "static protobuf_c_boolean\nparse_repeated_member(ScannedMember *scanned_member,\n\t\t void *member,\n\t\t ProtobufCMessage *message,\n\t\t ProtobufCAllocator *allocator)\n{\n\tconst ProtobufCFieldDescriptor *field = scanned_member->field;\n\tsize_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);\n\tsize_t siz = sizeof_elt_in_repeated_array(field->type);\n\tchar *array = *(char **) member;", "\tif (!parse_required_member(scanned_member, array + siz * (*p_n),\n\t\t\t\t allocator, FALSE))\n\t{\n\t\treturn FALSE;\n\t}\n\t*p_n += 1;\n\treturn TRUE;\n}", "static unsigned\nscan_varint(unsigned len, const uint8_t *data)\n{\n\tunsigned i;\n\tif (len > 10)\n\t\tlen = 10;\n\tfor (i = 0; i < len; i++)\n\t\tif ((data[i] & 0x80) == 0)\n\t\t\tbreak;\n\tif (i == len)\n\t\treturn 0;\n\treturn i + 1;\n}", "static protobuf_c_boolean\nparse_packed_repeated_member(ScannedMember *scanned_member,\n\t\t\t void *member,\n\t\t\t ProtobufCMessage *message)\n{\n\tconst ProtobufCFieldDescriptor *field = scanned_member->field;\n\tsize_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);\n\tsize_t siz = sizeof_elt_in_repeated_array(field->type);\n\tvoid *array = *(char **) member + siz * (*p_n);\n\tconst uint8_t *at = scanned_member->data + scanned_member->length_prefix_len;\n\tsize_t rem = scanned_member->len - scanned_member->length_prefix_len;\n\tsize_t count = 0;\n#if defined(WORDS_BIGENDIAN)\n\tunsigned i;\n#endif", "\tswitch (field->type) {\n\tcase PROTOBUF_C_TYPE_SFIXED32:\n\tcase PROTOBUF_C_TYPE_FIXED32:\n\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\tcount = (scanned_member->len - scanned_member->length_prefix_len) / 4;\n#if !defined(WORDS_BIGENDIAN)\n\t\tgoto no_unpacking_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\t((uint32_t *) array)[i] = parse_fixed_uint32(at);\n\t\t\tat += 4;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_SFIXED64:\n\tcase PROTOBUF_C_TYPE_FIXED64:\n\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\tcount = (scanned_member->len - scanned_member->length_prefix_len) / 8;\n#if !defined(WORDS_BIGENDIAN)\n\t\tgoto no_unpacking_needed;\n#else\n\t\tfor (i = 0; i < count; i++) {\n\t\t\t((uint64_t *) array)[i] = parse_fixed_uint64(at);\n\t\t\tat += 8;\n\t\t}\n\t\tbreak;\n#endif\n\tcase PROTOBUF_C_TYPE_ENUM:\n\tcase PROTOBUF_C_TYPE_INT32:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated int32 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int32_t *) array)[count++] = parse_int32(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_SINT32:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated sint32 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int32_t *) array)[count++] = unzigzag32(parse_uint32(s, at));\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_UINT32:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated enum or uint32 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((uint32_t *) array)[count++] = parse_uint32(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;", "\tcase PROTOBUF_C_TYPE_SINT64:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated sint64 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int64_t *) array)[count++] = unzigzag64(parse_uint64(s, at));\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_INT64:\n\tcase PROTOBUF_C_TYPE_UINT64:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated int64/uint64 value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((int64_t *) array)[count++] = parse_uint64(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tcase PROTOBUF_C_TYPE_BOOL:\n\t\twhile (rem > 0) {\n\t\t\tunsigned s = scan_varint(rem, at);\n\t\t\tif (s == 0) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"bad packed-repeated boolean value\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\t((protobuf_c_boolean *) array)[count++] = parse_boolean(s, at);\n\t\t\tat += s;\n\t\t\trem -= s;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\t}\n\t*p_n += count;\n\treturn TRUE;", "#if !defined(WORDS_BIGENDIAN)\nno_unpacking_needed:\n\tmemcpy(array, at, count * siz);\n\t*p_n += count;\n\treturn TRUE;\n#endif\n}", "static protobuf_c_boolean\nis_packable_type(ProtobufCType type)\n{\n\treturn\n\t\ttype != PROTOBUF_C_TYPE_STRING &&\n\t\ttype != PROTOBUF_C_TYPE_BYTES &&\n\t\ttype != PROTOBUF_C_TYPE_MESSAGE;\n}", "static protobuf_c_boolean\nparse_member(ScannedMember *scanned_member,\n\t ProtobufCMessage *message,\n\t ProtobufCAllocator *allocator)\n{\n\tconst ProtobufCFieldDescriptor *field = scanned_member->field;\n\tvoid *member;", "\tif (field == NULL) {\n\t\tProtobufCMessageUnknownField *ufield =\n\t\t\tmessage->unknown_fields +\n\t\t\t(message->n_unknown_fields++);\n\t\tufield->tag = scanned_member->tag;\n\t\tufield->wire_type = scanned_member->wire_type;\n\t\tufield->len = scanned_member->len;\n\t\tufield->data = do_alloc(allocator, scanned_member->len);\n\t\tif (ufield->data == NULL)\n\t\t\treturn FALSE;\n\t\tmemcpy(ufield->data, scanned_member->data, ufield->len);\n\t\treturn TRUE;\n\t}\n\tmember = (char *) message + field->offset;\n\tswitch (field->label) {\n\tcase PROTOBUF_C_LABEL_REQUIRED:\n\t\treturn parse_required_member(scanned_member, member,\n\t\t\t\t\t allocator, TRUE);\n\tcase PROTOBUF_C_LABEL_OPTIONAL:\n\tcase PROTOBUF_C_LABEL_NONE:\n\t\tif (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF)) {\n\t\t\treturn parse_oneof_member(scanned_member, member,\n\t\t\t\t\t\t message, allocator);\n\t\t} else {\n\t\t\treturn parse_optional_member(scanned_member, member,\n\t\t\t\t\t\t message, allocator);\n\t\t}\n\tcase PROTOBUF_C_LABEL_REPEATED:\n\t\tif (scanned_member->wire_type ==\n\t\t PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&\n\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||\n\t\t is_packable_type(field->type)))\n\t\t{\n\t\t\treturn parse_packed_repeated_member(scanned_member,\n\t\t\t\t\t\t\t member, message);\n\t\t} else {\n\t\t\treturn parse_repeated_member(scanned_member,\n\t\t\t\t\t\t member, message,\n\t\t\t\t\t\t allocator);\n\t\t}\n\t}\n\tPROTOBUF_C__ASSERT_NOT_REACHED();\n\treturn 0;\n}", "/**\n * Initialise messages generated by old code.\n *\n * This function is used if desc->message_init == NULL (which occurs\n * for old code, and which would be useful to support allocating\n * descriptors dynamically).\n */\nstatic void\nmessage_init_generic(const ProtobufCMessageDescriptor *desc,\n\t\t ProtobufCMessage *message)\n{\n\tunsigned i;", "\tmemset(message, 0, desc->sizeof_message);\n\tmessage->descriptor = desc;\n\tfor (i = 0; i < desc->n_fields; i++) {\n\t\tif (desc->fields[i].default_value != NULL &&\n\t\t desc->fields[i].label != PROTOBUF_C_LABEL_REPEATED)\n\t\t{\n\t\t\tvoid *field =\n\t\t\t\tSTRUCT_MEMBER_P(message, desc->fields[i].offset);\n\t\t\tconst void *dv = desc->fields[i].default_value;", "\t\t\tswitch (desc->fields[i].type) {\n\t\t\tcase PROTOBUF_C_TYPE_INT32:\n\t\t\tcase PROTOBUF_C_TYPE_SINT32:\n\t\t\tcase PROTOBUF_C_TYPE_SFIXED32:\n\t\t\tcase PROTOBUF_C_TYPE_UINT32:\n\t\t\tcase PROTOBUF_C_TYPE_FIXED32:\n\t\t\tcase PROTOBUF_C_TYPE_FLOAT:\n\t\t\tcase PROTOBUF_C_TYPE_ENUM:\n\t\t\t\tmemcpy(field, dv, 4);\n\t\t\t\tbreak;\n\t\t\tcase PROTOBUF_C_TYPE_INT64:\n\t\t\tcase PROTOBUF_C_TYPE_SINT64:\n\t\t\tcase PROTOBUF_C_TYPE_SFIXED64:\n\t\t\tcase PROTOBUF_C_TYPE_UINT64:\n\t\t\tcase PROTOBUF_C_TYPE_FIXED64:\n\t\t\tcase PROTOBUF_C_TYPE_DOUBLE:\n\t\t\t\tmemcpy(field, dv, 8);\n\t\t\t\tbreak;\n\t\t\tcase PROTOBUF_C_TYPE_BOOL:\n\t\t\t\tmemcpy(field, dv, sizeof(protobuf_c_boolean));\n\t\t\t\tbreak;\n\t\t\tcase PROTOBUF_C_TYPE_BYTES:\n\t\t\t\tmemcpy(field, dv, sizeof(ProtobufCBinaryData));\n\t\t\t\tbreak;", "\t\t\tcase PROTOBUF_C_TYPE_STRING:\n\t\t\tcase PROTOBUF_C_TYPE_MESSAGE:\n\t\t\t\t/*\n\t\t\t\t * The next line essentially implements a cast\n\t\t\t\t * from const, which is totally unavoidable.\n\t\t\t\t */\n\t\t\t\t*(const void **) field = dv;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}", "/**@}*/", "/*\n * ScannedMember slabs (an unpacking implementation detail). Before doing real\n * unpacking, we first scan through the elements to see how many there are (for\n * repeated fields), and which field to use (for non-repeated fields given\n * twice).\n *\n * In order to avoid allocations for small messages, we keep a stack-allocated\n * slab of ScannedMembers of size FIRST_SCANNED_MEMBER_SLAB_SIZE (16). After we\n * fill that up, we allocate each slab twice as large as the previous one.\n */\n#define FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2 4", "/*\n * The number of slabs, including the stack-allocated ones; choose the number so\n * that we would overflow if we needed a slab larger than provided.\n */\n#define MAX_SCANNED_MEMBER_SLAB\t\t\t\\\n (sizeof(unsigned int)*8 - 1\t\t\t\\\n - BOUND_SIZEOF_SCANNED_MEMBER_LOG2\t\t\\\n - FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2)", "#define REQUIRED_FIELD_BITMAP_SET(index)\t\\\n\t(required_fields_bitmap[(index)/8] |= (1UL<<((index)%8)))", "#define REQUIRED_FIELD_BITMAP_IS_SET(index)\t\\\n\t(required_fields_bitmap[(index)/8] & (1UL<<((index)%8)))", "ProtobufCMessage *\nprotobuf_c_message_unpack(const ProtobufCMessageDescriptor *desc,\n\t\t\t ProtobufCAllocator *allocator,\n\t\t\t size_t len, const uint8_t *data)\n{\n\tProtobufCMessage *rv;\n\tsize_t rem = len;\n\tconst uint8_t *at = data;\n\tconst ProtobufCFieldDescriptor *last_field = desc->fields + 0;\n\tScannedMember first_member_slab[1UL <<\n\t\t\t\t\tFIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2];", "\t/*\n\t * scanned_member_slabs[i] is an array of arrays of ScannedMember.\n\t * The first slab (scanned_member_slabs[0] is just a pointer to\n\t * first_member_slab), above. All subsequent slabs will be allocated\n\t * using the allocator.\n\t */\n\tScannedMember *scanned_member_slabs[MAX_SCANNED_MEMBER_SLAB + 1];\n\tunsigned which_slab = 0; /* the slab we are currently populating */\n\tunsigned in_slab_index = 0; /* number of members in the slab */\n\tsize_t n_unknown = 0;\n\tunsigned f;\n\tunsigned j;\n\tunsigned i_slab;\n\tunsigned last_field_index = 0;\n\tunsigned required_fields_bitmap_len;\n\tunsigned char required_fields_bitmap_stack[16];\n\tunsigned char *required_fields_bitmap = required_fields_bitmap_stack;\n\tprotobuf_c_boolean required_fields_bitmap_alloced = FALSE;", "\tASSERT_IS_MESSAGE_DESCRIPTOR(desc);", "\tif (allocator == NULL)\n\t\tallocator = &protobuf_c__allocator;", "\trv = do_alloc(allocator, desc->sizeof_message);\n\tif (!rv)\n\t\treturn (NULL);\n\tscanned_member_slabs[0] = first_member_slab;", "\trequired_fields_bitmap_len = (desc->n_fields + 7) / 8;\n\tif (required_fields_bitmap_len > sizeof(required_fields_bitmap_stack)) {\n\t\trequired_fields_bitmap = do_alloc(allocator, required_fields_bitmap_len);\n\t\tif (!required_fields_bitmap) {\n\t\t\tdo_free(allocator, rv);\n\t\t\treturn (NULL);\n\t\t}\n\t\trequired_fields_bitmap_alloced = TRUE;\n\t}\n\tmemset(required_fields_bitmap, 0, required_fields_bitmap_len);", "\t/*\n\t * Generated code always defines \"message_init\". However, we provide a\n\t * fallback for (1) users of old protobuf-c generated-code that do not\n\t * provide the function, and (2) descriptors constructed from some other\n\t * source (most likely, direct construction from the .proto file).\n\t */\n\tif (desc->message_init != NULL)\n\t\tprotobuf_c_message_init(desc, rv);\n\telse\n\t\tmessage_init_generic(desc, rv);", "\twhile (rem > 0) {\n\t\tuint32_t tag;\n\t\tuint8_t wire_type;\n\t\tsize_t used = parse_tag_and_wiretype(rem, at, &tag, &wire_type);\n\t\tconst ProtobufCFieldDescriptor *field;\n\t\tScannedMember tmp;", "\t\tif (used == 0) {\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"error parsing tag/wiretype at offset %u\",\n\t\t\t\t\t\t(unsigned) (at - data));\n\t\t\tgoto error_cleanup_during_scan;\n\t\t}\n\t\t/*\n\t\t * \\todo Consider optimizing for field[1].id == tag, if field[1]\n\t\t * exists!\n\t\t */\n\t\tif (last_field == NULL || last_field->id != tag) {\n\t\t\t/* lookup field */\n\t\t\tint field_index =\n\t\t\t int_range_lookup(desc->n_field_ranges,\n\t\t\t\t\t desc->field_ranges,\n\t\t\t\t\t tag);\n\t\t\tif (field_index < 0) {\n\t\t\t\tfield = NULL;\n\t\t\t\tn_unknown++;\n\t\t\t} else {\n\t\t\t\tfield = desc->fields + field_index;\n\t\t\t\tlast_field = field;\n\t\t\t\tlast_field_index = field_index;\n\t\t\t}\n\t\t} else {\n\t\t\tfield = last_field;\n\t\t}", "\t\tif (field != NULL && field->label == PROTOBUF_C_LABEL_REQUIRED)\n\t\t\tREQUIRED_FIELD_BITMAP_SET(last_field_index);", "\t\tat += used;\n\t\trem -= used;\n\t\ttmp.tag = tag;\n\t\ttmp.wire_type = wire_type;\n\t\ttmp.field = field;\n\t\ttmp.data = at;\n\t\ttmp.length_prefix_len = 0;", "\t\tswitch (wire_type) {\n\t\tcase PROTOBUF_C_WIRE_TYPE_VARINT: {\n\t\t\tunsigned max_len = rem < 10 ? rem : 10;\n\t\t\tunsigned i;", "\t\t\tfor (i = 0; i < max_len; i++)\n\t\t\t\tif ((at[i] & 0x80) == 0)\n\t\t\t\t\tbreak;\n\t\t\tif (i == max_len) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"unterminated varint at offset %u\",\n\t\t\t\t\t\t\t(unsigned) (at - data));\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.len = i + 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_WIRE_TYPE_64BIT:\n\t\t\tif (rem < 8) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"too short after 64bit wiretype at offset %u\",\n\t\t\t\t\t\t\t(unsigned) (at - data));\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.len = 8;\n\t\t\tbreak;\n\t\tcase PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED: {\n\t\t\tsize_t pref_len;", "\t\t\ttmp.len = scan_length_prefixed_data(rem, at, &pref_len);\n\t\t\tif (tmp.len == 0) {\n\t\t\t\t/* NOTE: scan_length_prefixed_data calls UNPACK_ERROR */\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.length_prefix_len = pref_len;\n\t\t\tbreak;\n\t\t}\n\t\tcase PROTOBUF_C_WIRE_TYPE_32BIT:\n\t\t\tif (rem < 4) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"too short after 32bit wiretype at offset %u\",\n\t\t\t\t\t (unsigned) (at - data));\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\ttmp.len = 4;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tPROTOBUF_C_UNPACK_ERROR(\"unsupported tag %u at offset %u\",\n\t\t\t\t\t\twire_type, (unsigned) (at - data));\n\t\t\tgoto error_cleanup_during_scan;\n\t\t}", "\t\tif (in_slab_index == (1UL <<\n\t\t\t(which_slab + FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2)))\n\t\t{\n\t\t\tsize_t size;", "\t\t\tin_slab_index = 0;\n\t\t\tif (which_slab == MAX_SCANNED_MEMBER_SLAB) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"too many fields\");\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t}\n\t\t\twhich_slab++;\n\t\t\tsize = sizeof(ScannedMember)\n\t\t\t\t<< (which_slab + FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2);\n\t\t\tscanned_member_slabs[which_slab] = do_alloc(allocator, size);\n\t\t\tif (scanned_member_slabs[which_slab] == NULL)\n\t\t\t\tgoto error_cleanup_during_scan;\n\t\t}\n\t\tscanned_member_slabs[which_slab][in_slab_index++] = tmp;", "\t\tif (field != NULL && field->label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t *n = STRUCT_MEMBER_PTR(size_t, rv,\n\t\t\t\t\t\t field->quantifier_offset);\n\t\t\tif (wire_type == PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&\n\t\t\t (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||\n\t\t\t is_packable_type(field->type)))\n\t\t\t{\n\t\t\t\tsize_t count;\n\t\t\t\tif (!count_packed_elements(field->type,\n\t\t\t\t\t\t\t tmp.len -\n\t\t\t\t\t\t\t tmp.length_prefix_len,\n\t\t\t\t\t\t\t tmp.data +\n\t\t\t\t\t\t\t tmp.length_prefix_len,\n\t\t\t\t\t\t\t &count))\n\t\t\t\t{\n\t\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"counting packed elements\");\n\t\t\t\t\tgoto error_cleanup_during_scan;\n\t\t\t\t}\n\t\t\t\t*n += count;\n\t\t\t} else {\n\t\t\t\t*n += 1;\n\t\t\t}\n\t\t}", "\t\tat += tmp.len;\n\t\trem -= tmp.len;\n\t}", "\t/* allocate space for repeated fields, also check that all required fields have been set */\n\tfor (f = 0; f < desc->n_fields; f++) {\n\t\tconst ProtobufCFieldDescriptor *field = desc->fields + f;\n\t\tif (field->label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t siz =\n\t\t\t sizeof_elt_in_repeated_array(field->type);\n\t\t\tsize_t *n_ptr =\n\t\t\t STRUCT_MEMBER_PTR(size_t, rv,\n\t\t\t\t\t field->quantifier_offset);\n\t\t\tif (*n_ptr != 0) {\n\t\t\t\tunsigned n = *n_ptr;\n\t\t\t\tvoid *a;\n\t\t\t\t*n_ptr = 0;\n\t\t\t\tassert(rv->descriptor != NULL);\n#define CLEAR_REMAINING_N_PTRS() \\\n for(f++;f < desc->n_fields; f++) \\\n { \\\n field = desc->fields + f; \\\n if (field->label == PROTOBUF_C_LABEL_REPEATED) \\\n STRUCT_MEMBER (size_t, rv, field->quantifier_offset) = 0; \\\n }\n\t\t\t\ta = do_alloc(allocator, siz * n);\n\t\t\t\tif (!a) {\n\t\t\t\t\tCLEAR_REMAINING_N_PTRS();\n\t\t\t\t\tgoto error_cleanup;\n\t\t\t\t}\n\t\t\t\tSTRUCT_MEMBER(void *, rv, field->offset) = a;\n\t\t\t}\n\t\t} else if (field->label == PROTOBUF_C_LABEL_REQUIRED) {\n\t\t\tif (field->default_value == NULL &&\n\t\t\t !REQUIRED_FIELD_BITMAP_IS_SET(f))\n\t\t\t{\n\t\t\t\tCLEAR_REMAINING_N_PTRS();\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"message '%s': missing required field '%s'\",\n\t\t\t\t\t\t\tdesc->name, field->name);\n\t\t\t\tgoto error_cleanup;\n\t\t\t}\n\t\t}\n\t}\n#undef CLEAR_REMAINING_N_PTRS", "\t/* allocate space for unknown fields */\n\tif (n_unknown) {\n\t\trv->unknown_fields = do_alloc(allocator,\n\t\t\t\t\t n_unknown * sizeof(ProtobufCMessageUnknownField));\n\t\tif (rv->unknown_fields == NULL)\n\t\t\tgoto error_cleanup;\n\t}", "\t/* do real parsing */\n\tfor (i_slab = 0; i_slab <= which_slab; i_slab++) {\n\t\tunsigned max = (i_slab == which_slab) ?\n\t\t\tin_slab_index : (1UL << (i_slab + 4));\n\t\tScannedMember *slab = scanned_member_slabs[i_slab];", "\t\tfor (j = 0; j < max; j++) {\n\t\t\tif (!parse_member(slab + j, rv, allocator)) {\n\t\t\t\tPROTOBUF_C_UNPACK_ERROR(\"error parsing member %s of %s\",\n\t\t\t\t\t\t\tslab->field ? slab->field->name : \"*unknown-field*\",\n\t\t\t\t\tdesc->name);\n\t\t\t\tgoto error_cleanup;\n\t\t\t}\n\t\t}\n\t}", "\t/* cleanup */\n\tfor (j = 1; j <= which_slab; j++)\n\t\tdo_free(allocator, scanned_member_slabs[j]);\n\tif (required_fields_bitmap_alloced)\n\t\tdo_free(allocator, required_fields_bitmap);\n\treturn rv;", "error_cleanup:\n\tprotobuf_c_message_free_unpacked(rv, allocator);\n\tfor (j = 1; j <= which_slab; j++)\n\t\tdo_free(allocator, scanned_member_slabs[j]);\n\tif (required_fields_bitmap_alloced)\n\t\tdo_free(allocator, required_fields_bitmap);\n\treturn NULL;", "error_cleanup_during_scan:\n\tdo_free(allocator, rv);\n\tfor (j = 1; j <= which_slab; j++)\n\t\tdo_free(allocator, scanned_member_slabs[j]);\n\tif (required_fields_bitmap_alloced)\n\t\tdo_free(allocator, required_fields_bitmap);\n\treturn NULL;\n}", "void\nprotobuf_c_message_free_unpacked(ProtobufCMessage *message,\n\t\t\t\t ProtobufCAllocator *allocator)\n{\n\tconst ProtobufCMessageDescriptor *desc;\n\tunsigned f;", "\tif (message == NULL)\n\t\treturn;", "\tdesc = message->descriptor;", "\tASSERT_IS_MESSAGE(message);", "\tif (allocator == NULL)\n\t\tallocator = &protobuf_c__allocator;\n\tmessage->descriptor = NULL;\n\tfor (f = 0; f < desc->n_fields; f++) {\n\t\tif (0 != (desc->fields[f].flags & PROTOBUF_C_FIELD_FLAG_ONEOF) &&\n\t\t desc->fields[f].id !=\n\t\t STRUCT_MEMBER(uint32_t, message, desc->fields[f].quantifier_offset))\n\t\t{\n\t\t\t/* This is not the selected oneof, skip it */\n\t\t\tcontinue;\n\t\t}", "\t\tif (desc->fields[f].label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t n = STRUCT_MEMBER(size_t,\n\t\t\t\t\t\t message,\n\t\t\t\t\t\t desc->fields[f].quantifier_offset);\n\t\t\tvoid *arr = STRUCT_MEMBER(void *,\n\t\t\t\t\t\t message,\n\t\t\t\t\t\t desc->fields[f].offset);", "\t\t\tif (arr != NULL) {\n\t\t\t\tif (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {\n\t\t\t\t\tunsigned i;\n\t\t\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\t\t\tdo_free(allocator, ((char **) arr)[i]);\n\t\t\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\t\t\tunsigned i;\n\t\t\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\t\t\tdo_free(allocator, ((ProtobufCBinaryData *) arr)[i].data);\n\t\t\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\t\t\tunsigned i;\n\t\t\t\t\tfor (i = 0; i < n; i++)\n\t\t\t\t\t\tprotobuf_c_message_free_unpacked(\n\t\t\t\t\t\t\t((ProtobufCMessage **) arr)[i],\n\t\t\t\t\t\t\tallocator\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tdo_free(allocator, arr);\n\t\t\t}\n\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {\n\t\t\tchar *str = STRUCT_MEMBER(char *, message,\n\t\t\t\t\t\t desc->fields[f].offset);", "\t\t\tif (str && str != desc->fields[f].default_value)\n\t\t\t\tdo_free(allocator, str);\n\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\tvoid *data = STRUCT_MEMBER(ProtobufCBinaryData, message,\n\t\t\t\t\t\t desc->fields[f].offset).data;\n\t\t\tconst ProtobufCBinaryData *default_bd;", "\t\t\tdefault_bd = desc->fields[f].default_value;\n\t\t\tif (data != NULL &&\n\t\t\t (default_bd == NULL ||\n\t\t\t default_bd->data != data))\n\t\t\t{\n\t\t\t\tdo_free(allocator, data);\n\t\t\t}\n\t\t} else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\tProtobufCMessage *sm;", "\t\t\tsm = STRUCT_MEMBER(ProtobufCMessage *, message,\n\t\t\t\t\t desc->fields[f].offset);\n\t\t\tif (sm && sm != desc->fields[f].default_value)\n\t\t\t\tprotobuf_c_message_free_unpacked(sm, allocator);\n\t\t}\n\t}", "\tfor (f = 0; f < message->n_unknown_fields; f++)\n\t\tdo_free(allocator, message->unknown_fields[f].data);\n\tif (message->unknown_fields != NULL)\n\t\tdo_free(allocator, message->unknown_fields);", "\tdo_free(allocator, message);\n}", "void\nprotobuf_c_message_init(const ProtobufCMessageDescriptor * descriptor,\n\t\t\tvoid *message)\n{\n\tdescriptor->message_init((ProtobufCMessage *) (message));\n}", "protobuf_c_boolean\nprotobuf_c_message_check(const ProtobufCMessage *message)\n{\n\tunsigned i;", "\tif (!message ||\n\t !message->descriptor ||\n\t message->descriptor->magic != PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC)\n\t{\n\t\treturn FALSE;\n\t}", "\tfor (i = 0; i < message->descriptor->n_fields; i++) {\n\t\tconst ProtobufCFieldDescriptor *f = message->descriptor->fields + i;\n\t\tProtobufCType type = f->type;\n\t\tProtobufCLabel label = f->label;\n\t\tvoid *field = STRUCT_MEMBER_P (message, f->offset);", "\t\tif (f->flags & PROTOBUF_C_FIELD_FLAG_ONEOF) {\n\t\t\tconst uint32_t *oneof_case = STRUCT_MEMBER_P (message, f->quantifier_offset);\n\t\t\tif (f->id != *oneof_case) {\n\t\t\t\tcontinue; //Do not check if it is an unpopulated oneof member.\n\t\t\t}\n\t\t}", "\t\tif (label == PROTOBUF_C_LABEL_REPEATED) {\n\t\t\tsize_t *quantity = STRUCT_MEMBER_P (message, f->quantifier_offset);", "\t\t\tif (*quantity > 0 && *(void **) field == NULL) {\n\t\t\t\treturn FALSE;\n\t\t\t}", "\t\t\tif (type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\t\tProtobufCMessage **submessage = *(ProtobufCMessage ***) field;\n\t\t\t\tunsigned j;\n\t\t\t\tfor (j = 0; j < *quantity; j++) {\n\t\t\t\t\tif (!protobuf_c_message_check(submessage[j]))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t} else if (type == PROTOBUF_C_TYPE_STRING) {\n\t\t\t\tchar **string = *(char ***) field;\n\t\t\t\tunsigned j;\n\t\t\t\tfor (j = 0; j < *quantity; j++) {\n\t\t\t\t\tif (!string[j])\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t} else if (type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\t\tProtobufCBinaryData *bd = *(ProtobufCBinaryData **) field;\n\t\t\t\tunsigned j;\n\t\t\t\tfor (j = 0; j < *quantity; j++) {\n\t\t\t\t\tif (bd[j].len > 0 && bd[j].data == NULL)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}", "\t\t} else { /* PROTOBUF_C_LABEL_REQUIRED or PROTOBUF_C_LABEL_OPTIONAL */", "\t\t\tif (type == PROTOBUF_C_TYPE_MESSAGE) {\n\t\t\t\tProtobufCMessage *submessage = *(ProtobufCMessage **) field;\n\t\t\t\tif (label == PROTOBUF_C_LABEL_REQUIRED || submessage != NULL) {\n\t\t\t\t\tif (!protobuf_c_message_check(submessage))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t} else if (type == PROTOBUF_C_TYPE_STRING) {\n\t\t\t\tchar *string = *(char **) field;\n\t\t\t\tif (label == PROTOBUF_C_LABEL_REQUIRED && string == NULL)\n\t\t\t\t\treturn FALSE;\n\t\t\t} else if (type == PROTOBUF_C_TYPE_BYTES) {\n\t\t\t\tprotobuf_c_boolean *has = STRUCT_MEMBER_P (message, f->quantifier_offset);\n\t\t\t\tProtobufCBinaryData *bd = field;\n\t\t\t\tif (label == PROTOBUF_C_LABEL_REQUIRED || *has == TRUE) {\n\t\t\t\t\tif (bd->len > 0 && bd->data == NULL)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\treturn TRUE;\n}", "/* === services === */", "typedef void (*GenericHandler) (void *service,\n\t\t\t\tconst ProtobufCMessage *input,\n\t\t\t\tProtobufCClosure closure,\n\t\t\t\tvoid *closure_data);\nvoid\nprotobuf_c_service_invoke_internal(ProtobufCService *service,\n\t\t\t\t unsigned method_index,\n\t\t\t\t const ProtobufCMessage *input,\n\t\t\t\t ProtobufCClosure closure,\n\t\t\t\t void *closure_data)\n{\n\tGenericHandler *handlers;\n\tGenericHandler handler;", "\t/*\n\t * Verify that method_index is within range. If this fails, you are\n\t * likely invoking a newly added method on an old service. (Although\n\t * other memory corruption bugs can cause this assertion too.)\n\t */\n\tassert(method_index < service->descriptor->n_methods);", "\t/*\n\t * Get the array of virtual methods (which are enumerated by the\n\t * generated code).\n\t */\n\thandlers = (GenericHandler *) (service + 1);", "\t/*\n\t * Get our method and invoke it.\n\t * \\todo Seems like handler == NULL is a situation that needs handling.\n\t */\n\thandler = handlers[method_index];\n\t(*handler)(service, input, closure, closure_data);\n}", "void\nprotobuf_c_service_generated_init(ProtobufCService *service,\n\t\t\t\t const ProtobufCServiceDescriptor *descriptor,\n\t\t\t\t ProtobufCServiceDestroy destroy)\n{\n\tASSERT_IS_SERVICE_DESCRIPTOR(descriptor);\n\tservice->descriptor = descriptor;\n\tservice->destroy = destroy;\n\tservice->invoke = protobuf_c_service_invoke_internal;\n\tmemset(service + 1, 0, descriptor->n_methods * sizeof(GenericHandler));\n}", "void protobuf_c_service_destroy(ProtobufCService *service)\n{\n\tservice->destroy(service);\n}", "/* --- querying the descriptors --- */", "const ProtobufCEnumValue *\nprotobuf_c_enum_descriptor_get_value_by_name(const ProtobufCEnumDescriptor *desc,\n\t\t\t\t\t const char *name)\n{\n\tunsigned start = 0;\n\tunsigned count;", "\tif (desc == NULL || desc->values_by_name == NULL)\n\t\treturn NULL;", "\tcount = desc->n_value_names;", "\twhile (count > 1) {\n\t\tunsigned mid = start + count / 2;\n\t\tint rv = strcmp(desc->values_by_name[mid].name, name);\n\t\tif (rv == 0)\n\t\t\treturn desc->values + desc->values_by_name[mid].index;\n\t\telse if (rv < 0) {\n\t\t\tcount = start + count - (mid + 1);\n\t\t\tstart = mid + 1;\n\t\t} else\n\t\t\tcount = mid - start;\n\t}\n\tif (count == 0)\n\t\treturn NULL;\n\tif (strcmp(desc->values_by_name[start].name, name) == 0)\n\t\treturn desc->values + desc->values_by_name[start].index;\n\treturn NULL;\n}", "const ProtobufCEnumValue *\nprotobuf_c_enum_descriptor_get_value(const ProtobufCEnumDescriptor *desc,\n\t\t\t\t int value)\n{\n\tint rv = int_range_lookup(desc->n_value_ranges, desc->value_ranges, value);\n\tif (rv < 0)\n\t\treturn NULL;\n\treturn desc->values + rv;\n}", "const ProtobufCFieldDescriptor *\nprotobuf_c_message_descriptor_get_field_by_name(const ProtobufCMessageDescriptor *desc,\n\t\t\t\t\t\tconst char *name)\n{\n\tunsigned start = 0;\n\tunsigned count;\n\tconst ProtobufCFieldDescriptor *field;", "\tif (desc == NULL || desc->fields_sorted_by_name == NULL)\n\t\treturn NULL;", "\tcount = desc->n_fields;", "\twhile (count > 1) {\n\t\tunsigned mid = start + count / 2;\n\t\tint rv;\n\t\tfield = desc->fields + desc->fields_sorted_by_name[mid];\n\t\trv = strcmp(field->name, name);\n\t\tif (rv == 0)\n\t\t\treturn field;\n\t\telse if (rv < 0) {\n\t\t\tcount = start + count - (mid + 1);\n\t\t\tstart = mid + 1;\n\t\t} else\n\t\t\tcount = mid - start;\n\t}\n\tif (count == 0)\n\t\treturn NULL;\n\tfield = desc->fields + desc->fields_sorted_by_name[start];\n\tif (strcmp(field->name, name) == 0)\n\t\treturn field;\n\treturn NULL;\n}", "const ProtobufCFieldDescriptor *\nprotobuf_c_message_descriptor_get_field(const ProtobufCMessageDescriptor *desc,\n\t\t\t\t\tunsigned value)\n{\n\tint rv = int_range_lookup(desc->n_field_ranges,desc->field_ranges, value);\n\tif (rv < 0)\n\t\treturn NULL;\n\treturn desc->fields + rv;\n}", "const ProtobufCMethodDescriptor *\nprotobuf_c_service_descriptor_get_method_by_name(const ProtobufCServiceDescriptor *desc,\n\t\t\t\t\t\t const char *name)\n{\n\tunsigned start = 0;\n\tunsigned count;", "\tif (desc == NULL || desc->method_indices_by_name == NULL)\n\t\treturn NULL;", "\tcount = desc->n_methods;", "\twhile (count > 1) {\n\t\tunsigned mid = start + count / 2;\n\t\tunsigned mid_index = desc->method_indices_by_name[mid];\n\t\tconst char *mid_name = desc->methods[mid_index].name;\n\t\tint rv = strcmp(mid_name, name);", "\t\tif (rv == 0)\n\t\t\treturn desc->methods + desc->method_indices_by_name[mid];\n\t\tif (rv < 0) {\n\t\t\tcount = start + count - (mid + 1);\n\t\t\tstart = mid + 1;\n\t\t} else {\n\t\t\tcount = mid - start;\n\t\t}\n\t}\n\tif (count == 0)\n\t\treturn NULL;\n\tif (strcmp(desc->methods[desc->method_indices_by_name[start]].name, name) == 0)\n\t\treturn desc->methods + desc->method_indices_by_name[start];\n\treturn NULL;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2610], "buggy_code_start_loc": [2606], "filenames": ["protobuf-c/protobuf-c.c"], "fixing_code_end_loc": [2613], "fixing_code_start_loc": [2606], "message": "protobuf-c before 1.4.1 has an unsigned integer overflow in parse_required_member.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:protobuf-c_project:protobuf-c:*:*:*:*:*:*:*:*", "matchCriteriaId": "036DA1F5-7D0A-427C-B29F-90FA388EBB1E", "versionEndExcluding": "1.4.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "protobuf-c before 1.4.1 has an unsigned integer overflow in parse_required_member."}], "evaluatorComment": null, "id": "CVE-2022-48468", "lastModified": "2023-04-29T07:15:07.207", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-13T21:15:07.077", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/protobuf-c/protobuf-c/commit/ec3d900001a13ccdaa8aef996b34c61159c76217"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/protobuf-c/protobuf-c/issues/499"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/protobuf-c/protobuf-c/pull/513"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes"], "url": "https://github.com/protobuf-c/protobuf-c/releases/tag/v1.4.1"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/EI4JZSHJXW7WOOTAQSV5SUCC5GE2GC2B/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/UGLZZYPOLI733DPETL444E3GY5KSS6LG/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/VNUEZZEPR2F6M67ANXLOPJX6AQL3TK4P/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/protobuf-c/protobuf-c/commit/ec3d900001a13ccdaa8aef996b34c61159c76217"}, "type": "CWE-190"}
297
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * History:\n * Started: Aug 9 by Lawrence Foard (entropy@world.std.com),\n * to allow user process control of SCSI devices.\n * Development Sponsored by Killy Corp. NY NY\n *\n * Original driver (sg.c):\n * Copyright (C) 1992 Lawrence Foard\n * Version 2 and 3 extensions to driver:\n * Copyright (C) 1998 - 2014 Douglas Gilbert\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n */", "static int sg_version_num = 30536;\t/* 2 digits for each component */\n#define SG_VERSION_STR \"3.5.36\"", "/*\n * D. P. Gilbert (dgilbert@interlog.com), notes:\n * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First\n * the kernel/module needs to be built with CONFIG_SCSI_LOGGING\n * (otherwise the macros compile to empty statements).\n *\n */\n#include <linux/module.h>", "#include <linux/fs.h>\n#include <linux/kernel.h>\n#include <linux/sched.h>\n#include <linux/string.h>\n#include <linux/mm.h>\n#include <linux/errno.h>\n#include <linux/mtio.h>\n#include <linux/ioctl.h>\n#include <linux/slab.h>\n#include <linux/fcntl.h>\n#include <linux/init.h>\n#include <linux/poll.h>\n#include <linux/moduleparam.h>\n#include <linux/cdev.h>\n#include <linux/idr.h>\n#include <linux/seq_file.h>\n#include <linux/blkdev.h>\n#include <linux/delay.h>\n#include <linux/blktrace_api.h>\n#include <linux/mutex.h>\n#include <linux/atomic.h>\n#include <linux/ratelimit.h>\n#include <linux/uio.h>", "#include \"scsi.h\"\n#include <scsi/scsi_dbg.h>\n#include <scsi/scsi_host.h>\n#include <scsi/scsi_driver.h>\n#include <scsi/scsi_ioctl.h>\n#include <scsi/sg.h>", "#include \"scsi_logging.h\"", "#ifdef CONFIG_SCSI_PROC_FS\n#include <linux/proc_fs.h>\nstatic char *sg_version_date = \"20140603\";", "static int sg_proc_init(void);\nstatic void sg_proc_cleanup(void);\n#endif", "#define SG_ALLOW_DIO_DEF 0", "#define SG_MAX_DEVS 32768", "/* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type\n * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater\n * than 16 bytes are \"variable length\" whose length is a multiple of 4\n */\n#define SG_MAX_CDB_SIZE 252", "/*\n * Suppose you want to calculate the formula muldiv(x,m,d)=int(x * m / d)\n * Then when using 32 bit integers x * m may overflow during the calculation.\n * Replacing muldiv(x) by muldiv(x)=((x % d) * m) / d + int(x / d) * m\n * calculates the same, but prevents the overflow when both m and d\n * are \"small\" numbers (like HZ and USER_HZ).\n * Of course an overflow is inavoidable if the result of muldiv doesn't fit\n * in 32 bits.\n */\n#define MULDIV(X,MUL,DIV) ((((X % DIV) * MUL) / DIV) + ((X / DIV) * MUL))", "#define SG_DEFAULT_TIMEOUT MULDIV(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)", "int sg_big_buff = SG_DEF_RESERVED_SIZE;\n/* N.B. This variable is readable and writeable via\n /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer\n of this size (or less if there is not enough memory) will be reserved\n for use by this file descriptor. [Deprecated usage: this variable is also\n readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into\n the kernel (i.e. it is not a module).] */\nstatic int def_reserved_size = -1;\t/* picks up init parameter */\nstatic int sg_allow_dio = SG_ALLOW_DIO_DEF;", "static int scatter_elem_sz = SG_SCATTER_SZ;\nstatic int scatter_elem_sz_prev = SG_SCATTER_SZ;", "#define SG_SECTOR_SZ 512", "static int sg_add_device(struct device *, struct class_interface *);\nstatic void sg_remove_device(struct device *, struct class_interface *);", "static DEFINE_IDR(sg_index_idr);\nstatic DEFINE_RWLOCK(sg_index_lock);\t/* Also used to lock\n\t\t\t\t\t\t\t file descriptor list for device */", "static struct class_interface sg_interface = {\n\t.add_dev = sg_add_device,\n\t.remove_dev = sg_remove_device,\n};", "typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */\n\tunsigned short k_use_sg; /* Count of kernel scatter-gather pieces */\n\tunsigned sglist_len; /* size of malloc'd scatter-gather list ++ */\n\tunsigned bufflen;\t/* Size of (aggregate) data buffer */\n\tstruct page **pages;\n\tint page_order;\n\tchar dio_in_use;\t/* 0->indirect IO (or mmap), 1->dio */\n\tunsigned char cmd_opcode; /* first byte of command */\n} Sg_scatter_hold;", "struct sg_device;\t\t/* forward declarations */\nstruct sg_fd;", "typedef struct sg_request {\t/* SG_MAX_QUEUE requests outstanding per file */\n\tstruct sg_request *nextrp;\t/* NULL -> tail request (slist) */\n\tstruct sg_fd *parentfp;\t/* NULL -> not in use */\n\tSg_scatter_hold data;\t/* hold buffer, perhaps scatter list */\n\tsg_io_hdr_t header;\t/* scsi command+info, see <scsi/sg.h> */\n\tunsigned char sense_b[SCSI_SENSE_BUFFERSIZE];\n\tchar res_used;\t\t/* 1 -> using reserve buffer, 0 -> not ... */\n\tchar orphan;\t\t/* 1 -> drop on sight, 0 -> normal */\n\tchar sg_io_owned;\t/* 1 -> packet belongs to SG_IO */\n\t/* done protected by rq_list_lock */\n\tchar done;\t\t/* 0->before bh, 1->before read, 2->read */\n\tstruct request *rq;\n\tstruct bio *bio;\n\tstruct execute_work ew;\n} Sg_request;", "typedef struct sg_fd {\t\t/* holds the state of a file descriptor */\n\tstruct list_head sfd_siblings; /* protected by device's sfd_lock */\n\tstruct sg_device *parentdp;\t/* owning device */\n\twait_queue_head_t read_wait;\t/* queue read until command done */\n\trwlock_t rq_list_lock;\t/* protect access to list in req_arr */\n\tint timeout;\t\t/* defaults to SG_DEFAULT_TIMEOUT */\n\tint timeout_user;\t/* defaults to SG_DEFAULT_TIMEOUT_USER */\n\tSg_scatter_hold reserve;\t/* buffer held for this file descriptor */\n\tunsigned save_scat_len;\t/* original length of trunc. scat. element */\n\tSg_request *headrp;\t/* head of request slist, NULL->empty */\n\tstruct fasync_struct *async_qp;\t/* used by asynchronous notification */\n\tSg_request req_arr[SG_MAX_QUEUE];\t/* used as singly-linked list */\n\tchar low_dma;\t\t/* as in parent but possibly overridden to 1 */\n\tchar force_packid;\t/* 1 -> pack_id input to read(), 0 -> ignored */\n\tchar cmd_q;\t\t/* 1 -> allow command queuing, 0 -> don't */\n\tunsigned char next_cmd_len; /* 0: automatic, >0: use on next write() */\n\tchar keep_orphan;\t/* 0 -> drop orphan (def), 1 -> keep for read() */\n\tchar mmap_called;\t/* 0 -> mmap() never called on this fd */\n\tstruct kref f_ref;\n\tstruct execute_work ew;\n} Sg_fd;", "typedef struct sg_device { /* holds the state of each scsi generic device */\n\tstruct scsi_device *device;\n\twait_queue_head_t open_wait; /* queue open() when O_EXCL present */\n\tstruct mutex open_rel_lock; /* held when in open() or release() */\n\tint sg_tablesize;\t/* adapter's max scatter-gather table size */\n\tu32 index;\t\t/* device index number */\n\tstruct list_head sfds;\n\trwlock_t sfd_lock; /* protect access to sfd list */\n\tatomic_t detaching; /* 0->device usable, 1->device detaching */\n\tbool exclude;\t\t/* 1->open(O_EXCL) succeeded and is active */\n\tint open_cnt;\t\t/* count of opens (perhaps < num(sfds) ) */\n\tchar sgdebug;\t\t/* 0->off, 1->sense, 9->dump dev, 10-> all devs */\n\tstruct gendisk *disk;\n\tstruct cdev * cdev;\t/* char_dev [sysfs: /sys/cdev/major/sg<n>] */\n\tstruct kref d_ref;\n} Sg_device;", "/* tasklet or soft irq callback */\nstatic void sg_rq_end_io(struct request *rq, int uptodate);\nstatic int sg_start_req(Sg_request *srp, unsigned char *cmd);\nstatic int sg_finish_rem_req(Sg_request * srp);\nstatic int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);\nstatic ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count,\n\t\t\t Sg_request * srp);\nstatic ssize_t sg_new_write(Sg_fd *sfp, struct file *file,\n\t\t\tconst char __user *buf, size_t count, int blocking,\n\t\t\tint read_only, int sg_io_owned, Sg_request **o_srp);\nstatic int sg_common_write(Sg_fd * sfp, Sg_request * srp,\n\t\t\t unsigned char *cmnd, int timeout, int blocking);\nstatic int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);\nstatic void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp);\nstatic void sg_build_reserve(Sg_fd * sfp, int req_size);\nstatic void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);\nstatic void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);\nstatic Sg_fd *sg_add_sfp(Sg_device * sdp);\nstatic void sg_remove_sfp(struct kref *);\nstatic Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id);\nstatic Sg_request *sg_add_request(Sg_fd * sfp);\nstatic int sg_remove_request(Sg_fd * sfp, Sg_request * srp);\nstatic int sg_res_in_use(Sg_fd * sfp);\nstatic Sg_device *sg_get_dev(int dev);\nstatic void sg_device_destroy(struct kref *kref);", "#define SZ_SG_HEADER sizeof(struct sg_header)\n#define SZ_SG_IO_HDR sizeof(sg_io_hdr_t)\n#define SZ_SG_IOVEC sizeof(sg_iovec_t)\n#define SZ_SG_REQ_INFO sizeof(sg_req_info_t)", "#define sg_printk(prefix, sdp, fmt, a...) \\\n\tsdev_prefix_printk(prefix, (sdp)->device,\t\t\\\n\t\t\t (sdp)->disk->disk_name, fmt, ##a)", "static int sg_allow_access(struct file *filp, unsigned char *cmd)\n{\n\tstruct sg_fd *sfp = filp->private_data;", "\tif (sfp->parentdp->device->type == TYPE_SCANNER)\n\t\treturn 0;", "\treturn blk_verify_command(cmd, filp->f_mode & FMODE_WRITE);\n}", "static int\nopen_wait(Sg_device *sdp, int flags)\n{\n\tint retval = 0;", "\tif (flags & O_EXCL) {\n\t\twhile (sdp->open_cnt > 0) {\n\t\t\tmutex_unlock(&sdp->open_rel_lock);\n\t\t\tretval = wait_event_interruptible(sdp->open_wait,\n\t\t\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t\t\t !sdp->open_cnt));\n\t\t\tmutex_lock(&sdp->open_rel_lock);", "\t\t\tif (retval) /* -ERESTARTSYS */\n\t\t\t\treturn retval;\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t}\n\t} else {\n\t\twhile (sdp->exclude) {\n\t\t\tmutex_unlock(&sdp->open_rel_lock);\n\t\t\tretval = wait_event_interruptible(sdp->open_wait,\n\t\t\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t\t\t !sdp->exclude));\n\t\t\tmutex_lock(&sdp->open_rel_lock);", "\t\t\tif (retval) /* -ERESTARTSYS */\n\t\t\t\treturn retval;\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t}\n\t}", "\treturn retval;\n}", "/* Returns 0 on success, else a negated errno value */\nstatic int\nsg_open(struct inode *inode, struct file *filp)\n{\n\tint dev = iminor(inode);\n\tint flags = filp->f_flags;\n\tstruct request_queue *q;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tint retval;", "\tnonseekable_open(inode, filp);\n\tif ((flags & O_EXCL) && (O_RDONLY == (flags & O_ACCMODE)))\n\t\treturn -EPERM; /* Can't lock it with read only access */\n\tsdp = sg_get_dev(dev);\n\tif (IS_ERR(sdp))\n\t\treturn PTR_ERR(sdp);", "\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_open: flags=0x%x\\n\", flags));", "\t/* This driver's module count bumped by fops_get in <linux/fs.h> */\n\t/* Prevent the device driver from vanishing while we sleep */\n\tretval = scsi_device_get(sdp->device);\n\tif (retval)\n\t\tgoto sg_put;", "\tretval = scsi_autopm_get_device(sdp->device);\n\tif (retval)\n\t\tgoto sdp_put;", "\t/* scsi_block_when_processing_errors() may block so bypass\n\t * check if O_NONBLOCK. Permits SCSI commands to be issued\n\t * during error recovery. Tread carefully. */\n\tif (!((flags & O_NONBLOCK) ||\n\t scsi_block_when_processing_errors(sdp->device))) {\n\t\tretval = -ENXIO;\n\t\t/* we are in error recovery for this device */\n\t\tgoto error_out;\n\t}", "\tmutex_lock(&sdp->open_rel_lock);\n\tif (flags & O_NONBLOCK) {\n\t\tif (flags & O_EXCL) {\n\t\t\tif (sdp->open_cnt > 0) {\n\t\t\t\tretval = -EBUSY;\n\t\t\t\tgoto error_mutex_locked;\n\t\t\t}\n\t\t} else {\n\t\t\tif (sdp->exclude) {\n\t\t\t\tretval = -EBUSY;\n\t\t\t\tgoto error_mutex_locked;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tretval = open_wait(sdp, flags);\n\t\tif (retval) /* -ERESTARTSYS or -ENODEV */\n\t\t\tgoto error_mutex_locked;\n\t}", "\t/* N.B. at this point we are holding the open_rel_lock */\n\tif (flags & O_EXCL)\n\t\tsdp->exclude = true;", "\tif (sdp->open_cnt < 1) { /* no existing opens */\n\t\tsdp->sgdebug = 0;\n\t\tq = sdp->device->request_queue;\n\t\tsdp->sg_tablesize = queue_max_segments(q);\n\t}\n\tsfp = sg_add_sfp(sdp);\n\tif (IS_ERR(sfp)) {\n\t\tretval = PTR_ERR(sfp);\n\t\tgoto out_undo;\n\t}", "\tfilp->private_data = sfp;\n\tsdp->open_cnt++;\n\tmutex_unlock(&sdp->open_rel_lock);", "\tretval = 0;\nsg_put:\n\tkref_put(&sdp->d_ref, sg_device_destroy);\n\treturn retval;", "out_undo:\n\tif (flags & O_EXCL) {\n\t\tsdp->exclude = false; /* undo if error */\n\t\twake_up_interruptible(&sdp->open_wait);\n\t}\nerror_mutex_locked:\n\tmutex_unlock(&sdp->open_rel_lock);\nerror_out:\n\tscsi_autopm_put_device(sdp->device);\nsdp_put:\n\tscsi_device_put(sdp->device);\n\tgoto sg_put;\n}", "/* Release resources associated with a successful sg_open()\n * Returns 0 on success, else a negated errno value */\nstatic int\nsg_release(struct inode *inode, struct file *filp)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, \"sg_release\\n\"));", "\tmutex_lock(&sdp->open_rel_lock);\n\tscsi_autopm_put_device(sdp->device);\n\tkref_put(&sfp->f_ref, sg_remove_sfp);\n\tsdp->open_cnt--;", "\t/* possibly many open()s waiting on exlude clearing, start many;\n\t * only open(O_EXCL)s wait on 0==open_cnt so only start one */\n\tif (sdp->exclude) {\n\t\tsdp->exclude = false;\n\t\twake_up_interruptible_all(&sdp->open_wait);\n\t} else if (0 == sdp->open_cnt) {\n\t\twake_up_interruptible(&sdp->open_wait);\n\t}\n\tmutex_unlock(&sdp->open_rel_lock);\n\treturn 0;\n}", "static ssize_t\nsg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tint req_pack_id = -1;\n\tsg_io_hdr_t *hp;\n\tstruct sg_header *old_hdr = NULL;\n\tint retval = 0;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_read: count=%d\\n\", (int) count));", "\tif (!access_ok(VERIFY_WRITE, buf, count))\n\t\treturn -EFAULT;\n\tif (sfp->force_packid && (count >= SZ_SG_HEADER)) {\n\t\told_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);\n\t\tif (!old_hdr)\n\t\t\treturn -ENOMEM;\n\t\tif (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) {\n\t\t\tretval = -EFAULT;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (old_hdr->reply_len < 0) {\n\t\t\tif (count >= SZ_SG_IO_HDR) {\n\t\t\t\tsg_io_hdr_t *new_hdr;\n\t\t\t\tnew_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL);\n\t\t\t\tif (!new_hdr) {\n\t\t\t\t\tretval = -ENOMEM;\n\t\t\t\t\tgoto free_old_hdr;\n\t\t\t\t}\n\t\t\t\tretval =__copy_from_user\n\t\t\t\t (new_hdr, buf, SZ_SG_IO_HDR);\n\t\t\t\treq_pack_id = new_hdr->pack_id;\n\t\t\t\tkfree(new_hdr);\n\t\t\t\tif (retval) {\n\t\t\t\t\tretval = -EFAULT;\n\t\t\t\t\tgoto free_old_hdr;\n\t\t\t\t}\n\t\t\t}\n\t\t} else\n\t\t\treq_pack_id = old_hdr->pack_id;\n\t}\n\tsrp = sg_get_rq_mark(sfp, req_pack_id);\n\tif (!srp) {\t\t/* now wait on packet to arrive */\n\t\tif (atomic_read(&sdp->detaching)) {\n\t\t\tretval = -ENODEV;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (filp->f_flags & O_NONBLOCK) {\n\t\t\tretval = -EAGAIN;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tretval = wait_event_interruptible(sfp->read_wait,\n\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t(srp = sg_get_rq_mark(sfp, req_pack_id))));\n\t\tif (atomic_read(&sdp->detaching)) {\n\t\t\tretval = -ENODEV;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (retval) {\n\t\t\t/* -ERESTARTSYS as signal hit process */\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t}\n\tif (srp->header.interface_id != '\\0') {\n\t\tretval = sg_new_read(sfp, buf, count, srp);\n\t\tgoto free_old_hdr;\n\t}", "\thp = &srp->header;\n\tif (old_hdr == NULL) {\n\t\told_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);\n\t\tif (! old_hdr) {\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t}\n\tmemset(old_hdr, 0, SZ_SG_HEADER);\n\told_hdr->reply_len = (int) hp->timeout;\n\told_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */\n\told_hdr->pack_id = hp->pack_id;\n\told_hdr->twelve_byte =\n\t ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;\n\told_hdr->target_status = hp->masked_status;\n\told_hdr->host_status = hp->host_status;\n\told_hdr->driver_status = hp->driver_status;\n\tif ((CHECK_CONDITION & hp->masked_status) ||\n\t (DRIVER_SENSE & hp->driver_status))\n\t\tmemcpy(old_hdr->sense_buffer, srp->sense_b,\n\t\t sizeof (old_hdr->sense_buffer));\n\tswitch (hp->host_status) {\n\t/* This setup of 'result' is for backward compatibility and is best\n\t ignored by the user who should use target, host + driver status */\n\tcase DID_OK:\n\tcase DID_PASSTHROUGH:\n\tcase DID_SOFT_ERROR:\n\t\told_hdr->result = 0;\n\t\tbreak;\n\tcase DID_NO_CONNECT:\n\tcase DID_BUS_BUSY:\n\tcase DID_TIME_OUT:\n\t\told_hdr->result = EBUSY;\n\t\tbreak;\n\tcase DID_BAD_TARGET:\n\tcase DID_ABORT:\n\tcase DID_PARITY:\n\tcase DID_RESET:\n\tcase DID_BAD_INTR:\n\t\told_hdr->result = EIO;\n\t\tbreak;\n\tcase DID_ERROR:\n\t\told_hdr->result = (srp->sense_b[0] == 0 && \n\t\t\t\t hp->masked_status == GOOD) ? 0 : EIO;\n\t\tbreak;\n\tdefault:\n\t\told_hdr->result = EIO;\n\t\tbreak;\n\t}", "\t/* Now copy the result back to the user buffer. */\n\tif (count >= SZ_SG_HEADER) {\n\t\tif (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {\n\t\t\tretval = -EFAULT;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tbuf += SZ_SG_HEADER;\n\t\tif (count > old_hdr->reply_len)\n\t\t\tcount = old_hdr->reply_len;\n\t\tif (count > SZ_SG_HEADER) {\n\t\t\tif (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {\n\t\t\t\tretval = -EFAULT;\n\t\t\t\tgoto free_old_hdr;\n\t\t\t}\n\t\t}\n\t} else\n\t\tcount = (old_hdr->result == 0) ? 0 : -EIO;\n\tsg_finish_rem_req(srp);\n\tretval = count;\nfree_old_hdr:\n\tkfree(old_hdr);\n\treturn retval;\n}", "static ssize_t\nsg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp)\n{\n\tsg_io_hdr_t *hp = &srp->header;\n\tint err = 0, err2;\n\tint len;", "\tif (count < SZ_SG_IO_HDR) {\n\t\terr = -EINVAL;\n\t\tgoto err_out;\n\t}\n\thp->sb_len_wr = 0;\n\tif ((hp->mx_sb_len > 0) && hp->sbp) {\n\t\tif ((CHECK_CONDITION & hp->masked_status) ||\n\t\t (DRIVER_SENSE & hp->driver_status)) {\n\t\t\tint sb_len = SCSI_SENSE_BUFFERSIZE;\n\t\t\tsb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len;\n\t\t\tlen = 8 + (int) srp->sense_b[7];\t/* Additional sense length field */\n\t\t\tlen = (len > sb_len) ? sb_len : len;\n\t\t\tif (copy_to_user(hp->sbp, srp->sense_b, len)) {\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto err_out;\n\t\t\t}\n\t\t\thp->sb_len_wr = len;\n\t\t}\n\t}\n\tif (hp->masked_status || hp->host_status || hp->driver_status)\n\t\thp->info |= SG_INFO_CHECK;\n\tif (copy_to_user(buf, hp, SZ_SG_IO_HDR)) {\n\t\terr = -EFAULT;\n\t\tgoto err_out;\n\t}\nerr_out:\n\terr2 = sg_finish_rem_req(srp);\n\treturn err ? : err2 ? : count;\n}", "static ssize_t\nsg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)\n{\n\tint mxsize, cmd_size, k;\n\tint input_size, blocking;\n\tunsigned char opcode;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tstruct sg_header old_hdr;\n\tsg_io_hdr_t *hp;\n\tunsigned char cmnd[SG_MAX_CDB_SIZE];", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_write: count=%d\\n\", (int) count));\n\tif (atomic_read(&sdp->detaching))\n\t\treturn -ENODEV;\n\tif (!((filp->f_flags & O_NONBLOCK) ||\n\t scsi_block_when_processing_errors(sdp->device)))\n\t\treturn -ENXIO;", "\tif (!access_ok(VERIFY_READ, buf, count))\n\t\treturn -EFAULT;\t/* protects following copy_from_user()s + get_user()s */\n\tif (count < SZ_SG_HEADER)\n\t\treturn -EIO;\n\tif (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))\n\t\treturn -EFAULT;\n\tblocking = !(filp->f_flags & O_NONBLOCK);\n\tif (old_hdr.reply_len < 0)\n\t\treturn sg_new_write(sfp, filp, buf, count,\n\t\t\t\t blocking, 0, 0, NULL);\n\tif (count < (SZ_SG_HEADER + 6))\n\t\treturn -EIO;\t/* The minimum scsi command length is 6 bytes. */", "\tif (!(srp = sg_add_request(sfp))) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,\n\t\t\t\t\t \"sg_write: queue full\\n\"));\n\t\treturn -EDOM;\n\t}\n\tbuf += SZ_SG_HEADER;\n\t__get_user(opcode, buf);\n\tif (sfp->next_cmd_len > 0) {\n\t\tcmd_size = sfp->next_cmd_len;\n\t\tsfp->next_cmd_len = 0;\t/* reset so only this write() effected */\n\t} else {\n\t\tcmd_size = COMMAND_SIZE(opcode);\t/* based on SCSI command group */\n\t\tif ((opcode >= 0xc0) && old_hdr.twelve_byte)\n\t\t\tcmd_size = 12;\n\t}\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,\n\t\t\"sg_write: scsi opcode=0x%02x, cmd_size=%d\\n\", (int) opcode, cmd_size));\n/* Determine buffer size. */\n\tinput_size = count - cmd_size;\n\tmxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;\n\tmxsize -= SZ_SG_HEADER;\n\tinput_size -= SZ_SG_HEADER;\n\tif (input_size < 0) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EIO;\t/* User did not pass enough bytes for this command. */\n\t}\n\thp = &srp->header;\n\thp->interface_id = '\\0';\t/* indicator of old interface tunnelled */\n\thp->cmd_len = (unsigned char) cmd_size;\n\thp->iovec_count = 0;\n\thp->mx_sb_len = 0;\n\tif (input_size > 0)\n\t\thp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?\n\t\t SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;\n\telse\n\t\thp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;\n\thp->dxfer_len = mxsize;\n\tif (hp->dxfer_direction == SG_DXFER_TO_DEV)\n\t\thp->dxferp = (char __user *)buf + cmd_size;\n\telse\n\t\thp->dxferp = NULL;\n\thp->sbp = NULL;\n\thp->timeout = old_hdr.reply_len;\t/* structure abuse ... */\n\thp->flags = input_size;\t/* structure abuse ... */\n\thp->pack_id = old_hdr.pack_id;\n\thp->usr_ptr = NULL;\n\tif (__copy_from_user(cmnd, buf, cmd_size))\n\t\treturn -EFAULT;\n\t/*\n\t * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,\n\t * but is is possible that the app intended SG_DXFER_TO_DEV, because there\n\t * is a non-zero input_size, so emit a warning.\n\t */\n\tif (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {\n\t\tstatic char cmd[TASK_COMM_LEN];\n\t\tif (strcmp(current->comm, cmd)) {\n\t\t\tprintk_ratelimited(KERN_WARNING\n\t\t\t\t\t \"sg_write: data in/out %d/%d bytes \"\n\t\t\t\t\t \"for SCSI command 0x%x-- guessing \"\n\t\t\t\t\t \"data in;\\n program %s not setting \"\n\t\t\t\t\t \"count and/or reply_len properly\\n\",\n\t\t\t\t\t old_hdr.reply_len - (int)SZ_SG_HEADER,\n\t\t\t\t\t input_size, (unsigned int) cmnd[0],\n\t\t\t\t\t current->comm);\n\t\t\tstrcpy(cmd, current->comm);\n\t\t}\n\t}\n\tk = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);\n\treturn (k < 0) ? k : count;\n}", "static ssize_t\nsg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf,\n\t\t size_t count, int blocking, int read_only, int sg_io_owned,\n\t\t Sg_request **o_srp)\n{\n\tint k;\n\tSg_request *srp;\n\tsg_io_hdr_t *hp;\n\tunsigned char cmnd[SG_MAX_CDB_SIZE];\n\tint timeout;\n\tunsigned long ul_timeout;", "\tif (count < SZ_SG_IO_HDR)\n\t\treturn -EINVAL;\n\tif (!access_ok(VERIFY_READ, buf, count))\n\t\treturn -EFAULT; /* protects following copy_from_user()s + get_user()s */", "\tsfp->cmd_q = 1;\t/* when sg_io_hdr seen, set command queuing on */\n\tif (!(srp = sg_add_request(sfp))) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t\t \"sg_new_write: queue full\\n\"));\n\t\treturn -EDOM;\n\t}\n\tsrp->sg_io_owned = sg_io_owned;\n\thp = &srp->header;\n\tif (__copy_from_user(hp, buf, SZ_SG_IO_HDR)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EFAULT;\n\t}\n\tif (hp->interface_id != 'S') {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -ENOSYS;\n\t}\n\tif (hp->flags & SG_FLAG_MMAP_IO) {\n\t\tif (hp->dxfer_len > sfp->reserve.bufflen) {\n\t\t\tsg_remove_request(sfp, srp);\n\t\t\treturn -ENOMEM;\t/* MMAP_IO size must fit in reserve buffer */\n\t\t}\n\t\tif (hp->flags & SG_FLAG_DIRECT_IO) {\n\t\t\tsg_remove_request(sfp, srp);\n\t\t\treturn -EINVAL;\t/* either MMAP_IO or DIRECT_IO (not both) */\n\t\t}\n\t\tif (sg_res_in_use(sfp)) {\n\t\t\tsg_remove_request(sfp, srp);\n\t\t\treturn -EBUSY;\t/* reserve buffer already being used */\n\t\t}\n\t}\n\tul_timeout = msecs_to_jiffies(srp->header.timeout);\n\ttimeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX;\n\tif ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EMSGSIZE;\n\t}\n\tif (!access_ok(VERIFY_READ, hp->cmdp, hp->cmd_len)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EFAULT;\t/* protects following copy_from_user()s + get_user()s */\n\t}\n\tif (__copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EFAULT;\n\t}\n\tif (read_only && sg_allow_access(file, cmnd)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EPERM;\n\t}\n\tk = sg_common_write(sfp, srp, cmnd, timeout, blocking);\n\tif (k < 0)\n\t\treturn k;\n\tif (o_srp)\n\t\t*o_srp = srp;\n\treturn count;\n}", "static int\nsg_common_write(Sg_fd * sfp, Sg_request * srp,\n\t\tunsigned char *cmnd, int timeout, int blocking)\n{\n\tint k, at_head;\n\tSg_device *sdp = sfp->parentdp;\n\tsg_io_hdr_t *hp = &srp->header;", "\tsrp->data.cmd_opcode = cmnd[0];\t/* hold opcode of command */\n\thp->status = 0;\n\thp->masked_status = 0;\n\thp->msg_status = 0;\n\thp->info = 0;\n\thp->host_status = 0;\n\thp->driver_status = 0;\n\thp->resid = 0;\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\\n\",\n\t\t\t(int) cmnd[0], (int) hp->cmd_len));", "\tk = sg_start_req(srp, cmnd);\n\tif (k) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\"sg_common_write: start_req err=%d\\n\", k));\n\t\tsg_finish_rem_req(srp);\n\t\treturn k;\t/* probably out of space --> ENOMEM */\n\t}\n\tif (atomic_read(&sdp->detaching)) {\n\t\tif (srp->bio)\n\t\t\tblk_end_request_all(srp->rq, -EIO);\n\t\tsg_finish_rem_req(srp);\n\t\treturn -ENODEV;\n\t}", "\thp->duration = jiffies_to_msecs(jiffies);\n\tif (hp->interface_id != '\\0' &&\t/* v3 (or later) interface */\n\t (SG_FLAG_Q_AT_TAIL & hp->flags))\n\t\tat_head = 0;\n\telse\n\t\tat_head = 1;", "\tsrp->rq->timeout = timeout;\n\tkref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */\n\tblk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,\n\t\t\t srp->rq, at_head, sg_rq_end_io);\n\treturn 0;\n}", "static int srp_done(Sg_fd *sfp, Sg_request *srp)\n{\n\tunsigned long flags;\n\tint ret;", "\tread_lock_irqsave(&sfp->rq_list_lock, flags);\n\tret = srp->done;\n\tread_unlock_irqrestore(&sfp->rq_list_lock, flags);\n\treturn ret;\n}", "static int max_sectors_bytes(struct request_queue *q)\n{\n\tunsigned int max_sectors = queue_max_sectors(q);", "\tmax_sectors = min_t(unsigned int, max_sectors, INT_MAX >> 9);", "\treturn max_sectors << 9;\n}", "static long\nsg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)\n{\n\tvoid __user *p = (void __user *)arg;\n\tint __user *ip = p;\n\tint result, val, read_only;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tunsigned long iflags;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;", "\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_ioctl: cmd=0x%x\\n\", (int) cmd_in));\n\tread_only = (O_RDWR != (filp->f_flags & O_ACCMODE));", "\tswitch (cmd_in) {\n\tcase SG_IO:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tif (!scsi_block_when_processing_errors(sdp->device))\n\t\t\treturn -ENXIO;\n\t\tif (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR))\n\t\t\treturn -EFAULT;\n\t\tresult = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR,\n\t\t\t\t 1, read_only, 1, &srp);\n\t\tif (result < 0)\n\t\t\treturn result;\n\t\tresult = wait_event_interruptible(sfp->read_wait,\n\t\t\t(srp_done(sfp, srp) || atomic_read(&sdp->detaching)));\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\twrite_lock_irq(&sfp->rq_list_lock);\n\t\tif (srp->done) {\n\t\t\tsrp->done = 2;\n\t\t\twrite_unlock_irq(&sfp->rq_list_lock);\n\t\t\tresult = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp);\n\t\t\treturn (result < 0) ? result : 0;\n\t\t}\n\t\tsrp->orphan = 1;\n\t\twrite_unlock_irq(&sfp->rq_list_lock);\n\t\treturn result;\t/* -ERESTARTSYS because signal hit process */\n\tcase SG_SET_TIMEOUT:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tif (val < 0)\n\t\t\treturn -EIO;\n\t\tif (val >= MULDIV (INT_MAX, USER_HZ, HZ))\n\t\t val = MULDIV (INT_MAX, USER_HZ, HZ);\n\t\tsfp->timeout_user = val;\n\t\tsfp->timeout = MULDIV (val, HZ, USER_HZ);", "\t\treturn 0;\n\tcase SG_GET_TIMEOUT:\t/* N.B. User receives timeout as return value */\n\t\t\t\t/* strange ..., for backward compatibility */\n\t\treturn sfp->timeout_user;\n\tcase SG_SET_FORCE_LOW_DMA:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tif (val) {\n\t\t\tsfp->low_dma = 1;\n\t\t\tif ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) {\n\t\t\t\tval = (int) sfp->reserve.bufflen;\n\t\t\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t\t\t\tsg_build_reserve(sfp, val);\n\t\t\t}\n\t\t} else {\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t\tsfp->low_dma = sdp->device->host->unchecked_isa_dma;\n\t\t}\n\t\treturn 0;\n\tcase SG_GET_LOW_DMA:\n\t\treturn put_user((int) sfp->low_dma, ip);\n\tcase SG_GET_SCSI_ID:\n\t\tif (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t)))\n\t\t\treturn -EFAULT;\n\t\telse {\n\t\t\tsg_scsi_id_t __user *sg_idp = p;", "\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t\t__put_user((int) sdp->device->host->host_no,\n\t\t\t\t &sg_idp->host_no);\n\t\t\t__put_user((int) sdp->device->channel,\n\t\t\t\t &sg_idp->channel);\n\t\t\t__put_user((int) sdp->device->id, &sg_idp->scsi_id);\n\t\t\t__put_user((int) sdp->device->lun, &sg_idp->lun);\n\t\t\t__put_user((int) sdp->device->type, &sg_idp->scsi_type);\n\t\t\t__put_user((short) sdp->device->host->cmd_per_lun,\n\t\t\t\t &sg_idp->h_cmd_per_lun);\n\t\t\t__put_user((short) sdp->device->queue_depth,\n\t\t\t\t &sg_idp->d_queue_depth);\n\t\t\t__put_user(0, &sg_idp->unused[0]);\n\t\t\t__put_user(0, &sg_idp->unused[1]);\n\t\t\treturn 0;\n\t\t}\n\tcase SG_SET_FORCE_PACK_ID:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->force_packid = val ? 1 : 0;\n\t\treturn 0;\n\tcase SG_GET_PACK_ID:\n\t\tif (!access_ok(VERIFY_WRITE, ip, sizeof (int)))\n\t\t\treturn -EFAULT;\n\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\tfor (srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t\tif ((1 == srp->done) && (!srp->sg_io_owned)) {\n\t\t\t\tread_unlock_irqrestore(&sfp->rq_list_lock,\n\t\t\t\t\t\t iflags);\n\t\t\t\t__put_user(srp->header.pack_id, ip);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\t__put_user(-1, ip);\n\t\treturn 0;\n\tcase SG_GET_NUM_WAITING:\n\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\tfor (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t\tif ((1 == srp->done) && (!srp->sg_io_owned))\n\t\t\t\t++val;\n\t\t}\n\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\treturn put_user(val, ip);\n\tcase SG_GET_SG_TABLESIZE:\n\t\treturn put_user(sdp->sg_tablesize, ip);\n\tcase SG_SET_RESERVED_SIZE:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n if (val < 0)\n return -EINVAL;\n\t\tval = min_t(int, val,\n\t\t\t max_sectors_bytes(sdp->device->request_queue));\n\t\tif (val != sfp->reserve.bufflen) {\n\t\t\tif (sg_res_in_use(sfp) || sfp->mmap_called)\n\t\t\t\treturn -EBUSY;\n\t\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t\t\tsg_build_reserve(sfp, val);\n\t\t}\n\t\treturn 0;\n\tcase SG_GET_RESERVED_SIZE:\n\t\tval = min_t(int, sfp->reserve.bufflen,\n\t\t\t max_sectors_bytes(sdp->device->request_queue));\n\t\treturn put_user(val, ip);\n\tcase SG_SET_COMMAND_Q:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->cmd_q = val ? 1 : 0;\n\t\treturn 0;\n\tcase SG_GET_COMMAND_Q:\n\t\treturn put_user((int) sfp->cmd_q, ip);\n\tcase SG_SET_KEEP_ORPHAN:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->keep_orphan = val;\n\t\treturn 0;\n\tcase SG_GET_KEEP_ORPHAN:\n\t\treturn put_user((int) sfp->keep_orphan, ip);\n\tcase SG_NEXT_CMD_LEN:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->next_cmd_len = (val > 0) ? val : 0;\n\t\treturn 0;\n\tcase SG_GET_VERSION_NUM:\n\t\treturn put_user(sg_version_num, ip);\n\tcase SG_GET_ACCESS_COUNT:\n\t\t/* faked - we don't have a real access count anymore */\n\t\tval = (sdp->device ? 1 : 0);\n\t\treturn put_user(val, ip);\n\tcase SG_GET_REQUEST_TABLE:\n\t\tif (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE))\n\t\t\treturn -EFAULT;\n\t\telse {\n\t\t\tsg_req_info_t *rinfo;\n\t\t\tunsigned int ms;", "\t\t\trinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE,\n\t\t\t\t\t\t\t\tGFP_KERNEL);\n\t\t\tif (!rinfo)\n\t\t\t\treturn -ENOMEM;\n\t\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\t\tfor (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE;\n\t\t\t ++val, srp = srp ? srp->nextrp : srp) {\n\t\t\t\tmemset(&rinfo[val], 0, SZ_SG_REQ_INFO);\n\t\t\t\tif (srp) {\n\t\t\t\t\trinfo[val].req_state = srp->done + 1;\n\t\t\t\t\trinfo[val].problem =\n\t\t\t\t\t srp->header.masked_status & \n\t\t\t\t\t srp->header.host_status & \n\t\t\t\t\t srp->header.driver_status;\n\t\t\t\t\tif (srp->done)\n\t\t\t\t\t\trinfo[val].duration =\n\t\t\t\t\t\t\tsrp->header.duration;\n\t\t\t\t\telse {\n\t\t\t\t\t\tms = jiffies_to_msecs(jiffies);\n\t\t\t\t\t\trinfo[val].duration =\n\t\t\t\t\t\t (ms > srp->header.duration) ?\n\t\t\t\t\t\t (ms - srp->header.duration) : 0;\n\t\t\t\t\t}\n\t\t\t\t\trinfo[val].orphan = srp->orphan;\n\t\t\t\t\trinfo[val].sg_io_owned =\n\t\t\t\t\t\t\tsrp->sg_io_owned;\n\t\t\t\t\trinfo[val].pack_id =\n\t\t\t\t\t\t\tsrp->header.pack_id;\n\t\t\t\t\trinfo[val].usr_ptr =\n\t\t\t\t\t\t\tsrp->header.usr_ptr;\n\t\t\t\t}\n\t\t\t}\n\t\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\t\tresult = __copy_to_user(p, rinfo, \n\t\t\t\t\t\tSZ_SG_REQ_INFO * SG_MAX_QUEUE);\n\t\t\tresult = result ? -EFAULT : 0;\n\t\t\tkfree(rinfo);\n\t\t\treturn result;\n\t\t}\n\tcase SG_EMULATED_HOST:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\treturn put_user(sdp->device->host->hostt->emulated, ip);\n\tcase SCSI_IOCTL_SEND_COMMAND:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tif (read_only) {\n\t\t\tunsigned char opcode = WRITE_6;\n\t\t\tScsi_Ioctl_Command __user *siocp = p;", "\t\t\tif (copy_from_user(&opcode, siocp->data, 1))\n\t\t\t\treturn -EFAULT;\n\t\t\tif (sg_allow_access(filp, &opcode))\n\t\t\t\treturn -EPERM;\n\t\t}\n\t\treturn sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p);\n\tcase SG_SET_DEBUG:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsdp->sgdebug = (char) val;\n\t\treturn 0;\n\tcase BLKSECTGET:\n\t\treturn put_user(max_sectors_bytes(sdp->device->request_queue),\n\t\t\t\tip);\n\tcase BLKTRACESETUP:\n\t\treturn blk_trace_setup(sdp->device->request_queue,\n\t\t\t\t sdp->disk->disk_name,\n\t\t\t\t MKDEV(SCSI_GENERIC_MAJOR, sdp->index),\n\t\t\t\t NULL,\n\t\t\t\t (char *)arg);\n\tcase BLKTRACESTART:\n\t\treturn blk_trace_startstop(sdp->device->request_queue, 1);\n\tcase BLKTRACESTOP:\n\t\treturn blk_trace_startstop(sdp->device->request_queue, 0);\n\tcase BLKTRACETEARDOWN:\n\t\treturn blk_trace_remove(sdp->device->request_queue);\n\tcase SCSI_IOCTL_GET_IDLUN:\n\tcase SCSI_IOCTL_GET_BUS_NUMBER:\n\tcase SCSI_IOCTL_PROBE_HOST:\n\tcase SG_GET_TRANSFORM:\n\tcase SG_SCSI_RESET:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tbreak;\n\tdefault:\n\t\tif (read_only)\n\t\t\treturn -EPERM;\t/* don't know so take safe approach */\n\t\tbreak;\n\t}", "\tresult = scsi_ioctl_block_when_processing_errors(sdp->device,\n\t\t\tcmd_in, filp->f_flags & O_NDELAY);\n\tif (result)\n\t\treturn result;\n\treturn scsi_ioctl(sdp->device, cmd_in, p);\n}", "#ifdef CONFIG_COMPAT\nstatic long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tstruct scsi_device *sdev;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;", "\tsdev = sdp->device;\n\tif (sdev->host->hostt->compat_ioctl) { \n\t\tint ret;", "\t\tret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg);", "\t\treturn ret;\n\t}\n\t\n\treturn -ENOIOCTLCMD;\n}\n#endif", "static unsigned int\nsg_poll(struct file *filp, poll_table * wait)\n{\n\tunsigned int res = 0;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tint count = 0;\n\tunsigned long iflags;", "\tsfp = filp->private_data;\n\tif (!sfp)\n\t\treturn POLLERR;\n\tsdp = sfp->parentdp;\n\tif (!sdp)\n\t\treturn POLLERR;\n\tpoll_wait(filp, &sfp->read_wait, wait);\n\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tfor (srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t/* if any read waiting, flag it */\n\t\tif ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned))\n\t\t\tres = POLLIN | POLLRDNORM;\n\t\t++count;\n\t}\n\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);", "\tif (atomic_read(&sdp->detaching))\n\t\tres |= POLLHUP;\n\telse if (!sfp->cmd_q) {\n\t\tif (0 == count)\n\t\t\tres |= POLLOUT | POLLWRNORM;\n\t} else if (count < SG_MAX_QUEUE)\n\t\tres |= POLLOUT | POLLWRNORM;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_poll: res=0x%x\\n\", (int) res));\n\treturn res;\n}", "static int\nsg_fasync(int fd, struct file *filp, int mode)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_fasync: mode=%d\\n\", mode));", "\treturn fasync_helper(fd, filp, mode, &sfp->async_qp);\n}", "static int\nsg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)\n{\n\tSg_fd *sfp;\n\tunsigned long offset, len, sa;\n\tSg_scatter_hold *rsv_schp;\n\tint k, length;", "\tif ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))\n\t\treturn VM_FAULT_SIGBUS;\n\trsv_schp = &sfp->reserve;\n\toffset = vmf->pgoff << PAGE_SHIFT;\n\tif (offset >= rsv_schp->bufflen)\n\t\treturn VM_FAULT_SIGBUS;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_vma_fault: offset=%lu, scatg=%d\\n\",\n\t\t\t\t offset, rsv_schp->k_use_sg));\n\tsa = vma->vm_start;\n\tlength = 1 << (PAGE_SHIFT + rsv_schp->page_order);\n\tfor (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {\n\t\tlen = vma->vm_end - sa;\n\t\tlen = (len < length) ? len : length;\n\t\tif (offset < len) {\n\t\t\tstruct page *page = nth_page(rsv_schp->pages[k],\n\t\t\t\t\t\t offset >> PAGE_SHIFT);\n\t\t\tget_page(page);\t/* increment page count */\n\t\t\tvmf->page = page;\n\t\t\treturn 0; /* success */\n\t\t}\n\t\tsa += len;\n\t\toffset -= len;\n\t}", "\treturn VM_FAULT_SIGBUS;\n}", "static const struct vm_operations_struct sg_mmap_vm_ops = {\n\t.fault = sg_vma_fault,\n};", "static int\nsg_mmap(struct file *filp, struct vm_area_struct *vma)\n{\n\tSg_fd *sfp;\n\tunsigned long req_sz, len, sa;\n\tSg_scatter_hold *rsv_schp;\n\tint k, length;", "\tif ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))\n\t\treturn -ENXIO;\n\treq_sz = vma->vm_end - vma->vm_start;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_mmap starting, vm_start=%p, len=%d\\n\",\n\t\t\t\t (void *) vma->vm_start, (int) req_sz));\n\tif (vma->vm_pgoff)\n\t\treturn -EINVAL;\t/* want no offset */\n\trsv_schp = &sfp->reserve;\n\tif (req_sz > rsv_schp->bufflen)\n\t\treturn -ENOMEM;\t/* cannot map more than reserved buffer */", "\tsa = vma->vm_start;\n\tlength = 1 << (PAGE_SHIFT + rsv_schp->page_order);\n\tfor (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {\n\t\tlen = vma->vm_end - sa;\n\t\tlen = (len < length) ? len : length;\n\t\tsa += len;\n\t}", "\tsfp->mmap_called = 1;\n\tvma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;\n\tvma->vm_private_data = sfp;\n\tvma->vm_ops = &sg_mmap_vm_ops;\n\treturn 0;\n}", "static void\nsg_rq_end_io_usercontext(struct work_struct *work)\n{\n\tstruct sg_request *srp = container_of(work, struct sg_request, ew.work);\n\tstruct sg_fd *sfp = srp->parentfp;", "\tsg_finish_rem_req(srp);\n\tkref_put(&sfp->f_ref, sg_remove_sfp);\n}", "/*\n * This function is a \"bottom half\" handler that is called by the mid\n * level when a command is completed (or has failed).\n */\nstatic void\nsg_rq_end_io(struct request *rq, int uptodate)\n{\n\tstruct sg_request *srp = rq->end_io_data;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tunsigned long iflags;\n\tunsigned int ms;\n\tchar *sense;\n\tint result, resid, done = 1;", "\tif (WARN_ON(srp->done != 0))\n\t\treturn;", "\tsfp = srp->parentfp;\n\tif (WARN_ON(sfp == NULL))\n\t\treturn;", "\tsdp = sfp->parentdp;\n\tif (unlikely(atomic_read(&sdp->detaching)))\n\t\tpr_info(\"%s: device detaching\\n\", __func__);", "\tsense = rq->sense;\n\tresult = rq->errors;\n\tresid = rq->resid_len;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_cmd_done: pack_id=%d, res=0x%x\\n\",\n\t\t\t\t srp->header.pack_id, result));\n\tsrp->header.resid = resid;\n\tms = jiffies_to_msecs(jiffies);\n\tsrp->header.duration = (ms > srp->header.duration) ?\n\t\t\t\t(ms - srp->header.duration) : 0;\n\tif (0 != result) {\n\t\tstruct scsi_sense_hdr sshdr;", "\t\tsrp->header.status = 0xff & result;\n\t\tsrp->header.masked_status = status_byte(result);\n\t\tsrp->header.msg_status = msg_byte(result);\n\t\tsrp->header.host_status = host_byte(result);\n\t\tsrp->header.driver_status = driver_byte(result);\n\t\tif ((sdp->sgdebug > 0) &&\n\t\t ((CHECK_CONDITION == srp->header.masked_status) ||\n\t\t (COMMAND_TERMINATED == srp->header.masked_status)))\n\t\t\t__scsi_print_sense(sdp->device, __func__, sense,\n\t\t\t\t\t SCSI_SENSE_BUFFERSIZE);", "\t\t/* Following if statement is a patch supplied by Eric Youngdale */\n\t\tif (driver_byte(result) != 0\n\t\t && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr)\n\t\t && !scsi_sense_is_deferred(&sshdr)\n\t\t && sshdr.sense_key == UNIT_ATTENTION\n\t\t && sdp->device->removable) {\n\t\t\t/* Detected possible disc change. Set the bit - this */\n\t\t\t/* may be used if there are filesystems using this device */\n\t\t\tsdp->device->changed = 1;\n\t\t}\n\t}\n\t/* Rely on write phase to clean out srp status values, so no \"else\" */", "\t/*\n\t * Free the request as soon as it is complete so that its resources\n\t * can be reused without waiting for userspace to read() the\n\t * result. But keep the associated bio (if any) around until\n\t * blk_rq_unmap_user() can be called from user context.\n\t */\n\tsrp->rq = NULL;\n\tif (rq->cmd != rq->__cmd)\n\t\tkfree(rq->cmd);\n\t__blk_put_request(rq->q, rq);", "\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tif (unlikely(srp->orphan)) {\n\t\tif (sfp->keep_orphan)\n\t\t\tsrp->sg_io_owned = 0;\n\t\telse\n\t\t\tdone = 0;\n\t}\n\tsrp->done = done;\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);", "\tif (likely(done)) {\n\t\t/* Now wake up any sg_read() that is waiting for this\n\t\t * packet.\n\t\t */\n\t\twake_up_interruptible(&sfp->read_wait);\n\t\tkill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN);\n\t\tkref_put(&sfp->f_ref, sg_remove_sfp);\n\t} else {\n\t\tINIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext);\n\t\tschedule_work(&srp->ew.work);\n\t}\n}", "static const struct file_operations sg_fops = {\n\t.owner = THIS_MODULE,\n\t.read = sg_read,\n\t.write = sg_write,\n\t.poll = sg_poll,\n\t.unlocked_ioctl = sg_ioctl,\n#ifdef CONFIG_COMPAT\n\t.compat_ioctl = sg_compat_ioctl,\n#endif\n\t.open = sg_open,\n\t.mmap = sg_mmap,\n\t.release = sg_release,\n\t.fasync = sg_fasync,\n\t.llseek = no_llseek,\n};", "static struct class *sg_sysfs_class;", "static int sg_sysfs_valid = 0;", "static Sg_device *\nsg_alloc(struct gendisk *disk, struct scsi_device *scsidp)\n{\n\tstruct request_queue *q = scsidp->request_queue;\n\tSg_device *sdp;\n\tunsigned long iflags;\n\tint error;\n\tu32 k;", "\tsdp = kzalloc(sizeof(Sg_device), GFP_KERNEL);\n\tif (!sdp) {\n\t\tsdev_printk(KERN_WARNING, scsidp, \"%s: kmalloc Sg_device \"\n\t\t\t \"failure\\n\", __func__);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}", "\tidr_preload(GFP_KERNEL);\n\twrite_lock_irqsave(&sg_index_lock, iflags);", "\terror = idr_alloc(&sg_index_idr, sdp, 0, SG_MAX_DEVS, GFP_NOWAIT);\n\tif (error < 0) {\n\t\tif (error == -ENOSPC) {\n\t\t\tsdev_printk(KERN_WARNING, scsidp,\n\t\t\t\t \"Unable to attach sg device type=%d, minor number exceeds %d\\n\",\n\t\t\t\t scsidp->type, SG_MAX_DEVS - 1);\n\t\t\terror = -ENODEV;\n\t\t} else {\n\t\t\tsdev_printk(KERN_WARNING, scsidp, \"%s: idr \"\n\t\t\t\t \"allocation Sg_device failure: %d\\n\",\n\t\t\t\t __func__, error);\n\t\t}\n\t\tgoto out_unlock;\n\t}\n\tk = error;", "\tSCSI_LOG_TIMEOUT(3, sdev_printk(KERN_INFO, scsidp,\n\t\t\t\t\t\"sg_alloc: dev=%d \\n\", k));\n\tsprintf(disk->disk_name, \"sg%d\", k);\n\tdisk->first_minor = k;\n\tsdp->disk = disk;\n\tsdp->device = scsidp;\n\tmutex_init(&sdp->open_rel_lock);\n\tINIT_LIST_HEAD(&sdp->sfds);\n\tinit_waitqueue_head(&sdp->open_wait);\n\tatomic_set(&sdp->detaching, 0);\n\trwlock_init(&sdp->sfd_lock);\n\tsdp->sg_tablesize = queue_max_segments(q);\n\tsdp->index = k;\n\tkref_init(&sdp->d_ref);\n\terror = 0;", "out_unlock:\n\twrite_unlock_irqrestore(&sg_index_lock, iflags);\n\tidr_preload_end();", "\tif (error) {\n\t\tkfree(sdp);\n\t\treturn ERR_PTR(error);\n\t}\n\treturn sdp;\n}", "static int\nsg_add_device(struct device *cl_dev, struct class_interface *cl_intf)\n{\n\tstruct scsi_device *scsidp = to_scsi_device(cl_dev->parent);\n\tstruct gendisk *disk;\n\tSg_device *sdp = NULL;\n\tstruct cdev * cdev = NULL;\n\tint error;\n\tunsigned long iflags;", "\tdisk = alloc_disk(1);\n\tif (!disk) {\n\t\tpr_warn(\"%s: alloc_disk failed\\n\", __func__);\n\t\treturn -ENOMEM;\n\t}\n\tdisk->major = SCSI_GENERIC_MAJOR;", "\terror = -ENOMEM;\n\tcdev = cdev_alloc();\n\tif (!cdev) {\n\t\tpr_warn(\"%s: cdev_alloc failed\\n\", __func__);\n\t\tgoto out;\n\t}\n\tcdev->owner = THIS_MODULE;\n\tcdev->ops = &sg_fops;", "\tsdp = sg_alloc(disk, scsidp);\n\tif (IS_ERR(sdp)) {\n\t\tpr_warn(\"%s: sg_alloc failed\\n\", __func__);\n\t\terror = PTR_ERR(sdp);\n\t\tgoto out;\n\t}", "\terror = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1);\n\tif (error)\n\t\tgoto cdev_add_err;", "\tsdp->cdev = cdev;\n\tif (sg_sysfs_valid) {\n\t\tstruct device *sg_class_member;", "\t\tsg_class_member = device_create(sg_sysfs_class, cl_dev->parent,\n\t\t\t\t\t\tMKDEV(SCSI_GENERIC_MAJOR,\n\t\t\t\t\t\t sdp->index),\n\t\t\t\t\t\tsdp, \"%s\", disk->disk_name);\n\t\tif (IS_ERR(sg_class_member)) {\n\t\t\tpr_err(\"%s: device_create failed\\n\", __func__);\n\t\t\terror = PTR_ERR(sg_class_member);\n\t\t\tgoto cdev_add_err;\n\t\t}\n\t\terror = sysfs_create_link(&scsidp->sdev_gendev.kobj,\n\t\t\t\t\t &sg_class_member->kobj, \"generic\");\n\t\tif (error)\n\t\t\tpr_err(\"%s: unable to make symlink 'generic' back \"\n\t\t\t \"to sg%d\\n\", __func__, sdp->index);\n\t} else\n\t\tpr_warn(\"%s: sg_sys Invalid\\n\", __func__);", "\tsdev_printk(KERN_NOTICE, scsidp, \"Attached scsi generic sg%d \"\n\t\t \"type %d\\n\", sdp->index, scsidp->type);", "\tdev_set_drvdata(cl_dev, sdp);", "\treturn 0;", "cdev_add_err:\n\twrite_lock_irqsave(&sg_index_lock, iflags);\n\tidr_remove(&sg_index_idr, sdp->index);\n\twrite_unlock_irqrestore(&sg_index_lock, iflags);\n\tkfree(sdp);", "out:\n\tput_disk(disk);\n\tif (cdev)\n\t\tcdev_del(cdev);\n\treturn error;\n}", "static void\nsg_device_destroy(struct kref *kref)\n{\n\tstruct sg_device *sdp = container_of(kref, struct sg_device, d_ref);\n\tunsigned long flags;", "\t/* CAUTION! Note that the device can still be found via idr_find()\n\t * even though the refcount is 0. Therefore, do idr_remove() BEFORE\n\t * any other cleanup.\n\t */", "\twrite_lock_irqsave(&sg_index_lock, flags);\n\tidr_remove(&sg_index_idr, sdp->index);\n\twrite_unlock_irqrestore(&sg_index_lock, flags);", "\tSCSI_LOG_TIMEOUT(3,\n\t\tsg_printk(KERN_INFO, sdp, \"sg_device_destroy\\n\"));", "\tput_disk(sdp->disk);\n\tkfree(sdp);\n}", "static void\nsg_remove_device(struct device *cl_dev, struct class_interface *cl_intf)\n{\n\tstruct scsi_device *scsidp = to_scsi_device(cl_dev->parent);\n\tSg_device *sdp = dev_get_drvdata(cl_dev);\n\tunsigned long iflags;\n\tSg_fd *sfp;\n\tint val;", "\tif (!sdp)\n\t\treturn;\n\t/* want sdp->detaching non-zero as soon as possible */\n\tval = atomic_inc_return(&sdp->detaching);\n\tif (val > 1)\n\t\treturn; /* only want to do following once per device */", "\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"%s\\n\", __func__));", "\tread_lock_irqsave(&sdp->sfd_lock, iflags);\n\tlist_for_each_entry(sfp, &sdp->sfds, sfd_siblings) {\n\t\twake_up_interruptible_all(&sfp->read_wait);\n\t\tkill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP);\n\t}\n\twake_up_interruptible_all(&sdp->open_wait);\n\tread_unlock_irqrestore(&sdp->sfd_lock, iflags);", "\tsysfs_remove_link(&scsidp->sdev_gendev.kobj, \"generic\");\n\tdevice_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));\n\tcdev_del(sdp->cdev);\n\tsdp->cdev = NULL;", "\tkref_put(&sdp->d_ref, sg_device_destroy);\n}", "module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);\nmodule_param_named(def_reserved_size, def_reserved_size, int,\n\t\t S_IRUGO | S_IWUSR);\nmodule_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);", "MODULE_AUTHOR(\"Douglas Gilbert\");\nMODULE_DESCRIPTION(\"SCSI generic (sg) driver\");\nMODULE_LICENSE(\"GPL\");\nMODULE_VERSION(SG_VERSION_STR);\nMODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);", "MODULE_PARM_DESC(scatter_elem_sz, \"scatter gather element \"\n \"size (default: max(SG_SCATTER_SZ, PAGE_SIZE))\");\nMODULE_PARM_DESC(def_reserved_size, \"size of buffer reserved for each fd\");\nMODULE_PARM_DESC(allow_dio, \"allow direct I/O (default: 0 (disallow))\");", "static int __init\ninit_sg(void)\n{\n\tint rc;", "\tif (scatter_elem_sz < PAGE_SIZE) {\n\t\tscatter_elem_sz = PAGE_SIZE;\n\t\tscatter_elem_sz_prev = scatter_elem_sz;\n\t}\n\tif (def_reserved_size >= 0)\n\t\tsg_big_buff = def_reserved_size;\n\telse\n\t\tdef_reserved_size = sg_big_buff;", "\trc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), \n\t\t\t\t SG_MAX_DEVS, \"sg\");\n\tif (rc)\n\t\treturn rc;\n sg_sysfs_class = class_create(THIS_MODULE, \"scsi_generic\");\n if ( IS_ERR(sg_sysfs_class) ) {\n\t\trc = PTR_ERR(sg_sysfs_class);\n\t\tgoto err_out;\n }\n\tsg_sysfs_valid = 1;\n\trc = scsi_register_interface(&sg_interface);\n\tif (0 == rc) {\n#ifdef CONFIG_SCSI_PROC_FS\n\t\tsg_proc_init();\n#endif\t\t\t\t/* CONFIG_SCSI_PROC_FS */\n\t\treturn 0;\n\t}\n\tclass_destroy(sg_sysfs_class);\nerr_out:\n\tunregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);\n\treturn rc;\n}", "static void __exit\nexit_sg(void)\n{\n#ifdef CONFIG_SCSI_PROC_FS\n\tsg_proc_cleanup();\n#endif\t\t\t\t/* CONFIG_SCSI_PROC_FS */\n\tscsi_unregister_interface(&sg_interface);\n\tclass_destroy(sg_sysfs_class);\n\tsg_sysfs_valid = 0;\n\tunregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),\n\t\t\t\t SG_MAX_DEVS);\n\tidr_destroy(&sg_index_idr);\n}", "static int\nsg_start_req(Sg_request *srp, unsigned char *cmd)\n{\n\tint res;\n\tstruct request *rq;\n\tSg_fd *sfp = srp->parentfp;\n\tsg_io_hdr_t *hp = &srp->header;\n\tint dxfer_len = (int) hp->dxfer_len;\n\tint dxfer_dir = hp->dxfer_direction;\n\tunsigned int iov_count = hp->iovec_count;\n\tSg_scatter_hold *req_schp = &srp->data;\n\tSg_scatter_hold *rsv_schp = &sfp->reserve;\n\tstruct request_queue *q = sfp->parentdp->device->request_queue;\n\tstruct rq_map_data *md, map_data;\n\tint rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;\n\tunsigned char *long_cmdp = NULL;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_start_req: dxfer_len=%d\\n\",\n\t\t\t\t dxfer_len));", "\tif (hp->cmd_len > BLK_MAX_CDB) {\n\t\tlong_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);\n\t\tif (!long_cmdp)\n\t\t\treturn -ENOMEM;\n\t}", "\t/*\n\t * NOTE\n\t *\n\t * With scsi-mq enabled, there are a fixed number of preallocated\n\t * requests equal in number to shost->can_queue. If all of the\n\t * preallocated requests are already in use, then using GFP_ATOMIC with\n\t * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL\n\t * will cause blk_get_request() to sleep until an active command\n\t * completes, freeing up a request. Neither option is ideal, but\n\t * GFP_KERNEL is the better choice to prevent userspace from getting an\n\t * unexpected EWOULDBLOCK.\n\t *\n\t * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually\n\t * does not sleep except under memory pressure.\n\t */\n\trq = blk_get_request(q, rw, GFP_KERNEL);\n\tif (IS_ERR(rq)) {\n\t\tkfree(long_cmdp);\n\t\treturn PTR_ERR(rq);\n\t}", "\tblk_rq_set_block_pc(rq);", "\tif (hp->cmd_len > BLK_MAX_CDB)\n\t\trq->cmd = long_cmdp;\n\tmemcpy(rq->cmd, cmd, hp->cmd_len);\n\trq->cmd_len = hp->cmd_len;", "\tsrp->rq = rq;\n\trq->end_io_data = srp;\n\trq->sense = srp->sense_b;\n\trq->retries = SG_DEFAULT_RETRIES;", "\tif ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))\n\t\treturn 0;", "\tif (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&\n\t dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&\n\t !sfp->parentdp->device->host->unchecked_isa_dma &&\n\t blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))\n\t\tmd = NULL;\n\telse\n\t\tmd = &map_data;", "\tif (md) {\n\t\tif (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)\n\t\t\tsg_link_reserve(sfp, srp, dxfer_len);\n\t\telse {\n\t\t\tres = sg_build_indirect(req_schp, sfp, dxfer_len);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t}", "\t\tmd->pages = req_schp->pages;\n\t\tmd->page_order = req_schp->page_order;\n\t\tmd->nr_entries = req_schp->k_use_sg;\n\t\tmd->offset = 0;\n\t\tmd->null_mapped = hp->dxferp ? 0 : 1;\n\t\tif (dxfer_dir == SG_DXFER_TO_FROM_DEV)\n\t\t\tmd->from_user = 1;\n\t\telse\n\t\t\tmd->from_user = 0;\n\t}", "", "\n\tif (iov_count) {\n\t\tint size = sizeof(struct iovec) * iov_count;\n\t\tstruct iovec *iov;\n\t\tstruct iov_iter i;", "\t\tiov = memdup_user(hp->dxferp, size);\n\t\tif (IS_ERR(iov))\n\t\t\treturn PTR_ERR(iov);", "\t\tiov_iter_init(&i, rw, iov, iov_count,\n\t\t\t min_t(size_t, hp->dxfer_len,\n\t\t\t\t iov_length(iov, iov_count)));", "\t\tres = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);\n\t\tkfree(iov);\n\t} else\n\t\tres = blk_rq_map_user(q, rq, md, hp->dxferp,\n\t\t\t\t hp->dxfer_len, GFP_ATOMIC);", "\tif (!res) {\n\t\tsrp->bio = rq->bio;", "\t\tif (!md) {\n\t\t\treq_schp->dio_in_use = 1;\n\t\t\thp->info |= SG_INFO_DIRECT_IO;\n\t\t}\n\t}\n\treturn res;\n}", "static int\nsg_finish_rem_req(Sg_request *srp)\n{\n\tint ret = 0;", "\tSg_fd *sfp = srp->parentfp;\n\tSg_scatter_hold *req_schp = &srp->data;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_finish_rem_req: res_used=%d\\n\",\n\t\t\t\t (int) srp->res_used));\n\tif (srp->bio)\n\t\tret = blk_rq_unmap_user(srp->bio);", "\tif (srp->rq) {\n\t\tif (srp->rq->cmd != srp->rq->__cmd)\n\t\t\tkfree(srp->rq->cmd);\n\t\tblk_put_request(srp->rq);\n\t}", "\tif (srp->res_used)\n\t\tsg_unlink_reserve(sfp, srp);\n\telse\n\t\tsg_remove_scat(sfp, req_schp);", "\tsg_remove_request(sfp, srp);", "\treturn ret;\n}", "static int\nsg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)\n{\n\tint sg_bufflen = tablesize * sizeof(struct page *);\n\tgfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;", "\tschp->pages = kzalloc(sg_bufflen, gfp_flags);\n\tif (!schp->pages)\n\t\treturn -ENOMEM;\n\tschp->sglist_len = sg_bufflen;\n\treturn tablesize;\t/* number of scat_gath elements allocated */\n}", "static int\nsg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)\n{\n\tint ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;\n\tint sg_tablesize = sfp->parentdp->sg_tablesize;\n\tint blk_size = buff_size, order;\n\tgfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;", "\tif (blk_size < 0)\n\t\treturn -EFAULT;\n\tif (0 == blk_size)\n\t\t++blk_size;\t/* don't know why */\n\t/* round request up to next highest SG_SECTOR_SZ byte boundary */\n\tblk_size = ALIGN(blk_size, SG_SECTOR_SZ);\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\"sg_build_indirect: buff_size=%d, blk_size=%d\\n\",\n\t\tbuff_size, blk_size));", "\t/* N.B. ret_sz carried into this block ... */\n\tmx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);\n\tif (mx_sc_elems < 0)\n\t\treturn mx_sc_elems;\t/* most likely -ENOMEM */", "\tnum = scatter_elem_sz;\n\tif (unlikely(num != scatter_elem_sz_prev)) {\n\t\tif (num < PAGE_SIZE) {\n\t\t\tscatter_elem_sz = PAGE_SIZE;\n\t\t\tscatter_elem_sz_prev = PAGE_SIZE;\n\t\t} else\n\t\t\tscatter_elem_sz_prev = num;\n\t}", "\tif (sfp->low_dma)\n\t\tgfp_mask |= GFP_DMA;", "\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))\n\t\tgfp_mask |= __GFP_ZERO;", "\torder = get_order(num);\nretry:\n\tret_sz = 1 << (PAGE_SHIFT + order);", "\tfor (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;\n\t k++, rem_sz -= ret_sz) {", "\t\tnum = (rem_sz > scatter_elem_sz_prev) ?\n\t\t\tscatter_elem_sz_prev : rem_sz;", "\t\tschp->pages[k] = alloc_pages(gfp_mask, order);\n\t\tif (!schp->pages[k])\n\t\t\tgoto out;", "\t\tif (num == scatter_elem_sz_prev) {\n\t\t\tif (unlikely(ret_sz > scatter_elem_sz_prev)) {\n\t\t\t\tscatter_elem_sz = ret_sz;\n\t\t\t\tscatter_elem_sz_prev = ret_sz;\n\t\t\t}\n\t\t}", "\t\tSCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_build_indirect: k=%d, num=%d, ret_sz=%d\\n\",\n\t\t\t\t k, num, ret_sz));\n\t}\t\t/* end of for loop */", "\tschp->page_order = order;\n\tschp->k_use_sg = k;\n\tSCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_build_indirect: k_use_sg=%d, rem_sz=%d\\n\",\n\t\t\t k, rem_sz));", "\tschp->bufflen = blk_size;\n\tif (rem_sz > 0)\t/* must have failed */\n\t\treturn -ENOMEM;\n\treturn 0;\nout:\n\tfor (i = 0; i < k; i++)\n\t\t__free_pages(schp->pages[i], order);", "\tif (--order >= 0)\n\t\tgoto retry;", "\treturn -ENOMEM;\n}", "static void\nsg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)\n{\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_remove_scat: k_use_sg=%d\\n\", schp->k_use_sg));\n\tif (schp->pages && schp->sglist_len > 0) {\n\t\tif (!schp->dio_in_use) {\n\t\t\tint k;", "\t\t\tfor (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {\n\t\t\t\tSCSI_LOG_TIMEOUT(5,\n\t\t\t\t\tsg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t\t\"sg_remove_scat: k=%d, pg=0x%p\\n\",\n\t\t\t\t\tk, schp->pages[k]));\n\t\t\t\t__free_pages(schp->pages[k], schp->page_order);\n\t\t\t}", "\t\t\tkfree(schp->pages);\n\t\t}\n\t}\n\tmemset(schp, 0, sizeof (*schp));\n}", "static int\nsg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)\n{\n\tSg_scatter_hold *schp = &srp->data;\n\tint k, num;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,\n\t\t\t \"sg_read_oxfer: num_read_xfer=%d\\n\",\n\t\t\t num_read_xfer));\n\tif ((!outp) || (num_read_xfer <= 0))\n\t\treturn 0;", "\tnum = 1 << (PAGE_SHIFT + schp->page_order);\n\tfor (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {\n\t\tif (num > num_read_xfer) {\n\t\t\tif (__copy_to_user(outp, page_address(schp->pages[k]),\n\t\t\t\t\t num_read_xfer))\n\t\t\t\treturn -EFAULT;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tif (__copy_to_user(outp, page_address(schp->pages[k]),\n\t\t\t\t\t num))\n\t\t\t\treturn -EFAULT;\n\t\t\tnum_read_xfer -= num;\n\t\t\tif (num_read_xfer <= 0)\n\t\t\t\tbreak;\n\t\t\toutp += num;\n\t\t}\n\t}", "\treturn 0;\n}", "static void\nsg_build_reserve(Sg_fd * sfp, int req_size)\n{\n\tSg_scatter_hold *schp = &sfp->reserve;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_build_reserve: req_size=%d\\n\", req_size));\n\tdo {\n\t\tif (req_size < PAGE_SIZE)\n\t\t\treq_size = PAGE_SIZE;\n\t\tif (0 == sg_build_indirect(schp, sfp, req_size))\n\t\t\treturn;\n\t\telse\n\t\t\tsg_remove_scat(sfp, schp);\n\t\treq_size >>= 1;\t/* divide by 2 */\n\t} while (req_size > (PAGE_SIZE / 2));\n}", "static void\nsg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)\n{\n\tSg_scatter_hold *req_schp = &srp->data;\n\tSg_scatter_hold *rsv_schp = &sfp->reserve;\n\tint k, num, rem;", "\tsrp->res_used = 1;\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_link_reserve: size=%d\\n\", size));\n\trem = size;", "\tnum = 1 << (PAGE_SHIFT + rsv_schp->page_order);\n\tfor (k = 0; k < rsv_schp->k_use_sg; k++) {\n\t\tif (rem <= num) {\n\t\t\treq_schp->k_use_sg = k + 1;\n\t\t\treq_schp->sglist_len = rsv_schp->sglist_len;\n\t\t\treq_schp->pages = rsv_schp->pages;", "\t\t\treq_schp->bufflen = size;\n\t\t\treq_schp->page_order = rsv_schp->page_order;\n\t\t\tbreak;\n\t\t} else\n\t\t\trem -= num;\n\t}", "\tif (k >= rsv_schp->k_use_sg)\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_link_reserve: BAD size\\n\"));\n}", "static void\nsg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)\n{\n\tSg_scatter_hold *req_schp = &srp->data;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,\n\t\t\t\t \"sg_unlink_reserve: req->k_use_sg=%d\\n\",\n\t\t\t\t (int) req_schp->k_use_sg));\n\treq_schp->k_use_sg = 0;\n\treq_schp->bufflen = 0;\n\treq_schp->pages = NULL;\n\treq_schp->page_order = 0;\n\treq_schp->sglist_len = 0;\n\tsfp->save_scat_len = 0;\n\tsrp->res_used = 0;\n}", "static Sg_request *\nsg_get_rq_mark(Sg_fd * sfp, int pack_id)\n{\n\tSg_request *resp;\n\tunsigned long iflags;", "\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tfor (resp = sfp->headrp; resp; resp = resp->nextrp) {\n\t\t/* look for requests that are ready + not SG_IO owned */\n\t\tif ((1 == resp->done) && (!resp->sg_io_owned) &&\n\t\t ((-1 == pack_id) || (resp->header.pack_id == pack_id))) {\n\t\t\tresp->done = 2;\t/* guard against other readers */\n\t\t\tbreak;\n\t\t}\n\t}\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn resp;\n}", "/* always adds to end of list */\nstatic Sg_request *\nsg_add_request(Sg_fd * sfp)\n{\n\tint k;\n\tunsigned long iflags;\n\tSg_request *resp;\n\tSg_request *rp = sfp->req_arr;", "\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tresp = sfp->headrp;\n\tif (!resp) {\n\t\tmemset(rp, 0, sizeof (Sg_request));\n\t\trp->parentfp = sfp;\n\t\tresp = rp;\n\t\tsfp->headrp = resp;\n\t} else {\n\t\tif (0 == sfp->cmd_q)\n\t\t\tresp = NULL;\t/* command queuing disallowed */\n\t\telse {\n\t\t\tfor (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) {\n\t\t\t\tif (!rp->parentfp)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (k < SG_MAX_QUEUE) {\n\t\t\t\tmemset(rp, 0, sizeof (Sg_request));\n\t\t\t\trp->parentfp = sfp;\n\t\t\t\twhile (resp->nextrp)\n\t\t\t\t\tresp = resp->nextrp;\n\t\t\t\tresp->nextrp = rp;\n\t\t\t\tresp = rp;\n\t\t\t} else\n\t\t\t\tresp = NULL;\n\t\t}\n\t}\n\tif (resp) {\n\t\tresp->nextrp = NULL;\n\t\tresp->header.duration = jiffies_to_msecs(jiffies);\n\t}\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn resp;\n}", "/* Return of 1 for found; 0 for not found */\nstatic int\nsg_remove_request(Sg_fd * sfp, Sg_request * srp)\n{\n\tSg_request *prev_rp;\n\tSg_request *rp;\n\tunsigned long iflags;\n\tint res = 0;", "\tif ((!sfp) || (!srp) || (!sfp->headrp))\n\t\treturn res;\n\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tprev_rp = sfp->headrp;\n\tif (srp == prev_rp) {\n\t\tsfp->headrp = prev_rp->nextrp;\n\t\tprev_rp->parentfp = NULL;\n\t\tres = 1;\n\t} else {\n\t\twhile ((rp = prev_rp->nextrp)) {\n\t\t\tif (srp == rp) {\n\t\t\t\tprev_rp->nextrp = rp->nextrp;\n\t\t\t\trp->parentfp = NULL;\n\t\t\t\tres = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprev_rp = rp;\n\t\t}\n\t}\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn res;\n}", "static Sg_fd *\nsg_add_sfp(Sg_device * sdp)\n{\n\tSg_fd *sfp;\n\tunsigned long iflags;\n\tint bufflen;", "\tsfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN);\n\tif (!sfp)\n\t\treturn ERR_PTR(-ENOMEM);", "\tinit_waitqueue_head(&sfp->read_wait);\n\trwlock_init(&sfp->rq_list_lock);", "\tkref_init(&sfp->f_ref);\n\tsfp->timeout = SG_DEFAULT_TIMEOUT;\n\tsfp->timeout_user = SG_DEFAULT_TIMEOUT_USER;\n\tsfp->force_packid = SG_DEF_FORCE_PACK_ID;\n\tsfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ?\n\t sdp->device->host->unchecked_isa_dma : 1;\n\tsfp->cmd_q = SG_DEF_COMMAND_Q;\n\tsfp->keep_orphan = SG_DEF_KEEP_ORPHAN;\n\tsfp->parentdp = sdp;\n\twrite_lock_irqsave(&sdp->sfd_lock, iflags);\n\tif (atomic_read(&sdp->detaching)) {\n\t\twrite_unlock_irqrestore(&sdp->sfd_lock, iflags);\n\t\treturn ERR_PTR(-ENODEV);\n\t}\n\tlist_add_tail(&sfp->sfd_siblings, &sdp->sfds);\n\twrite_unlock_irqrestore(&sdp->sfd_lock, iflags);\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_add_sfp: sfp=0x%p\\n\", sfp));\n\tif (unlikely(sg_big_buff != def_reserved_size))\n\t\tsg_big_buff = def_reserved_size;", "\tbufflen = min_t(int, sg_big_buff,\n\t\t\tmax_sectors_bytes(sdp->device->request_queue));\n\tsg_build_reserve(sfp, bufflen);\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_add_sfp: bufflen=%d, k_use_sg=%d\\n\",\n\t\t\t\t sfp->reserve.bufflen,\n\t\t\t\t sfp->reserve.k_use_sg));", "\tkref_get(&sdp->d_ref);\n\t__module_get(THIS_MODULE);\n\treturn sfp;\n}", "static void\nsg_remove_sfp_usercontext(struct work_struct *work)\n{\n\tstruct sg_fd *sfp = container_of(work, struct sg_fd, ew.work);\n\tstruct sg_device *sdp = sfp->parentdp;", "\t/* Cleanup any responses which were never read(). */\n\twhile (sfp->headrp)\n\t\tsg_finish_rem_req(sfp->headrp);", "\tif (sfp->reserve.bufflen > 0) {\n\t\tSCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,\n\t\t\t\t\"sg_remove_sfp: bufflen=%d, k_use_sg=%d\\n\",\n\t\t\t\t(int) sfp->reserve.bufflen,\n\t\t\t\t(int) sfp->reserve.k_use_sg));\n\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t}", "\tSCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,\n\t\t\t\"sg_remove_sfp: sfp=0x%p\\n\", sfp));\n\tkfree(sfp);", "\tscsi_device_put(sdp->device);\n\tkref_put(&sdp->d_ref, sg_device_destroy);\n\tmodule_put(THIS_MODULE);\n}", "static void\nsg_remove_sfp(struct kref *kref)\n{\n\tstruct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref);\n\tstruct sg_device *sdp = sfp->parentdp;\n\tunsigned long iflags;", "\twrite_lock_irqsave(&sdp->sfd_lock, iflags);\n\tlist_del(&sfp->sfd_siblings);\n\twrite_unlock_irqrestore(&sdp->sfd_lock, iflags);", "\tINIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext);\n\tschedule_work(&sfp->ew.work);\n}", "static int\nsg_res_in_use(Sg_fd * sfp)\n{\n\tconst Sg_request *srp;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tfor (srp = sfp->headrp; srp; srp = srp->nextrp)\n\t\tif (srp->res_used)\n\t\t\tbreak;\n\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn srp ? 1 : 0;\n}", "#ifdef CONFIG_SCSI_PROC_FS\nstatic int\nsg_idr_max_id(int id, void *p, void *data)\n{\n\tint *k = data;", "\tif (*k < id)\n\t\t*k = id;", "\treturn 0;\n}", "static int\nsg_last_dev(void)\n{\n\tint k = -1;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tidr_for_each(&sg_index_idr, sg_idr_max_id, &k);\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn k + 1;\t\t/* origin 1 */\n}\n#endif", "/* must be called with sg_index_lock held */\nstatic Sg_device *sg_lookup_dev(int dev)\n{\n\treturn idr_find(&sg_index_idr, dev);\n}", "static Sg_device *\nsg_get_dev(int dev)\n{\n\tstruct sg_device *sdp;\n\tunsigned long flags;", "\tread_lock_irqsave(&sg_index_lock, flags);\n\tsdp = sg_lookup_dev(dev);\n\tif (!sdp)\n\t\tsdp = ERR_PTR(-ENXIO);\n\telse if (atomic_read(&sdp->detaching)) {\n\t\t/* If sdp->detaching, then the refcount may already be 0, in\n\t\t * which case it would be a bug to do kref_get().\n\t\t */\n\t\tsdp = ERR_PTR(-ENODEV);\n\t} else\n\t\tkref_get(&sdp->d_ref);\n\tread_unlock_irqrestore(&sg_index_lock, flags);", "\treturn sdp;\n}", "#ifdef CONFIG_SCSI_PROC_FS", "static struct proc_dir_entry *sg_proc_sgp = NULL;", "static char sg_proc_sg_dirname[] = \"scsi/sg\";", "static int sg_proc_seq_show_int(struct seq_file *s, void *v);", "static int sg_proc_single_open_adio(struct inode *inode, struct file *file);\nstatic ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer,\n\t\t\t size_t count, loff_t *off);\nstatic const struct file_operations adio_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_adio,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.write = sg_proc_write_adio,\n\t.release = single_release,\n};", "static int sg_proc_single_open_dressz(struct inode *inode, struct file *file);\nstatic ssize_t sg_proc_write_dressz(struct file *filp, \n\t\tconst char __user *buffer, size_t count, loff_t *off);\nstatic const struct file_operations dressz_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_dressz,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.write = sg_proc_write_dressz,\n\t.release = single_release,\n};", "static int sg_proc_seq_show_version(struct seq_file *s, void *v);\nstatic int sg_proc_single_open_version(struct inode *inode, struct file *file);\nstatic const struct file_operations version_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_version,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = single_release,\n};", "static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v);\nstatic int sg_proc_single_open_devhdr(struct inode *inode, struct file *file);\nstatic const struct file_operations devhdr_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_devhdr,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = single_release,\n};", "static int sg_proc_seq_show_dev(struct seq_file *s, void *v);\nstatic int sg_proc_open_dev(struct inode *inode, struct file *file);\nstatic void * dev_seq_start(struct seq_file *s, loff_t *pos);\nstatic void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos);\nstatic void dev_seq_stop(struct seq_file *s, void *v);\nstatic const struct file_operations dev_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_open_dev,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = seq_release,\n};\nstatic const struct seq_operations dev_seq_ops = {\n\t.start = dev_seq_start,\n\t.next = dev_seq_next,\n\t.stop = dev_seq_stop,\n\t.show = sg_proc_seq_show_dev,\n};", "static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v);\nstatic int sg_proc_open_devstrs(struct inode *inode, struct file *file);\nstatic const struct file_operations devstrs_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_open_devstrs,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = seq_release,\n};\nstatic const struct seq_operations devstrs_seq_ops = {\n\t.start = dev_seq_start,\n\t.next = dev_seq_next,\n\t.stop = dev_seq_stop,\n\t.show = sg_proc_seq_show_devstrs,\n};", "static int sg_proc_seq_show_debug(struct seq_file *s, void *v);\nstatic int sg_proc_open_debug(struct inode *inode, struct file *file);\nstatic const struct file_operations debug_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_open_debug,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = seq_release,\n};\nstatic const struct seq_operations debug_seq_ops = {\n\t.start = dev_seq_start,\n\t.next = dev_seq_next,\n\t.stop = dev_seq_stop,\n\t.show = sg_proc_seq_show_debug,\n};", "\nstruct sg_proc_leaf {\n\tconst char * name;\n\tconst struct file_operations * fops;\n};", "static const struct sg_proc_leaf sg_proc_leaf_arr[] = {\n\t{\"allow_dio\", &adio_fops},\n\t{\"debug\", &debug_fops},\n\t{\"def_reserved_size\", &dressz_fops},\n\t{\"device_hdr\", &devhdr_fops},\n\t{\"devices\", &dev_fops},\n\t{\"device_strs\", &devstrs_fops},\n\t{\"version\", &version_fops}\n};", "static int\nsg_proc_init(void)\n{\n\tint num_leaves = ARRAY_SIZE(sg_proc_leaf_arr);\n\tint k;", "\tsg_proc_sgp = proc_mkdir(sg_proc_sg_dirname, NULL);\n\tif (!sg_proc_sgp)\n\t\treturn 1;\n\tfor (k = 0; k < num_leaves; ++k) {\n\t\tconst struct sg_proc_leaf *leaf = &sg_proc_leaf_arr[k];\n\t\tumode_t mask = leaf->fops->write ? S_IRUGO | S_IWUSR : S_IRUGO;\n\t\tproc_create(leaf->name, mask, sg_proc_sgp, leaf->fops);\n\t}\n\treturn 0;\n}", "static void\nsg_proc_cleanup(void)\n{\n\tint k;\n\tint num_leaves = ARRAY_SIZE(sg_proc_leaf_arr);", "\tif (!sg_proc_sgp)\n\t\treturn;\n\tfor (k = 0; k < num_leaves; ++k)\n\t\tremove_proc_entry(sg_proc_leaf_arr[k].name, sg_proc_sgp);\n\tremove_proc_entry(sg_proc_sg_dirname, NULL);\n}", "\nstatic int sg_proc_seq_show_int(struct seq_file *s, void *v)\n{\n\tseq_printf(s, \"%d\\n\", *((int *)s->private));\n\treturn 0;\n}", "static int sg_proc_single_open_adio(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_int, &sg_allow_dio);\n}", "static ssize_t \nsg_proc_write_adio(struct file *filp, const char __user *buffer,\n\t\t size_t count, loff_t *off)\n{\n\tint err;\n\tunsigned long num;", "\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))\n\t\treturn -EACCES;\n\terr = kstrtoul_from_user(buffer, count, 0, &num);\n\tif (err)\n\t\treturn err;\n\tsg_allow_dio = num ? 1 : 0;\n\treturn count;\n}", "static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_int, &sg_big_buff);\n}", "static ssize_t \nsg_proc_write_dressz(struct file *filp, const char __user *buffer,\n\t\t size_t count, loff_t *off)\n{\n\tint err;\n\tunsigned long k = ULONG_MAX;", "\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))\n\t\treturn -EACCES;", "\terr = kstrtoul_from_user(buffer, count, 0, &k);\n\tif (err)\n\t\treturn err;\n\tif (k <= 1048576) {\t/* limit \"big buff\" to 1 MB */\n\t\tsg_big_buff = k;\n\t\treturn count;\n\t}\n\treturn -ERANGE;\n}", "static int sg_proc_seq_show_version(struct seq_file *s, void *v)\n{\n\tseq_printf(s, \"%d\\t%s [%s]\\n\", sg_version_num, SG_VERSION_STR,\n\t\t sg_version_date);\n\treturn 0;\n}", "static int sg_proc_single_open_version(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_version, NULL);\n}", "static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v)\n{\n\tseq_puts(s, \"host\\tchan\\tid\\tlun\\ttype\\topens\\tqdepth\\tbusy\\tonline\\n\");\n\treturn 0;\n}", "static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_devhdr, NULL);\n}", "struct sg_proc_deviter {\n\tloff_t\tindex;\n\tsize_t\tmax;\n};", "static void * dev_seq_start(struct seq_file *s, loff_t *pos)\n{\n\tstruct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL);", "\ts->private = it;\n\tif (! it)\n\t\treturn NULL;", "\tit->index = *pos;\n\tit->max = sg_last_dev();\n\tif (it->index >= it->max)\n\t\treturn NULL;\n\treturn it;\n}", "static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos)\n{\n\tstruct sg_proc_deviter * it = s->private;", "\t*pos = ++it->index;\n\treturn (it->index < it->max) ? it : NULL;\n}", "static void dev_seq_stop(struct seq_file *s, void *v)\n{\n\tkfree(s->private);\n}", "static int sg_proc_open_dev(struct inode *inode, struct file *file)\n{\n return seq_open(file, &dev_seq_ops);\n}", "static int sg_proc_seq_show_dev(struct seq_file *s, void *v)\n{\n\tstruct sg_proc_deviter * it = (struct sg_proc_deviter *) v;\n\tSg_device *sdp;\n\tstruct scsi_device *scsidp;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tsdp = it ? sg_lookup_dev(it->index) : NULL;\n\tif ((NULL == sdp) || (NULL == sdp->device) ||\n\t (atomic_read(&sdp->detaching)))\n\t\tseq_puts(s, \"-1\\t-1\\t-1\\t-1\\t-1\\t-1\\t-1\\t-1\\t-1\\n\");\n\telse {\n\t\tscsidp = sdp->device;\n\t\tseq_printf(s, \"%d\\t%d\\t%d\\t%llu\\t%d\\t%d\\t%d\\t%d\\t%d\\n\",\n\t\t\t scsidp->host->host_no, scsidp->channel,\n\t\t\t scsidp->id, scsidp->lun, (int) scsidp->type,\n\t\t\t 1,\n\t\t\t (int) scsidp->queue_depth,\n\t\t\t (int) atomic_read(&scsidp->device_busy),\n\t\t\t (int) scsi_device_online(scsidp));\n\t}\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn 0;\n}", "static int sg_proc_open_devstrs(struct inode *inode, struct file *file)\n{\n return seq_open(file, &devstrs_seq_ops);\n}", "static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v)\n{\n\tstruct sg_proc_deviter * it = (struct sg_proc_deviter *) v;\n\tSg_device *sdp;\n\tstruct scsi_device *scsidp;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tsdp = it ? sg_lookup_dev(it->index) : NULL;\n\tscsidp = sdp ? sdp->device : NULL;\n\tif (sdp && scsidp && (!atomic_read(&sdp->detaching)))\n\t\tseq_printf(s, \"%8.8s\\t%16.16s\\t%4.4s\\n\",\n\t\t\t scsidp->vendor, scsidp->model, scsidp->rev);\n\telse\n\t\tseq_puts(s, \"<no active device>\\n\");\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn 0;\n}", "/* must be called while holding sg_index_lock */\nstatic void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp)\n{\n\tint k, m, new_interface, blen, usg;\n\tSg_request *srp;\n\tSg_fd *fp;\n\tconst sg_io_hdr_t *hp;\n\tconst char * cp;\n\tunsigned int ms;", "\tk = 0;\n\tlist_for_each_entry(fp, &sdp->sfds, sfd_siblings) {\n\t\tk++;\n\t\tread_lock(&fp->rq_list_lock); /* irqs already disabled */\n\t\tseq_printf(s, \" FD(%d): timeout=%dms bufflen=%d \"\n\t\t\t \"(res)sgat=%d low_dma=%d\\n\", k,\n\t\t\t jiffies_to_msecs(fp->timeout),\n\t\t\t fp->reserve.bufflen,\n\t\t\t (int) fp->reserve.k_use_sg,\n\t\t\t (int) fp->low_dma);\n\t\tseq_printf(s, \" cmd_q=%d f_packid=%d k_orphan=%d closed=0\\n\",\n\t\t\t (int) fp->cmd_q, (int) fp->force_packid,\n\t\t\t (int) fp->keep_orphan);\n\t\tfor (m = 0, srp = fp->headrp;\n\t\t\t\tsrp != NULL;\n\t\t\t\t++m, srp = srp->nextrp) {\n\t\t\thp = &srp->header;\n\t\t\tnew_interface = (hp->interface_id == '\\0') ? 0 : 1;\n\t\t\tif (srp->res_used) {\n\t\t\t\tif (new_interface && \n\t\t\t\t (SG_FLAG_MMAP_IO & hp->flags))\n\t\t\t\t\tcp = \" mmap>> \";\n\t\t\t\telse\n\t\t\t\t\tcp = \" rb>> \";\n\t\t\t} else {\n\t\t\t\tif (SG_INFO_DIRECT_IO_MASK & hp->info)\n\t\t\t\t\tcp = \" dio>> \";\n\t\t\t\telse\n\t\t\t\t\tcp = \" \";\n\t\t\t}\n\t\t\tseq_puts(s, cp);\n\t\t\tblen = srp->data.bufflen;\n\t\t\tusg = srp->data.k_use_sg;\n\t\t\tseq_puts(s, srp->done ?\n\t\t\t\t ((1 == srp->done) ? \"rcv:\" : \"fin:\")\n\t\t\t\t : \"act:\");\n\t\t\tseq_printf(s, \" id=%d blen=%d\",\n\t\t\t\t srp->header.pack_id, blen);\n\t\t\tif (srp->done)\n\t\t\t\tseq_printf(s, \" dur=%d\", hp->duration);\n\t\t\telse {\n\t\t\t\tms = jiffies_to_msecs(jiffies);\n\t\t\t\tseq_printf(s, \" t_o/elap=%d/%d\",\n\t\t\t\t\t(new_interface ? hp->timeout :\n\t\t\t\t\t\t jiffies_to_msecs(fp->timeout)),\n\t\t\t\t\t(ms > hp->duration ? ms - hp->duration : 0));\n\t\t\t}\n\t\t\tseq_printf(s, \"ms sgat=%d op=0x%02x\\n\", usg,\n\t\t\t\t (int) srp->data.cmd_opcode);\n\t\t}\n\t\tif (0 == m)\n\t\t\tseq_puts(s, \" No requests active\\n\");\n\t\tread_unlock(&fp->rq_list_lock);\n\t}\n}", "static int sg_proc_open_debug(struct inode *inode, struct file *file)\n{\n return seq_open(file, &debug_seq_ops);\n}", "static int sg_proc_seq_show_debug(struct seq_file *s, void *v)\n{\n\tstruct sg_proc_deviter * it = (struct sg_proc_deviter *) v;\n\tSg_device *sdp;\n\tunsigned long iflags;", "\tif (it && (0 == it->index))\n\t\tseq_printf(s, \"max_active_device=%d def_reserved_size=%d\\n\",\n\t\t\t (int)it->max, sg_big_buff);", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tsdp = it ? sg_lookup_dev(it->index) : NULL;\n\tif (NULL == sdp)\n\t\tgoto skip;\n\tread_lock(&sdp->sfd_lock);\n\tif (!list_empty(&sdp->sfds)) {\n\t\tseq_printf(s, \" >>> device=%s \", sdp->disk->disk_name);\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\tseq_puts(s, \"detaching pending close \");\n\t\telse if (sdp->device) {\n\t\t\tstruct scsi_device *scsidp = sdp->device;", "\t\t\tseq_printf(s, \"%d:%d:%d:%llu em=%d\",\n\t\t\t\t scsidp->host->host_no,\n\t\t\t\t scsidp->channel, scsidp->id,\n\t\t\t\t scsidp->lun,\n\t\t\t\t scsidp->host->hostt->emulated);\n\t\t}\n\t\tseq_printf(s, \" sg_tablesize=%d excl=%d open_cnt=%d\\n\",\n\t\t\t sdp->sg_tablesize, sdp->exclude, sdp->open_cnt);\n\t\tsg_proc_debug_helper(s, sdp);\n\t}\n\tread_unlock(&sdp->sfd_lock);\nskip:\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn 0;\n}", "#endif\t\t\t\t/* CONFIG_SCSI_PROC_FS */", "module_init(init_sg);\nmodule_exit(exit_sg);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1745], "buggy_code_start_loc": [1745], "filenames": ["drivers/scsi/sg.c"], "fixing_code_end_loc": [1749], "fixing_code_start_loc": [1746], "message": "Integer overflow in the sg_start_req function in drivers/scsi/sg.c in the Linux kernel 2.6.x through 4.x before 4.1 allows local users to cause a denial of service or possibly have unspecified other impact via a large iov_count value in a write request.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "4884A404-34BE-4D52-B749-219701AF2BC2", "versionEndExcluding": "4.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B6B7CAD7-9D4E-4FDB-88E3-1E583210A01F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:15.04:*:*:*:*:*:*:*", "matchCriteriaId": "F38D3B7E-8429-473F-BB31-FC3583EE5A5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_desktop:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "F4BC592E-17CC-4DD4-8B2C-CFD99383649C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_server:11:sp2:*:*:ltss:*:*:*", "matchCriteriaId": "C202F75B-221A-40BB-8A0D-451335B39937", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_server:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "DD4BBD63-E038-45CE-9537-D96831E99A06", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_server:11:sp3:*:*:*:vmware:*:*", "matchCriteriaId": "0EA03350-8702-43D5-8605-5FB765A3F60B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Integer overflow in the sg_start_req function in drivers/scsi/sg.c in the Linux kernel 2.6.x through 4.x before 4.1 allows local users to cause a denial of service or possibly have unspecified other impact via a large iov_count value in a write request."}, {"lang": "es", "value": "Desbordamiento de entero en la funci\u00f3n sg_start_req en drivers/scsi/sg.c en el kernel de Linux 2.6.x hasta la versi\u00f3n 4.x en versiones anteriores a 4.1 permite a usuarios locales provocar una denegaci\u00f3n de servicio o posiblemente tener otro impacto no especificado a trav\u00e9s de un valor iov_count grande en una petici\u00f3n de escritura."}], "evaluatorComment": null, "id": "CVE-2015-5707", "lastModified": "2020-06-02T14:57:56.980", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2015-10-19T10:59:05.037", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=451a2886b6bf90e2fb378f7c46c655450fb96e81"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=fdc81f45e9f57858da6351836507fbcf1b7583ee"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-09/msg00004.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-09/msg00018.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-09/msg00021.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00026.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00027.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00028.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00029.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00030.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00031.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00032.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2015/dsa-3329"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/08/01/6"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/76145"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1033521"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2733-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2734-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2737-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2738-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2750-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2759-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2760-1"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1250030"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/451a2886b6bf90e2fb378f7c46c655450fb96e81"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/fdc81f45e9f57858da6351836507fbcf1b7583ee"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://source.android.com/security/bulletin/2017-07-01"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/451a2886b6bf90e2fb378f7c46c655450fb96e81"}, "type": "CWE-190"}
298
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * History:\n * Started: Aug 9 by Lawrence Foard (entropy@world.std.com),\n * to allow user process control of SCSI devices.\n * Development Sponsored by Killy Corp. NY NY\n *\n * Original driver (sg.c):\n * Copyright (C) 1992 Lawrence Foard\n * Version 2 and 3 extensions to driver:\n * Copyright (C) 1998 - 2014 Douglas Gilbert\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n */", "static int sg_version_num = 30536;\t/* 2 digits for each component */\n#define SG_VERSION_STR \"3.5.36\"", "/*\n * D. P. Gilbert (dgilbert@interlog.com), notes:\n * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First\n * the kernel/module needs to be built with CONFIG_SCSI_LOGGING\n * (otherwise the macros compile to empty statements).\n *\n */\n#include <linux/module.h>", "#include <linux/fs.h>\n#include <linux/kernel.h>\n#include <linux/sched.h>\n#include <linux/string.h>\n#include <linux/mm.h>\n#include <linux/errno.h>\n#include <linux/mtio.h>\n#include <linux/ioctl.h>\n#include <linux/slab.h>\n#include <linux/fcntl.h>\n#include <linux/init.h>\n#include <linux/poll.h>\n#include <linux/moduleparam.h>\n#include <linux/cdev.h>\n#include <linux/idr.h>\n#include <linux/seq_file.h>\n#include <linux/blkdev.h>\n#include <linux/delay.h>\n#include <linux/blktrace_api.h>\n#include <linux/mutex.h>\n#include <linux/atomic.h>\n#include <linux/ratelimit.h>\n#include <linux/uio.h>", "#include \"scsi.h\"\n#include <scsi/scsi_dbg.h>\n#include <scsi/scsi_host.h>\n#include <scsi/scsi_driver.h>\n#include <scsi/scsi_ioctl.h>\n#include <scsi/sg.h>", "#include \"scsi_logging.h\"", "#ifdef CONFIG_SCSI_PROC_FS\n#include <linux/proc_fs.h>\nstatic char *sg_version_date = \"20140603\";", "static int sg_proc_init(void);\nstatic void sg_proc_cleanup(void);\n#endif", "#define SG_ALLOW_DIO_DEF 0", "#define SG_MAX_DEVS 32768", "/* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type\n * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater\n * than 16 bytes are \"variable length\" whose length is a multiple of 4\n */\n#define SG_MAX_CDB_SIZE 252", "/*\n * Suppose you want to calculate the formula muldiv(x,m,d)=int(x * m / d)\n * Then when using 32 bit integers x * m may overflow during the calculation.\n * Replacing muldiv(x) by muldiv(x)=((x % d) * m) / d + int(x / d) * m\n * calculates the same, but prevents the overflow when both m and d\n * are \"small\" numbers (like HZ and USER_HZ).\n * Of course an overflow is inavoidable if the result of muldiv doesn't fit\n * in 32 bits.\n */\n#define MULDIV(X,MUL,DIV) ((((X % DIV) * MUL) / DIV) + ((X / DIV) * MUL))", "#define SG_DEFAULT_TIMEOUT MULDIV(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)", "int sg_big_buff = SG_DEF_RESERVED_SIZE;\n/* N.B. This variable is readable and writeable via\n /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer\n of this size (or less if there is not enough memory) will be reserved\n for use by this file descriptor. [Deprecated usage: this variable is also\n readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into\n the kernel (i.e. it is not a module).] */\nstatic int def_reserved_size = -1;\t/* picks up init parameter */\nstatic int sg_allow_dio = SG_ALLOW_DIO_DEF;", "static int scatter_elem_sz = SG_SCATTER_SZ;\nstatic int scatter_elem_sz_prev = SG_SCATTER_SZ;", "#define SG_SECTOR_SZ 512", "static int sg_add_device(struct device *, struct class_interface *);\nstatic void sg_remove_device(struct device *, struct class_interface *);", "static DEFINE_IDR(sg_index_idr);\nstatic DEFINE_RWLOCK(sg_index_lock);\t/* Also used to lock\n\t\t\t\t\t\t\t file descriptor list for device */", "static struct class_interface sg_interface = {\n\t.add_dev = sg_add_device,\n\t.remove_dev = sg_remove_device,\n};", "typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */\n\tunsigned short k_use_sg; /* Count of kernel scatter-gather pieces */\n\tunsigned sglist_len; /* size of malloc'd scatter-gather list ++ */\n\tunsigned bufflen;\t/* Size of (aggregate) data buffer */\n\tstruct page **pages;\n\tint page_order;\n\tchar dio_in_use;\t/* 0->indirect IO (or mmap), 1->dio */\n\tunsigned char cmd_opcode; /* first byte of command */\n} Sg_scatter_hold;", "struct sg_device;\t\t/* forward declarations */\nstruct sg_fd;", "typedef struct sg_request {\t/* SG_MAX_QUEUE requests outstanding per file */\n\tstruct sg_request *nextrp;\t/* NULL -> tail request (slist) */\n\tstruct sg_fd *parentfp;\t/* NULL -> not in use */\n\tSg_scatter_hold data;\t/* hold buffer, perhaps scatter list */\n\tsg_io_hdr_t header;\t/* scsi command+info, see <scsi/sg.h> */\n\tunsigned char sense_b[SCSI_SENSE_BUFFERSIZE];\n\tchar res_used;\t\t/* 1 -> using reserve buffer, 0 -> not ... */\n\tchar orphan;\t\t/* 1 -> drop on sight, 0 -> normal */\n\tchar sg_io_owned;\t/* 1 -> packet belongs to SG_IO */\n\t/* done protected by rq_list_lock */\n\tchar done;\t\t/* 0->before bh, 1->before read, 2->read */\n\tstruct request *rq;\n\tstruct bio *bio;\n\tstruct execute_work ew;\n} Sg_request;", "typedef struct sg_fd {\t\t/* holds the state of a file descriptor */\n\tstruct list_head sfd_siblings; /* protected by device's sfd_lock */\n\tstruct sg_device *parentdp;\t/* owning device */\n\twait_queue_head_t read_wait;\t/* queue read until command done */\n\trwlock_t rq_list_lock;\t/* protect access to list in req_arr */\n\tint timeout;\t\t/* defaults to SG_DEFAULT_TIMEOUT */\n\tint timeout_user;\t/* defaults to SG_DEFAULT_TIMEOUT_USER */\n\tSg_scatter_hold reserve;\t/* buffer held for this file descriptor */\n\tunsigned save_scat_len;\t/* original length of trunc. scat. element */\n\tSg_request *headrp;\t/* head of request slist, NULL->empty */\n\tstruct fasync_struct *async_qp;\t/* used by asynchronous notification */\n\tSg_request req_arr[SG_MAX_QUEUE];\t/* used as singly-linked list */\n\tchar low_dma;\t\t/* as in parent but possibly overridden to 1 */\n\tchar force_packid;\t/* 1 -> pack_id input to read(), 0 -> ignored */\n\tchar cmd_q;\t\t/* 1 -> allow command queuing, 0 -> don't */\n\tunsigned char next_cmd_len; /* 0: automatic, >0: use on next write() */\n\tchar keep_orphan;\t/* 0 -> drop orphan (def), 1 -> keep for read() */\n\tchar mmap_called;\t/* 0 -> mmap() never called on this fd */\n\tstruct kref f_ref;\n\tstruct execute_work ew;\n} Sg_fd;", "typedef struct sg_device { /* holds the state of each scsi generic device */\n\tstruct scsi_device *device;\n\twait_queue_head_t open_wait; /* queue open() when O_EXCL present */\n\tstruct mutex open_rel_lock; /* held when in open() or release() */\n\tint sg_tablesize;\t/* adapter's max scatter-gather table size */\n\tu32 index;\t\t/* device index number */\n\tstruct list_head sfds;\n\trwlock_t sfd_lock; /* protect access to sfd list */\n\tatomic_t detaching; /* 0->device usable, 1->device detaching */\n\tbool exclude;\t\t/* 1->open(O_EXCL) succeeded and is active */\n\tint open_cnt;\t\t/* count of opens (perhaps < num(sfds) ) */\n\tchar sgdebug;\t\t/* 0->off, 1->sense, 9->dump dev, 10-> all devs */\n\tstruct gendisk *disk;\n\tstruct cdev * cdev;\t/* char_dev [sysfs: /sys/cdev/major/sg<n>] */\n\tstruct kref d_ref;\n} Sg_device;", "/* tasklet or soft irq callback */\nstatic void sg_rq_end_io(struct request *rq, int uptodate);\nstatic int sg_start_req(Sg_request *srp, unsigned char *cmd);\nstatic int sg_finish_rem_req(Sg_request * srp);\nstatic int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);\nstatic ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count,\n\t\t\t Sg_request * srp);\nstatic ssize_t sg_new_write(Sg_fd *sfp, struct file *file,\n\t\t\tconst char __user *buf, size_t count, int blocking,\n\t\t\tint read_only, int sg_io_owned, Sg_request **o_srp);\nstatic int sg_common_write(Sg_fd * sfp, Sg_request * srp,\n\t\t\t unsigned char *cmnd, int timeout, int blocking);\nstatic int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);\nstatic void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp);\nstatic void sg_build_reserve(Sg_fd * sfp, int req_size);\nstatic void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);\nstatic void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);\nstatic Sg_fd *sg_add_sfp(Sg_device * sdp);\nstatic void sg_remove_sfp(struct kref *);\nstatic Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id);\nstatic Sg_request *sg_add_request(Sg_fd * sfp);\nstatic int sg_remove_request(Sg_fd * sfp, Sg_request * srp);\nstatic int sg_res_in_use(Sg_fd * sfp);\nstatic Sg_device *sg_get_dev(int dev);\nstatic void sg_device_destroy(struct kref *kref);", "#define SZ_SG_HEADER sizeof(struct sg_header)\n#define SZ_SG_IO_HDR sizeof(sg_io_hdr_t)\n#define SZ_SG_IOVEC sizeof(sg_iovec_t)\n#define SZ_SG_REQ_INFO sizeof(sg_req_info_t)", "#define sg_printk(prefix, sdp, fmt, a...) \\\n\tsdev_prefix_printk(prefix, (sdp)->device,\t\t\\\n\t\t\t (sdp)->disk->disk_name, fmt, ##a)", "static int sg_allow_access(struct file *filp, unsigned char *cmd)\n{\n\tstruct sg_fd *sfp = filp->private_data;", "\tif (sfp->parentdp->device->type == TYPE_SCANNER)\n\t\treturn 0;", "\treturn blk_verify_command(cmd, filp->f_mode & FMODE_WRITE);\n}", "static int\nopen_wait(Sg_device *sdp, int flags)\n{\n\tint retval = 0;", "\tif (flags & O_EXCL) {\n\t\twhile (sdp->open_cnt > 0) {\n\t\t\tmutex_unlock(&sdp->open_rel_lock);\n\t\t\tretval = wait_event_interruptible(sdp->open_wait,\n\t\t\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t\t\t !sdp->open_cnt));\n\t\t\tmutex_lock(&sdp->open_rel_lock);", "\t\t\tif (retval) /* -ERESTARTSYS */\n\t\t\t\treturn retval;\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t}\n\t} else {\n\t\twhile (sdp->exclude) {\n\t\t\tmutex_unlock(&sdp->open_rel_lock);\n\t\t\tretval = wait_event_interruptible(sdp->open_wait,\n\t\t\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t\t\t !sdp->exclude));\n\t\t\tmutex_lock(&sdp->open_rel_lock);", "\t\t\tif (retval) /* -ERESTARTSYS */\n\t\t\t\treturn retval;\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t}\n\t}", "\treturn retval;\n}", "/* Returns 0 on success, else a negated errno value */\nstatic int\nsg_open(struct inode *inode, struct file *filp)\n{\n\tint dev = iminor(inode);\n\tint flags = filp->f_flags;\n\tstruct request_queue *q;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tint retval;", "\tnonseekable_open(inode, filp);\n\tif ((flags & O_EXCL) && (O_RDONLY == (flags & O_ACCMODE)))\n\t\treturn -EPERM; /* Can't lock it with read only access */\n\tsdp = sg_get_dev(dev);\n\tif (IS_ERR(sdp))\n\t\treturn PTR_ERR(sdp);", "\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_open: flags=0x%x\\n\", flags));", "\t/* This driver's module count bumped by fops_get in <linux/fs.h> */\n\t/* Prevent the device driver from vanishing while we sleep */\n\tretval = scsi_device_get(sdp->device);\n\tif (retval)\n\t\tgoto sg_put;", "\tretval = scsi_autopm_get_device(sdp->device);\n\tif (retval)\n\t\tgoto sdp_put;", "\t/* scsi_block_when_processing_errors() may block so bypass\n\t * check if O_NONBLOCK. Permits SCSI commands to be issued\n\t * during error recovery. Tread carefully. */\n\tif (!((flags & O_NONBLOCK) ||\n\t scsi_block_when_processing_errors(sdp->device))) {\n\t\tretval = -ENXIO;\n\t\t/* we are in error recovery for this device */\n\t\tgoto error_out;\n\t}", "\tmutex_lock(&sdp->open_rel_lock);\n\tif (flags & O_NONBLOCK) {\n\t\tif (flags & O_EXCL) {\n\t\t\tif (sdp->open_cnt > 0) {\n\t\t\t\tretval = -EBUSY;\n\t\t\t\tgoto error_mutex_locked;\n\t\t\t}\n\t\t} else {\n\t\t\tif (sdp->exclude) {\n\t\t\t\tretval = -EBUSY;\n\t\t\t\tgoto error_mutex_locked;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tretval = open_wait(sdp, flags);\n\t\tif (retval) /* -ERESTARTSYS or -ENODEV */\n\t\t\tgoto error_mutex_locked;\n\t}", "\t/* N.B. at this point we are holding the open_rel_lock */\n\tif (flags & O_EXCL)\n\t\tsdp->exclude = true;", "\tif (sdp->open_cnt < 1) { /* no existing opens */\n\t\tsdp->sgdebug = 0;\n\t\tq = sdp->device->request_queue;\n\t\tsdp->sg_tablesize = queue_max_segments(q);\n\t}\n\tsfp = sg_add_sfp(sdp);\n\tif (IS_ERR(sfp)) {\n\t\tretval = PTR_ERR(sfp);\n\t\tgoto out_undo;\n\t}", "\tfilp->private_data = sfp;\n\tsdp->open_cnt++;\n\tmutex_unlock(&sdp->open_rel_lock);", "\tretval = 0;\nsg_put:\n\tkref_put(&sdp->d_ref, sg_device_destroy);\n\treturn retval;", "out_undo:\n\tif (flags & O_EXCL) {\n\t\tsdp->exclude = false; /* undo if error */\n\t\twake_up_interruptible(&sdp->open_wait);\n\t}\nerror_mutex_locked:\n\tmutex_unlock(&sdp->open_rel_lock);\nerror_out:\n\tscsi_autopm_put_device(sdp->device);\nsdp_put:\n\tscsi_device_put(sdp->device);\n\tgoto sg_put;\n}", "/* Release resources associated with a successful sg_open()\n * Returns 0 on success, else a negated errno value */\nstatic int\nsg_release(struct inode *inode, struct file *filp)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, \"sg_release\\n\"));", "\tmutex_lock(&sdp->open_rel_lock);\n\tscsi_autopm_put_device(sdp->device);\n\tkref_put(&sfp->f_ref, sg_remove_sfp);\n\tsdp->open_cnt--;", "\t/* possibly many open()s waiting on exlude clearing, start many;\n\t * only open(O_EXCL)s wait on 0==open_cnt so only start one */\n\tif (sdp->exclude) {\n\t\tsdp->exclude = false;\n\t\twake_up_interruptible_all(&sdp->open_wait);\n\t} else if (0 == sdp->open_cnt) {\n\t\twake_up_interruptible(&sdp->open_wait);\n\t}\n\tmutex_unlock(&sdp->open_rel_lock);\n\treturn 0;\n}", "static ssize_t\nsg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tint req_pack_id = -1;\n\tsg_io_hdr_t *hp;\n\tstruct sg_header *old_hdr = NULL;\n\tint retval = 0;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_read: count=%d\\n\", (int) count));", "\tif (!access_ok(VERIFY_WRITE, buf, count))\n\t\treturn -EFAULT;\n\tif (sfp->force_packid && (count >= SZ_SG_HEADER)) {\n\t\told_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);\n\t\tif (!old_hdr)\n\t\t\treturn -ENOMEM;\n\t\tif (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) {\n\t\t\tretval = -EFAULT;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (old_hdr->reply_len < 0) {\n\t\t\tif (count >= SZ_SG_IO_HDR) {\n\t\t\t\tsg_io_hdr_t *new_hdr;\n\t\t\t\tnew_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL);\n\t\t\t\tif (!new_hdr) {\n\t\t\t\t\tretval = -ENOMEM;\n\t\t\t\t\tgoto free_old_hdr;\n\t\t\t\t}\n\t\t\t\tretval =__copy_from_user\n\t\t\t\t (new_hdr, buf, SZ_SG_IO_HDR);\n\t\t\t\treq_pack_id = new_hdr->pack_id;\n\t\t\t\tkfree(new_hdr);\n\t\t\t\tif (retval) {\n\t\t\t\t\tretval = -EFAULT;\n\t\t\t\t\tgoto free_old_hdr;\n\t\t\t\t}\n\t\t\t}\n\t\t} else\n\t\t\treq_pack_id = old_hdr->pack_id;\n\t}\n\tsrp = sg_get_rq_mark(sfp, req_pack_id);\n\tif (!srp) {\t\t/* now wait on packet to arrive */\n\t\tif (atomic_read(&sdp->detaching)) {\n\t\t\tretval = -ENODEV;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (filp->f_flags & O_NONBLOCK) {\n\t\t\tretval = -EAGAIN;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tretval = wait_event_interruptible(sfp->read_wait,\n\t\t\t(atomic_read(&sdp->detaching) ||\n\t\t\t(srp = sg_get_rq_mark(sfp, req_pack_id))));\n\t\tif (atomic_read(&sdp->detaching)) {\n\t\t\tretval = -ENODEV;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tif (retval) {\n\t\t\t/* -ERESTARTSYS as signal hit process */\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t}\n\tif (srp->header.interface_id != '\\0') {\n\t\tretval = sg_new_read(sfp, buf, count, srp);\n\t\tgoto free_old_hdr;\n\t}", "\thp = &srp->header;\n\tif (old_hdr == NULL) {\n\t\told_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);\n\t\tif (! old_hdr) {\n\t\t\tretval = -ENOMEM;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t}\n\tmemset(old_hdr, 0, SZ_SG_HEADER);\n\told_hdr->reply_len = (int) hp->timeout;\n\told_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */\n\told_hdr->pack_id = hp->pack_id;\n\told_hdr->twelve_byte =\n\t ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;\n\told_hdr->target_status = hp->masked_status;\n\told_hdr->host_status = hp->host_status;\n\told_hdr->driver_status = hp->driver_status;\n\tif ((CHECK_CONDITION & hp->masked_status) ||\n\t (DRIVER_SENSE & hp->driver_status))\n\t\tmemcpy(old_hdr->sense_buffer, srp->sense_b,\n\t\t sizeof (old_hdr->sense_buffer));\n\tswitch (hp->host_status) {\n\t/* This setup of 'result' is for backward compatibility and is best\n\t ignored by the user who should use target, host + driver status */\n\tcase DID_OK:\n\tcase DID_PASSTHROUGH:\n\tcase DID_SOFT_ERROR:\n\t\told_hdr->result = 0;\n\t\tbreak;\n\tcase DID_NO_CONNECT:\n\tcase DID_BUS_BUSY:\n\tcase DID_TIME_OUT:\n\t\told_hdr->result = EBUSY;\n\t\tbreak;\n\tcase DID_BAD_TARGET:\n\tcase DID_ABORT:\n\tcase DID_PARITY:\n\tcase DID_RESET:\n\tcase DID_BAD_INTR:\n\t\told_hdr->result = EIO;\n\t\tbreak;\n\tcase DID_ERROR:\n\t\told_hdr->result = (srp->sense_b[0] == 0 && \n\t\t\t\t hp->masked_status == GOOD) ? 0 : EIO;\n\t\tbreak;\n\tdefault:\n\t\told_hdr->result = EIO;\n\t\tbreak;\n\t}", "\t/* Now copy the result back to the user buffer. */\n\tif (count >= SZ_SG_HEADER) {\n\t\tif (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {\n\t\t\tretval = -EFAULT;\n\t\t\tgoto free_old_hdr;\n\t\t}\n\t\tbuf += SZ_SG_HEADER;\n\t\tif (count > old_hdr->reply_len)\n\t\t\tcount = old_hdr->reply_len;\n\t\tif (count > SZ_SG_HEADER) {\n\t\t\tif (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {\n\t\t\t\tretval = -EFAULT;\n\t\t\t\tgoto free_old_hdr;\n\t\t\t}\n\t\t}\n\t} else\n\t\tcount = (old_hdr->result == 0) ? 0 : -EIO;\n\tsg_finish_rem_req(srp);\n\tretval = count;\nfree_old_hdr:\n\tkfree(old_hdr);\n\treturn retval;\n}", "static ssize_t\nsg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp)\n{\n\tsg_io_hdr_t *hp = &srp->header;\n\tint err = 0, err2;\n\tint len;", "\tif (count < SZ_SG_IO_HDR) {\n\t\terr = -EINVAL;\n\t\tgoto err_out;\n\t}\n\thp->sb_len_wr = 0;\n\tif ((hp->mx_sb_len > 0) && hp->sbp) {\n\t\tif ((CHECK_CONDITION & hp->masked_status) ||\n\t\t (DRIVER_SENSE & hp->driver_status)) {\n\t\t\tint sb_len = SCSI_SENSE_BUFFERSIZE;\n\t\t\tsb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len;\n\t\t\tlen = 8 + (int) srp->sense_b[7];\t/* Additional sense length field */\n\t\t\tlen = (len > sb_len) ? sb_len : len;\n\t\t\tif (copy_to_user(hp->sbp, srp->sense_b, len)) {\n\t\t\t\terr = -EFAULT;\n\t\t\t\tgoto err_out;\n\t\t\t}\n\t\t\thp->sb_len_wr = len;\n\t\t}\n\t}\n\tif (hp->masked_status || hp->host_status || hp->driver_status)\n\t\thp->info |= SG_INFO_CHECK;\n\tif (copy_to_user(buf, hp, SZ_SG_IO_HDR)) {\n\t\terr = -EFAULT;\n\t\tgoto err_out;\n\t}\nerr_out:\n\terr2 = sg_finish_rem_req(srp);\n\treturn err ? : err2 ? : count;\n}", "static ssize_t\nsg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)\n{\n\tint mxsize, cmd_size, k;\n\tint input_size, blocking;\n\tunsigned char opcode;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tstruct sg_header old_hdr;\n\tsg_io_hdr_t *hp;\n\tunsigned char cmnd[SG_MAX_CDB_SIZE];", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_write: count=%d\\n\", (int) count));\n\tif (atomic_read(&sdp->detaching))\n\t\treturn -ENODEV;\n\tif (!((filp->f_flags & O_NONBLOCK) ||\n\t scsi_block_when_processing_errors(sdp->device)))\n\t\treturn -ENXIO;", "\tif (!access_ok(VERIFY_READ, buf, count))\n\t\treturn -EFAULT;\t/* protects following copy_from_user()s + get_user()s */\n\tif (count < SZ_SG_HEADER)\n\t\treturn -EIO;\n\tif (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))\n\t\treturn -EFAULT;\n\tblocking = !(filp->f_flags & O_NONBLOCK);\n\tif (old_hdr.reply_len < 0)\n\t\treturn sg_new_write(sfp, filp, buf, count,\n\t\t\t\t blocking, 0, 0, NULL);\n\tif (count < (SZ_SG_HEADER + 6))\n\t\treturn -EIO;\t/* The minimum scsi command length is 6 bytes. */", "\tif (!(srp = sg_add_request(sfp))) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,\n\t\t\t\t\t \"sg_write: queue full\\n\"));\n\t\treturn -EDOM;\n\t}\n\tbuf += SZ_SG_HEADER;\n\t__get_user(opcode, buf);\n\tif (sfp->next_cmd_len > 0) {\n\t\tcmd_size = sfp->next_cmd_len;\n\t\tsfp->next_cmd_len = 0;\t/* reset so only this write() effected */\n\t} else {\n\t\tcmd_size = COMMAND_SIZE(opcode);\t/* based on SCSI command group */\n\t\tif ((opcode >= 0xc0) && old_hdr.twelve_byte)\n\t\t\tcmd_size = 12;\n\t}\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,\n\t\t\"sg_write: scsi opcode=0x%02x, cmd_size=%d\\n\", (int) opcode, cmd_size));\n/* Determine buffer size. */\n\tinput_size = count - cmd_size;\n\tmxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;\n\tmxsize -= SZ_SG_HEADER;\n\tinput_size -= SZ_SG_HEADER;\n\tif (input_size < 0) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EIO;\t/* User did not pass enough bytes for this command. */\n\t}\n\thp = &srp->header;\n\thp->interface_id = '\\0';\t/* indicator of old interface tunnelled */\n\thp->cmd_len = (unsigned char) cmd_size;\n\thp->iovec_count = 0;\n\thp->mx_sb_len = 0;\n\tif (input_size > 0)\n\t\thp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?\n\t\t SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;\n\telse\n\t\thp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;\n\thp->dxfer_len = mxsize;\n\tif (hp->dxfer_direction == SG_DXFER_TO_DEV)\n\t\thp->dxferp = (char __user *)buf + cmd_size;\n\telse\n\t\thp->dxferp = NULL;\n\thp->sbp = NULL;\n\thp->timeout = old_hdr.reply_len;\t/* structure abuse ... */\n\thp->flags = input_size;\t/* structure abuse ... */\n\thp->pack_id = old_hdr.pack_id;\n\thp->usr_ptr = NULL;\n\tif (__copy_from_user(cmnd, buf, cmd_size))\n\t\treturn -EFAULT;\n\t/*\n\t * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,\n\t * but is is possible that the app intended SG_DXFER_TO_DEV, because there\n\t * is a non-zero input_size, so emit a warning.\n\t */\n\tif (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {\n\t\tstatic char cmd[TASK_COMM_LEN];\n\t\tif (strcmp(current->comm, cmd)) {\n\t\t\tprintk_ratelimited(KERN_WARNING\n\t\t\t\t\t \"sg_write: data in/out %d/%d bytes \"\n\t\t\t\t\t \"for SCSI command 0x%x-- guessing \"\n\t\t\t\t\t \"data in;\\n program %s not setting \"\n\t\t\t\t\t \"count and/or reply_len properly\\n\",\n\t\t\t\t\t old_hdr.reply_len - (int)SZ_SG_HEADER,\n\t\t\t\t\t input_size, (unsigned int) cmnd[0],\n\t\t\t\t\t current->comm);\n\t\t\tstrcpy(cmd, current->comm);\n\t\t}\n\t}\n\tk = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);\n\treturn (k < 0) ? k : count;\n}", "static ssize_t\nsg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf,\n\t\t size_t count, int blocking, int read_only, int sg_io_owned,\n\t\t Sg_request **o_srp)\n{\n\tint k;\n\tSg_request *srp;\n\tsg_io_hdr_t *hp;\n\tunsigned char cmnd[SG_MAX_CDB_SIZE];\n\tint timeout;\n\tunsigned long ul_timeout;", "\tif (count < SZ_SG_IO_HDR)\n\t\treturn -EINVAL;\n\tif (!access_ok(VERIFY_READ, buf, count))\n\t\treturn -EFAULT; /* protects following copy_from_user()s + get_user()s */", "\tsfp->cmd_q = 1;\t/* when sg_io_hdr seen, set command queuing on */\n\tif (!(srp = sg_add_request(sfp))) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t\t \"sg_new_write: queue full\\n\"));\n\t\treturn -EDOM;\n\t}\n\tsrp->sg_io_owned = sg_io_owned;\n\thp = &srp->header;\n\tif (__copy_from_user(hp, buf, SZ_SG_IO_HDR)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EFAULT;\n\t}\n\tif (hp->interface_id != 'S') {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -ENOSYS;\n\t}\n\tif (hp->flags & SG_FLAG_MMAP_IO) {\n\t\tif (hp->dxfer_len > sfp->reserve.bufflen) {\n\t\t\tsg_remove_request(sfp, srp);\n\t\t\treturn -ENOMEM;\t/* MMAP_IO size must fit in reserve buffer */\n\t\t}\n\t\tif (hp->flags & SG_FLAG_DIRECT_IO) {\n\t\t\tsg_remove_request(sfp, srp);\n\t\t\treturn -EINVAL;\t/* either MMAP_IO or DIRECT_IO (not both) */\n\t\t}\n\t\tif (sg_res_in_use(sfp)) {\n\t\t\tsg_remove_request(sfp, srp);\n\t\t\treturn -EBUSY;\t/* reserve buffer already being used */\n\t\t}\n\t}\n\tul_timeout = msecs_to_jiffies(srp->header.timeout);\n\ttimeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX;\n\tif ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EMSGSIZE;\n\t}\n\tif (!access_ok(VERIFY_READ, hp->cmdp, hp->cmd_len)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EFAULT;\t/* protects following copy_from_user()s + get_user()s */\n\t}\n\tif (__copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EFAULT;\n\t}\n\tif (read_only && sg_allow_access(file, cmnd)) {\n\t\tsg_remove_request(sfp, srp);\n\t\treturn -EPERM;\n\t}\n\tk = sg_common_write(sfp, srp, cmnd, timeout, blocking);\n\tif (k < 0)\n\t\treturn k;\n\tif (o_srp)\n\t\t*o_srp = srp;\n\treturn count;\n}", "static int\nsg_common_write(Sg_fd * sfp, Sg_request * srp,\n\t\tunsigned char *cmnd, int timeout, int blocking)\n{\n\tint k, at_head;\n\tSg_device *sdp = sfp->parentdp;\n\tsg_io_hdr_t *hp = &srp->header;", "\tsrp->data.cmd_opcode = cmnd[0];\t/* hold opcode of command */\n\thp->status = 0;\n\thp->masked_status = 0;\n\thp->msg_status = 0;\n\thp->info = 0;\n\thp->host_status = 0;\n\thp->driver_status = 0;\n\thp->resid = 0;\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\\n\",\n\t\t\t(int) cmnd[0], (int) hp->cmd_len));", "\tk = sg_start_req(srp, cmnd);\n\tif (k) {\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\"sg_common_write: start_req err=%d\\n\", k));\n\t\tsg_finish_rem_req(srp);\n\t\treturn k;\t/* probably out of space --> ENOMEM */\n\t}\n\tif (atomic_read(&sdp->detaching)) {\n\t\tif (srp->bio)\n\t\t\tblk_end_request_all(srp->rq, -EIO);\n\t\tsg_finish_rem_req(srp);\n\t\treturn -ENODEV;\n\t}", "\thp->duration = jiffies_to_msecs(jiffies);\n\tif (hp->interface_id != '\\0' &&\t/* v3 (or later) interface */\n\t (SG_FLAG_Q_AT_TAIL & hp->flags))\n\t\tat_head = 0;\n\telse\n\t\tat_head = 1;", "\tsrp->rq->timeout = timeout;\n\tkref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */\n\tblk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,\n\t\t\t srp->rq, at_head, sg_rq_end_io);\n\treturn 0;\n}", "static int srp_done(Sg_fd *sfp, Sg_request *srp)\n{\n\tunsigned long flags;\n\tint ret;", "\tread_lock_irqsave(&sfp->rq_list_lock, flags);\n\tret = srp->done;\n\tread_unlock_irqrestore(&sfp->rq_list_lock, flags);\n\treturn ret;\n}", "static int max_sectors_bytes(struct request_queue *q)\n{\n\tunsigned int max_sectors = queue_max_sectors(q);", "\tmax_sectors = min_t(unsigned int, max_sectors, INT_MAX >> 9);", "\treturn max_sectors << 9;\n}", "static long\nsg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)\n{\n\tvoid __user *p = (void __user *)arg;\n\tint __user *ip = p;\n\tint result, val, read_only;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tunsigned long iflags;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;", "\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_ioctl: cmd=0x%x\\n\", (int) cmd_in));\n\tread_only = (O_RDWR != (filp->f_flags & O_ACCMODE));", "\tswitch (cmd_in) {\n\tcase SG_IO:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tif (!scsi_block_when_processing_errors(sdp->device))\n\t\t\treturn -ENXIO;\n\t\tif (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR))\n\t\t\treturn -EFAULT;\n\t\tresult = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR,\n\t\t\t\t 1, read_only, 1, &srp);\n\t\tif (result < 0)\n\t\t\treturn result;\n\t\tresult = wait_event_interruptible(sfp->read_wait,\n\t\t\t(srp_done(sfp, srp) || atomic_read(&sdp->detaching)));\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\twrite_lock_irq(&sfp->rq_list_lock);\n\t\tif (srp->done) {\n\t\t\tsrp->done = 2;\n\t\t\twrite_unlock_irq(&sfp->rq_list_lock);\n\t\t\tresult = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp);\n\t\t\treturn (result < 0) ? result : 0;\n\t\t}\n\t\tsrp->orphan = 1;\n\t\twrite_unlock_irq(&sfp->rq_list_lock);\n\t\treturn result;\t/* -ERESTARTSYS because signal hit process */\n\tcase SG_SET_TIMEOUT:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tif (val < 0)\n\t\t\treturn -EIO;\n\t\tif (val >= MULDIV (INT_MAX, USER_HZ, HZ))\n\t\t val = MULDIV (INT_MAX, USER_HZ, HZ);\n\t\tsfp->timeout_user = val;\n\t\tsfp->timeout = MULDIV (val, HZ, USER_HZ);", "\t\treturn 0;\n\tcase SG_GET_TIMEOUT:\t/* N.B. User receives timeout as return value */\n\t\t\t\t/* strange ..., for backward compatibility */\n\t\treturn sfp->timeout_user;\n\tcase SG_SET_FORCE_LOW_DMA:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tif (val) {\n\t\t\tsfp->low_dma = 1;\n\t\t\tif ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) {\n\t\t\t\tval = (int) sfp->reserve.bufflen;\n\t\t\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t\t\t\tsg_build_reserve(sfp, val);\n\t\t\t}\n\t\t} else {\n\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t\tsfp->low_dma = sdp->device->host->unchecked_isa_dma;\n\t\t}\n\t\treturn 0;\n\tcase SG_GET_LOW_DMA:\n\t\treturn put_user((int) sfp->low_dma, ip);\n\tcase SG_GET_SCSI_ID:\n\t\tif (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t)))\n\t\t\treturn -EFAULT;\n\t\telse {\n\t\t\tsg_scsi_id_t __user *sg_idp = p;", "\t\t\tif (atomic_read(&sdp->detaching))\n\t\t\t\treturn -ENODEV;\n\t\t\t__put_user((int) sdp->device->host->host_no,\n\t\t\t\t &sg_idp->host_no);\n\t\t\t__put_user((int) sdp->device->channel,\n\t\t\t\t &sg_idp->channel);\n\t\t\t__put_user((int) sdp->device->id, &sg_idp->scsi_id);\n\t\t\t__put_user((int) sdp->device->lun, &sg_idp->lun);\n\t\t\t__put_user((int) sdp->device->type, &sg_idp->scsi_type);\n\t\t\t__put_user((short) sdp->device->host->cmd_per_lun,\n\t\t\t\t &sg_idp->h_cmd_per_lun);\n\t\t\t__put_user((short) sdp->device->queue_depth,\n\t\t\t\t &sg_idp->d_queue_depth);\n\t\t\t__put_user(0, &sg_idp->unused[0]);\n\t\t\t__put_user(0, &sg_idp->unused[1]);\n\t\t\treturn 0;\n\t\t}\n\tcase SG_SET_FORCE_PACK_ID:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->force_packid = val ? 1 : 0;\n\t\treturn 0;\n\tcase SG_GET_PACK_ID:\n\t\tif (!access_ok(VERIFY_WRITE, ip, sizeof (int)))\n\t\t\treturn -EFAULT;\n\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\tfor (srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t\tif ((1 == srp->done) && (!srp->sg_io_owned)) {\n\t\t\t\tread_unlock_irqrestore(&sfp->rq_list_lock,\n\t\t\t\t\t\t iflags);\n\t\t\t\t__put_user(srp->header.pack_id, ip);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\t__put_user(-1, ip);\n\t\treturn 0;\n\tcase SG_GET_NUM_WAITING:\n\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\tfor (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t\tif ((1 == srp->done) && (!srp->sg_io_owned))\n\t\t\t\t++val;\n\t\t}\n\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\treturn put_user(val, ip);\n\tcase SG_GET_SG_TABLESIZE:\n\t\treturn put_user(sdp->sg_tablesize, ip);\n\tcase SG_SET_RESERVED_SIZE:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n if (val < 0)\n return -EINVAL;\n\t\tval = min_t(int, val,\n\t\t\t max_sectors_bytes(sdp->device->request_queue));\n\t\tif (val != sfp->reserve.bufflen) {\n\t\t\tif (sg_res_in_use(sfp) || sfp->mmap_called)\n\t\t\t\treturn -EBUSY;\n\t\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t\t\tsg_build_reserve(sfp, val);\n\t\t}\n\t\treturn 0;\n\tcase SG_GET_RESERVED_SIZE:\n\t\tval = min_t(int, sfp->reserve.bufflen,\n\t\t\t max_sectors_bytes(sdp->device->request_queue));\n\t\treturn put_user(val, ip);\n\tcase SG_SET_COMMAND_Q:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->cmd_q = val ? 1 : 0;\n\t\treturn 0;\n\tcase SG_GET_COMMAND_Q:\n\t\treturn put_user((int) sfp->cmd_q, ip);\n\tcase SG_SET_KEEP_ORPHAN:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->keep_orphan = val;\n\t\treturn 0;\n\tcase SG_GET_KEEP_ORPHAN:\n\t\treturn put_user((int) sfp->keep_orphan, ip);\n\tcase SG_NEXT_CMD_LEN:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsfp->next_cmd_len = (val > 0) ? val : 0;\n\t\treturn 0;\n\tcase SG_GET_VERSION_NUM:\n\t\treturn put_user(sg_version_num, ip);\n\tcase SG_GET_ACCESS_COUNT:\n\t\t/* faked - we don't have a real access count anymore */\n\t\tval = (sdp->device ? 1 : 0);\n\t\treturn put_user(val, ip);\n\tcase SG_GET_REQUEST_TABLE:\n\t\tif (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE))\n\t\t\treturn -EFAULT;\n\t\telse {\n\t\t\tsg_req_info_t *rinfo;\n\t\t\tunsigned int ms;", "\t\t\trinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE,\n\t\t\t\t\t\t\t\tGFP_KERNEL);\n\t\t\tif (!rinfo)\n\t\t\t\treturn -ENOMEM;\n\t\t\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\t\t\tfor (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE;\n\t\t\t ++val, srp = srp ? srp->nextrp : srp) {\n\t\t\t\tmemset(&rinfo[val], 0, SZ_SG_REQ_INFO);\n\t\t\t\tif (srp) {\n\t\t\t\t\trinfo[val].req_state = srp->done + 1;\n\t\t\t\t\trinfo[val].problem =\n\t\t\t\t\t srp->header.masked_status & \n\t\t\t\t\t srp->header.host_status & \n\t\t\t\t\t srp->header.driver_status;\n\t\t\t\t\tif (srp->done)\n\t\t\t\t\t\trinfo[val].duration =\n\t\t\t\t\t\t\tsrp->header.duration;\n\t\t\t\t\telse {\n\t\t\t\t\t\tms = jiffies_to_msecs(jiffies);\n\t\t\t\t\t\trinfo[val].duration =\n\t\t\t\t\t\t (ms > srp->header.duration) ?\n\t\t\t\t\t\t (ms - srp->header.duration) : 0;\n\t\t\t\t\t}\n\t\t\t\t\trinfo[val].orphan = srp->orphan;\n\t\t\t\t\trinfo[val].sg_io_owned =\n\t\t\t\t\t\t\tsrp->sg_io_owned;\n\t\t\t\t\trinfo[val].pack_id =\n\t\t\t\t\t\t\tsrp->header.pack_id;\n\t\t\t\t\trinfo[val].usr_ptr =\n\t\t\t\t\t\t\tsrp->header.usr_ptr;\n\t\t\t\t}\n\t\t\t}\n\t\t\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\t\t\tresult = __copy_to_user(p, rinfo, \n\t\t\t\t\t\tSZ_SG_REQ_INFO * SG_MAX_QUEUE);\n\t\t\tresult = result ? -EFAULT : 0;\n\t\t\tkfree(rinfo);\n\t\t\treturn result;\n\t\t}\n\tcase SG_EMULATED_HOST:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\treturn put_user(sdp->device->host->hostt->emulated, ip);\n\tcase SCSI_IOCTL_SEND_COMMAND:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tif (read_only) {\n\t\t\tunsigned char opcode = WRITE_6;\n\t\t\tScsi_Ioctl_Command __user *siocp = p;", "\t\t\tif (copy_from_user(&opcode, siocp->data, 1))\n\t\t\t\treturn -EFAULT;\n\t\t\tif (sg_allow_access(filp, &opcode))\n\t\t\t\treturn -EPERM;\n\t\t}\n\t\treturn sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p);\n\tcase SG_SET_DEBUG:\n\t\tresult = get_user(val, ip);\n\t\tif (result)\n\t\t\treturn result;\n\t\tsdp->sgdebug = (char) val;\n\t\treturn 0;\n\tcase BLKSECTGET:\n\t\treturn put_user(max_sectors_bytes(sdp->device->request_queue),\n\t\t\t\tip);\n\tcase BLKTRACESETUP:\n\t\treturn blk_trace_setup(sdp->device->request_queue,\n\t\t\t\t sdp->disk->disk_name,\n\t\t\t\t MKDEV(SCSI_GENERIC_MAJOR, sdp->index),\n\t\t\t\t NULL,\n\t\t\t\t (char *)arg);\n\tcase BLKTRACESTART:\n\t\treturn blk_trace_startstop(sdp->device->request_queue, 1);\n\tcase BLKTRACESTOP:\n\t\treturn blk_trace_startstop(sdp->device->request_queue, 0);\n\tcase BLKTRACETEARDOWN:\n\t\treturn blk_trace_remove(sdp->device->request_queue);\n\tcase SCSI_IOCTL_GET_IDLUN:\n\tcase SCSI_IOCTL_GET_BUS_NUMBER:\n\tcase SCSI_IOCTL_PROBE_HOST:\n\tcase SG_GET_TRANSFORM:\n\tcase SG_SCSI_RESET:\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\treturn -ENODEV;\n\t\tbreak;\n\tdefault:\n\t\tif (read_only)\n\t\t\treturn -EPERM;\t/* don't know so take safe approach */\n\t\tbreak;\n\t}", "\tresult = scsi_ioctl_block_when_processing_errors(sdp->device,\n\t\t\tcmd_in, filp->f_flags & O_NDELAY);\n\tif (result)\n\t\treturn result;\n\treturn scsi_ioctl(sdp->device, cmd_in, p);\n}", "#ifdef CONFIG_COMPAT\nstatic long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tstruct scsi_device *sdev;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;", "\tsdev = sdp->device;\n\tif (sdev->host->hostt->compat_ioctl) { \n\t\tint ret;", "\t\tret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg);", "\t\treturn ret;\n\t}\n\t\n\treturn -ENOIOCTLCMD;\n}\n#endif", "static unsigned int\nsg_poll(struct file *filp, poll_table * wait)\n{\n\tunsigned int res = 0;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tSg_request *srp;\n\tint count = 0;\n\tunsigned long iflags;", "\tsfp = filp->private_data;\n\tif (!sfp)\n\t\treturn POLLERR;\n\tsdp = sfp->parentdp;\n\tif (!sdp)\n\t\treturn POLLERR;\n\tpoll_wait(filp, &sfp->read_wait, wait);\n\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tfor (srp = sfp->headrp; srp; srp = srp->nextrp) {\n\t\t/* if any read waiting, flag it */\n\t\tif ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned))\n\t\t\tres = POLLIN | POLLRDNORM;\n\t\t++count;\n\t}\n\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);", "\tif (atomic_read(&sdp->detaching))\n\t\tres |= POLLHUP;\n\telse if (!sfp->cmd_q) {\n\t\tif (0 == count)\n\t\t\tres |= POLLOUT | POLLWRNORM;\n\t} else if (count < SG_MAX_QUEUE)\n\t\tres |= POLLOUT | POLLWRNORM;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_poll: res=0x%x\\n\", (int) res));\n\treturn res;\n}", "static int\nsg_fasync(int fd, struct file *filp, int mode)\n{\n\tSg_device *sdp;\n\tSg_fd *sfp;", "\tif ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))\n\t\treturn -ENXIO;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_fasync: mode=%d\\n\", mode));", "\treturn fasync_helper(fd, filp, mode, &sfp->async_qp);\n}", "static int\nsg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)\n{\n\tSg_fd *sfp;\n\tunsigned long offset, len, sa;\n\tSg_scatter_hold *rsv_schp;\n\tint k, length;", "\tif ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))\n\t\treturn VM_FAULT_SIGBUS;\n\trsv_schp = &sfp->reserve;\n\toffset = vmf->pgoff << PAGE_SHIFT;\n\tif (offset >= rsv_schp->bufflen)\n\t\treturn VM_FAULT_SIGBUS;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_vma_fault: offset=%lu, scatg=%d\\n\",\n\t\t\t\t offset, rsv_schp->k_use_sg));\n\tsa = vma->vm_start;\n\tlength = 1 << (PAGE_SHIFT + rsv_schp->page_order);\n\tfor (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {\n\t\tlen = vma->vm_end - sa;\n\t\tlen = (len < length) ? len : length;\n\t\tif (offset < len) {\n\t\t\tstruct page *page = nth_page(rsv_schp->pages[k],\n\t\t\t\t\t\t offset >> PAGE_SHIFT);\n\t\t\tget_page(page);\t/* increment page count */\n\t\t\tvmf->page = page;\n\t\t\treturn 0; /* success */\n\t\t}\n\t\tsa += len;\n\t\toffset -= len;\n\t}", "\treturn VM_FAULT_SIGBUS;\n}", "static const struct vm_operations_struct sg_mmap_vm_ops = {\n\t.fault = sg_vma_fault,\n};", "static int\nsg_mmap(struct file *filp, struct vm_area_struct *vma)\n{\n\tSg_fd *sfp;\n\tunsigned long req_sz, len, sa;\n\tSg_scatter_hold *rsv_schp;\n\tint k, length;", "\tif ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))\n\t\treturn -ENXIO;\n\treq_sz = vma->vm_end - vma->vm_start;\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_mmap starting, vm_start=%p, len=%d\\n\",\n\t\t\t\t (void *) vma->vm_start, (int) req_sz));\n\tif (vma->vm_pgoff)\n\t\treturn -EINVAL;\t/* want no offset */\n\trsv_schp = &sfp->reserve;\n\tif (req_sz > rsv_schp->bufflen)\n\t\treturn -ENOMEM;\t/* cannot map more than reserved buffer */", "\tsa = vma->vm_start;\n\tlength = 1 << (PAGE_SHIFT + rsv_schp->page_order);\n\tfor (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {\n\t\tlen = vma->vm_end - sa;\n\t\tlen = (len < length) ? len : length;\n\t\tsa += len;\n\t}", "\tsfp->mmap_called = 1;\n\tvma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;\n\tvma->vm_private_data = sfp;\n\tvma->vm_ops = &sg_mmap_vm_ops;\n\treturn 0;\n}", "static void\nsg_rq_end_io_usercontext(struct work_struct *work)\n{\n\tstruct sg_request *srp = container_of(work, struct sg_request, ew.work);\n\tstruct sg_fd *sfp = srp->parentfp;", "\tsg_finish_rem_req(srp);\n\tkref_put(&sfp->f_ref, sg_remove_sfp);\n}", "/*\n * This function is a \"bottom half\" handler that is called by the mid\n * level when a command is completed (or has failed).\n */\nstatic void\nsg_rq_end_io(struct request *rq, int uptodate)\n{\n\tstruct sg_request *srp = rq->end_io_data;\n\tSg_device *sdp;\n\tSg_fd *sfp;\n\tunsigned long iflags;\n\tunsigned int ms;\n\tchar *sense;\n\tint result, resid, done = 1;", "\tif (WARN_ON(srp->done != 0))\n\t\treturn;", "\tsfp = srp->parentfp;\n\tif (WARN_ON(sfp == NULL))\n\t\treturn;", "\tsdp = sfp->parentdp;\n\tif (unlikely(atomic_read(&sdp->detaching)))\n\t\tpr_info(\"%s: device detaching\\n\", __func__);", "\tsense = rq->sense;\n\tresult = rq->errors;\n\tresid = rq->resid_len;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_cmd_done: pack_id=%d, res=0x%x\\n\",\n\t\t\t\t srp->header.pack_id, result));\n\tsrp->header.resid = resid;\n\tms = jiffies_to_msecs(jiffies);\n\tsrp->header.duration = (ms > srp->header.duration) ?\n\t\t\t\t(ms - srp->header.duration) : 0;\n\tif (0 != result) {\n\t\tstruct scsi_sense_hdr sshdr;", "\t\tsrp->header.status = 0xff & result;\n\t\tsrp->header.masked_status = status_byte(result);\n\t\tsrp->header.msg_status = msg_byte(result);\n\t\tsrp->header.host_status = host_byte(result);\n\t\tsrp->header.driver_status = driver_byte(result);\n\t\tif ((sdp->sgdebug > 0) &&\n\t\t ((CHECK_CONDITION == srp->header.masked_status) ||\n\t\t (COMMAND_TERMINATED == srp->header.masked_status)))\n\t\t\t__scsi_print_sense(sdp->device, __func__, sense,\n\t\t\t\t\t SCSI_SENSE_BUFFERSIZE);", "\t\t/* Following if statement is a patch supplied by Eric Youngdale */\n\t\tif (driver_byte(result) != 0\n\t\t && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr)\n\t\t && !scsi_sense_is_deferred(&sshdr)\n\t\t && sshdr.sense_key == UNIT_ATTENTION\n\t\t && sdp->device->removable) {\n\t\t\t/* Detected possible disc change. Set the bit - this */\n\t\t\t/* may be used if there are filesystems using this device */\n\t\t\tsdp->device->changed = 1;\n\t\t}\n\t}\n\t/* Rely on write phase to clean out srp status values, so no \"else\" */", "\t/*\n\t * Free the request as soon as it is complete so that its resources\n\t * can be reused without waiting for userspace to read() the\n\t * result. But keep the associated bio (if any) around until\n\t * blk_rq_unmap_user() can be called from user context.\n\t */\n\tsrp->rq = NULL;\n\tif (rq->cmd != rq->__cmd)\n\t\tkfree(rq->cmd);\n\t__blk_put_request(rq->q, rq);", "\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tif (unlikely(srp->orphan)) {\n\t\tif (sfp->keep_orphan)\n\t\t\tsrp->sg_io_owned = 0;\n\t\telse\n\t\t\tdone = 0;\n\t}\n\tsrp->done = done;\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);", "\tif (likely(done)) {\n\t\t/* Now wake up any sg_read() that is waiting for this\n\t\t * packet.\n\t\t */\n\t\twake_up_interruptible(&sfp->read_wait);\n\t\tkill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN);\n\t\tkref_put(&sfp->f_ref, sg_remove_sfp);\n\t} else {\n\t\tINIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext);\n\t\tschedule_work(&srp->ew.work);\n\t}\n}", "static const struct file_operations sg_fops = {\n\t.owner = THIS_MODULE,\n\t.read = sg_read,\n\t.write = sg_write,\n\t.poll = sg_poll,\n\t.unlocked_ioctl = sg_ioctl,\n#ifdef CONFIG_COMPAT\n\t.compat_ioctl = sg_compat_ioctl,\n#endif\n\t.open = sg_open,\n\t.mmap = sg_mmap,\n\t.release = sg_release,\n\t.fasync = sg_fasync,\n\t.llseek = no_llseek,\n};", "static struct class *sg_sysfs_class;", "static int sg_sysfs_valid = 0;", "static Sg_device *\nsg_alloc(struct gendisk *disk, struct scsi_device *scsidp)\n{\n\tstruct request_queue *q = scsidp->request_queue;\n\tSg_device *sdp;\n\tunsigned long iflags;\n\tint error;\n\tu32 k;", "\tsdp = kzalloc(sizeof(Sg_device), GFP_KERNEL);\n\tif (!sdp) {\n\t\tsdev_printk(KERN_WARNING, scsidp, \"%s: kmalloc Sg_device \"\n\t\t\t \"failure\\n\", __func__);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}", "\tidr_preload(GFP_KERNEL);\n\twrite_lock_irqsave(&sg_index_lock, iflags);", "\terror = idr_alloc(&sg_index_idr, sdp, 0, SG_MAX_DEVS, GFP_NOWAIT);\n\tif (error < 0) {\n\t\tif (error == -ENOSPC) {\n\t\t\tsdev_printk(KERN_WARNING, scsidp,\n\t\t\t\t \"Unable to attach sg device type=%d, minor number exceeds %d\\n\",\n\t\t\t\t scsidp->type, SG_MAX_DEVS - 1);\n\t\t\terror = -ENODEV;\n\t\t} else {\n\t\t\tsdev_printk(KERN_WARNING, scsidp, \"%s: idr \"\n\t\t\t\t \"allocation Sg_device failure: %d\\n\",\n\t\t\t\t __func__, error);\n\t\t}\n\t\tgoto out_unlock;\n\t}\n\tk = error;", "\tSCSI_LOG_TIMEOUT(3, sdev_printk(KERN_INFO, scsidp,\n\t\t\t\t\t\"sg_alloc: dev=%d \\n\", k));\n\tsprintf(disk->disk_name, \"sg%d\", k);\n\tdisk->first_minor = k;\n\tsdp->disk = disk;\n\tsdp->device = scsidp;\n\tmutex_init(&sdp->open_rel_lock);\n\tINIT_LIST_HEAD(&sdp->sfds);\n\tinit_waitqueue_head(&sdp->open_wait);\n\tatomic_set(&sdp->detaching, 0);\n\trwlock_init(&sdp->sfd_lock);\n\tsdp->sg_tablesize = queue_max_segments(q);\n\tsdp->index = k;\n\tkref_init(&sdp->d_ref);\n\terror = 0;", "out_unlock:\n\twrite_unlock_irqrestore(&sg_index_lock, iflags);\n\tidr_preload_end();", "\tif (error) {\n\t\tkfree(sdp);\n\t\treturn ERR_PTR(error);\n\t}\n\treturn sdp;\n}", "static int\nsg_add_device(struct device *cl_dev, struct class_interface *cl_intf)\n{\n\tstruct scsi_device *scsidp = to_scsi_device(cl_dev->parent);\n\tstruct gendisk *disk;\n\tSg_device *sdp = NULL;\n\tstruct cdev * cdev = NULL;\n\tint error;\n\tunsigned long iflags;", "\tdisk = alloc_disk(1);\n\tif (!disk) {\n\t\tpr_warn(\"%s: alloc_disk failed\\n\", __func__);\n\t\treturn -ENOMEM;\n\t}\n\tdisk->major = SCSI_GENERIC_MAJOR;", "\terror = -ENOMEM;\n\tcdev = cdev_alloc();\n\tif (!cdev) {\n\t\tpr_warn(\"%s: cdev_alloc failed\\n\", __func__);\n\t\tgoto out;\n\t}\n\tcdev->owner = THIS_MODULE;\n\tcdev->ops = &sg_fops;", "\tsdp = sg_alloc(disk, scsidp);\n\tif (IS_ERR(sdp)) {\n\t\tpr_warn(\"%s: sg_alloc failed\\n\", __func__);\n\t\terror = PTR_ERR(sdp);\n\t\tgoto out;\n\t}", "\terror = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1);\n\tif (error)\n\t\tgoto cdev_add_err;", "\tsdp->cdev = cdev;\n\tif (sg_sysfs_valid) {\n\t\tstruct device *sg_class_member;", "\t\tsg_class_member = device_create(sg_sysfs_class, cl_dev->parent,\n\t\t\t\t\t\tMKDEV(SCSI_GENERIC_MAJOR,\n\t\t\t\t\t\t sdp->index),\n\t\t\t\t\t\tsdp, \"%s\", disk->disk_name);\n\t\tif (IS_ERR(sg_class_member)) {\n\t\t\tpr_err(\"%s: device_create failed\\n\", __func__);\n\t\t\terror = PTR_ERR(sg_class_member);\n\t\t\tgoto cdev_add_err;\n\t\t}\n\t\terror = sysfs_create_link(&scsidp->sdev_gendev.kobj,\n\t\t\t\t\t &sg_class_member->kobj, \"generic\");\n\t\tif (error)\n\t\t\tpr_err(\"%s: unable to make symlink 'generic' back \"\n\t\t\t \"to sg%d\\n\", __func__, sdp->index);\n\t} else\n\t\tpr_warn(\"%s: sg_sys Invalid\\n\", __func__);", "\tsdev_printk(KERN_NOTICE, scsidp, \"Attached scsi generic sg%d \"\n\t\t \"type %d\\n\", sdp->index, scsidp->type);", "\tdev_set_drvdata(cl_dev, sdp);", "\treturn 0;", "cdev_add_err:\n\twrite_lock_irqsave(&sg_index_lock, iflags);\n\tidr_remove(&sg_index_idr, sdp->index);\n\twrite_unlock_irqrestore(&sg_index_lock, iflags);\n\tkfree(sdp);", "out:\n\tput_disk(disk);\n\tif (cdev)\n\t\tcdev_del(cdev);\n\treturn error;\n}", "static void\nsg_device_destroy(struct kref *kref)\n{\n\tstruct sg_device *sdp = container_of(kref, struct sg_device, d_ref);\n\tunsigned long flags;", "\t/* CAUTION! Note that the device can still be found via idr_find()\n\t * even though the refcount is 0. Therefore, do idr_remove() BEFORE\n\t * any other cleanup.\n\t */", "\twrite_lock_irqsave(&sg_index_lock, flags);\n\tidr_remove(&sg_index_idr, sdp->index);\n\twrite_unlock_irqrestore(&sg_index_lock, flags);", "\tSCSI_LOG_TIMEOUT(3,\n\t\tsg_printk(KERN_INFO, sdp, \"sg_device_destroy\\n\"));", "\tput_disk(sdp->disk);\n\tkfree(sdp);\n}", "static void\nsg_remove_device(struct device *cl_dev, struct class_interface *cl_intf)\n{\n\tstruct scsi_device *scsidp = to_scsi_device(cl_dev->parent);\n\tSg_device *sdp = dev_get_drvdata(cl_dev);\n\tunsigned long iflags;\n\tSg_fd *sfp;\n\tint val;", "\tif (!sdp)\n\t\treturn;\n\t/* want sdp->detaching non-zero as soon as possible */\n\tval = atomic_inc_return(&sdp->detaching);\n\tif (val > 1)\n\t\treturn; /* only want to do following once per device */", "\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"%s\\n\", __func__));", "\tread_lock_irqsave(&sdp->sfd_lock, iflags);\n\tlist_for_each_entry(sfp, &sdp->sfds, sfd_siblings) {\n\t\twake_up_interruptible_all(&sfp->read_wait);\n\t\tkill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP);\n\t}\n\twake_up_interruptible_all(&sdp->open_wait);\n\tread_unlock_irqrestore(&sdp->sfd_lock, iflags);", "\tsysfs_remove_link(&scsidp->sdev_gendev.kobj, \"generic\");\n\tdevice_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));\n\tcdev_del(sdp->cdev);\n\tsdp->cdev = NULL;", "\tkref_put(&sdp->d_ref, sg_device_destroy);\n}", "module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);\nmodule_param_named(def_reserved_size, def_reserved_size, int,\n\t\t S_IRUGO | S_IWUSR);\nmodule_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);", "MODULE_AUTHOR(\"Douglas Gilbert\");\nMODULE_DESCRIPTION(\"SCSI generic (sg) driver\");\nMODULE_LICENSE(\"GPL\");\nMODULE_VERSION(SG_VERSION_STR);\nMODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);", "MODULE_PARM_DESC(scatter_elem_sz, \"scatter gather element \"\n \"size (default: max(SG_SCATTER_SZ, PAGE_SIZE))\");\nMODULE_PARM_DESC(def_reserved_size, \"size of buffer reserved for each fd\");\nMODULE_PARM_DESC(allow_dio, \"allow direct I/O (default: 0 (disallow))\");", "static int __init\ninit_sg(void)\n{\n\tint rc;", "\tif (scatter_elem_sz < PAGE_SIZE) {\n\t\tscatter_elem_sz = PAGE_SIZE;\n\t\tscatter_elem_sz_prev = scatter_elem_sz;\n\t}\n\tif (def_reserved_size >= 0)\n\t\tsg_big_buff = def_reserved_size;\n\telse\n\t\tdef_reserved_size = sg_big_buff;", "\trc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), \n\t\t\t\t SG_MAX_DEVS, \"sg\");\n\tif (rc)\n\t\treturn rc;\n sg_sysfs_class = class_create(THIS_MODULE, \"scsi_generic\");\n if ( IS_ERR(sg_sysfs_class) ) {\n\t\trc = PTR_ERR(sg_sysfs_class);\n\t\tgoto err_out;\n }\n\tsg_sysfs_valid = 1;\n\trc = scsi_register_interface(&sg_interface);\n\tif (0 == rc) {\n#ifdef CONFIG_SCSI_PROC_FS\n\t\tsg_proc_init();\n#endif\t\t\t\t/* CONFIG_SCSI_PROC_FS */\n\t\treturn 0;\n\t}\n\tclass_destroy(sg_sysfs_class);\nerr_out:\n\tunregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);\n\treturn rc;\n}", "static void __exit\nexit_sg(void)\n{\n#ifdef CONFIG_SCSI_PROC_FS\n\tsg_proc_cleanup();\n#endif\t\t\t\t/* CONFIG_SCSI_PROC_FS */\n\tscsi_unregister_interface(&sg_interface);\n\tclass_destroy(sg_sysfs_class);\n\tsg_sysfs_valid = 0;\n\tunregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),\n\t\t\t\t SG_MAX_DEVS);\n\tidr_destroy(&sg_index_idr);\n}", "static int\nsg_start_req(Sg_request *srp, unsigned char *cmd)\n{\n\tint res;\n\tstruct request *rq;\n\tSg_fd *sfp = srp->parentfp;\n\tsg_io_hdr_t *hp = &srp->header;\n\tint dxfer_len = (int) hp->dxfer_len;\n\tint dxfer_dir = hp->dxfer_direction;\n\tunsigned int iov_count = hp->iovec_count;\n\tSg_scatter_hold *req_schp = &srp->data;\n\tSg_scatter_hold *rsv_schp = &sfp->reserve;\n\tstruct request_queue *q = sfp->parentdp->device->request_queue;\n\tstruct rq_map_data *md, map_data;\n\tint rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;\n\tunsigned char *long_cmdp = NULL;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_start_req: dxfer_len=%d\\n\",\n\t\t\t\t dxfer_len));", "\tif (hp->cmd_len > BLK_MAX_CDB) {\n\t\tlong_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);\n\t\tif (!long_cmdp)\n\t\t\treturn -ENOMEM;\n\t}", "\t/*\n\t * NOTE\n\t *\n\t * With scsi-mq enabled, there are a fixed number of preallocated\n\t * requests equal in number to shost->can_queue. If all of the\n\t * preallocated requests are already in use, then using GFP_ATOMIC with\n\t * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL\n\t * will cause blk_get_request() to sleep until an active command\n\t * completes, freeing up a request. Neither option is ideal, but\n\t * GFP_KERNEL is the better choice to prevent userspace from getting an\n\t * unexpected EWOULDBLOCK.\n\t *\n\t * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually\n\t * does not sleep except under memory pressure.\n\t */\n\trq = blk_get_request(q, rw, GFP_KERNEL);\n\tif (IS_ERR(rq)) {\n\t\tkfree(long_cmdp);\n\t\treturn PTR_ERR(rq);\n\t}", "\tblk_rq_set_block_pc(rq);", "\tif (hp->cmd_len > BLK_MAX_CDB)\n\t\trq->cmd = long_cmdp;\n\tmemcpy(rq->cmd, cmd, hp->cmd_len);\n\trq->cmd_len = hp->cmd_len;", "\tsrp->rq = rq;\n\trq->end_io_data = srp;\n\trq->sense = srp->sense_b;\n\trq->retries = SG_DEFAULT_RETRIES;", "\tif ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))\n\t\treturn 0;", "\tif (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&\n\t dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&\n\t !sfp->parentdp->device->host->unchecked_isa_dma &&\n\t blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))\n\t\tmd = NULL;\n\telse\n\t\tmd = &map_data;", "\tif (md) {\n\t\tif (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)\n\t\t\tsg_link_reserve(sfp, srp, dxfer_len);\n\t\telse {\n\t\t\tres = sg_build_indirect(req_schp, sfp, dxfer_len);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t}", "\t\tmd->pages = req_schp->pages;\n\t\tmd->page_order = req_schp->page_order;\n\t\tmd->nr_entries = req_schp->k_use_sg;\n\t\tmd->offset = 0;\n\t\tmd->null_mapped = hp->dxferp ? 0 : 1;\n\t\tif (dxfer_dir == SG_DXFER_TO_FROM_DEV)\n\t\t\tmd->from_user = 1;\n\t\telse\n\t\t\tmd->from_user = 0;\n\t}", "\n\tif (unlikely(iov_count > MAX_UIOVEC))\n\t\treturn -EINVAL;", "\n\tif (iov_count) {\n\t\tint size = sizeof(struct iovec) * iov_count;\n\t\tstruct iovec *iov;\n\t\tstruct iov_iter i;", "\t\tiov = memdup_user(hp->dxferp, size);\n\t\tif (IS_ERR(iov))\n\t\t\treturn PTR_ERR(iov);", "\t\tiov_iter_init(&i, rw, iov, iov_count,\n\t\t\t min_t(size_t, hp->dxfer_len,\n\t\t\t\t iov_length(iov, iov_count)));", "\t\tres = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);\n\t\tkfree(iov);\n\t} else\n\t\tres = blk_rq_map_user(q, rq, md, hp->dxferp,\n\t\t\t\t hp->dxfer_len, GFP_ATOMIC);", "\tif (!res) {\n\t\tsrp->bio = rq->bio;", "\t\tif (!md) {\n\t\t\treq_schp->dio_in_use = 1;\n\t\t\thp->info |= SG_INFO_DIRECT_IO;\n\t\t}\n\t}\n\treturn res;\n}", "static int\nsg_finish_rem_req(Sg_request *srp)\n{\n\tint ret = 0;", "\tSg_fd *sfp = srp->parentfp;\n\tSg_scatter_hold *req_schp = &srp->data;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_finish_rem_req: res_used=%d\\n\",\n\t\t\t\t (int) srp->res_used));\n\tif (srp->bio)\n\t\tret = blk_rq_unmap_user(srp->bio);", "\tif (srp->rq) {\n\t\tif (srp->rq->cmd != srp->rq->__cmd)\n\t\t\tkfree(srp->rq->cmd);\n\t\tblk_put_request(srp->rq);\n\t}", "\tif (srp->res_used)\n\t\tsg_unlink_reserve(sfp, srp);\n\telse\n\t\tsg_remove_scat(sfp, req_schp);", "\tsg_remove_request(sfp, srp);", "\treturn ret;\n}", "static int\nsg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)\n{\n\tint sg_bufflen = tablesize * sizeof(struct page *);\n\tgfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;", "\tschp->pages = kzalloc(sg_bufflen, gfp_flags);\n\tif (!schp->pages)\n\t\treturn -ENOMEM;\n\tschp->sglist_len = sg_bufflen;\n\treturn tablesize;\t/* number of scat_gath elements allocated */\n}", "static int\nsg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)\n{\n\tint ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;\n\tint sg_tablesize = sfp->parentdp->sg_tablesize;\n\tint blk_size = buff_size, order;\n\tgfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;", "\tif (blk_size < 0)\n\t\treturn -EFAULT;\n\tif (0 == blk_size)\n\t\t++blk_size;\t/* don't know why */\n\t/* round request up to next highest SG_SECTOR_SZ byte boundary */\n\tblk_size = ALIGN(blk_size, SG_SECTOR_SZ);\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\"sg_build_indirect: buff_size=%d, blk_size=%d\\n\",\n\t\tbuff_size, blk_size));", "\t/* N.B. ret_sz carried into this block ... */\n\tmx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);\n\tif (mx_sc_elems < 0)\n\t\treturn mx_sc_elems;\t/* most likely -ENOMEM */", "\tnum = scatter_elem_sz;\n\tif (unlikely(num != scatter_elem_sz_prev)) {\n\t\tif (num < PAGE_SIZE) {\n\t\t\tscatter_elem_sz = PAGE_SIZE;\n\t\t\tscatter_elem_sz_prev = PAGE_SIZE;\n\t\t} else\n\t\t\tscatter_elem_sz_prev = num;\n\t}", "\tif (sfp->low_dma)\n\t\tgfp_mask |= GFP_DMA;", "\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))\n\t\tgfp_mask |= __GFP_ZERO;", "\torder = get_order(num);\nretry:\n\tret_sz = 1 << (PAGE_SHIFT + order);", "\tfor (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;\n\t k++, rem_sz -= ret_sz) {", "\t\tnum = (rem_sz > scatter_elem_sz_prev) ?\n\t\t\tscatter_elem_sz_prev : rem_sz;", "\t\tschp->pages[k] = alloc_pages(gfp_mask, order);\n\t\tif (!schp->pages[k])\n\t\t\tgoto out;", "\t\tif (num == scatter_elem_sz_prev) {\n\t\t\tif (unlikely(ret_sz > scatter_elem_sz_prev)) {\n\t\t\t\tscatter_elem_sz = ret_sz;\n\t\t\t\tscatter_elem_sz_prev = ret_sz;\n\t\t\t}\n\t\t}", "\t\tSCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_build_indirect: k=%d, num=%d, ret_sz=%d\\n\",\n\t\t\t\t k, num, ret_sz));\n\t}\t\t/* end of for loop */", "\tschp->page_order = order;\n\tschp->k_use_sg = k;\n\tSCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_build_indirect: k_use_sg=%d, rem_sz=%d\\n\",\n\t\t\t k, rem_sz));", "\tschp->bufflen = blk_size;\n\tif (rem_sz > 0)\t/* must have failed */\n\t\treturn -ENOMEM;\n\treturn 0;\nout:\n\tfor (i = 0; i < k; i++)\n\t\t__free_pages(schp->pages[i], order);", "\tif (--order >= 0)\n\t\tgoto retry;", "\treturn -ENOMEM;\n}", "static void\nsg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)\n{\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_remove_scat: k_use_sg=%d\\n\", schp->k_use_sg));\n\tif (schp->pages && schp->sglist_len > 0) {\n\t\tif (!schp->dio_in_use) {\n\t\t\tint k;", "\t\t\tfor (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {\n\t\t\t\tSCSI_LOG_TIMEOUT(5,\n\t\t\t\t\tsg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t\t\"sg_remove_scat: k=%d, pg=0x%p\\n\",\n\t\t\t\t\tk, schp->pages[k]));\n\t\t\t\t__free_pages(schp->pages[k], schp->page_order);\n\t\t\t}", "\t\t\tkfree(schp->pages);\n\t\t}\n\t}\n\tmemset(schp, 0, sizeof (*schp));\n}", "static int\nsg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)\n{\n\tSg_scatter_hold *schp = &srp->data;\n\tint k, num;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,\n\t\t\t \"sg_read_oxfer: num_read_xfer=%d\\n\",\n\t\t\t num_read_xfer));\n\tif ((!outp) || (num_read_xfer <= 0))\n\t\treturn 0;", "\tnum = 1 << (PAGE_SHIFT + schp->page_order);\n\tfor (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {\n\t\tif (num > num_read_xfer) {\n\t\t\tif (__copy_to_user(outp, page_address(schp->pages[k]),\n\t\t\t\t\t num_read_xfer))\n\t\t\t\treturn -EFAULT;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tif (__copy_to_user(outp, page_address(schp->pages[k]),\n\t\t\t\t\t num))\n\t\t\t\treturn -EFAULT;\n\t\t\tnum_read_xfer -= num;\n\t\t\tif (num_read_xfer <= 0)\n\t\t\t\tbreak;\n\t\t\toutp += num;\n\t\t}\n\t}", "\treturn 0;\n}", "static void\nsg_build_reserve(Sg_fd * sfp, int req_size)\n{\n\tSg_scatter_hold *schp = &sfp->reserve;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_build_reserve: req_size=%d\\n\", req_size));\n\tdo {\n\t\tif (req_size < PAGE_SIZE)\n\t\t\treq_size = PAGE_SIZE;\n\t\tif (0 == sg_build_indirect(schp, sfp, req_size))\n\t\t\treturn;\n\t\telse\n\t\t\tsg_remove_scat(sfp, schp);\n\t\treq_size >>= 1;\t/* divide by 2 */\n\t} while (req_size > (PAGE_SIZE / 2));\n}", "static void\nsg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)\n{\n\tSg_scatter_hold *req_schp = &srp->data;\n\tSg_scatter_hold *rsv_schp = &sfp->reserve;\n\tint k, num, rem;", "\tsrp->res_used = 1;\n\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t \"sg_link_reserve: size=%d\\n\", size));\n\trem = size;", "\tnum = 1 << (PAGE_SHIFT + rsv_schp->page_order);\n\tfor (k = 0; k < rsv_schp->k_use_sg; k++) {\n\t\tif (rem <= num) {\n\t\t\treq_schp->k_use_sg = k + 1;\n\t\t\treq_schp->sglist_len = rsv_schp->sglist_len;\n\t\t\treq_schp->pages = rsv_schp->pages;", "\t\t\treq_schp->bufflen = size;\n\t\t\treq_schp->page_order = rsv_schp->page_order;\n\t\t\tbreak;\n\t\t} else\n\t\t\trem -= num;\n\t}", "\tif (k >= rsv_schp->k_use_sg)\n\t\tSCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,\n\t\t\t\t \"sg_link_reserve: BAD size\\n\"));\n}", "static void\nsg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)\n{\n\tSg_scatter_hold *req_schp = &srp->data;", "\tSCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,\n\t\t\t\t \"sg_unlink_reserve: req->k_use_sg=%d\\n\",\n\t\t\t\t (int) req_schp->k_use_sg));\n\treq_schp->k_use_sg = 0;\n\treq_schp->bufflen = 0;\n\treq_schp->pages = NULL;\n\treq_schp->page_order = 0;\n\treq_schp->sglist_len = 0;\n\tsfp->save_scat_len = 0;\n\tsrp->res_used = 0;\n}", "static Sg_request *\nsg_get_rq_mark(Sg_fd * sfp, int pack_id)\n{\n\tSg_request *resp;\n\tunsigned long iflags;", "\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tfor (resp = sfp->headrp; resp; resp = resp->nextrp) {\n\t\t/* look for requests that are ready + not SG_IO owned */\n\t\tif ((1 == resp->done) && (!resp->sg_io_owned) &&\n\t\t ((-1 == pack_id) || (resp->header.pack_id == pack_id))) {\n\t\t\tresp->done = 2;\t/* guard against other readers */\n\t\t\tbreak;\n\t\t}\n\t}\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn resp;\n}", "/* always adds to end of list */\nstatic Sg_request *\nsg_add_request(Sg_fd * sfp)\n{\n\tint k;\n\tunsigned long iflags;\n\tSg_request *resp;\n\tSg_request *rp = sfp->req_arr;", "\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tresp = sfp->headrp;\n\tif (!resp) {\n\t\tmemset(rp, 0, sizeof (Sg_request));\n\t\trp->parentfp = sfp;\n\t\tresp = rp;\n\t\tsfp->headrp = resp;\n\t} else {\n\t\tif (0 == sfp->cmd_q)\n\t\t\tresp = NULL;\t/* command queuing disallowed */\n\t\telse {\n\t\t\tfor (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) {\n\t\t\t\tif (!rp->parentfp)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (k < SG_MAX_QUEUE) {\n\t\t\t\tmemset(rp, 0, sizeof (Sg_request));\n\t\t\t\trp->parentfp = sfp;\n\t\t\t\twhile (resp->nextrp)\n\t\t\t\t\tresp = resp->nextrp;\n\t\t\t\tresp->nextrp = rp;\n\t\t\t\tresp = rp;\n\t\t\t} else\n\t\t\t\tresp = NULL;\n\t\t}\n\t}\n\tif (resp) {\n\t\tresp->nextrp = NULL;\n\t\tresp->header.duration = jiffies_to_msecs(jiffies);\n\t}\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn resp;\n}", "/* Return of 1 for found; 0 for not found */\nstatic int\nsg_remove_request(Sg_fd * sfp, Sg_request * srp)\n{\n\tSg_request *prev_rp;\n\tSg_request *rp;\n\tunsigned long iflags;\n\tint res = 0;", "\tif ((!sfp) || (!srp) || (!sfp->headrp))\n\t\treturn res;\n\twrite_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tprev_rp = sfp->headrp;\n\tif (srp == prev_rp) {\n\t\tsfp->headrp = prev_rp->nextrp;\n\t\tprev_rp->parentfp = NULL;\n\t\tres = 1;\n\t} else {\n\t\twhile ((rp = prev_rp->nextrp)) {\n\t\t\tif (srp == rp) {\n\t\t\t\tprev_rp->nextrp = rp->nextrp;\n\t\t\t\trp->parentfp = NULL;\n\t\t\t\tres = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprev_rp = rp;\n\t\t}\n\t}\n\twrite_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn res;\n}", "static Sg_fd *\nsg_add_sfp(Sg_device * sdp)\n{\n\tSg_fd *sfp;\n\tunsigned long iflags;\n\tint bufflen;", "\tsfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN);\n\tif (!sfp)\n\t\treturn ERR_PTR(-ENOMEM);", "\tinit_waitqueue_head(&sfp->read_wait);\n\trwlock_init(&sfp->rq_list_lock);", "\tkref_init(&sfp->f_ref);\n\tsfp->timeout = SG_DEFAULT_TIMEOUT;\n\tsfp->timeout_user = SG_DEFAULT_TIMEOUT_USER;\n\tsfp->force_packid = SG_DEF_FORCE_PACK_ID;\n\tsfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ?\n\t sdp->device->host->unchecked_isa_dma : 1;\n\tsfp->cmd_q = SG_DEF_COMMAND_Q;\n\tsfp->keep_orphan = SG_DEF_KEEP_ORPHAN;\n\tsfp->parentdp = sdp;\n\twrite_lock_irqsave(&sdp->sfd_lock, iflags);\n\tif (atomic_read(&sdp->detaching)) {\n\t\twrite_unlock_irqrestore(&sdp->sfd_lock, iflags);\n\t\treturn ERR_PTR(-ENODEV);\n\t}\n\tlist_add_tail(&sfp->sfd_siblings, &sdp->sfds);\n\twrite_unlock_irqrestore(&sdp->sfd_lock, iflags);\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_add_sfp: sfp=0x%p\\n\", sfp));\n\tif (unlikely(sg_big_buff != def_reserved_size))\n\t\tsg_big_buff = def_reserved_size;", "\tbufflen = min_t(int, sg_big_buff,\n\t\t\tmax_sectors_bytes(sdp->device->request_queue));\n\tsg_build_reserve(sfp, bufflen);\n\tSCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,\n\t\t\t\t \"sg_add_sfp: bufflen=%d, k_use_sg=%d\\n\",\n\t\t\t\t sfp->reserve.bufflen,\n\t\t\t\t sfp->reserve.k_use_sg));", "\tkref_get(&sdp->d_ref);\n\t__module_get(THIS_MODULE);\n\treturn sfp;\n}", "static void\nsg_remove_sfp_usercontext(struct work_struct *work)\n{\n\tstruct sg_fd *sfp = container_of(work, struct sg_fd, ew.work);\n\tstruct sg_device *sdp = sfp->parentdp;", "\t/* Cleanup any responses which were never read(). */\n\twhile (sfp->headrp)\n\t\tsg_finish_rem_req(sfp->headrp);", "\tif (sfp->reserve.bufflen > 0) {\n\t\tSCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,\n\t\t\t\t\"sg_remove_sfp: bufflen=%d, k_use_sg=%d\\n\",\n\t\t\t\t(int) sfp->reserve.bufflen,\n\t\t\t\t(int) sfp->reserve.k_use_sg));\n\t\tsg_remove_scat(sfp, &sfp->reserve);\n\t}", "\tSCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,\n\t\t\t\"sg_remove_sfp: sfp=0x%p\\n\", sfp));\n\tkfree(sfp);", "\tscsi_device_put(sdp->device);\n\tkref_put(&sdp->d_ref, sg_device_destroy);\n\tmodule_put(THIS_MODULE);\n}", "static void\nsg_remove_sfp(struct kref *kref)\n{\n\tstruct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref);\n\tstruct sg_device *sdp = sfp->parentdp;\n\tunsigned long iflags;", "\twrite_lock_irqsave(&sdp->sfd_lock, iflags);\n\tlist_del(&sfp->sfd_siblings);\n\twrite_unlock_irqrestore(&sdp->sfd_lock, iflags);", "\tINIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext);\n\tschedule_work(&sfp->ew.work);\n}", "static int\nsg_res_in_use(Sg_fd * sfp)\n{\n\tconst Sg_request *srp;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sfp->rq_list_lock, iflags);\n\tfor (srp = sfp->headrp; srp; srp = srp->nextrp)\n\t\tif (srp->res_used)\n\t\t\tbreak;\n\tread_unlock_irqrestore(&sfp->rq_list_lock, iflags);\n\treturn srp ? 1 : 0;\n}", "#ifdef CONFIG_SCSI_PROC_FS\nstatic int\nsg_idr_max_id(int id, void *p, void *data)\n{\n\tint *k = data;", "\tif (*k < id)\n\t\t*k = id;", "\treturn 0;\n}", "static int\nsg_last_dev(void)\n{\n\tint k = -1;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tidr_for_each(&sg_index_idr, sg_idr_max_id, &k);\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn k + 1;\t\t/* origin 1 */\n}\n#endif", "/* must be called with sg_index_lock held */\nstatic Sg_device *sg_lookup_dev(int dev)\n{\n\treturn idr_find(&sg_index_idr, dev);\n}", "static Sg_device *\nsg_get_dev(int dev)\n{\n\tstruct sg_device *sdp;\n\tunsigned long flags;", "\tread_lock_irqsave(&sg_index_lock, flags);\n\tsdp = sg_lookup_dev(dev);\n\tif (!sdp)\n\t\tsdp = ERR_PTR(-ENXIO);\n\telse if (atomic_read(&sdp->detaching)) {\n\t\t/* If sdp->detaching, then the refcount may already be 0, in\n\t\t * which case it would be a bug to do kref_get().\n\t\t */\n\t\tsdp = ERR_PTR(-ENODEV);\n\t} else\n\t\tkref_get(&sdp->d_ref);\n\tread_unlock_irqrestore(&sg_index_lock, flags);", "\treturn sdp;\n}", "#ifdef CONFIG_SCSI_PROC_FS", "static struct proc_dir_entry *sg_proc_sgp = NULL;", "static char sg_proc_sg_dirname[] = \"scsi/sg\";", "static int sg_proc_seq_show_int(struct seq_file *s, void *v);", "static int sg_proc_single_open_adio(struct inode *inode, struct file *file);\nstatic ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer,\n\t\t\t size_t count, loff_t *off);\nstatic const struct file_operations adio_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_adio,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.write = sg_proc_write_adio,\n\t.release = single_release,\n};", "static int sg_proc_single_open_dressz(struct inode *inode, struct file *file);\nstatic ssize_t sg_proc_write_dressz(struct file *filp, \n\t\tconst char __user *buffer, size_t count, loff_t *off);\nstatic const struct file_operations dressz_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_dressz,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.write = sg_proc_write_dressz,\n\t.release = single_release,\n};", "static int sg_proc_seq_show_version(struct seq_file *s, void *v);\nstatic int sg_proc_single_open_version(struct inode *inode, struct file *file);\nstatic const struct file_operations version_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_version,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = single_release,\n};", "static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v);\nstatic int sg_proc_single_open_devhdr(struct inode *inode, struct file *file);\nstatic const struct file_operations devhdr_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_single_open_devhdr,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = single_release,\n};", "static int sg_proc_seq_show_dev(struct seq_file *s, void *v);\nstatic int sg_proc_open_dev(struct inode *inode, struct file *file);\nstatic void * dev_seq_start(struct seq_file *s, loff_t *pos);\nstatic void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos);\nstatic void dev_seq_stop(struct seq_file *s, void *v);\nstatic const struct file_operations dev_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_open_dev,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = seq_release,\n};\nstatic const struct seq_operations dev_seq_ops = {\n\t.start = dev_seq_start,\n\t.next = dev_seq_next,\n\t.stop = dev_seq_stop,\n\t.show = sg_proc_seq_show_dev,\n};", "static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v);\nstatic int sg_proc_open_devstrs(struct inode *inode, struct file *file);\nstatic const struct file_operations devstrs_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_open_devstrs,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = seq_release,\n};\nstatic const struct seq_operations devstrs_seq_ops = {\n\t.start = dev_seq_start,\n\t.next = dev_seq_next,\n\t.stop = dev_seq_stop,\n\t.show = sg_proc_seq_show_devstrs,\n};", "static int sg_proc_seq_show_debug(struct seq_file *s, void *v);\nstatic int sg_proc_open_debug(struct inode *inode, struct file *file);\nstatic const struct file_operations debug_fops = {\n\t.owner = THIS_MODULE,\n\t.open = sg_proc_open_debug,\n\t.read = seq_read,\n\t.llseek = seq_lseek,\n\t.release = seq_release,\n};\nstatic const struct seq_operations debug_seq_ops = {\n\t.start = dev_seq_start,\n\t.next = dev_seq_next,\n\t.stop = dev_seq_stop,\n\t.show = sg_proc_seq_show_debug,\n};", "\nstruct sg_proc_leaf {\n\tconst char * name;\n\tconst struct file_operations * fops;\n};", "static const struct sg_proc_leaf sg_proc_leaf_arr[] = {\n\t{\"allow_dio\", &adio_fops},\n\t{\"debug\", &debug_fops},\n\t{\"def_reserved_size\", &dressz_fops},\n\t{\"device_hdr\", &devhdr_fops},\n\t{\"devices\", &dev_fops},\n\t{\"device_strs\", &devstrs_fops},\n\t{\"version\", &version_fops}\n};", "static int\nsg_proc_init(void)\n{\n\tint num_leaves = ARRAY_SIZE(sg_proc_leaf_arr);\n\tint k;", "\tsg_proc_sgp = proc_mkdir(sg_proc_sg_dirname, NULL);\n\tif (!sg_proc_sgp)\n\t\treturn 1;\n\tfor (k = 0; k < num_leaves; ++k) {\n\t\tconst struct sg_proc_leaf *leaf = &sg_proc_leaf_arr[k];\n\t\tumode_t mask = leaf->fops->write ? S_IRUGO | S_IWUSR : S_IRUGO;\n\t\tproc_create(leaf->name, mask, sg_proc_sgp, leaf->fops);\n\t}\n\treturn 0;\n}", "static void\nsg_proc_cleanup(void)\n{\n\tint k;\n\tint num_leaves = ARRAY_SIZE(sg_proc_leaf_arr);", "\tif (!sg_proc_sgp)\n\t\treturn;\n\tfor (k = 0; k < num_leaves; ++k)\n\t\tremove_proc_entry(sg_proc_leaf_arr[k].name, sg_proc_sgp);\n\tremove_proc_entry(sg_proc_sg_dirname, NULL);\n}", "\nstatic int sg_proc_seq_show_int(struct seq_file *s, void *v)\n{\n\tseq_printf(s, \"%d\\n\", *((int *)s->private));\n\treturn 0;\n}", "static int sg_proc_single_open_adio(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_int, &sg_allow_dio);\n}", "static ssize_t \nsg_proc_write_adio(struct file *filp, const char __user *buffer,\n\t\t size_t count, loff_t *off)\n{\n\tint err;\n\tunsigned long num;", "\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))\n\t\treturn -EACCES;\n\terr = kstrtoul_from_user(buffer, count, 0, &num);\n\tif (err)\n\t\treturn err;\n\tsg_allow_dio = num ? 1 : 0;\n\treturn count;\n}", "static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_int, &sg_big_buff);\n}", "static ssize_t \nsg_proc_write_dressz(struct file *filp, const char __user *buffer,\n\t\t size_t count, loff_t *off)\n{\n\tint err;\n\tunsigned long k = ULONG_MAX;", "\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))\n\t\treturn -EACCES;", "\terr = kstrtoul_from_user(buffer, count, 0, &k);\n\tif (err)\n\t\treturn err;\n\tif (k <= 1048576) {\t/* limit \"big buff\" to 1 MB */\n\t\tsg_big_buff = k;\n\t\treturn count;\n\t}\n\treturn -ERANGE;\n}", "static int sg_proc_seq_show_version(struct seq_file *s, void *v)\n{\n\tseq_printf(s, \"%d\\t%s [%s]\\n\", sg_version_num, SG_VERSION_STR,\n\t\t sg_version_date);\n\treturn 0;\n}", "static int sg_proc_single_open_version(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_version, NULL);\n}", "static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v)\n{\n\tseq_puts(s, \"host\\tchan\\tid\\tlun\\ttype\\topens\\tqdepth\\tbusy\\tonline\\n\");\n\treturn 0;\n}", "static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, sg_proc_seq_show_devhdr, NULL);\n}", "struct sg_proc_deviter {\n\tloff_t\tindex;\n\tsize_t\tmax;\n};", "static void * dev_seq_start(struct seq_file *s, loff_t *pos)\n{\n\tstruct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL);", "\ts->private = it;\n\tif (! it)\n\t\treturn NULL;", "\tit->index = *pos;\n\tit->max = sg_last_dev();\n\tif (it->index >= it->max)\n\t\treturn NULL;\n\treturn it;\n}", "static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos)\n{\n\tstruct sg_proc_deviter * it = s->private;", "\t*pos = ++it->index;\n\treturn (it->index < it->max) ? it : NULL;\n}", "static void dev_seq_stop(struct seq_file *s, void *v)\n{\n\tkfree(s->private);\n}", "static int sg_proc_open_dev(struct inode *inode, struct file *file)\n{\n return seq_open(file, &dev_seq_ops);\n}", "static int sg_proc_seq_show_dev(struct seq_file *s, void *v)\n{\n\tstruct sg_proc_deviter * it = (struct sg_proc_deviter *) v;\n\tSg_device *sdp;\n\tstruct scsi_device *scsidp;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tsdp = it ? sg_lookup_dev(it->index) : NULL;\n\tif ((NULL == sdp) || (NULL == sdp->device) ||\n\t (atomic_read(&sdp->detaching)))\n\t\tseq_puts(s, \"-1\\t-1\\t-1\\t-1\\t-1\\t-1\\t-1\\t-1\\t-1\\n\");\n\telse {\n\t\tscsidp = sdp->device;\n\t\tseq_printf(s, \"%d\\t%d\\t%d\\t%llu\\t%d\\t%d\\t%d\\t%d\\t%d\\n\",\n\t\t\t scsidp->host->host_no, scsidp->channel,\n\t\t\t scsidp->id, scsidp->lun, (int) scsidp->type,\n\t\t\t 1,\n\t\t\t (int) scsidp->queue_depth,\n\t\t\t (int) atomic_read(&scsidp->device_busy),\n\t\t\t (int) scsi_device_online(scsidp));\n\t}\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn 0;\n}", "static int sg_proc_open_devstrs(struct inode *inode, struct file *file)\n{\n return seq_open(file, &devstrs_seq_ops);\n}", "static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v)\n{\n\tstruct sg_proc_deviter * it = (struct sg_proc_deviter *) v;\n\tSg_device *sdp;\n\tstruct scsi_device *scsidp;\n\tunsigned long iflags;", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tsdp = it ? sg_lookup_dev(it->index) : NULL;\n\tscsidp = sdp ? sdp->device : NULL;\n\tif (sdp && scsidp && (!atomic_read(&sdp->detaching)))\n\t\tseq_printf(s, \"%8.8s\\t%16.16s\\t%4.4s\\n\",\n\t\t\t scsidp->vendor, scsidp->model, scsidp->rev);\n\telse\n\t\tseq_puts(s, \"<no active device>\\n\");\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn 0;\n}", "/* must be called while holding sg_index_lock */\nstatic void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp)\n{\n\tint k, m, new_interface, blen, usg;\n\tSg_request *srp;\n\tSg_fd *fp;\n\tconst sg_io_hdr_t *hp;\n\tconst char * cp;\n\tunsigned int ms;", "\tk = 0;\n\tlist_for_each_entry(fp, &sdp->sfds, sfd_siblings) {\n\t\tk++;\n\t\tread_lock(&fp->rq_list_lock); /* irqs already disabled */\n\t\tseq_printf(s, \" FD(%d): timeout=%dms bufflen=%d \"\n\t\t\t \"(res)sgat=%d low_dma=%d\\n\", k,\n\t\t\t jiffies_to_msecs(fp->timeout),\n\t\t\t fp->reserve.bufflen,\n\t\t\t (int) fp->reserve.k_use_sg,\n\t\t\t (int) fp->low_dma);\n\t\tseq_printf(s, \" cmd_q=%d f_packid=%d k_orphan=%d closed=0\\n\",\n\t\t\t (int) fp->cmd_q, (int) fp->force_packid,\n\t\t\t (int) fp->keep_orphan);\n\t\tfor (m = 0, srp = fp->headrp;\n\t\t\t\tsrp != NULL;\n\t\t\t\t++m, srp = srp->nextrp) {\n\t\t\thp = &srp->header;\n\t\t\tnew_interface = (hp->interface_id == '\\0') ? 0 : 1;\n\t\t\tif (srp->res_used) {\n\t\t\t\tif (new_interface && \n\t\t\t\t (SG_FLAG_MMAP_IO & hp->flags))\n\t\t\t\t\tcp = \" mmap>> \";\n\t\t\t\telse\n\t\t\t\t\tcp = \" rb>> \";\n\t\t\t} else {\n\t\t\t\tif (SG_INFO_DIRECT_IO_MASK & hp->info)\n\t\t\t\t\tcp = \" dio>> \";\n\t\t\t\telse\n\t\t\t\t\tcp = \" \";\n\t\t\t}\n\t\t\tseq_puts(s, cp);\n\t\t\tblen = srp->data.bufflen;\n\t\t\tusg = srp->data.k_use_sg;\n\t\t\tseq_puts(s, srp->done ?\n\t\t\t\t ((1 == srp->done) ? \"rcv:\" : \"fin:\")\n\t\t\t\t : \"act:\");\n\t\t\tseq_printf(s, \" id=%d blen=%d\",\n\t\t\t\t srp->header.pack_id, blen);\n\t\t\tif (srp->done)\n\t\t\t\tseq_printf(s, \" dur=%d\", hp->duration);\n\t\t\telse {\n\t\t\t\tms = jiffies_to_msecs(jiffies);\n\t\t\t\tseq_printf(s, \" t_o/elap=%d/%d\",\n\t\t\t\t\t(new_interface ? hp->timeout :\n\t\t\t\t\t\t jiffies_to_msecs(fp->timeout)),\n\t\t\t\t\t(ms > hp->duration ? ms - hp->duration : 0));\n\t\t\t}\n\t\t\tseq_printf(s, \"ms sgat=%d op=0x%02x\\n\", usg,\n\t\t\t\t (int) srp->data.cmd_opcode);\n\t\t}\n\t\tif (0 == m)\n\t\t\tseq_puts(s, \" No requests active\\n\");\n\t\tread_unlock(&fp->rq_list_lock);\n\t}\n}", "static int sg_proc_open_debug(struct inode *inode, struct file *file)\n{\n return seq_open(file, &debug_seq_ops);\n}", "static int sg_proc_seq_show_debug(struct seq_file *s, void *v)\n{\n\tstruct sg_proc_deviter * it = (struct sg_proc_deviter *) v;\n\tSg_device *sdp;\n\tunsigned long iflags;", "\tif (it && (0 == it->index))\n\t\tseq_printf(s, \"max_active_device=%d def_reserved_size=%d\\n\",\n\t\t\t (int)it->max, sg_big_buff);", "\tread_lock_irqsave(&sg_index_lock, iflags);\n\tsdp = it ? sg_lookup_dev(it->index) : NULL;\n\tif (NULL == sdp)\n\t\tgoto skip;\n\tread_lock(&sdp->sfd_lock);\n\tif (!list_empty(&sdp->sfds)) {\n\t\tseq_printf(s, \" >>> device=%s \", sdp->disk->disk_name);\n\t\tif (atomic_read(&sdp->detaching))\n\t\t\tseq_puts(s, \"detaching pending close \");\n\t\telse if (sdp->device) {\n\t\t\tstruct scsi_device *scsidp = sdp->device;", "\t\t\tseq_printf(s, \"%d:%d:%d:%llu em=%d\",\n\t\t\t\t scsidp->host->host_no,\n\t\t\t\t scsidp->channel, scsidp->id,\n\t\t\t\t scsidp->lun,\n\t\t\t\t scsidp->host->hostt->emulated);\n\t\t}\n\t\tseq_printf(s, \" sg_tablesize=%d excl=%d open_cnt=%d\\n\",\n\t\t\t sdp->sg_tablesize, sdp->exclude, sdp->open_cnt);\n\t\tsg_proc_debug_helper(s, sdp);\n\t}\n\tread_unlock(&sdp->sfd_lock);\nskip:\n\tread_unlock_irqrestore(&sg_index_lock, iflags);\n\treturn 0;\n}", "#endif\t\t\t\t/* CONFIG_SCSI_PROC_FS */", "module_init(init_sg);\nmodule_exit(exit_sg);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1745], "buggy_code_start_loc": [1745], "filenames": ["drivers/scsi/sg.c"], "fixing_code_end_loc": [1749], "fixing_code_start_loc": [1746], "message": "Integer overflow in the sg_start_req function in drivers/scsi/sg.c in the Linux kernel 2.6.x through 4.x before 4.1 allows local users to cause a denial of service or possibly have unspecified other impact via a large iov_count value in a write request.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "4884A404-34BE-4D52-B749-219701AF2BC2", "versionEndExcluding": "4.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.6.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B6B7CAD7-9D4E-4FDB-88E3-1E583210A01F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:15.04:*:*:*:*:*:*:*", "matchCriteriaId": "F38D3B7E-8429-473F-BB31-FC3583EE5A5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_desktop:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "F4BC592E-17CC-4DD4-8B2C-CFD99383649C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_server:11:sp2:*:*:ltss:*:*:*", "matchCriteriaId": "C202F75B-221A-40BB-8A0D-451335B39937", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_server:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "DD4BBD63-E038-45CE-9537-D96831E99A06", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:suse_linux_enterprise_server:11:sp3:*:*:*:vmware:*:*", "matchCriteriaId": "0EA03350-8702-43D5-8605-5FB765A3F60B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Integer overflow in the sg_start_req function in drivers/scsi/sg.c in the Linux kernel 2.6.x through 4.x before 4.1 allows local users to cause a denial of service or possibly have unspecified other impact via a large iov_count value in a write request."}, {"lang": "es", "value": "Desbordamiento de entero en la funci\u00f3n sg_start_req en drivers/scsi/sg.c en el kernel de Linux 2.6.x hasta la versi\u00f3n 4.x en versiones anteriores a 4.1 permite a usuarios locales provocar una denegaci\u00f3n de servicio o posiblemente tener otro impacto no especificado a trav\u00e9s de un valor iov_count grande en una petici\u00f3n de escritura."}], "evaluatorComment": null, "id": "CVE-2015-5707", "lastModified": "2020-06-02T14:57:56.980", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2015-10-19T10:59:05.037", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=451a2886b6bf90e2fb378f7c46c655450fb96e81"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=fdc81f45e9f57858da6351836507fbcf1b7583ee"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-09/msg00004.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-09/msg00018.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-09/msg00021.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00026.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00027.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00028.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00029.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00030.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00031.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2015-11/msg00032.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2015/dsa-3329"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/08/01/6"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/76145"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1033521"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2733-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2734-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2737-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2738-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2750-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2759-1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "http://www.ubuntu.com/usn/USN-2760-1"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1250030"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/451a2886b6bf90e2fb378f7c46c655450fb96e81"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/fdc81f45e9f57858da6351836507fbcf1b7583ee"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://source.android.com/security/bulletin/2017-07-01"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/451a2886b6bf90e2fb378f7c46c655450fb96e81"}, "type": "CWE-190"}
298
Determine whether the {function_name} code is vulnerable or not.
[ "## Parse Server Changelog", "### master", "[Full Changelog](https://github.com/parse-community/parse-server/compare/4.5.0...master)", "\n### 4.5.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.4.0...4.5.0)", "__BREAKING CHANGES:__\n- FIX: Consistent casing for afterLiveQueryEvent. The afterLiveQueryEvent was introduced in 4.4.0 with inconsistent casing for the event names, which was fixed in 4.5.0. [#7023](https://github.com/parse-community/parse-server/pull/7023). Thanks to [dblythy](https://github.com/dblythy).\n___\n- FIX: Properly handle serverURL and publicServerUrl in Batch requests. [#7049](https://github.com/parse-community/parse-server/pull/7049). Thanks to [Zach Goldberg](https://github.com/ZachGoldberg).\n- IMPROVE: Prevent invalid column names (className and length). [#7053](https://github.com/parse-community/parse-server/pull/7053). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: GraphQL: Remove viewer from logout mutation. [#7029](https://github.com/parse-community/parse-server/pull/7029). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- IMPROVE: GraphQL: Optimize on Relation. [#7044](https://github.com/parse-community/parse-server/pull/7044). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW: Include sessionToken in onLiveQueryEvent. [#7043](https://github.com/parse-community/parse-server/pull/7043). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Definitions for accountLockout and passwordPolicy. [#7040](https://github.com/parse-community/parse-server/pull/7040). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Fix typo in server definitions for emailVerifyTokenReuseIfValid. [#7037](https://github.com/parse-community/parse-server/pull/7037). Thanks to [dblythy](https://github.com/dblythy).\n- SECURITY FIX: LDAP auth stores password in plain text. See [GHSA-4w46-w44m-3jq3](https://github.com/parse-community/parse-server/security/advisories/GHSA-4w46-w44m-3jq3) for more details about the vulnerability and [da905a3](https://github.com/parse-community/parse-server/commit/da905a357d062ab4fea727a21eac231acc2ed92a) for the fix. Thanks to [Fabian Strachanski](https://github.com/fastrde).\n- NEW: Reuse tokens if they haven't expired. [#7017](https://github.com/parse-community/parse-server/pull/7017). Thanks to [dblythy](https://github.com/dblythy).\n- NEW: Add LDAPS-support to LDAP-Authcontroller. [#7014](https://github.com/parse-community/parse-server/pull/7014). Thanks to [Fabian Strachanski](https://github.com/fastrde).\n- FIX: (beforeSave/afterSave): Return value instead of Parse.Op for nested fields. [#7005](https://github.com/parse-community/parse-server/pull/7005). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: (beforeSave): Skip Sanitizing Database results. [#7003](https://github.com/parse-community/parse-server/pull/7003). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Fix includeAll for querying a Pointer and Pointer array. [#7002](https://github.com/parse-community/parse-server/pull/7002). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: Add encryptionKey to src/options/index.js. [#6999](https://github.com/parse-community/parse-server/pull/6999). Thanks to [dblythy](https://github.com/dblythy).\n- IMPROVE: Update PostgresStorageAdapter.js. [#6989](https://github.com/parse-community/parse-server/pull/6989). Thanks to [Vitaly Tomilov](https://github.com/vitaly-t).", "### 4.4.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.3.0...4.4.0)\n- IMPROVE: Update PostgresStorageAdapter.js. [#6981](https://github.com/parse-community/parse-server/pull/6981). Thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n- NEW: skipWithMasterKey on Built-In Validator. [#6972](https://github.com/parse-community/parse-server/issues/6972). Thanks to [dblythy](https://github.com/dblythy).\n- NEW: Add fileKey rotation to GridFSBucketAdapter. [#6768](https://github.com/parse-community/parse-server/pull/6768). Thanks to [Corey Baker](https://github.com/cbaker6).\n- IMPROVE: Remove unused parameter in Cloud Function. [#6969](https://github.com/parse-community/parse-server/issues/6969). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: Validation Handler Update. [#6968](https://github.com/parse-community/parse-server/issues/6968). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: (directAccess): Properly handle response status. [#6966](https://github.com/parse-community/parse-server/issues/6966). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Remove hostnameMaxLen for Mongo URL. [#6693](https://github.com/parse-community/parse-server/issues/6693). Thanks to [markhoward02](https://github.com/markhoward02).\n- IMPROVE: Show a message if cloud functions are duplicated. [#6963](https://github.com/parse-community/parse-server/issues/6963). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Pass request.query to afterFind. [#6960](https://github.com/parse-community/parse-server/issues/6960). Thanks to [dblythy](https://github.com/dblythy).\n- SECURITY FIX: Patch session vulnerability over Live Query. See [GHSA-2xm2-xj2q-qgpj](https://github.com/parse-community/parse-server/security/advisories/GHSA-2xm2-xj2q-qgpj) for more details about the vulnerability and [78b59fb](https://github.com/parse-community/parse-server/commit/78b59fb26b1c36e3cdbd42ba9fec025003267f58) for the fix. Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo).\n- IMPROVE: LiveQueryEvent Error Logging Improvements. [#6951](https://github.com/parse-community/parse-server/issues/6951). Thanks to [dblythy](https://github.com/dblythy).\n- IMPROVE: Include stack in Cloud Code. [#6958](https://github.com/parse-community/parse-server/issues/6958). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: (jobs): Add Error Message to JobStatus Failure. [#6954](https://github.com/parse-community/parse-server/issues/6954). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- NEW: Create Cloud function afterLiveQueryEvent. [#6859](https://github.com/parse-community/parse-server/issues/6859). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Update vkontakte API to the latest version. [#6944](https://github.com/parse-community/parse-server/issues/6944). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo).\n- FIX: Use an empty object as default value of options for Google Sign in. [#6844](https://github.com/parse-community/parse-server/issues/6844). Thanks to [Kevin Kuang](https://github.com/kvnkuang).\n- FIX: Postgres: prepend className to unique indexes. [#6741](https://github.com/parse-community/parse-server/pull/6741). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: GraphQL: Transform input types also on user mutations. [#6934](https://github.com/parse-community/parse-server/pull/6934). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Set objectId into query for Email Validation. [#6930](https://github.com/parse-community/parse-server/pull/6930). Thanks to [Danaru](https://github.com/Danaru87).\n- FIX: GraphQL: Optimize queries, fixes some null returns (on object), fix stitched GraphQLUpload. [#6709](https://github.com/parse-community/parse-server/pull/6709). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Do not throw error if user provide a pointer like index onMongo. [#6923](https://github.com/parse-community/parse-server/pull/6923). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Hotfix instagram api. [#6922](https://github.com/parse-community/parse-server/issues/6922). Thanks to [Tim](https://github.com/timination).\n- FIX: (directAccess/cloud-code): Pass installationId with LogIn. [#6903](https://github.com/parse-community/parse-server/issues/6903). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Fix bcrypt binary incompatibility. [#6891](https://github.com/parse-community/parse-server/issues/6891). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- NEW: Keycloak auth adapter. [#6376](https://github.com/parse-community/parse-server/issues/6376). Thanks to [Rhuan](https://github.com/rhuanbarreto).\n- IMPROVE: Changed incorrect key name in apple auth adapter tests. [#6861](https://github.com/parse-community/parse-server/issues/6861). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- FIX: Fix mutating beforeSubscribe Query. [#6868](https://github.com/parse-community/parse-server/issues/6868). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Fix beforeLogin for users logging in with AuthData. [#6872](https://github.com/parse-community/parse-server/issues/6872). Thanks to [Kevin Kuang](https://github.com/kvnkuang).\n- FIX: Remove Facebook AccountKit auth. [#6870](https://github.com/parse-community/parse-server/issues/6870). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Updated TOKEN_ISSUER to 'accounts.google.com'. [#6836](https://github.com/parse-community/parse-server/issues/6836). Thanks to [Arjun Vedak](https://github.com/arjun3396).\n- IMPROVE: Optimized deletion of class field from schema by using an index if available to do an index scan instead of a collection scan. [#6815](https://github.com/parse-community/parse-server/issues/6815). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- IMPROVE: Enable MongoDB transaction test for MongoDB >= 4.0.4 [#6827](https://github.com/parse-community/parse-server/pull/6827). Thanks to [Manuel](https://github.com/mtrezza).", "### 4.3.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.2.0...4.3.0)\n- PERFORMANCE: Optimizing pointer CLP query decoration done by DatabaseController#addPointerPermissions [#6747](https://github.com/parse-community/parse-server/pull/6747). Thanks to [mess-lelouch](https://github.com/mess-lelouch).\n- SECURITY: Fix security breach on GraphQL viewer [78239ac](https://github.com/parse-community/parse-server/commit/78239ac9071167fdf243c55ae4bc9a2c0b0d89aa), [secuity advisory](https://github.com/parse-community/parse-server/security/advisories/GHSA-236h-rqv8-8q73). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Save context not present if direct access enabled [#6764](https://github.com/parse-community/parse-server/pull/6764). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani).\n- NEW: Before Connect + Before Subscribe [#6793](https://github.com/parse-community/parse-server/pull/6793). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Add version to playground to fix CDN [#6804](https://github.com/parse-community/parse-server/pull/6804). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW (EXPERIMENTAL): Idempotency enforcement for client requests. This deduplicates requests where the client intends to send one request to Parse Server but due to network issues the server receives the request multiple times. **Caution, this is an experimental feature that may not be appropriate for production.** [#6748](https://github.com/parse-community/parse-server/issues/6748). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- FIX: Add production Google Auth Adapter instead of using the development url [#6734](https://github.com/parse-community/parse-server/pull/6734). Thanks to [SebC.](https://github.com/SebC99).\n- IMPROVE: Run Prettier JS Again Without requiring () on arrow functions [#6796](https://github.com/parse-community/parse-server/pull/6796). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: Run Prettier JS [#6795](https://github.com/parse-community/parse-server/pull/6795). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: Replace bcrypt with @node-rs/bcrypt [#6794](https://github.com/parse-community/parse-server/pull/6794). Thanks to [LongYinan](https://github.com/Brooooooklyn).\n- IMPROVE: Make clear description of anonymous user [#6655](https://github.com/parse-community/parse-server/pull/6655). Thanks to [Jerome De Leon](https://github.com/JeromeDeLeon).\n- IMPROVE: Simplify GraphQL merge system to avoid js ref bugs [#6791](https://github.com/parse-community/parse-server/pull/6791). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW: Pass context in beforeDelete, afterDelete, beforeFind and Parse.Cloud.run [#6666](https://github.com/parse-community/parse-server/pull/6666). Thanks to [yog27ray](https://github.com/yog27ray).\n- NEW: Allow passing custom gql schema function to ParseServer#start options [#6762](https://github.com/parse-community/parse-server/pull/6762). Thanks to [Luca](https://github.com/lucatk).\n- NEW: Allow custom cors origin header [#6772](https://github.com/parse-community/parse-server/pull/6772). Thanks to [Kevin Yao](https://github.com/kzmeyao).\n- FIX: Fix context for cascade-saving and saving existing object [#6735](https://github.com/parse-community/parse-server/pull/6735). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Add file bucket encryption using fileKey [#6765](https://github.com/parse-community/parse-server/pull/6765). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: Removed gaze from dev dependencies and removed not working dev script [#6745](https://github.com/parse-community/parse-server/pull/6745). Thanks to [Vincent Semrau](https://github.com/vince1995).\n- IMPROVE: Upgrade graphql-tools to v6 [#6701](https://github.com/parse-community/parse-server/pull/6701). Thanks to [Yaacov Rydzinski](https://github.com/yaacovCR).\n- NEW: Support Metadata in GridFSAdapter [#6660](https://github.com/parse-community/parse-server/pull/6660). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- NEW: Allow to unset file from graphql [#6651](https://github.com/parse-community/parse-server/pull/6651). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW: Handle shutdown for RedisCacheAdapter [#6658](https://github.com/parse-community/parse-server/pull/6658). Thanks to [promisenxu](https://github.com/promisenxu).\n- FIX: Fix explain on user class [#6650](https://github.com/parse-community/parse-server/pull/6650). Thanks to [Manuel](https://github.com/mtrezza).\n- FIX: Fix read preference for aggregate [#6585](https://github.com/parse-community/parse-server/pull/6585). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Add context to Parse.Object.save [#6626](https://github.com/parse-community/parse-server/pull/6626). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Adding ssl config params to Postgres URI [#6580](https://github.com/parse-community/parse-server/pull/6580). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: Travis postgres update: removing unnecessary start of mongo-runner [#6594](https://github.com/parse-community/parse-server/pull/6594). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: ObjectId size for Pointer in Postgres [#6619](https://github.com/parse-community/parse-server/pull/6619). Thanks to [Corey Baker](https://github.com/cbaker6).\n- IMPROVE: Improve a test case [#6629](https://github.com/parse-community/parse-server/pull/6629). Thanks to [Gordon Sun](https://github.com/sunshineo).\n- NEW: Allow to resolve automatically Parse Type fields from Custom Schema [#6562](https://github.com/parse-community/parse-server/pull/6562). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Remove wrong console log in test [#6627](https://github.com/parse-community/parse-server/pull/6627). Thanks to [Gordon Sun](https://github.com/sunshineo).\n- IMPROVE: Graphql tools v5 [#6611](https://github.com/parse-community/parse-server/pull/6611). Thanks to [Yaacov Rydzinski](https://github.com/yaacovCR).\n- FIX: Catch JSON.parse and return 403 properly [#6589](https://github.com/parse-community/parse-server/pull/6589). Thanks to [Gordon Sun](https://github.com/sunshineo).\n- PERFORMANCE: Allow covering relation queries with minimal index [#6581](https://github.com/parse-community/parse-server/pull/6581). Thanks to [Noah Silas](https://github.com/noahsilas).\n- FIX: Fix Postgres group aggregation [#6522](https://github.com/parse-community/parse-server/pull/6522). Thanks to [Siddharth Ramesh](https://github.com/srameshr).\n- NEW: Allow set user mapped from JWT directly on request [#6411](https://github.com/parse-community/parse-server/pull/6411). Thanks to [Gordon Sun](https://github.com/sunshineo).", "### 4.2.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.1.0...4.2.0)", "__BREAKING CHANGES:__\n- CHANGE: The Sign-In with Apple authentication adapter parameter `client_id` has been changed to `clientId`. If using the Apple authentication adapter, this change requires to update the Parse Server configuration accordingly. See [#6523](https://github.com/parse-community/parse-server/pull/6523) for details.\n___\n- UPGRADE: Parse JS SDK to 2.12.0 [#6548](https://github.com/parse-community/parse-server/pull/6548)\n- NEW: Support Group aggregation on multiple columns for Postgres [#6483](https://github.com/parse-community/parse-server/pull/6483). Thanks to [Siddharth Ramesh](https://github.com/srameshr).\n- FIX: Improve test reliability by instructing Travis to only install one version of Postgres [#6490](https://github.com/parse-community/parse-server/pull/6490). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- FIX: Unknown type bug on overloaded types [#6494](https://github.com/parse-community/parse-server/pull/6494). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Improve reliability of 'SignIn with AppleID' [#6416](https://github.com/parse-community/parse-server/pull/6416). Thanks to [Andy King](https://github.com/andrewking0207).\n- FIX: Improve Travis reliability by separating Postgres & Mongo scripts [#6505](https://github.com/parse-community/parse-server/pull/6505). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- NEW: Apple SignIn support for multiple IDs [#6523](https://github.com/parse-community/parse-server/pull/6523). Thanks to [UnderratedDev](https://github.com/UnderratedDev).\n- NEW: Add support for new Instagram API [#6398](https://github.com/parse-community/parse-server/pull/6398). Thanks to [Maravilho Singa](https://github.com/maravilhosinga).\n- FIX: Updating Postgres/Postgis Call and Postgis to 3.0 [#6528](https://github.com/parse-community/parse-server/pull/6528). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- FIX: enableExpressErrorHandler logic [#6423](https://github.com/parse-community/parse-server/pull/6423). Thanks to [Nikolay Andryukhin](https://github.com/hybeats).\n- FIX: Change Order Enum Strategy for GraphQL [#6515](https://github.com/parse-community/parse-server/pull/6515). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Switch ACL to Relay Global Id for GraphQL [#6495](https://github.com/parse-community/parse-server/pull/6495). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Handle keys for pointer fields properly for GraphQL [#6499](https://github.com/parse-community/parse-server/pull/6499). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: GraphQL file mutation [#6507](https://github.com/parse-community/parse-server/pull/6507). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Aggregate geoNear with date query [#6540](https://github.com/parse-community/parse-server/pull/6540). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Add file triggers and file meta data [#6344](https://github.com/parse-community/parse-server/pull/6344). Thanks to [stevestencil](https://github.com/stevestencil).\n- FIX: Improve local testing of postgres [#6531](https://github.com/parse-community/parse-server/pull/6531). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- NEW: Case insensitive username and email indexing and query planning for Postgres [#6506](https://github.com/parse-community/parse-server/issues/6441). Thanks to\n[Corey Baker](https://github.com/cbaker6).", "### 4.1.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.0.2...4.1.0)", "_SECURITY RELEASE_: see [advisory](https://github.com/parse-community/parse-server/security/advisories/GHSA-h4mf-75hf-67w4) for details\n- SECURITY FIX: Patch Regex vulnerabilities. See [3a3a5ee](https://github.com/parse-community/parse-server/commit/3a3a5eee5ffa48da1352423312cb767de14de269). Special thanks to [W0lfw00d](https://github.com/W0lfw00d) for identifying and [responsibly reporting](https://github.com/parse-community/parse-server/blob/master/SECURITY.md) the vulnerability. Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo) for the speedy fix.", "### 4.0.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.0.1...4.0.2)", "__BREAKING CHANGES:__\n1. Remove Support for Mongo 3.2 & 3.4. The new minimum supported version is Mongo 3.6.\n2. Change username and email validation to be case insensitive. This change should be transparent in most use cases. The validation behavior should now behave 'as expected'. See [#5634](https://github.com/parse-community/parse-server/pull/5634) for details.", "> __Special Note on Upgrading to Parse Server 4.0.0 and above__\n>\n> In addition to the breaking changes noted above, [#5634](https://github.com/parse-community/parse-server/pull/5634) introduces a two new case insensitive indexes on the `User` collection. Special care should be taken when upgrading to this version to ensure that:\n>\n> 1. The new indexes can be successfully created (see issue [#6465](https://github.com/parse-community/parse-server/issues/6465) for details on a potential issue for your installation).\n>\n> 2. Care is taken ensure that there is adequate compute capacity to create the index in the background while still servicing requests.", "- FIX: attempt to get travis to deploy to npmjs again. See [#6475](https://github.com/parse-community/parse-server/pull/6457). Thanks to [Arthur Cinader](https://github.com/acinader).", "### 4.0.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.0.0...4.0.1)\n- FIX: correct 'new' travis config to properly deploy. See [#6452](https://github.com/parse-community/parse-server/pull/6452). Thanks to [Arthur Cinader](https://github.com/acinader).\n- FIX: Better message on not allowed to protect default fields. See [#6439](https://github.com/parse-community/parse-server/pull/6439).Thanks to [Old Grandpa](https://github.com/BufferUnderflower)", "### 4.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.10.0...4.0.0)", "> __Special Note on Upgrading to Parse Server 4.0.0 and above__\n>\n> In addition to the breaking changes noted below, [#5634](https://github.com/parse-community/parse-server/pull/5634) introduces a two new case insensitive indexes on the `User` collection. Special care should be taken when upgrading to this version to ensure that:\n>\n> 1. The new indexes can be successfully created (see issue [#6465](https://github.com/parse-community/parse-server/issues/6465) for details on a potential issue for your installation).\n>\n> 2. Care is taken ensure that there is adequate compute capacity to create the index in the background while still servicing requests.", "- NEW: add hint option to Parse.Query [#6322](https://github.com/parse-community/parse-server/pull/6322). Thanks to [Steve Stencil](https://github.com/stevestencil)\n- FIX: CLP objectId size validation fix [#6332](https://github.com/parse-community/parse-server/pull/6332). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- FIX: Add volumes to Docker command [#6356](https://github.com/parse-community/parse-server/pull/6356). Thanks to [Kasra Bigdeli](https://github.com/githubsaturn)\n- NEW: GraphQL 3rd Party LoginWith Support [#6371](https://github.com/parse-community/parse-server/pull/6371). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: GraphQL Geo Queries [#6363](https://github.com/parse-community/parse-server/pull/6363). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: GraphQL Nested File Upload [#6372](https://github.com/parse-community/parse-server/pull/6372). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Granular CLP pointer permissions [#6352](https://github.com/parse-community/parse-server/pull/6352). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- FIX: Add missing colon for customPages [#6393](https://github.com/parse-community/parse-server/pull/6393). Thanks to [Jerome De Leon](https://github.com/JeromeDeLeon)\n- NEW: `afterLogin` cloud code hook [#6387](https://github.com/parse-community/parse-server/pull/6387). Thanks to [David Corona](https://github.com/davesters)\n- FIX: __BREAKING CHANGE__ Prevent new usernames or emails that clash with existing users' email or username if it only differs by case. For example, don't allow a new user with the name 'Jane' if we already have a user 'jane'. [#5634](https://github.com/parse-community/parse-server/pull/5634). Thanks to [Arthur Cinader](https://github.com/acinader)\n- FIX: Support Travis CI V2. [#6414](https://github.com/parse-community/parse-server/pull/6414). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Prevent crashing on websocket error. [#6418](https://github.com/parse-community/parse-server/pull/6418). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Allow protectedFields for Authenticated users and Public. [$6415](https://github.com/parse-community/parse-server/pull/6415). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- FIX: Correct bug in determining GraphQL pointer errors when mutating. [#6413](https://github.com/parse-community/parse-server/pull/6431). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Allow true GraphQL Schema Customization. [#6360](https://github.com/parse-community/parse-server/pull/6360). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- __BREAKING CHANGE__: Remove Support for Mongo version < 3.6 [#6445](https://github.com/parse-community/parse-server/pull/6445). Thanks to [Arthur Cinader](https://github.com/acinader)", "### 3.10.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.9.0...3.10.0)\n- FIX: correct and cover ordering queries in GraphQL [#6316](https://github.com/parse-community/parse-server/pull/6316). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL support for reset password email [#6301](https://github.com/parse-community/parse-server/pull/6301). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: Add default limit to GraphQL fetch [#6304](https://github.com/parse-community/parse-server/pull/6304). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- DOCS: use bash syntax highlighting [#6302](https://github.com/parse-community/parse-server/pull/6302). Thanks to [Jerome De Leon](https://github.com/JeromeDeLeon)\n- NEW: Add max log file option [#6296](https://github.com/parse-community/parse-server/pull/6296). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: support user supplied objectId [#6101](https://github.com/parse-community/parse-server/pull/6101). Thanks to [Ruhan](https://github.com/rhuanbarretos)\n- FIX: Add missing encodeURIComponent on username [#6278](https://github.com/parse-community/parse-server/pull/6278). Thanks to [Christopher Brookes](https://github.com/Klaitos)\n- NEW: update PostgresStorageAdapter.js to use async/await [#6275](https://github.com/parse-community/parse-server/pull/6275). Thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n- NEW: Support required fields on output type for GraphQL [#6279](https://github.com/parse-community/parse-server/pull/6279). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Support required fields for GraphQL [#6271](https://github.com/parse-community/parse-server/pull/6279). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- CHANGE: use mongodb 3.3.5 [#6263](https://github.com/parse-community/parse-server/pull/6263). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: GraphQL: DX Relational Where Query [#6255](https://github.com/parse-community/parse-server/pull/6255). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- CHANGE: test against Postgres 11 [#6260](https://github.com/parse-community/parse-server/pull/6260). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- CHANGE: test against Postgres 11 [#6260](https://github.com/parse-community/parse-server/pull/6260). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: GraphQL alias for mutations in classConfigs [#6258](https://github.com/parse-community/parse-server/pull/6258). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- NEW: GraphQL classConfig query alias [#6257](https://github.com/parse-community/parse-server/pull/6257). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- NEW: Allow validateFilename to return a string or Parse Error [#6246](https://github.com/parse-community/parse-server/pull/6246). Thanks to [Mike Patnode](https://github.com/mpatnode)\n- NEW: Relay Spec [#6089](https://github.com/parse-community/parse-server/pull/6089). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Set default ACL for GraphQL [#6249](https://github.com/parse-community/parse-server/pull/6249). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: LDAP auth Adapter [#6226](https://github.com/parse-community/parse-server/pull/6226). Thanks to [Julian Dax](https://github.com/brodo)\n- FIX: improve beforeFind to include Query info [#6237](https://github.com/parse-community/parse-server/pull/6237). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: improve websocket error handling [#6230](https://github.com/parse-community/parse-server/pull/6230). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: addition of an afterLogout trigger [#6217](https://github.com/parse-community/parse-server/pull/6217). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Initialize default logger [#6186](https://github.com/parse-community/parse-server/pull/6186). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Add funding link [#6192](https://github.com/parse-community/parse-server/pull/6192 ). Thanks to [Tom Fox](https://github.com/TomWFox)\n- FIX: installationId on LiveQuery connect [#6180](https://github.com/parse-community/parse-server/pull/6180). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Add exposing port in docker container [#6165](https://github.com/parse-community/parse-server/pull/6165). Thanks to [Priyash Patil](https://github.com/priyashpatil)\n- NEW: Support Google Play Games Service [#6147](https://github.com/parse-community/parse-server/pull/6147). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- DOC: Throw error when setting authData to null [#6154](https://github.com/parse-community/parse-server/pull/6154). Thanks to [Manuel](https://github.com/mtrezza)\n- CHANGE: Move filename validation out of the Router and into the FilesAdaptor [#6157](https://github.com/parse-community/parse-server/pull/6157). Thanks to [Mike Patnode](https://github.com/mpatnode)\n- NEW: Added warning for special URL sensitive characters for appId [#6159](https://github.com/parse-community/parse-server/pull/6159). Thanks to [Saimoom Safayet Akash](https://github.com/saimoomsafayet)\n- NEW: Support Apple Game Center Auth [#6143](https://github.com/parse-community/parse-server/pull/6143). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- CHANGE: test with Node 12 [#6133](https://github.com/parse-community/parse-server/pull/6133). Thanks to [Arthur Cinader](https://github.com/acinader)\n- FIX: prevent after find from firing when saving objects [#6127](https://github.com/parse-community/parse-server/pull/6127). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: GraphQL Mutations not returning updated information [6130](https://github.com/parse-community/parse-server/pull/6130). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- CHANGE: Cleanup Schema cache per request [#6216](https://github.com/parse-community/parse-server/pull/6216). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- DOC: Improve installation instructions [#6120](https://github.com/parse-community/parse-server/pull/6120). Thanks to [Andres Galante](https://github.com/andresgalante)\n- DOC: add code formatting to contributing guidelines [#6119](https://github.com/parse-community/parse-server/pull/6119). Thanks to [Andres Galante](https://github.com/andresgalante)\n- NEW: Add GraphQL ACL Type + Input [#5957](https://github.com/parse-community/parse-server/pull/5957). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- CHANGE: replace public key [#6099](https://github.com/parse-community/parse-server/pull/6099). Thanks to [Arthur Cinader](https://github.com/acinader)\n- NEW: Support microsoft authentication in GraphQL [#6051](https://github.com/parse-community/parse-server/pull/6051). Thanks to [Alann Maulana](https://github.com/alann-maulana)\n- NEW: Install parse-server 3.9.0 instead of 2.2 [#6069](https://github.com/parse-community/parse-server/pull/6069). Thanks to [Julian Dax](https://github.com/brodo)\n- NEW: Use #!/bin/bash instead of #!/bin/sh [#6062](https://github.com/parse-community/parse-server/pull/6062). Thanks to [Julian Dax](https://github.com/brodo)\n- DOC: Update GraphQL readme section [#6030](https://github.com/parse-community/parse-server/pull/6030). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "### 3.9.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.8.0...3.9.0)\n- NEW: Add allowHeaders to Options [#6044](https://github.com/parse-community/parse-server/pull/6044). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- CHANGE: Introduce ReadOptionsInput to GraphQL API [#6030](https://github.com/parse-community/parse-server/pull/6030). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Stream video with GridFSBucketAdapter (implements byte-range requests) [#6028](https://github.com/parse-community/parse-server/pull/6028). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Aggregate not matching null values [#6043](https://github.com/parse-community/parse-server/pull/6043). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Improve callCloudCode mutation to receive a CloudCodeFunction enum instead of a String in the GraphQL API [#6029](https://github.com/parse-community/parse-server/pull/6029). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- TEST: Add more tests to transactions [#6022](https://github.com/parse-community/parse-server/pull/6022). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Pointer constraint input type as ID in the GraphQL API [#6020](https://github.com/parse-community/parse-server/pull/6020). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- CHANGE: Remove underline from operators of the GraphQL API [#6024](https://github.com/parse-community/parse-server/pull/6024). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Make method async as expected in usage [#6025](https://github.com/parse-community/parse-server/pull/6025). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- DOC: Added breaking change note to 3.8 release [#6023](https://github.com/parse-community/parse-server/pull/6023). Thanks to [Manuel](https://github.com/mtrezza)\n- NEW: Added support for line auth [#6007](https://github.com/parse-community/parse-server/pull/6007). Thanks to [Saimoom Safayet Akash](https://github.com/saimoomsafayet)\n- FIX: Fix aggregate group id [#5994](https://github.com/parse-community/parse-server/pull/5994). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Schema operations instead of generic operations in the GraphQL API [#5993](https://github.com/parse-community/parse-server/pull/5993). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- DOC: Fix changelog formatting[#6009](https://github.com/parse-community/parse-server/pull/6009). Thanks to [Tom Fox](https://github.com/TomWFox)\n- CHANGE: Rename objectId to id in the GraphQL API [#5985](https://github.com/parse-community/parse-server/pull/5985). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- FIX: Fix beforeLogin trigger when user has a file [#6001](https://github.com/parse-community/parse-server/pull/6001). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- DOC: Update GraphQL Docs with the latest changes [#5980](https://github.com/parse-community/parse-server/pull/5980). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "### 3.8.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.7.2...3.8.0)\n- NEW: Protected fields pointer-permissions support [#5951](https://github.com/parse-community/parse-server/pull/5951). Thanks to [Dobbias Nan](https://github.com/Dobbias)\n- NEW: GraphQL DX: Relation/Pointer [#5946](https://github.com/parse-community/parse-server/pull/5946). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Master Key Only Config Properties [#5953](https://github.com/parse-community/parse-server/pull/5954). Thanks to [Manuel](https://github.com/mtrezza)\n- FIX: Better validation when creating a Relation fields [#5922](https://github.com/parse-community/parse-server/pull/5922). Thanks to [Lucas Alencar](https://github.com/alencarlucas)\n- NEW: enable GraphQL file upload [#5944](https://github.com/parse-community/parse-server/pull/5944). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Handle shutdown on grid adapters [#5943](https://github.com/parse-community/parse-server/pull/5943). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Fix GraphQL max upload size [#5940](https://github.com/parse-community/parse-server/pull/5940). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Remove Buffer() deprecation notice [#5942](https://github.com/parse-community/parse-server/pull/5942). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Remove MongoDB unified topology deprecation notice from the grid adapter [#5941](https://github.com/parse-community/parse-server/pull/5941). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: add callback for serverCloseComplete [#5937](https://github.com/parse-community/parse-server/pull/5937). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- DOCS: Add Cloud Code guide to README [#5936](https://github.com/parse-community/parse-server/pull/5936). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Remove nested operations from GraphQL API [#5931](https://github.com/parse-community/parse-server/pull/5931). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Improve Live Query Monitoring [#5927](https://github.com/parse-community/parse-server/pull/5927). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: GraphQL: Fix undefined Array [#5296](https://github.com/parse-community/parse-server/pull/5926). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Added array support for pointer-permissions [#5921](https://github.com/parse-community/parse-server/pull/5921). Thanks to [Dobbias Nan](https://github.com/Dobbias)\n- GraphQL: Renaming Types/Inputs [#5921](https://github.com/parse-community/parse-server/pull/5921). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: Lint no-prototype-builtins [#5920](https://github.com/parse-community/parse-server/pull/5920). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- GraphQL: Inline Fragment on Array Fields [#5908](https://github.com/parse-community/parse-server/pull/5908). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- DOCS: Add instructions to launch a compatible Docker Postgres [](). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- Fix: Undefined dot notation in matchKeyInQuery [#5917](https://github.com/parse-community/parse-server/pull/5917). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- Fix: Logger print JSON and Numbers [#5916](https://github.com/parse-community/parse-server/pull/5916). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- GraphQL: Return specific Type on specific Mutation [#5893](https://github.com/parse-community/parse-server/pull/5893). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: Apple sign-in authAdapter [#5891](https://github.com/parse-community/parse-server/pull/5891). Thanks to [SebC](https://github.com/SebC99).\n- DOCS: Add GraphQL beta notice [#5886](https://github.com/parse-community/parse-server/pull/5886). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- GraphQL: Remove \"password\" output field from _User class [#5889](https://github.com/parse-community/parse-server/pull/5889). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- GraphQL: Object constraints [#5715](https://github.com/parse-community/parse-server/pull/5715). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- DOCS: README top section overhaul + add sponsors [#5876](https://github.com/parse-community/parse-server/pull/5876). Thanks to [Tom Fox](https://github.com/TomWFox)\n- FIX: Return a Promise from classUpdate method [#5877](https://github.com/parse-community/parse-server/pull/5877). Thanks to [Lucas Alencar](https://github.com/alencarlucas)\n- FIX: Use UTC Month in aggregate tests [#5879](https://github.com/parse-community/parse-server/pull/5879). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Transaction was aborting before all promises have either resolved or rejected [#5878](https://github.com/parse-community/parse-server/pull/5878). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Use transactions for batch operation [#5849](https://github.com/parse-community/parse-server/pull/5849). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "#### Breaking Changes:\n- If you are running Parse Server on top of a MongoDB deployment which does not fit the [Retryable Writes Requirements](https://docs.mongodb.com/manual/core/retryable-writes/#prerequisites), you will have to add `retryWrites=false` to your connection string in order to upgrade to Parse Server 3.8.", "### 3.7.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.7.1...3.7.2)", "- FIX: Live Query was failing on release 3.7.1", "### 3.7.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.7.0...3.7.1)", "- FIX: Missing APN module\n- FIX: Set falsy values as default to schema fields [#5868](https://github.com/parse-community/parse-server/pull/5868), thanks to [Lucas Alencar](https://github.com/alencarlucas)\n- NEW: Implement WebSocketServer Adapter [#5866](https://github.com/parse-community/parse-server/pull/5866), thanks to [Diamond Lewis](https://github.com/dplewis)", "### 3.7.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.6.0...3.7.0)", "- FIX: Prevent linkWith sessionToken from generating new session [#5801](https://github.com/parse-community/parse-server/pull/5801), thanks to [Diamond Lewis](https://github.com/dplewis)\n- GraphQL: Improve session token error messages [#5753](https://github.com/parse-community/parse-server/pull/5753), thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- NEW: GraphQL { functions { call } } generic mutation [#5818](https://github.com/parse-community/parse-server/pull/5818), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL Custom Schema [#5821](https://github.com/parse-community/parse-server/pull/5821), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL custom schema on CLI [#5828](https://github.com/parse-community/parse-server/pull/5828), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL @mock directive [#5836](https://github.com/parse-community/parse-server/pull/5836), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: GraphQL _or operator not working [#5840](https://github.com/parse-community/parse-server/pull/5840), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Add \"count\" to CLP initial value [#5841](https://github.com/parse-community/parse-server/pull/5841), thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- NEW: Add ability to alter the response from the after save trigger [#5814](https://github.com/parse-community/parse-server/pull/5814), thanks to [BrunoMaurice](https://github.com/brunoMaurice)\n- FIX: Cache apple public key for the case it fails to fetch again [#5848](https://github.com/parse-community/parse-server/pull/5848), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL Configuration Options [#5782](https://github.com/parse-community/parse-server/pull/5782), thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- NEW: Required fields and default values [#5835](https://github.com/parse-community/parse-server/pull/5835), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Postgres safely escape strings in nested objects [#5855](https://github.com/parse-community/parse-server/pull/5855), thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Support PhantAuth authentication [#5850](https://github.com/parse-community/parse-server/pull/5850), thanks to [Ivan SZKIBA](https://github.com/szkiba)\n- FIX: Remove uws package [#5860](https://github.com/parse-community/parse-server/pull/5860), thanks to [Zeal Murapa](https://github.com/GoGross)", "### 3.6.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.5.0...3.6.0)", "- SECURITY FIX: Address [Security Advisory](https://github.com/parse-community/parse-server/security/advisories/GHSA-8w3j-g983-8jh5) of a potential [Enumeration Attack](https://www.owasp.org/index.php/Testing_for_User_Enumeration_and_Guessable_User_Account_(OWASP-AT-002)#Description_of_the_Issue) [73b0f9a](https://github.com/parse-community/parse-server/commit/73b0f9a339b81f5d757725dc557955a7b670a3ec), big thanks to [Fabian Strachanski](https://github.com/fastrde) for identifying the problem, creating a fix and following the [vulnerability disclosure guidelines](https://github.com/parse-community/parse-server/blob/master/SECURITY.md#parse-community-vulnerability-disclosure-program)\n- NEW: Added rest option: excludeKeys [#5737](https://github.com/parse-community/parse-server/pull/5737), thanks to [Raschid J.F. Rafeally](https://github.com/RaschidJFR)\n- FIX: LiveQuery create event with fields [#5790](https://github.com/parse-community/parse-server/pull/5790), thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Generate sessionToken with linkWith [#5799](https://github.com/parse-community/parse-server/pull/5799), thanks to [Diamond Lewis](https://github.com/dplewis)", "### 3.5.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.4...3.5.0)", "- NEW: GraphQL Support [#5674](https://github.com/parse-community/parse-server/pull/5674), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "[GraphQL Guide](https://github.com/parse-community/parse-server#graphql)", "- NEW: Sign in with Apple [#5694](https://github.com/parse-community/parse-server/pull/5694), thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: AppSecret to Facebook Auth [#5695](https://github.com/parse-community/parse-server/pull/5695), thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Postgres: Regex support foreign characters [#5598](https://github.com/parse-community/parse-server/pull/5598), thanks to [Jeff Gu Kang](https://github.com/JeffGuKang)\n- FIX: Winston Logger string interpolation [#5729](https://github.com/parse-community/parse-server/pull/5729), thanks to [Diamond Lewis](https://github.com/dplewis)", "### 3.4.4\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.3...3.4.4)", "Fix: Commit changes", "### 3.4.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.2...3.4.3)", "Fix: Use changes in master to travis configuration to enable pushing to npm and gh_pages. See diff for details.", "### 3.4.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.1...3.4.2)", "Fix: In my haste to get a [Security Fix](https://github.com/parse-community/parse-server/security/advisories/GHSA-2479-qvv7-47qq) out, I added [8709daf](https://github.com/parse-community/parse-server/commit/8709daf698ea69b59268cb66f0f7cee75b52daa5) to master instead of to 3.4.1. This commit fixes that. [Arthur Cinader](https://github.com/acinader)", "### 3.4.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.0...3.4.1)", "Security Fix: see Advisory: [GHSA-2479-qvv7-47q](https://github.com/parse-community/parse-server/security/advisories/GHSA-2479-qvv7-47qq) for details [8709daf](https://github.com/parse-community/parse-server/commit/8709daf698ea69b59268cb66f0f7cee75b52daa5). Big thanks to: [Benjamin Simonsson](https://github.com/BenniPlejd) for identifying the issue and promptly bringing it to the Parse Community's attention and also big thanks to the indefatigable [Diamond Lewis](https://github.com/dplewis) for crafting a failing test and then a solution within an hour of the report.", "### 3.4.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.3.0...3.4.0)\n- NEW: Aggregate supports group by date fields [#5538](https://github.com/parse-community/parse-server/pull/5538) thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: API for Read Preferences [#3963](https://github.com/parse-community/parse-server/pull/3963) thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Add Redis options for LiveQuery [#5584](https://github.com/parse-community/parse-server/pull/5584) thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Add Direct Access option for Server Config [#5550](https://github.com/parse-community/parse-server/pull/5550) thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: updating mixed array in Postgres [#5552](https://github.com/parse-community/parse-server/pull/5552) thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: notEqualTo GeoPoint Query in Postgres [#5549](https://github.com/parse-community/parse-server/pull/5549), thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: put the timestamp back in logs that was lost after Winston upgrade [#5571](https://github.com/parse-community/parse-server/pull/5571), thanks to [Steven Rowe](https://github.com/mrowe009) and [Arthur Cinader](https://github.com/acinader)\n- FIX: Validates permission before calling beforeSave [#5546](https://github.com/parse-community/parse-server/pull/5546), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Remove userSensitiveFields default value. [#5588](https://github.com/parse-community/parse-server/pull/5588), thanks to [William George](https://github.com/awgeorge)\n- FIX: Decode Date JSON value in LiveQuery. [#5540](https://github.com/parse-community/parse-server/pull/5540), thanks to [ananfang](https://github.com/ananfang)", "\n### 3.3.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.3...3.3.0)\n- NEW: beforeLogin trigger with support for auth providers ([#5445](https://github.com/parse-community/parse-server/pull/5445)), thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- NEW: RFC 7662 compliant OAuth2 auth adapter ([#4910](https://github.com/parse-community/parse-server/pull/4910)), thanks to [Müller Zsolt](https://github.com/zsmuller)\n- FIX: cannot change password when maxPasswordHistory is 1 ([#5191](https://github.com/parse-community/parse-server/pull/5191)), thanks to [Tulsi Sapkota](https://github.com/Tolsee)\n- FIX (Postgres): count being very slow on large Parse Classes' collections ([#5330](https://github.com/parse-community/parse-server/pull/5330)), thanks to [CoderickLamar](https://github.com/CoderickLamar)\n- FIX: using per-key basis queue ([#5420](https://github.com/parse-community/parse-server/pull/5420)), thanks to [Georges Jamous](https://github.com/georgesjamous)\n- FIX: issue on count with Geo constraints and mongo ([#5286](https://github.com/parse-community/parse-server/pull/5286)), thanks to [Julien Quéré](https://github.com/jlnquere)", "### 3.2.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.2...3.2.3)\n- Correct previous release with patch that is fully merged", "### 3.2.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.1...3.2.2)\n- Security fix to properly process userSensitiveFields when parse-server is started with\n ../lib/cli/parse-server [#5463](https://github.com/parse-community/parse-server/pull/5463\n )", "### 3.2.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.0...3.2.1)\n- Increment package.json version to match the deployment tag", "### 3.2.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.3...3.2.0)\n- NEW: Support accessing sensitive fields with an explicit ACL. Not documented yet, see [tests](https://github.com/parse-community/parse-server/blob/f2c332ea6a984808ad5b2e3ce34864a20724f72b/spec/UserPII.spec.js#L526) for examples\n- Upgrade Parse SDK JS to 2.3.1 [#5457](https://github.com/parse-community/parse-server/pull/5457)\n- Hides token contents in logStartupOptions if they arrive as a buffer [#6a9380](https://github.com/parse-community/parse-server/commit/6a93806c62205a56a8f4e3b8765848c552510337)\n- Support custom message for password requirements [#5399](https://github.com/parse-community/parse-server/pull/5399)\n- Support for Ajax password reset [#5332](https://github.com/parse-community/parse-server/pull/5332)\n- Postgres: Refuse to build unsafe JSON lists for contains [#5337](https://github.com/parse-community/parse-server/pull/5337)\n- Properly handle return values in beforeSave [#5228](https://github.com/parse-community/parse-server/pull/5228)\n- Fixes issue when querying user roles [#5276](https://github.com/parse-community/parse-server/pull/5276)\n- Fixes issue affecting update with CLP [#5269](https://github.com/parse-community/parse-server/pull/5269)", "### 3.1.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.2...3.1.3)", "- Postgres: Fixes support for global configuration\n- Postgres: Fixes support for numeric arrays\n- Postgres: Fixes issue affecting queries on empty arrays\n- LiveQuery: Adds support for transmitting the original object\n- Queries: Use estimated count if query is empty\n- Docker: Reduces the size of the docker image to 154Mb", "\n### 3.1.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.1...3.1.2)", "- Removes dev script, use TDD instead of server.\n- Removes nodemon and problematic dependencies.\n- Addressed event-stream security debacle.", "### 3.1.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.0...3.1.1)", "#### Improvements:\n* Fixes issue that would prevent users with large number of roles to resolve all of them [Antoine Cormouls](https://github.com/Moumouls) (#5131, #5132)\n* Fixes distinct query on special fields ([#5144](https://github.com/parse-community/parse-server/pull/5144))", "\n### 3.1.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.0.0...3.1.0)", "#### Breaking Changes:\n* Return success on sendPasswordResetEmail even if email not found. (#7fe4030)\n#### Security Fix:\n* Expire password reset tokens on email change (#5104)\n#### Improvements:\n* Live Query CLPs (#4387)\n* Reduces number of calls to injectDefaultSchema (#5107)\n* Remove runtime dependency on request (#5076)\n#### Bug fixes:\n* Fixes issue with vkontatke authentication (#4977)\n* Use the correct function when validating google auth tokens (#5018)\n* fix unexpected 'delete' trigger issue on LiveQuery (#5031)\n* Improves performance for roles and ACL's in live query server (#5126)", "\n### 3.0.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.4...3.0.0)", "`parse-server` 3.0.0 comes with brand new handlers for cloud code. It now fully supports promises and async / await.\nFor more informations, visit the v3.0.0 [migration guide](https://github.com/parse-community/parse-server/blob/master/3.0.0.md).", "#### Breaking changes:\n* Cloud Code handlers have a new interface based on promises.\n* response.success / response.error are removed in Cloud Code\n* Cloud Code runs with Parse-SDK 2.0\n* The aggregate now require aggregates to be passed in the form: `{\"pipeline\": [...]}` (REST Only)", "#### Improvements:\n* Adds Pipeline Operator to Aggregate Router.\n* Adds documentations for parse-server's adapters, constructors and more.\n* Adds ability to pass a context object between `beforeSave` and `afterSave` affecting the same object.", "#### Bug Fixes:\n* Fixes issue that would crash the server when mongo objects had undefined values [#4966](https://github.com/parse-community/parse-server/issues/4966)\n* Fixes issue that prevented ACL's from being used with `select` (see [#571](https://github.com/parse-community/Parse-SDK-JS/issues/571))", "#### Dependency updates:\n* [@parse/simple-mailgun-adapter@1.1.0](https://www.npmjs.com/package/@parse/simple-mailgun-adapter)\n* [mongodb@3.1.3](https://www.npmjs.com/package/mongodb)\n* [request@2.88.0](https://www.npmjs.com/package/request)", "##### Devevelopment Dependencies Updates:\n* [@parse/minami@1.0.0](https://www.npmjs.com/package/@parse/minami)\n* [deep-diff@1.0.2](https://www.npmjs.com/package/deep-diff)\n* [flow-bin@0.79.0](https://www.npmjs.com/package/flow-bin)\n* [jsdoc@3.5.5](https://www.npmjs.com/package/jsdoc)\n* [jsdoc-babel@0.4.0](https://www.npmjs.com/package/jsdoc-babel)", "### 2.8.4\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.3...2.8.4)", "#### Improvements:\n* Adds ability to forward errors to express handler (#4697)\n* Adds ability to increment the push badge with an arbitrary value (#4889)\n* Adds ability to preserve the file names when uploading (#4915)\n* `_User` now follow regular ACL policy. Letting administrator lock user out. (#4860) and (#4898)\n* Ensure dates are properly handled in aggregates (#4743)\n* Aggregates: Improved support for stages sharing the same name\n* Add includeAll option\n* Added verify password to users router and tests. (#4747)\n* Ensure read preference is never overriden, so DB config prevails (#4833)\n* add support for geoWithin.centerSphere queries via withJSON (#4825)\n* Allow sorting an object field (#4806)\n* Postgres: Don't merge JSON fields after save() to keep same behaviour as MongoDB (#4808) (#4815)", "#### Dependency updates\n* [commander@2.16.0](https://www.npmjs.com/package/commander)\n* [mongodb@3.1.1](https://www.npmjs.com/package/mongodb)\n* [pg-promise@8.4.5](https://www.npmjs.com/package/pg-promise)\n* [ws@6.0.0](https://www.npmjs.com/package/ws)\n* [bcrypt@3.0.0](https://www.npmjs.com/package/bcrypt)\n* [uws@10.148.1](https://www.npmjs.com/package/uws)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.2.0](https://www.npmjs.com/package/cross-env)\n* [eslint@5.0.0](https://www.npmjs.com/package/eslint)\n* [flow-bin@0.76.0](https://www.npmjs.com/package/flow-bin)\n* [mongodb-runner@4.0.0](https://www.npmjs.com/package/mongodb-runner)\n* [nodemon@1.18.1](https://www.npmjs.com/package/nodemon)\n* [nyc@12.0.2](https://www.npmjs.com/package/nyc)\n* [request-promise@4.2.2](https://www.npmjs.com/package/request-promise)\n* [supports-color@5.4.0](https://www.npmjs.com/package/supports-color)", "### 2.8.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.2...2.8.3)", "#### Improvements:", "* Adds support for JS SDK 2.0 job status header\n* Removes npm-git scripts as npm supports using git repositories that build, thanks to [Florent Vilmart](https://github.com/flovilmart)", "\n### 2.8.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.1...2.8.2)", "##### Bug Fixes:\n* Ensure legacy users without ACL's are not locked out, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements:\n* Use common HTTP agent to increase webhooks performance, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Adds withinPolygon support for Polygon objects, thanks to [Mads Bjerre](https://github.com/madsb)", "#### Dependency Updates:\n* [ws@5.2.0](https://www.npmjs.com/package/ws)\n* [commander@2.15.1](https://www.npmjs.com/package/commander)\n* [nodemon@1.17.5](https://www.npmjs.com/package/nodemon)", "##### Devevelopment Dependencies Updates:\n* [flow-bin@0.73.0](https://www.npmjs.com/package/flow-bin)\n* [cross-env@5.1.6](https://www.npmjs.com/package/cross-env)\n* [gaze@1.1.3](https://www.npmjs.com/package/gaze)\n* [deepcopy@1.0.0](https://www.npmjs.com/package/deepcopy)\n* [deep-diff@1.0.1](https://www.npmjs.com/package/deep-diff)", "\n### 2.8.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.1...2.8.0)", "Ensure all the files are properly exported to the final package.", "### 2.8.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.0...2.7.4)", "#### New Features\n* Adding Mongodb element to add `arrayMatches` the #4762 (#4766), thanks to [Jérémy Piednoel](https://github.com/jeremypiednoel)\n* Adds ability to Lockout users (#4749), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes:\n* Fixes issue when using afterFind with relations (#4752), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New query condition support to match all strings that starts with some other given strings (#3864), thanks to [Eduard Bosch Bertran](https://github.com/eduardbosch)\n* Allow creation of indices on default fields (#4738), thanks to [Claire Neveu](https://github.com/ClaireNeveu)\n* Purging empty class (#4676), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Postgres: Fixes issues comparing to zero or false (#4667), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Fix Aggregate Match Pointer (#4643), thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Improvements:\n* Allow Parse.Error when returning from Cloud Code (#4695), thanks to [Saulo Tauil](https://github.com/saulogt)\n* Fix typo: \"requrest\" -> \"request\" (#4761), thanks to [Joseph Frazier](https://github.com/josephfrazier)\n* Send version for Vkontakte API (#4725), thanks to [oleg](https://github.com/alekoleg)\n* Ensure we respond with invalid password even if email is unverified (#4708), thanks to [dblythy](https://github.com/dblythy)\n* Add _password_history to default sensitive data (#4699), thanks to [Jong Eun Lee](https://github.com/yomybaby)\n* Check for node version in postinstall script (#4657), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Remove FB Graph API version from URL to use the oldest non deprecated version, thanks to [SebC](https://github.com/SebC99)", "#### Dependency Updates:\n* [@parse/push-adapter@2.0.3](https://www.npmjs.com/package/@parse/push-adapter)\n* [@parse/simple-mailgun-adapter@1.0.2](https://www.npmjs.com/package/@parse/simple-mailgun-adapter)\n* [uws@10.148.0](https://www.npmjs.com/package/uws)\n* [body-parser@1.18.3](https://www.npmjs.com/package/body-parser)\n* [mime@2.3.1](https://www.npmjs.com/package/mime)\n* [request@2.85.0](https://www.npmjs.com/package/request)\n* [mongodb@3.0.7](https://www.npmjs.com/package/mongodb)\n* [bcrypt@2.0.1](https://www.npmjs.com/package/bcrypt)\n* [ws@5.1.1](https://www.npmjs.com/package/ws)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.1.5](https://www.npmjs.com/package/cross-env)\n* [flow-bin@0.71.0](https://www.npmjs.com/package/flow-bin)\n* [deep-diff@1.0.0](https://www.npmjs.com/package/deep-diff)\n* [nodemon@1.17.3](https://www.npmjs.com/package/nodemon)", "\n### 2.7.4\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.4...2.7.3)", "#### Bug Fixes:\n* Fixes an issue affecting polygon queries, thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Dependency Updates:\n* [pg-promise@8.2.1](https://www.npmjs.com/package/pg-promise)", "##### Development Dependencies Updates:\n* [nodemon@1.17.1](https://www.npmjs.com/package/nodemon)", "### 2.7.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.3...2.7.2)", "#### Improvements:\n* Improve documentation for LiveQuery options, thanks to [Arthur Cinader](https://github.com/acinader)\n* Improve documentation for using cloud code with docker, thanks to [Stephen Tuso](https://github.com/stephentuso)\n* Adds support for Facebook's AccountKit, thanks to [6thfdwp](https://github.com/6thfdwp)\n* Disable afterFind routines when running aggregates, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Improve support for distinct aggregations of nulls, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Regenreate the email verification token when requesting a new email, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)", "#### Bug Fixes:\n* Fix issue affecting readOnly masterKey and purge command, thanks to [AreyouHappy](https://github.com/AreyouHappy)\n* Fixes Issue unsetting in beforeSave doesn't allow object creation, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Fixes issue crashing server on invalid live query payload, thanks to [fridays](https://github.com/fridays)\n* Fixes issue affecting postgres storage adapter \"undefined property '__op'\", thanks to [Tyson Andre](https://github,com/TysonAndre)", "#### Dependency Updates:\n* [winston@2.4.1](https://www.npmjs.com/package/winston)\n* [pg-promise@8.2.0](https://www.npmjs.com/package/pg-promise)\n* [commander@2.15.0](https://www.npmjs.com/package/commander)\n* [lru-cache@4.1.2](https://www.npmjs.com/package/lru-cache)\n* [parse@1.11.1](https://www.npmjs.com/package/parse)\n* [ws@5.0.0](https://www.npmjs.com/package/ws)\n* [mongodb@3.0.4](https://www.npmjs.com/package/mongodb)\n* [lodash@4.17.5](https://www.npmjs.com/package/lodash)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.1.4](https://www.npmjs.com/package/cross-env)\n* [flow-bin@0.67.1](https://www.npmjs.com/package/flow-bin)\n* [jasmine@3.1.0](https://www.npmjs.com/package/jasmine)\n* [parse@1.11.1](https://www.npmjs.com/package/parse)\n* [babel-eslint@8.2.2](https://www.npmjs.com/package/babel-eslint)\n* [nodemon@1.15.0](https://www.npmjs.com/package/nodemon)", "### 2.7.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.2...2.7.1)", "#### Improvements:\n* Improved match aggregate\n* Do not mark the empty push as failed\n* Support pointer in aggregate query\n* Introduces flow types for storage\n* Postgres: Refactoring of Postgres Storage Adapter\n* Postgres: Support for multiple projection in aggregate\n* Postgres: performance optimizations\n* Adds infos about vulnerability disclosures\n* Adds ability to login with email when provided as username", "#### Bug Fixes\n* Scrub Passwords with URL Encoded Characters\n* Fixes issue affecting using sorting in beforeFind", "#### Dependency Updates:\n* [commander@2.13.0](https://www.npmjs.com/package/commander)\n* [semver@5.5.0](https://www.npmjs.com/package/semver)\n* [pg-promise@7.4.0](https://www.npmjs.com/package/pg-promise)\n* [ws@4.0.0](https://www.npmjs.com/package/ws)\n* [mime@2.2.0](https://www.npmjs.com/package/mime)\n* [parse@1.11.0](https://www.npmjs.com/package/parse)", "##### Devevelopment Dependencies Updates:\n* [nodemon@1.14.11](https://www.npmjs.com/package/nodemon)\n* [flow-bin@0.64.0](https://www.npmjs.com/package/flow-bin)\n* [jasmine@2.9.0](https://www.npmjs.com/package/jasmine)\n* [cross-env@5.1.3](https://www.npmjs.com/package/cross-env)", "### 2.7.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.1...2.7.0)", ":warning: Fixes a security issue affecting Class Level Permissions", "* Adds support for dot notation when using matchesKeyInQuery, thanks to [Henrik](https://github.com/bohemima) and [Arthur Cinader](https://github.com/acinader)", "### 2.7.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.0...2.6.5)", ":warning: This version contains an issue affecting Class Level Permissions on mongoDB. Please upgrade to 2.7.1.", "Starting parse-server 2.7.0, the minimun nodejs version is 6.11.4, please update your engines before updating parse-server", "#### New Features:\n* Aggregation endpoints, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Adds indexation options onto Schema endpoints, thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Bug fixes:\n* Fixes sessionTokens being overridden in 'find' (#4332), thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Proper `handleShutdown()` feature to close database connections (#4361), thanks to [CHANG, TZU-YEN](https://github.com/trylovetom)\n* Fixes issue affecting state of _PushStatus objects, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Fixes issue affecting calling password reset password pages with wrong appid, thanks to [Bryan de Leon](https://github.com/bryandel)\n* Fixes issue affecting duplicates _Sessions on successive logins, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements:\n* Updates contributing guides, and improves windows support, thanks to [Addison Elliott](https://github.com/addisonelliott)\n* Uses new official scoped packaged, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improves health checks responses, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Add password confirmation to choose_password, thanks to [Worathiti Manosroi](https://github.com/pungme)\n* Improve performance of relation queries, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [commander@2.12.1](https://www.npmjs.com/package/commander)\n* [ws@3.3.2](https://www.npmjs.com/package/ws)\n* [uws@9.14.0](https://www.npmjs.com/package/uws)\n* [pg-promise@7.3.2](https://www.npmjs.com/package/pg-promise)\n* [parse@1.10.2](https://www.npmjs.com/package/parse)\n* [pg-promise@7.3.1](https://www.npmjs.com/package/pg-promise)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.1.1](https://www.npmjs.com/package/cross-env)", "", "### 2.6.5\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.5...2.6.4)", "#### New Features:\n* Adds support for read-only masterKey, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Adds support for relative time queries (mongodb only), thanks to [Marvel Mathew](https://github.com/marvelm)", "#### Improvements:\n* Handle possible afterSave exception, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Add support for expiration interval in Push, thanks to [Marvel Mathew](https://github.com/marvelm)", "#### Bug Fixes:\n* The REST API key was improperly inferred from environment when using the CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.6.4\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.4...2.6.3)", "#### Improvements:\n* Improves management of configurations and default values, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Adds ability to start ParseServer with `ParseServer.start(options)`, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Adds request original IP to cloud code hooks, thanks to [Gustav Ahlberg](https://github.com/Gyran)\n* Corrects some outdated links, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Adds serverURL validation on startup, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Adds ability to login with POST requests alongside GET, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Adds ability to login with email, instead of username, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug Fixes:\n* Fixes issue affecting beforeSaves and increments, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)", "#### Dependency Updates:\n* [parse-server-push-adapter@2.0.2](https://www.npmjs.com/package/parse-server-push-adapter)\n* [semver@5.4.1](https://www.npmjs.com/package/semver)\n* [pg-promise@7.0.3](https://www.npmjs.com/package/pg-promise)\n* [mongodb@2.2.33](https://www.npmjs.com/package/mongodb)\n* [parse@1.10.1](https://www.npmjs.com/package/parse)\n* [express@4.16.0](https://www.npmjs.com/package/express)\n* [mime@1.4.1](https://www.npmjs.com/package/mime)\n* [parse-server-simple-mailgun-adapter@1.0.1](https://www.npmjs.com/package/parse-server-simple-mailgun-adapter)", "##### Devevelopment Dependencies Updates:\n* [babel-preset-env@1.6.1](https://www.npmjs.com/package/babel-preset-env)\n* [cross-env@5.1.0](https://www.npmjs.com/package/cross-env)\n* [mongodb-runner@3.6.1](https://www.npmjs.com/package/mongodb-runner)\n* [eslint-plugin-flowtype@2.39.1](https://www.npmjs.com/package/eslint-plugin-flowtype)\n* [eslint@4.9.0](https://www.npmjs.com/package/eslint)", "### 2.6.3\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.2...2.6.3)", "#### Improvements:\n* Queries on Pointer fields with `$in` and `$nin` now supports list of objectId's, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* LiveQueries on `$in` and `$nin` for pointer fields work as expected thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Also remove device token when APNS error is BadDeviceToken, thanks to [Mauricio Tollin](https://github.com/)\n* LRU cache is not available on the ParseServer object, thanks to [Tyler Brock](https://github.com/tbrock)\n* Error messages are more expressive, thanks to [Tyler Brock](https://github.com/tbrock)\n* Postgres: Properly handle undefined field values, thanks to [Diamond Lewis](https://github.com/dlewis)\n* Updating with two GeoPoints fails correctly, thanks to [Anthony Mosca](https://github.com/aontas)", "#### New Features:\n* Adds ability to set a maxLimit on server configuration for queries, thanks to [Chris Norris](https://github.com/)", "#### Bug fixes:\n* Fixes issue affecting reporting `_PushStatus` with misconfigured serverURL, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting deletion of class that doesn't exist, thanks to [Diamond Lewis](https://github.com/dlewis)", "#### Dependency Updates:\n* [winston@2.4.0](https://www.npmjs.com/package/winston)\n* [pg-promise@6.10.2](https://www.npmjs.com/package/pg-promise)\n* [winston-daily-rotate-file@1.6.0](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [request@2.83.0](https://www.npmjs.com/package/request)\n* [body-parser@1.18.2](https://www.npmjs.com/package/body-parser)", "##### Devevelopment Dependencies Updates:\n* [request-promise@4.2.2](https://www.npmjs.com/package/request-promise)\n* [eslint@4.7.1](https://www.npmjs.com/package/eslint)", "### 2.6.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.1...2.6.2)", "#### Improvements:\n* PushWorker/PushQueue channels are properly prefixed with the Parse applicationId, thanks to [Marvel Mathew](https://github.com/marvelm)\n* You can use Parse.Cloud.afterSave hooks on _PushStatus\n* You can use Parse.Cloud.onLiveQueryEvent to track the number of clients and subscriptions\n* Adds support for more fields from the Audience class.", "#### New Features:\n* Push: Adds ability to track sentPerUTC offset if your push scheduler supports it.\n* Push: Adds support for cleaning up invalid deviceTokens from _Installation (PARSE_SERVER_CLEANUP_INVALID_INSTALLATIONS=1).", "#### Dependency Updates:\n* [ws@3.2.0](https://www.npmjs.com/package/ws)\n* [pg-promise@6.5.3](https://www.npmjs.com/package/pg-promise)\n* [winston-daily-rotate-file@1.5.0](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [body-parser@1.18.1](https://www.npmjs.com/package/body-parser)", "##### Devevelopment Dependencies Updates:\n* [nodemon@1.12.1](https://www.npmjs.com/package/nodemon)\n* [mongodb-runner@3.6.0](https://www.npmjs.com/package/mongodb-runner)\n* [babel-eslint@8.0.0](https://www.npmjs.com/package/babel-eslint)", "### 2.6.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.0...2.6.1)", "#### Improvements:\n* Improves overall performance of the server, more particularly with large query results.\n* Improves performance of InMemoryCacheAdapter by removing serialization.\n* Improves logging performance by skipping necessary log calls.\n* Refactors object routers to simplify logic.\n* Adds automatic indexing on $text indexes, thanks to [Diamon Lewis](https://github.com/dplewis)", "#### New Features:\n* Push: Adds ability to send localized pushes according to the _Installation localeIdentifier\n* Push: proper support for scheduling push in user's locale time, thanks to [Marvel Mathew](https://github.com/marvelm)\n* LiveQuery: Adds ability to use LiveQuery with a masterKey, thanks to [Jeremy May](https://github.com/kenishi)", "#### Bug Fixes:\n* Fixes an issue that would duplicate Session objects per userId-installationId pair.\n* Fixes an issue affecting pointer permissions introduced in this release.\n* Fixes an issue that would prevent displaying audiences correctly in dashboard.\n* Fixes an issue affecting preventLoginWithUnverifiedEmail upon signups.", "#### Dependency Updates:\n* [pg-promise@6.3.2](https://www.npmjs.com/package/pg-promise)\n* [body-parser@1.18.0](https://www.npmjs.com/package/body-parser)\n* [nodemon@1.11.1](https://www.npmjs.com/package/nodemon)", "##### Devevelopment Dependencies Updates:\n* [babel-cli@6.26.0](https://www.npmjs.com/package/babel-cli)", "### 2.6.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.3...2.6.0)", "#### Breaking Changes:\n* [parse-server-s3-adapter@1.2.0](https://www.npmjs.com/package/parse-server-s3-adapter): A new deprecation notice is introduced with parse-server-s3-adapter's version 1.2.0. An upcoming release will remove passing key and password arguments. AWS credentials should be set using AWS best practices. See the [Deprecation Notice for AWS credentials]( https://github.com/parse-server-modules/parse-server-s3-adapter/blob/master/README.md#deprecation-notice----aws-credentials) section of the adapter's README.", "#### New Features\n* Polygon is fully supported as a type, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Query supports PolygonContains, thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Improvements\n* Postgres: Adds support nested contains and containedIn, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Postgres: Adds support for `null` in containsAll queries, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Cloud Code: Request headers are passed to the cloud functions, thanks to [miguel-s](https://github.com/miguel-s)\n* Push: All push queries now filter only where deviceToken exists", "#### Bug Fixes:\n* Fixes issue affecting updates of _User objects when authData was passed.\n* Push: Pushing to an empty audience should now properly report a failed _PushStatus\n* Linking Users: Fixes issue affecting linking users with sessionToken only", "#### Dependency Updates:\n* [ws@3.1.0](https://www.npmjs.com/package/ws)\n* [mime@1.4.0](https://www.npmjs.com/package/mime)\n* [semver@5.4.0](https://www.npmjs.com/package/semver)\n* [uws@8.14.1](https://www.npmjs.com/package/uws)\n* [bcrypt@1.0.3](https://www.npmjs.com/package/bcrypt)\n* [mongodb@2.2.31](https://www.npmjs.com/package/mongodb)\n* [redis@2.8.0](https://www.npmjs.com/package/redis)\n* [pg-promise@6.3.1](https://www.npmjs.com/package/pg-promise)\n* [commander@2.11.0](https://www.npmjs.com/package/commander)", "##### Devevelopment Dependencies Updates:\n* [jasmine@2.8.0](https://www.npmjs.com/package/jasmine)\n* [babel-register@6.26.0](https://www.npmjs.com/package/babel-register)\n* [babel-core@6.26.0](https://www.npmjs.com/package/babel-core)\n* [cross-env@5.0.2](https://www.npmjs.com/package/cross-env)", "### 2.5.3\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.2...2.5.3)", "#### New Features:\n* badge property on android installations will now be set as on iOS (#3970), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug Fixes:\n* Fixes incorrect number parser for cache options", "### 2.5.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.1...2.5.2)", "#### Improvements:\n* Restores ability to run on node >= 4.6\n* Adds ability to configure cache from CLI\n* Removes runtime check for node >= 4.6", "### 2.5.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.0...2.5.1)", "#### New Features:\n* Adds ability to set default objectId size (#3950), thanks to [Steven Shipton](https://github.com/steven-supersolid)", "#### Improvements:\n* Uses LRU cache instead of InMemoryCache by default (#3979), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* iOS pushes are now using HTTP/2.0 instead of binary API (#3983), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [parse@1.10.0](https://www.npmjs.com/package/parse)\n* [pg-promise@6.3.0](https://www.npmjs.com/package/pg-promise)\n* [parse-server-s3-adapter@1.1.0](https://www.npmjs.com/package/parse-server-s3-adapter)\n* [parse-server-push-adapter@2.0.0](https://www.npmjs.com/package/parse-server-push-adapter)", "### 2.5.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.4.2...2.5.0)", "#### New Features:\n* Adds ability to run full text search (#3904), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Adds ability to run `$withinPolygon` queries (#3889), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Adds ability to pass read preference per query with mongodb (#3865), thanks to [davimacedo](https://github.com/davimacedo)\n* beforeFind trigger now includes `isGet` for get queries (#3862), thanks to [davimacedo](https://github.com/davimacedo)\n* Adds endpoints for dashboard's audience API (#3861), thanks to [davimacedo](https://github.com/davimacedo)\n* Restores the job scheduling endpoints (#3927), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements:\n* Removes unnecessary warning when using maxTimeMs with mongodb, thanks to [Tyler Brock](https://github.com/tbrock)\n* Improves access control on system classes (#3916), thanks to [Worathiti Manosroi](https://github.com/pungme)\n* Adds bytes support in postgres (#3894), thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Bug Fixes:\n* Fixes issue with vkontakte adapter that would hang the request, thanks to [Denis Trofimov](https://github.com/denistrofimov)\n* Fixes issue affecting null relational data (#3924), thanks to [davimacedo](https://github.com/davimacedo)\n* Fixes issue affecting session token deletion (#3937), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting the serverInfo endpoint (#3933), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting beforeSave with dot-noted sub-documents (#3912), thanks to [IlyaDiallo](https://github.com/IlyaDiallo)\n* Fixes issue affecting emails being sent when using a 3rd party auth (#3882), thanks to [davimacedo](https://github.com/davimacedo)", "#### Dependency Updates:\n* [commander@2.10.0](https://www.npmjs.com/package/commander)\n* [pg-promise@5.9.7](https://www.npmjs.com/package/pg-promise)\n* [lru-cache@4.1.0](https://www.npmjs.com/package/lru-cache)\n* [mongodb@2.2.28](https://www.npmjs.com/package/mongodb)", "##### Devevelopment dependencies\n* [babel-core@6.25.0](https://www.npmjs.com/package/babel-core)\n* [cross-env@5.0.1](https://www.npmjs.com/package/cross-env)\n* [nyc@11.0.2](https://www.npmjs.com/package/nyc)", "### 2.4.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.4.1...2.4.2)", "#### New Features:\n* ParseQuery: Support for withinPolygon [#3866](https://github.com/parse-community/parse-server/pull/3866), thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Improvements:\n* Postgres: Use transactions when deleting a class, [#3869](https://github.com/parse-community/parse-server/pull/3836), thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n* Postgres: Proper support for GeoPoint equality query, [#3874](https://github.com/parse-community/parse-server/pull/3836), thanks to [Diamond Lewis](https://github.com/dplewis)\n* beforeSave and liveQuery will be correctly triggered on email verification [#3851](https://github.com/parse-community/parse-server/pull/3851), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes:\n* Skip authData validation if it hasn't changed, on PUT requests [#3872](https://github.com/parse-community/parse-server/pull/3872), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [mongodb@2.2.27](https://www.npmjs.com/package/mongodb)\n* [pg-promise@5.7.2](https://www.npmjs.com/package/pg-promise)", "\n### 2.4.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.4.0...2.4.1)", "#### Bug fixes:\n* Fixes issue affecting relation updates ([#3835](https://github.com/parse-community/parse-server/pull/3835), [#3836](https://github.com/parse-community/parse-server/pull/3836)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting sending push notifications, thanks to [Felipe Andrade](https://github.com/felipemobile)\n* Session are always cleared when updating the passwords ([#3289](https://github.com/parse-community/parse-server/pull/3289), [#3821](https://github.com/parse-community/parse-server/pull/3821), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [body-parser@1.17.2](https://www.npmjs.com/package/body-parser)\n* [pg-promise@5.7.1](https://www.npmjs.com/package/pg-promise)\n* [ws@3.0.0](https://www.npmjs.com/package/ws)", "\n### 2.4.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.8...2.4.0)", "Starting 2.4.0, parse-server is tested against node 6.10 and 7.10, mongodb 3.2 and 3.4.\nIf you experience issues with older versions, please [open a issue](https://github.com/parse-community/parse-server/issues).", "#### New Features:\n* Adds `count` Class Level Permission ([#3814](https://github.com/parse-community/parse-server/pull/3814)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Proper graceful shutdown support ([#3786](https://github.com/parse-community/parse-server/pull/3786)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Let parse-server store as `scheduled` Push Notifications with push_time (#3717, #3722), thanks to [Felipe Andrade](https://github.com/felipemobile)", "#### Improvements\n* Parse-Server images are built through docker hub, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Skip authData validation if it hasn't changed, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* [postgres] Improve performance when adding many new fields to the Schema ([#3740](https://github.com/parse-community/parse-server/pull/3740)), thanks to [Paulo Vítor S Reis](https://github.com/paulovitin)\n* Test maintenance, wordsmithing and nits ([#3744](https://github.com/parse-community/parse-server/pull/3744)), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Bug Fixes:\n* [postgres] Fixes issue affecting deleting multiple fields of a Schema ([#3734](https://github.com/parse-community/parse-server/pull/3734), [#3735](https://github.com/parse-community/parse-server/pull/3735)), thanks to [Paulo Vítor S Reis](https://github.com/paulovitin)\n* Fix issue affecting _PushStatus state ([#3808](https://github.com/parse-community/parse-server/pull/3808)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* requiresAuthentication Class Level Permission behaves correctly, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Email Verification related fields are not exposed ([#3681](https://github.com/parse-community/parse-server/pull/3681), [#3393](https://github.com/parse-community/parse-server/pull/3393), [#3432](https://github.com/parse-community/parse-server/pull/3432)), thanks to [Anthony Mosca](https://github.com/aontas)\n* HTTP query parameters are properly obfuscated in logs ([#3793](https://github.com/parse-community/parse-server/pull/3793), [#3789](https://github.com/parse-community/parse-server/pull/3789)), thanks to [@youngerong](https://github.com/youngerong)\n* Improve handling of `$near` operators in `$or` queries ([#3767](https://github.com/parse-community/parse-server/pull/3767), [#3798](https://github.com/parse-community/parse-server/pull/3798)), thanks to [Jack Wearden](https://github.com/NotBobTheBuilder)\n* Fix issue affecting arrays of pointers ([#3169](https://github.com/parse-community/parse-server/pull/3169)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix issue affecting overloaded query constraints ([#3723](https://github.com/parse-community/parse-server/pull/3723), [#3678](https://github.com/parse-community/parse-server/pull/3678)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Properly catch unhandled rejections in _Installation updates ([#3795](https://github.com/parse-community/parse-server/pull/3795)), thanks to [kahoona77](https://github.com/kahoona77)", "#### Dependency Updates:", "* [uws@0.14.5](https://www.npmjs.com/package/uws)\n* [mime@1.3.6](https://www.npmjs.com/package/mime)\n* [mongodb@2.2.26](https://www.npmjs.com/package/mongodb)\n* [pg-promise@5.7.0](https://www.npmjs.com/package/pg-promise)\n* [semver@5.3.0](https://www.npmjs.com/package/semver)", "##### Devevelopment dependencies\n* [babel-cli@6.24.1](https://www.npmjs.com/package/babel-cli)\n* [babel-core@6.24.1](https://www.npmjs.com/package/babel-core)\n* [babel-preset-es2015@6.24.1](https://www.npmjs.com/package/babel-preset-es2015)\n* [babel-preset-stage-0@6.24.1](https://www.npmjs.com/package/babel-preset-stage-0)\n* [babel-register@6.24.1](https://www.npmjs.com/package/babel-register)\n* [cross-env@5.0.0](https://www.npmjs.com/package/cross-env)\n* [deep-diff@0.3.8](https://www.npmjs.com/package/deep-diff)\n* [gaze@1.1.2](https://www.npmjs.com/package/gaze)\n* [jasmine@2.6.0](https://www.npmjs.com/package/jasmine)\n* [jasmine-spec-reporter@4.1.0](https://www.npmjs.com/package/jasmine-spec-reporter)\n* [mongodb-runner@3.5.0](https://www.npmjs.com/package/mongodb-runner)\n* [nyc@10.3.2](https://www.npmjs.com/package/nyc)\n* [request-promise@4.2.1](https://www.npmjs.com/package/request-promise)", "\n### 2.3.8\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.7...2.3.8)", "#### New Features\n* Support for PG-Promise options, thanks to [ren dong](https://github.com/rendongsc)", "#### Improvements\n* Improves support for graceful shutdown, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improves configuration validation for Twitter Authentication, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)", "#### Bug Fixes\n* Fixes issue affecting GeoPoint __type with Postgres, thanks to [zhoul-HS](https://github.com/zhoul-HS)\n* Prevent user creation if username or password is empty, thanks to [Wissam Abirached](https://github.com/wabirached)", "#### Dependency Updates:\n* [cross-env@4.0.0 ](https://www.npmjs.com/package/cross-env)\n* [ws@2.2.3](https://www.npmjs.com/package/ws)\n* [babel-core@6.24.0](https://www.npmjs.com/package/babel-core)\n* [uws@0.14.0](https://www.npmjs.com/package/uws)\n* [babel-preset-es2015@6.24.0](https://www.npmjs.com/package/babel-preset-es2015)\n* [babel-plugin-syntax-flow@6.18.0](https://www.npmjs.com/package/babel-plugin-syntax-flow)\n* [babel-cli@6.24.0](https://www.npmjs.com/package/babel-cli)\n* [babel-register@6.24.0](https://www.npmjs.com/package/babel-register)\n* [winston-daily-rotate-file@1.4.6](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [mongodb@2.2.25](https://www.npmjs.com/package/mongodb)\n* [redis@2.7.0](https://www.npmjs.com/package/redis)\n* [pg-promise@5.6.4](https://www.npmjs.com/package/pg-promise)\n* [parse-server-push-adapter@1.3.0](https://www.npmjs.com/package/parse-server-push-adapter)", "### 2.3.7\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.6...2.3.7)", "#### New Features\n* New endpoint to resend verification email, thanks to [Xy Ziemba](https://github.com/xyziemba)", "#### Improvements\n* Add TTL option for Redis Cache Adapter, thanks to [Ryan Foster](https://github.com/f0ster)\n* Update Postgres Storage Adapter, thanks to [Vitaly Tomilov](https://github.com/vitaly-t)", "#### Bug Fixes\n* Add index on Role.name, fixes (#3579), thanks to [Natan Rolnik](https://github.com/natanrolnik)\n* Fix default value of userSensitiveFields, fixes (#3593), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Dependency Updates:\n* [body-parser@1.17.1](https://www.npmjs.com/package/body-parser)\n* [express@4.15.2](https://www.npmjs.com/package/express)\n* [request@2.81.0](https://www.npmjs.com/package/request)\n* [winston-daily-rotate-file@1.4.5](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [ws@2.2.0](https://www.npmjs.com/package/ws)", "\n### 2.3.6\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.5...2.3.6)", "#### Improvements\n* Adds support for injecting a middleware for instumentation in the CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Alleviate mongodb bug with $or queries [SERVER-13732](https://jira.mongodb.org/browse/SERVER-13732), thanks to [Jack Wearden](https://github.com/NotBobTheBuilder)", "#### Bug Fixes\n* Fix issue affecting password policy and empty passwords, thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)\n* Fix issue when logging url in non string objects, thanks to [Paulo Vítor S Reis](https://github.com/paulovitin)", "#### Dependencies updates:\n* [ws@2.1.0](https://npmjs.com/package/ws)\n* [uws@0.13.0](https://npmjs.com/package/uws)\n* [pg-promise@5.6.2](https://npmjs.com/package/pg-promise)", "\n### 2.3.5\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.3...2.3.5)", "#### Bug Fixes\n* Allow empty client key\n(#3497), thanks to [Arthur Cinader](https://github.com/acinader)\n* Fix LiveQuery unsafe user\n(#3525), thanks to [David Starke](https://github.com/dstarke)\n* Use `flushdb` instead of `flushall` in RedisCacheAdapter\n(#3523), thanks to [Jeremy Louie](https://github.com/JeremyPlease)\n* Fix saving GeoPoints and Files in `_GlobalConfig` (Make sure we don't treat\ndot notation keys as topLevel atoms)\n(#3531), thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.3.3\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.2...2.3.3)", "#### Breaking Changes\n* **Minimum Node engine bumped to 4.6** (#3480), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug Fixes\n* Add logging on failure to create file (#3424), thanks to [Arthur Cinader](https://github.com/acinader)\n* Log Parse Errors so they are intelligible (#3431), thanks to [Arthur Cinader](https://github.com/acinader)\n* MongoDB $or Queries avoid SERVER-13732 bug (#3476), thanks to [Jack Wearden](https://github.com/NotBobTheBuilder)\n* Mongo object to Parse object date serialization - avoid re-serialization of iso of type Date (#3389), thanks to [nodechefMatt](https://github.com/nodechefMatt)", "#### Improvements\n* Ground preparations for push scalability (#3080), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Use uWS as optional dependency for ws server (#3231), thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.3.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.1...2.3.2)", "#### New features\n* Add parseFrameURL for masking user-facing pages (#3267), thanks to [Lenart Rudel](https://github.com/lenart)", "#### Bug fixes\n* Fix Parse-Server to work with winston-daily-rotate-1.4.2 (#3335), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Improvements\n* Add support for regex string for password policy validatorPattern setting (#3331), thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)\n* LiveQuery should match subobjects with dot notation (#3322), thanks to [David Starke](https://github.com/dstarke)\n* Reduce time to process high number of installations for push (#3264), thanks to [jeacott1](https://github.com/jeacott1)\n* Fix trivial typo in error message (#3238), thanks to [Arthur Cinader](https://github.com/acinader)", "### 2.3.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.0...2.3.1)", "A major issue was introduced when refactoring the authentication modules.\nThis release addresses only that issue.", "### 2.3.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.2.25...2.3.0)", "#### Breaking changes\n* Parse.Cloud.useMasterKey() is a no-op, please refer to (Cloud Code migration guide)[https://github.com/ParsePlatform/parse-server/wiki/Compatibility-with-Hosted-Parse#cloud-code]\n* Authentication helpers are now proper adapters, deprecates oauth option in favor of auth.\n* DEPRECATES: facebookAppIds, use `auth: { facebook: { appIds: [\"AAAAAAAAA\" ] } }`\n* `email` field is not returned anymore for `Parse.User` queries. (Provided only on the user itself if provided).", "#### New Features\n* Adds ability to restrict access through Class Level Permissions to only authenticated users [see docs](http://parseplatform.github.io/docs/ios/guide/#requires-authentication-permission-requires-parse-server---230)\n* Adds ability to strip sensitive data from `_User` responses, strips emails by default, thanks to [Arthur Cinader](https://github.com/acinader)\n* Adds password history support for password policies, thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)", "#### Improvements\n* Bump parse-server-s3-adapter to 1.0.6, thanks to [Arthur Cinader](https://github.com/acinader)\n* Using PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS let you create user sessions when passing {installationId: \"xxx-xxx\"} on signup in cloud code, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Add CLI option to pass `host` parameter when creating parse-server from CLI, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)", "#### Bug fixes\n* Ensure batch routes are only using posix paths, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Ensure falsy options from CLI are properly taken into account, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Fixes issues affecting calls to `matchesKeyInQuery` with pointers.\n* Ensure that `select` keys can be changed in triggers (beforeFind...), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Housekeeping\n* Enables and enforces linting with eslint, thanks to [Arthur Cinader](https://github.com/acinader)", "### 2.2.25", "Postgres support requires v9.5", "#### New Features\n* Dockerizing Parse Server, thanks to [Kirill Kravinsky](https://github.com/woyorus)\n* Login with qq, wechat, weibo, thanks to [haifeizhang]()\n* Password policy, validation and expiration, thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)\n* Health check on /health, thanks to [Kirill Kravinsky](https://github.com/woyorus)\n* Reuse SchemaCache across requests option, thanks to [Steven Shipton](https://github.com/steven-supersolid)", "#### Improvements\n* Better support for CLI options, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Specity a database timeout with maxTimeMS, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Adds the username to reset password success pages, thanks to [Halim Qarroum](https://github.com/HQarroum)\n* Better support for Redis cache adapter, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Better coverage of Postgres, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)", "#### Bug Fixes\n* Fixes issue when sending push to multiple installations, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issues with twitter authentication, thanks to [jonas-db](https://github.com/jonas-db)\n* Ignore createdAt fields update, thanks to [Yuki Takeichi](https://github.com/yuki-takeichi)\n* Improve support for array equality with LiveQuery, thanks to [David Poetzsch-Heffter](https://github.com/dpoetzsch)\n* Improve support for batch endpoint when serverURL and publicServerURL have different paths, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Support saving relation objects, thanks to [Yuki Takeichi](https://github.com/yuki-takeichi)", "### 2.2.24", "#### New Features\n* LiveQuery: Bring your own adapter (#2902), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* LiveQuery: Adds \"update\" operator to update a query subscription (#2935), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements\n* Better Postgres support, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Logs the function name when failing (#2963), thanks to [Michael Helvey](https://github.com/michaelhelvey)\n* CLI: forces closing the connections with SIGINT/SIGTERM (#2964), thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Reduce the number of calls to the `_SCHEMA` table (#2912), thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* LiveQuery: Support for Role ACL's, thanks to [Aaron Blondeau](https://github.com/aaron-blondeau-dose)", "#### Bug Fixes\n* Better support for checking application and client keys, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Google OAuth, better support for android and web logins, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.23", "* Run liveQuery server from CLI with a different port, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Support for Postgres databaseURI, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Support for Postgres options, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Improved support for google login (id_token and access_token), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improvements with VKontakte login, thanks to [Eugene Antropov](https://github.com/antigp)\n* Improved support for `select` and `include`, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes", "* Fix error when updating installation with useMasterKey (#2888), thanks to [Jeremy Louie](https://github.com/JeremyPlease)\n* Fix bug affecting usage of multiple `notEqualTo`, thanks to [Jeremy Louie](https://github.com/JeremyPlease)\n* Improved support for null values in arrays, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.22", "* Minimum nodejs engine is now 4.5", "#### New Features\n* New: CLI for parse-live-query-server, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Start parse-live-query-server for parse-server CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes\n* Fix: Include with pointers are not conflicting with get CLP anymore, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Removes dependency on babel-polyfill, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Support nested select calls, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Use native column selection instead of runtime, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: installationId header is properly used when updating `_Installation` objects, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: don't crash parse-server on improperly formatted live-query messages, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Passwords are properly stripped out of logs, thanks to [Arthur Cinader](https://github.com/acinader)\n* Fix: Lookup for email in username if email is not set, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.21", "* Fix: Reverts removal of babel-polyfill", "### 2.2.20", "* New: Adds CloudCode handler for `beforeFind`, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: RedisCacheAdapter for syncing schema, role and user caches across servers, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Latest master build available at `ParsePlatform/parse-server#latest`, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Better support for upgradeToRevocableSession with missing session token, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Removes babel-polyfill runtime dependency, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Cluster option now support a boolean value for automatically choosing the right number of processes, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Filenames now appear correctly, thanks to [Lama Chandrasena](https://github.com/lama-buddy)\n* Fix: `_acl` is properly updated, thanks to [Steven Shipton](https://github.com/steven-supersolid)", "Other fixes by [Mathias Rangel Wulff](https://github.com/mathiasrw)", "### 2.2.19", "* New: support for upgrading to revocable sessions, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: NullCacheAdapter for disabling caching, thanks to [Yuki Takeichi](https://github.com/yuki-takeichi)\n* New: Account lockout policy [#2601](https://github.com/ParsePlatform/parse-server/pull/2601), thanks to [Diwakar Cherukumilli](https://github.com/cherukumilli)\n* New: Jobs endpoint for defining and run jobs (no scheduling), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Add --cluster option to the CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Support for login with vk.com, thanks to [Nurdaulet Bolatov](https://github.com/nbolatov)\n* New: experimental support for postgres databases, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: parse-server doesn't call next() after successful responses, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Nested objects are properly includeed with Pointer Permissions on, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: null values in include calls are properly handled, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Schema validations now runs after beforeSave hooks, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: usersname and passwords are properly type checked, thanks to [Bam Wang](https://github.com/bamwang)\n* Fix: logging in info log would log also in error log, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: removes extaneous logging from ParseLiveQueryServer, thanks to [Flavio Torres](https://github.com/flavionegrao)\n* Fix: support for Range requests for files, thanks to [Brage G. Staven](https://github.com/Bragegs)", "### 2.2.18", "* Fix: Improve support for objects in push alert, thanks to [Antoine Lenoir](https://github.com/alenoir)\n* Fix; Prevent pointed from getting clobbered when they are changed in a beforeSave, thanks to [sud](https://github.com/sud80)\n* Fix: Improve support for \"Bytes\" type, thanks to [CongHoang](https://github.com/conghoang)\n* Fix: Better logging compatability with Parse.com, thanks to [Arthur Cinader](https://github.com/acinader)\n* New: Add Janrain Capture and Janrain Engage auth provider, thanks to [Andrew Lane](https://github.com/AndrewLane)\n* Improved: Include content length header in files response, thanks to [Steven Van Bael](https://github.com/vbsteven)\n* Improved: Support byte range header for files, thanks to [Brage G. Staven](https://github.com/Bragegs)\n* Improved: Validations for LinkedIn access_tokens, thanks to [Felix Dumit](https://github.com/felix-dumit)\n* Improved: Experimental postgres support, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Perf: Use native bcrypt implementation if available, thanks to [Florent Vilmart](https://github.com/flovilmart)", "\n### [2.2.17](https://github.com/ParsePlatform/parse-server/tree/2.2.17) (07/23/2016)\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.2.16...2.2.17)", "* Cloud code logs [\\#2370](https://github.com/ParsePlatform/parse-server/pull/2370) ([flovilmart](https://github.com/flovilmart))\n* Make sure \\_PushStatus operations are run in order [\\#2367](https://github.com/ParsePlatform/parse-server/pull/2367) ([flovilmart](https://github.com/flovilmart))\n* Typo fix for error message when can't ensure uniqueness of user email addresses [\\#2360](https://github.com/ParsePlatform/parse-server/pull/2360) ([AndrewLane](https://github.com/AndrewLane))\n* LiveQuery constrains matching fix [\\#2357](https://github.com/ParsePlatform/parse-server/pull/2357) ([simonas-notcat](https://github.com/simonas-notcat))\n* Fix typo in logging for commander parseConfigFile [\\#2352](https://github.com/ParsePlatform/parse-server/pull/2352) ([AndrewLane](https://github.com/AndrewLane))\n* Fix minor typos in test names [\\#2351](https://github.com/ParsePlatform/parse-server/pull/2351) ([acinader](https://github.com/acinader))\n* Makes sure we don't strip authData or session token from users using masterKey [\\#2348](https://github.com/ParsePlatform/parse-server/pull/2348) ([flovilmart](https://github.com/flovilmart))\n* Run coverage with istanbul [\\#2340](https://github.com/ParsePlatform/parse-server/pull/2340) ([flovilmart](https://github.com/flovilmart))\n* Run next\\(\\) after successfully sending data to the client [\\#2338](https://github.com/ParsePlatform/parse-server/pull/2338) ([blacha](https://github.com/blacha))\n* Cache all the mongodb/version folder [\\#2336](https://github.com/ParsePlatform/parse-server/pull/2336) ([flovilmart](https://github.com/flovilmart))\n* updates usage of setting: emailVerifyTokenValidityDuration [\\#2331](https://github.com/ParsePlatform/parse-server/pull/2331) ([cherukumilli](https://github.com/cherukumilli))\n* Update Mongodb client to 2.2.4 [\\#2329](https://github.com/ParsePlatform/parse-server/pull/2329) ([flovilmart](https://github.com/flovilmart))\n* Allow usage of analytics adapter [\\#2327](https://github.com/ParsePlatform/parse-server/pull/2327) ([deashay](https://github.com/deashay))\n* Fix flaky tests [\\#2324](https://github.com/ParsePlatform/parse-server/pull/2324) ([flovilmart](https://github.com/flovilmart))\n* don't serve null authData values [\\#2320](https://github.com/ParsePlatform/parse-server/pull/2320) ([yuzeh](https://github.com/yuzeh))\n* Fix null relation problem [\\#2319](https://github.com/ParsePlatform/parse-server/pull/2319) ([flovilmart](https://github.com/flovilmart))\n* Clear the connectionPromise upon close or error [\\#2314](https://github.com/ParsePlatform/parse-server/pull/2314) ([flovilmart](https://github.com/flovilmart))\n* Report validation errors with correct error code [\\#2299](https://github.com/ParsePlatform/parse-server/pull/2299) ([flovilmart](https://github.com/flovilmart))\n* Parses correctly Parse.Files and Dates when sent to Cloud Code Functions [\\#2297](https://github.com/ParsePlatform/parse-server/pull/2297) ([flovilmart](https://github.com/flovilmart))\n* Adding proper generic Not Implemented. [\\#2292](https://github.com/ParsePlatform/parse-server/pull/2292) ([vitaly-t](https://github.com/vitaly-t))\n* Adds schema caching capabilities \\(5s by default\\) [\\#2286](https://github.com/ParsePlatform/parse-server/pull/2286) ([flovilmart](https://github.com/flovilmart))\n* add digits oauth provider [\\#2284](https://github.com/ParsePlatform/parse-server/pull/2284) ([ranhsd](https://github.com/ranhsd))\n* Improve installations query [\\#2281](https://github.com/ParsePlatform/parse-server/pull/2281) ([flovilmart](https://github.com/flovilmart))\n* Adding request headers to cloud functions fixes \\#1461 [\\#2274](https://github.com/ParsePlatform/parse-server/pull/2274) ([blacha](https://github.com/blacha))\n* Creates a new sessionToken when updating password [\\#2266](https://github.com/ParsePlatform/parse-server/pull/2266) ([flovilmart](https://github.com/flovilmart))\n* Add Gitter chat link to the README. [\\#2264](https://github.com/ParsePlatform/parse-server/pull/2264) ([nlutsenko](https://github.com/nlutsenko))\n* Restores ability to include non pointer keys [\\#2263](https://github.com/ParsePlatform/parse-server/pull/2263) ([flovilmart](https://github.com/flovilmart))\n* Allow next middleware handle error in handleParseErrors [\\#2260](https://github.com/ParsePlatform/parse-server/pull/2260) ([mejcz](https://github.com/mejcz))\n* Exposes the ClientSDK infos if available [\\#2259](https://github.com/ParsePlatform/parse-server/pull/2259) ([flovilmart](https://github.com/flovilmart))\n* Adds support for multiple twitter auths options [\\#2256](https://github.com/ParsePlatform/parse-server/pull/2256) ([flovilmart](https://github.com/flovilmart))\n* validate\\_purchase fix for SANDBOX requests [\\#2253](https://github.com/ParsePlatform/parse-server/pull/2253) ([valeryvaskabovich](https://github.com/valeryvaskabovich))", "### 2.2.16 (7/10/2016)", "* New: Expose InMemoryCacheAdapter publicly, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* New: Add ability to prevent login with unverified email, thanks to [Diwakar Cherukumilli](https://github.com/cherukumilli)\n* Improved: Better error message for incorrect type, thanks to [Andrew Lane](https://github.com/AndrewLane)\n* Improved: Better error message for permission denied, thanks to [Blayne Chard](https://github.com/blacha)\n* Improved: Update authData on login, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improved: Ability to not check for old files on Parse.com, thanks to [OzgeAkin](https://github.com/OzgeAkin)\n* Fix: Issues with email adapter validation, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Issues with nested $or queries, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.15 (6/30/2016)", "* Fix: Type in description for Parse.Error.INVALID_QUERY, thanks to [Andrew Lane](https://github.com/AndrewLane)\n* Improvement: Stop requiring verifyUserEmails for password reset functionality, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Improvement: Kill without validation, thanks to [Drew Gross](https://github.com/drew-gross)\n* Fix: Deleting a file does not delete from fs.files, thanks to [David Keita](https://github.com/maninga)\n* Fix: Postgres stoage adapter fix, thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n* Fix: Results invalid session when providing an invalid session token, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: issue creating an anonymous user, thanks to [Hussam Moqhim](https://github.com/hmoqhim)\n* Fix: make http response serializable, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Add postmark email adapter alternative [Glenn Reyes](https://github.com/glennreyes)", "### 2.2.14 (6/25/2016)", "* Hotfix: Fix Parse.Cloud.HTTPResponse serialization", "### 2.2.13 (6/12/2016)", "* Hotfix: Pin version of deepcopy", "### 2.2.12 (6/9/2016)", "* New: Custom error codes in cloud code response.error, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Fix: Crash in beforeSave when response is not an object, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Allow \"get\" on installations\n* Fix: Fix overly restrictive Class Level Permissions, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Fix nested date parsing in Cloud Code, thanks to [Marco Cheung](https://github.com/Marco129)\n* Fix: Support very old file formats from Parse.com", "### 2.2.11 (5/31/2016)", "* Security: Censor user password in logs, thanks to [Marco Cheung](https://github.com/Marco129)\n* New: Add PARSE_SERVER_LOGS_FOLDER env var for setting log folder, thanks to [KartikeyaRokde](https://github.com/KartikeyaRokde)\n* New: Webhook key support, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Perf: Add cache adapter and default caching of certain objects, thanks to [Blayne Chard](https://github.com/blacha)\n* Improvement: Better error messages for schema type mismatches, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Improvement: Better error messages for reset password emails\n* Improvement: Webhook key support in CLI, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Remove read only fields when using beforeSave, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Use content type provided by JS SDK, thanks to [Blayne Chard](https://github.com/blacha) and [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Tell the dashboard the stored push data is available, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Fix: Add support for HTTP Basic Auth, thanks to [Hussam Moqhim](https://github.com/hmoqhim)\n* Fix: Support for MongoDB version 3.2.6, (note: do not use MongoDB 3.2 with migrated apps that still have traffic on Parse.com), thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Prevent `pm2` from crashing when push notifications fail, thanks to [benishak](https://github.com/benishak)\n* Fix: Add full list of default _Installation fields, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Fix: Strip objectId out of hooks responses, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Fix external webhook response format, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Fix beforeSave when object is passed to `success`, thanks to [Madhav Bhagat](https://github.com/codebreach)\n* Fix: Remove use of deprecated APIs, thanks to [Emad Ehsan](https://github.com/emadehsan)\n* Fix: Crash when multiple Parse Servers on the same machine try to write to the same logs folder, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Fix: Various issues with key names in `Parse.Object`s\n* Fix: Treat Bytes type properly\n* Fix: Caching bugs that caused writes by masterKey or other session token to not show up to users reading with a different session token\n* Fix: Pin mongo driver version, preventing a regression in version 2.1.19\n* Fix: Various issues with pointer fields not being treated properly\n* Fix: Issues with pointed getting un-fetched due to changes in beforeSave\n* Fix: Fixed crash when deleting classes that have CLPs", "### 2.2.10 (5/15/2016)", "* Fix: Write legacy ACLs to Mongo so that clients that still go through Parse.com can read them, thanks to [Tyler Brock](https://github.com/TylerBrock) and [carmenlau](https://github.com/carmenlau)\n* Fix: Querying installations with limit = 0 and count = 1 now works, thanks to [ssk7833](https://github.com/ssk7833)\n* Fix: Return correct error when violating unique index, thanks to [Marco Cheung](https://github.com/Marco129)\n* Fix: Allow unsetting user's email, thanks to [Marco Cheung](https://github.com/Marco129)\n* New: Support for Node 6.1", "### 2.2.9 (5/9/2016)", "* Fix: Fix a regression that caused Parse Server to crash when a null parameter is passed to a Cloud function", "### 2.2.8 (5/8/2016)", "* New: Support for Pointer Permissions\n* New: Expose logger in Cloud Code\n* New: Option to revoke sessions on password reset\n* New: Option to expire inactive sessions\n* Perf: Improvements in ACL checking query\n* Fix: Issues when sending pushes to list of devices that contains invalid values\n* Fix: Issues caused by using babel-polyfill outside of Parse Server, but in the same express app\n* Fix: Remove creation of extra session tokens\n* Fix: Return authData when querying with master key\n* Fix: Bugs when deleting webhooks\n* Fix: Ignore _RevocableSession header, which might be sent by the JS SDK\n* Fix: Issues with querying via URL params\n* Fix: Properly encode \"Date\" parameters to cloud code functions", "\n### 2.2.7 (4/15/2016)", "* Adds support for --verbose and verbose option when running ParseServer [\\#1414](https://github.com/ParsePlatform/parse-server/pull/1414) ([flovilmart](https://github.com/flovilmart))\n* Adds limit = 0 as a valid parameter for queries [\\#1493](https://github.com/ParsePlatform/parse-server/pull/1493) ([seijiakiyama](https://github.com/seijiakiyama))\n* Makes sure we preserve Installations when updating a token \\(\\#1475\\) [\\#1486](https://github.com/ParsePlatform/parse-server/pull/1486) ([flovilmart](https://github.com/flovilmart))\n* Hotfix for tests [\\#1503](https://github.com/ParsePlatform/parse-server/pull/1503) ([flovilmart](https://github.com/flovilmart))\n* Enable logs [\\#1502](https://github.com/ParsePlatform/parse-server/pull/1502) ([drew-gross](https://github.com/drew-gross))\n* Do some triple equals for great justice [\\#1499](https://github.com/ParsePlatform/parse-server/pull/1499) ([TylerBrock](https://github.com/TylerBrock))\n* Apply credential stripping to all untransforms for \\_User [\\#1498](https://github.com/ParsePlatform/parse-server/pull/1498) ([TylerBrock](https://github.com/TylerBrock))\n* Checking if object has defined key for Pointer constraints in liveQuery [\\#1487](https://github.com/ParsePlatform/parse-server/pull/1487) ([simonas-notcat](https://github.com/simonas-notcat))\n* Remove collection prefix and default mongo URI [\\#1479](https://github.com/ParsePlatform/parse-server/pull/1479) ([drew-gross](https://github.com/drew-gross))\n* Store collection prefix in mongo adapter, and clean up adapter interface [\\#1472](https://github.com/ParsePlatform/parse-server/pull/1472) ([drew-gross](https://github.com/drew-gross))\n* Move field deletion logic into mongo adapter [\\#1471](https://github.com/ParsePlatform/parse-server/pull/1471) ([drew-gross](https://github.com/drew-gross))\n* Adds support for Long and Double mongodb types \\(fixes \\#1316\\) [\\#1470](https://github.com/ParsePlatform/parse-server/pull/1470) ([flovilmart](https://github.com/flovilmart))\n* Schema.js database agnostic [\\#1468](https://github.com/ParsePlatform/parse-server/pull/1468) ([flovilmart](https://github.com/flovilmart))\n* Remove console.log [\\#1465](https://github.com/ParsePlatform/parse-server/pull/1465) ([drew-gross](https://github.com/drew-gross))\n* Push status nits [\\#1462](https://github.com/ParsePlatform/parse-server/pull/1462) ([flovilmart](https://github.com/flovilmart))\n* Fixes \\#1444 [\\#1451](https://github.com/ParsePlatform/parse-server/pull/1451) ([flovilmart](https://github.com/flovilmart))\n* Removing sessionToken and authData from \\_User objects included in a query [\\#1450](https://github.com/ParsePlatform/parse-server/pull/1450) ([simonas-notcat](https://github.com/simonas-notcat))\n* Move mongo field type logic into mongoadapter [\\#1432](https://github.com/ParsePlatform/parse-server/pull/1432) ([drew-gross](https://github.com/drew-gross))\n* Prevents \\_User lock out when setting ACL on signup or afterwards [\\#1429](https://github.com/ParsePlatform/parse-server/pull/1429) ([flovilmart](https://github.com/flovilmart))\n* Update .travis.yml [\\#1428](https://github.com/ParsePlatform/parse-server/pull/1428) ([flovilmart](https://github.com/flovilmart))\n* Adds relation fields to objects [\\#1424](https://github.com/ParsePlatform/parse-server/pull/1424) ([flovilmart](https://github.com/flovilmart))\n* Update .travis.yml [\\#1423](https://github.com/ParsePlatform/parse-server/pull/1423) ([flovilmart](https://github.com/flovilmart))\n* Sets the defaultSchemas keys in the SchemaCollection [\\#1421](https://github.com/ParsePlatform/parse-server/pull/1421) ([flovilmart](https://github.com/flovilmart))\n* Fixes \\#1417 [\\#1420](https://github.com/ParsePlatform/parse-server/pull/1420) ([drew-gross](https://github.com/drew-gross))\n* Untransform should treat Array's as nested objects [\\#1416](https://github.com/ParsePlatform/parse-server/pull/1416) ([blacha](https://github.com/blacha))\n* Adds X-Parse-Push-Status-Id header [\\#1412](https://github.com/ParsePlatform/parse-server/pull/1412) ([flovilmart](https://github.com/flovilmart))\n* Schema format cleanup [\\#1407](https://github.com/ParsePlatform/parse-server/pull/1407) ([drew-gross](https://github.com/drew-gross))\n* Updates the publicServerURL option [\\#1397](https://github.com/ParsePlatform/parse-server/pull/1397) ([flovilmart](https://github.com/flovilmart))\n* Fix exception with non-expiring session tokens. [\\#1386](https://github.com/ParsePlatform/parse-server/pull/1386) ([0x18B2EE](https://github.com/0x18B2EE))\n* Move mongo schema format related logic into mongo adapter [\\#1385](https://github.com/ParsePlatform/parse-server/pull/1385) ([drew-gross](https://github.com/drew-gross))\n* WIP: Huge performance improvement on roles queries [\\#1383](https://github.com/ParsePlatform/parse-server/pull/1383) ([flovilmart](https://github.com/flovilmart))\n* Removes GCS Adapter from provided adapters [\\#1339](https://github.com/ParsePlatform/parse-server/pull/1339) ([flovilmart](https://github.com/flovilmart))\n* DBController refactoring [\\#1228](https://github.com/ParsePlatform/parse-server/pull/1228) ([flovilmart](https://github.com/flovilmart))\n* Spotify authentication [\\#1226](https://github.com/ParsePlatform/parse-server/pull/1226) ([1nput0utput](https://github.com/1nput0utput))\n* Expose DatabaseAdapter to simplify application tests [\\#1121](https://github.com/ParsePlatform/parse-server/pull/1121) ([steven-supersolid](https://github.com/steven-supersolid))", "### 2.2.6 (4/5/2016)", "* Important Fix: Disables find on installation from clients [\\#1374](https://github.com/ParsePlatform/parse-server/pull/1374) ([flovilmart](https://github.com/flovilmart))\n* Adds missing options to the CLI [\\#1368](https://github.com/ParsePlatform/parse-server/pull/1368) ([flovilmart](https://github.com/flovilmart))\n* Removes only master on travis [\\#1367](https://github.com/ParsePlatform/parse-server/pull/1367) ([flovilmart](https://github.com/flovilmart))\n* Auth.\\_loadRoles should not query the same role twice. [\\#1366](https://github.com/ParsePlatform/parse-server/pull/1366) ([blacha](https://github.com/blacha))", "### 2.2.5 (4/4/2016)", "* Improves config loading and tests [\\#1363](https://github.com/ParsePlatform/parse-server/pull/1363) ([flovilmart](https://github.com/flovilmart))\n* Adds travis configuration to deploy NPM on new version tags [\\#1361](https://github.com/ParsePlatform/parse-server/pull/1361) ([gfosco](https://github.com/gfosco))\n* Inject the default schemas properties when loading it [\\#1357](https://github.com/ParsePlatform/parse-server/pull/1357) ([flovilmart](https://github.com/flovilmart))\n* Adds console transport when testing with VERBOSE=1 [\\#1351](https://github.com/ParsePlatform/parse-server/pull/1351) ([flovilmart](https://github.com/flovilmart))\n* Make notEqual work on relations [\\#1350](https://github.com/ParsePlatform/parse-server/pull/1350) ([flovilmart](https://github.com/flovilmart))\n* Accept only bool for $exists in LiveQuery [\\#1315](https://github.com/ParsePlatform/parse-server/pull/1315) ([drew-gross](https://github.com/drew-gross))\n* Adds more options when using CLI/config [\\#1305](https://github.com/ParsePlatform/parse-server/pull/1305) ([flovilmart](https://github.com/flovilmart))\n* Update error message [\\#1297](https://github.com/ParsePlatform/parse-server/pull/1297) ([drew-gross](https://github.com/drew-gross))\n* Properly let masterKey add fields [\\#1291](https://github.com/ParsePlatform/parse-server/pull/1291) ([flovilmart](https://github.com/flovilmart))\n* Point to \\#1271 as how to write a good issue report [\\#1290](https://github.com/ParsePlatform/parse-server/pull/1290) ([drew-gross](https://github.com/drew-gross))\n* Adds ability to override mount with publicServerURL for production uses [\\#1287](https://github.com/ParsePlatform/parse-server/pull/1287) ([flovilmart](https://github.com/flovilmart))\n* Single object queries to use include and keys [\\#1280](https://github.com/ParsePlatform/parse-server/pull/1280) ([jeremyjackson89](https://github.com/jeremyjackson89))\n* Improves report for Push error in logs and \\_PushStatus [\\#1269](https://github.com/ParsePlatform/parse-server/pull/1269) ([flovilmart](https://github.com/flovilmart))\n* Removes all stdout/err logs while testing [\\#1268](https://github.com/ParsePlatform/parse-server/pull/1268) ([flovilmart](https://github.com/flovilmart))\n* Matching queries with doesNotExist constraint [\\#1250](https://github.com/ParsePlatform/parse-server/pull/1250) ([andrecardoso](https://github.com/andrecardoso))\n* Added session length option for session tokens to server configuration [\\#997](https://github.com/ParsePlatform/parse-server/pull/997) ([Kenishi](https://github.com/Kenishi))\n* Regression test for \\#1259 [\\#1286](https://github.com/ParsePlatform/parse-server/pull/1286) ([drew-gross](https://github.com/drew-gross))\n* Regression test for \\#871 [\\#1283](https://github.com/ParsePlatform/parse-server/pull/1283) ([drew-gross](https://github.com/drew-gross))\n* Add a test to repro \\#701 [\\#1281](https://github.com/ParsePlatform/parse-server/pull/1281) ([drew-gross](https://github.com/drew-gross))\n* Fix for \\#1334: using relative cloud code files broken [\\#1353](https://github.com/ParsePlatform/parse-server/pull/1353) ([airdrummingfool](https://github.com/airdrummingfool))\n* Fix Issue/1288 [\\#1346](https://github.com/ParsePlatform/parse-server/pull/1346) ([flovilmart](https://github.com/flovilmart))\n* Fixes \\#1271 [\\#1295](https://github.com/ParsePlatform/parse-server/pull/1295) ([drew-gross](https://github.com/drew-gross))\n* Fixes issue \\#1302 [\\#1314](https://github.com/ParsePlatform/parse-server/pull/1314) ([flovilmart](https://github.com/flovilmart))\n* Fixes bug related to include in queries [\\#1312](https://github.com/ParsePlatform/parse-server/pull/1312) ([flovilmart](https://github.com/flovilmart))", "\n### 2.2.4 (3/29/2016)", "* Hotfix: fixed imports issue for S3Adapter, GCSAdapter, FileSystemAdapter [\\#1263](https://github.com/ParsePlatform/parse-server/pull/1263) ([drew-gross](https://github.com/drew-gross)\n* Fix: Clean null authData values on _User update [\\#1199](https://github.com/ParsePlatform/parse-server/pull/1199) ([yuzeh](https://github.com/yuzeh))", "### 2.2.3 (3/29/2016)", "* Fixed bug with invalid email verification link on email update. [\\#1253](https://github.com/ParsePlatform/parse-server/pull/1253) ([kzielonka](https://github.com/kzielonka))\n* Badge update supports increment as well as Increment [\\#1248](https://github.com/ParsePlatform/parse-server/pull/1248) ([flovilmart](https://github.com/flovilmart))\n* Config/Push Tested with the dashboard. [\\#1235](https://github.com/ParsePlatform/parse-server/pull/1235) ([drew-gross](https://github.com/drew-gross))\n* Better logging with winston [\\#1234](https://github.com/ParsePlatform/parse-server/pull/1234) ([flovilmart](https://github.com/flovilmart))\n* Make GlobalConfig work like parse.com [\\#1210](https://github.com/ParsePlatform/parse-server/pull/1210) ([framp](https://github.com/framp))\n* Improve flattening of results from pushAdapter [\\#1204](https://github.com/ParsePlatform/parse-server/pull/1204) ([flovilmart](https://github.com/flovilmart))\n* Push adapters are provided by external packages [\\#1195](https://github.com/ParsePlatform/parse-server/pull/1195) ([flovilmart](https://github.com/flovilmart))\n* Fix flaky test [\\#1188](https://github.com/ParsePlatform/parse-server/pull/1188) ([drew-gross](https://github.com/drew-gross))\n* Fixes problem affecting finding array pointers [\\#1185](https://github.com/ParsePlatform/parse-server/pull/1185) ([flovilmart](https://github.com/flovilmart))\n* Moves Files adapters to external packages [\\#1172](https://github.com/ParsePlatform/parse-server/pull/1172) ([flovilmart](https://github.com/flovilmart))\n* Mark push as enabled in serverInfo endpoint [\\#1164](https://github.com/ParsePlatform/parse-server/pull/1164) ([drew-gross](https://github.com/drew-gross))\n* Document email adapter [\\#1144](https://github.com/ParsePlatform/parse-server/pull/1144) ([drew-gross](https://github.com/drew-gross))\n* Reset password fix [\\#1133](https://github.com/ParsePlatform/parse-server/pull/1133) ([carmenlau](https://github.com/carmenlau))", "### 2.2.2 (3/23/2016)", "* Important Fix: Mounts createLiveQueryServer, fix babel induced problem [\\#1153](https://github.com/ParsePlatform/parse-server/pull/1153) (flovilmart)\n* Move ParseServer to it's own file [\\#1166](https://github.com/ParsePlatform/parse-server/pull/1166) (flovilmart)\n* Update README.md * remove deploy buttons * replace with community links [\\#1139](https://github.com/ParsePlatform/parse-server/pull/1139) (drew-gross)\n* Adds bootstrap.sh [\\#1138](https://github.com/ParsePlatform/parse-server/pull/1138) (flovilmart)\n* Fix: Do not override username [\\#1142](https://github.com/ParsePlatform/parse-server/pull/1142) (flovilmart)\n* Fix: Add pushId back to GCM payload [\\#1168](https://github.com/ParsePlatform/parse-server/pull/1168) (wangmengyan95)", "### 2.2.1 (3/22/2016)", "* New: Add FileSystemAdapter file adapter [\\#1098](https://github.com/ParsePlatform/parse-server/pull/1098) (dtsolis)\n* New: Enabled CLP editing [\\#1128](https://github.com/ParsePlatform/parse-server/pull/1128) (drew-gross)\n* Improvement: Reduces the number of connections to mongo created [\\#1111](https://github.com/ParsePlatform/parse-server/pull/1111) (flovilmart)\n* Improvement: Make ParseServer a class [\\#980](https://github.com/ParsePlatform/parse-server/pull/980) (flovilmart)\n* Fix: Adds support for plain object in $add, $addUnique, $remove [\\#1114](https://github.com/ParsePlatform/parse-server/pull/1114) (flovilmart)\n* Fix: Generates default CLP, freezes objects [\\#1132](https://github.com/ParsePlatform/parse-server/pull/1132) (flovilmart)\n* Fix: Properly sets installationId on creating session with 3rd party auth [\\#1110](https://github.com/ParsePlatform/parse-server/pull/1110) (flovilmart)", "### 2.2.0 (3/18/2016)", "* New Feature: Real-time functionality with Live Queries! [\\#1092](https://github.com/ParsePlatform/parse-server/pull/1092) (wangmengyan95)\n* Improvement: Push Status API [\\#1004](https://github.com/ParsePlatform/parse-server/pull/1004) (flovilmart)\n* Improvement: Allow client operations on Roles [\\#1068](https://github.com/ParsePlatform/parse-server/pull/1068) (flovilmart)\n* Improvement: Add URI encoding to mongo auth parameters [\\#986](https://github.com/ParsePlatform/parse-server/pull/986) (bgw)\n* Improvement: Adds support for apps key in config file, but only support single app for now [\\#979](https://github.com/ParsePlatform/parse-server/pull/979) (flovilmart)\n* Documentation: Getting Started and Configuring Parse Server [\\#988](https://github.com/ParsePlatform/parse-server/pull/988) (hramos)\n* Fix: Various edge cases with REST API [\\#1066](https://github.com/ParsePlatform/parse-server/pull/1066) (flovilmart)\n* Fix: Makes sure the location in results has the proper objectId [\\#1065](https://github.com/ParsePlatform/parse-server/pull/1065) (flovilmart)\n* Fix: Third-party auth is properly removed when unlinked [\\#1081](https://github.com/ParsePlatform/parse-server/pull/1081) (flovilmart)\n* Fix: Clear the session-user cache when changing \\_User objects [\\#1072](https://github.com/ParsePlatform/parse-server/pull/1072) (gfosco)\n* Fix: Bug related to subqueries on unfetched objects [\\#1046](https://github.com/ParsePlatform/parse-server/pull/1046) (flovilmart)\n* Fix: Properly urlencode parameters for email validation and password reset [\\#1001](https://github.com/ParsePlatform/parse-server/pull/1001) (flovilmart)\n* Fix: Better sanitization/decoding of object data for afterSave triggers [\\#992](https://github.com/ParsePlatform/parse-server/pull/992) (flovilmart)\n* Fix: Changes default encoding for httpRequest [\\#892](https://github.com/ParsePlatform/parse-server/pull/892) (flovilmart)", "### 2.1.6 (3/11/2016)", "* Improvement: Full query support for badge Increment \\(\\#931\\) [\\#983](https://github.com/ParsePlatform/parse-server/pull/983) (flovilmart)\n* Improvement: Shutdown standalone parse server gracefully [\\#958](https://github.com/ParsePlatform/parse-server/pull/958) (raulr)\n* Improvement: Add database options to ParseServer constructor and pass to MongoStorageAdapter [\\#956](https://github.com/ParsePlatform/parse-server/pull/956) (steven-supersolid)\n* Improvement: AuthData logic refactor [\\#952](https://github.com/ParsePlatform/parse-server/pull/952) (flovilmart)\n* Improvement: Changed FileLoggerAdapterSpec to fail gracefully on Windows [\\#946](https://github.com/ParsePlatform/parse-server/pull/946) (aneeshd16)\n* Improvement: Add new schema collection type and replace all usages of direct mongo collection for schema operations. [\\#943](https://github.com/ParsePlatform/parse-server/pull/943) (nlutsenko)\n* Improvement: Adds CLP API to Schema router [\\#898](https://github.com/ParsePlatform/parse-server/pull/898) (flovilmart)\n* Fix: Cleans up authData null keys on login for android crash [\\#978](https://github.com/ParsePlatform/parse-server/pull/978) (flovilmart)\n* Fix: Do master query for before/afterSaveHook [\\#959](https://github.com/ParsePlatform/parse-server/pull/959) (wangmengyan95)\n* Fix: re-add shebang [\\#944](https://github.com/ParsePlatform/parse-server/pull/944) (flovilmart)\n* Fix: Added test command for Windows support [\\#886](https://github.com/ParsePlatform/parse-server/pull/886) (aneeshd16)", "### 2.1.5 (3/9/2016)", "* New: FileAdapter for Google Cloud Storage [\\#708](https://github.com/ParsePlatform/parse-server/pull/708) (mcdonamp)\n* Improvement: Minimize extra schema queries in some scenarios. [\\#919](https://github.com/ParsePlatform/parse-server/pull/919) (Marco129)\n* Improvement: Move DatabaseController and Schema fully to adaptive mongo collection. [\\#909](https://github.com/ParsePlatform/parse-server/pull/909) (nlutsenko)\n* Improvement: Cleanup PushController/PushRouter, remove raw mongo collection access. [\\#903](https://github.com/ParsePlatform/parse-server/pull/903) (nlutsenko)\n* Improvement: Increment badge the right way [\\#902](https://github.com/ParsePlatform/parse-server/pull/902) (flovilmart)\n* Improvement: Migrate ParseGlobalConfig to new database storage API. [\\#901](https://github.com/ParsePlatform/parse-server/pull/901) (nlutsenko)\n* Improvement: Improve delete flow for non-existent \\_Join collection [\\#881](https://github.com/ParsePlatform/parse-server/pull/881) (Marco129)\n* Improvement: Adding a role scenario test for issue 827 [\\#878](https://github.com/ParsePlatform/parse-server/pull/878) (gfosco)\n* Improvement: Test empty authData block on login for \\#413 [\\#863](https://github.com/ParsePlatform/parse-server/pull/863) (gfosco)\n* Improvement: Modified the npm dev script to support Windows [\\#846](https://github.com/ParsePlatform/parse-server/pull/846) (aneeshd16)\n* Improvement: Move HooksController to use MongoCollection instead of direct Mongo access. [\\#844](https://github.com/ParsePlatform/parse-server/pull/844) (nlutsenko)\n* Improvement: Adds public\\_html and views for packaging [\\#839](https://github.com/ParsePlatform/parse-server/pull/839) (flovilmart)\n* Improvement: Better support for windows builds [\\#831](https://github.com/ParsePlatform/parse-server/pull/831) (flovilmart)\n* Improvement: Convert Schema.js to ES6 class. [\\#826](https://github.com/ParsePlatform/parse-server/pull/826) (nlutsenko)\n* Improvement: Remove duplicated instructions [\\#816](https://github.com/ParsePlatform/parse-server/pull/816) (hramos)\n* Improvement: Completely migrate SchemasRouter to new MongoCollection API. [\\#794](https://github.com/ParsePlatform/parse-server/pull/794) (nlutsenko)\n* Fix: Do not require where clause in $dontSelect condition on queries. [\\#925](https://github.com/ParsePlatform/parse-server/pull/925) (nlutsenko)\n* Fix: Make sure that ACLs propagate to before/after save hooks. [\\#924](https://github.com/ParsePlatform/parse-server/pull/924) (nlutsenko)\n* Fix: Support params option in Parse.Cloud.httpRequest. [\\#912](https://github.com/ParsePlatform/parse-server/pull/912) (carmenlau)\n* Fix: Fix flaky Parse.GeoPoint test. [\\#908](https://github.com/ParsePlatform/parse-server/pull/908) (nlutsenko)\n* Fix: Handle legacy \\_client\\_permissions key in \\_SCHEMA. [\\#900](https://github.com/ParsePlatform/parse-server/pull/900) (drew-gross)\n* Fix: Fixes bug when querying equalTo on objectId and relation [\\#887](https://github.com/ParsePlatform/parse-server/pull/887) (flovilmart)\n* Fix: Allow crossdomain on filesRouter [\\#876](https://github.com/ParsePlatform/parse-server/pull/876) (flovilmart)\n* Fix: Remove limit when counting results. [\\#867](https://github.com/ParsePlatform/parse-server/pull/867) (gfosco)\n* Fix: beforeSave changes should propagate to the response [\\#865](https://github.com/ParsePlatform/parse-server/pull/865) (gfosco)\n* Fix: Delete relation field when \\_Join collection not exist [\\#864](https://github.com/ParsePlatform/parse-server/pull/864) (Marco129)\n* Fix: Related query on non-existing column [\\#861](https://github.com/ParsePlatform/parse-server/pull/861) (gfosco)\n* Fix: Update markdown in .github/ISSUE\\_TEMPLATE.md [\\#859](https://github.com/ParsePlatform/parse-server/pull/859) (igorshubovych)\n* Fix: Issue with creating wrong \\_Session for Facebook login [\\#857](https://github.com/ParsePlatform/parse-server/pull/857) (tobernguyen)\n* Fix: Leak warnings in tests, use mongodb-runner from node\\_modules [\\#843](https://github.com/ParsePlatform/parse-server/pull/843) (drew-gross)\n* Fix: Reversed roles lookup [\\#841](https://github.com/ParsePlatform/parse-server/pull/841) (flovilmart)\n* Fix: Improves loading of Push Adapter, fix loading of S3Adapter [\\#833](https://github.com/ParsePlatform/parse-server/pull/833) (flovilmart)\n* Fix: Add field to system schema [\\#828](https://github.com/ParsePlatform/parse-server/pull/828) (Marco129)", "### 2.1.4 (3/3/2016)", "* New: serverInfo endpoint that returns server version and info about the server's features\n* Improvement: Add support for badges on iOS\n* Improvement: Improve failure handling in cloud code http requests\n* Improvement: Add support for queries on pointers and relations\n* Improvement: Add support for multiple $in clauses in a query\n* Improvement: Add allowClientClassCreation config option\n* Improvement: Allow atomically setting subdocument keys\n* Improvement: Allow arbitrarily deeply nested roles\n* Improvement: Set proper content-type in S3 File Adapter\n* Improvement: S3 adapter auto-creates buckets\n* Improvement: Better error messages for many errors\n* Performance: Improved algorithm for validating client keys\n* Experimental: Parse Hooks and Hooks API\n* Experimental: Email verification and password reset emails\n* Experimental: Improve compatability of logs feature with Parse.com\n* Fix: Fix for attempting to delete missing classes via schemas API\n* Fix: Allow creation of system classes via schemas API\n* Fix: Allow missing where cause in $select\n* Fix: Improve handling of invalid object ids\n* Fix: Replace query overwriting existing query\n* Fix: Propagate installationId in cloud code triggers\n* Fix: Session expiresAt is now a Date instead of a string\n* Fix: Fix count queries\n* Fix: Disallow _Role objects without names or without ACL\n* Fix: Better handling of invalid types submitted\n* Fix: beforeSave will not be triggered for attempts to save with invalid authData\n* Fix: Fix duplicate device token issues on Android\n* Fix: Allow empty authData on signup\n* Fix: Allow Master Key Headers (CORS)\n* Fix: Fix bugs if JavaScript key was not provided in server configuration\n* Fix: Parse Files on objects can now be stored without URLs\n* Fix: allow both objectId or installationId when modifying installation\n* Fix: Command line works better when not given options", "### 2.1.3 (2/24/2016)", "* Feature: Add initial support for in-app purchases\n* Feature: Better error messages when attempting to run the server on a port that is already in use or without a server URL\n* Feature: Allow customization of max file size\n* Performance: Faster saves if not using beforeSave triggers\n* Fix: Send session token in response to current user endpoint\n* Fix: Remove triggers for _Session collection\n* Fix: Improve compatability of cloud code beforeSave hook for newly created object\n* Fix: ACL creation for master key only objects\n* Fix: Allow uploading files without Content-Type\n* Fix: Add features to http request to match Parse.com\n* Fix: Bugs in development script when running from locations other than project root\n* Fix: Can pass query constraints in URL\n* Fix: Objects with legacy \"_tombstone\" key now don't cause issues.\n* Fix: Allow nested keys in objects to begin with underscores\n* Fix: Allow correct headers for CORS", "### 2.1.2 (2/19/2016)", "* Change: The S3 file adapter constructor requires a bucket name\n* Fix: Parse Query should throw if improperly encoded\n* Fix: Issue where roles were not used in some requests\n* Fix: serverURL will no longer default to api.parse.com/1", "### 2.1.1 (2/18/2016)", "* Experimental: Schemas API support for DELETE operations\n* Fix: Session token issue fetching Users\n* Fix: Facebook auth validation\n* Fix: Invalid error when deleting missing session", "### 2.1.0 (2/17/2016)", "* Feature: Support for additional OAuth providers\n* Feature: Ability to implement custom OAuth providers\n* Feature: Support for deleting Parse Files\n* Feature: Allow querying roles\n* Feature: Support for logs, extensible via Log Adapter\n* Feature: New Push Adapter for sending push notifications through OneSignal\n* Feature: Tighter default security for Users\n* Feature: Pass parameters to cloud code in query string\n* Feature: Disable anonymous users via configuration.\n* Experimental: Schemas API support for PUT operations\n* Fix: Prevent installation ID from being added to User\n* Fix: Becoming a user works properly with sessions\n* Fix: Including multiple object when some object are unavailable will get all the objects that are available\n* Fix: Invalid URL for Parse Files\n* Fix: Making a query without a limit now returns 100 results\n* Fix: Expose installation id in cloud code\n* Fix: Correct username for Anonymous users\n* Fix: Session token issue after fetching user\n* Fix: Issues during install process\n* Fix: Issue with Unity SDK sending _noBody", "### 2.0.8 (2/11/2016)", "* Add: support for Android and iOS push notifications\n* Experimental: cloud code validation hooks (can mark as non-experimental after we have docs)\n* Experimental: support for schemas API (GET and POST only)\n* Experimental: support for Parse Config (GET and POST only)\n* Fix: Querying objects with equality constraint on array column\n* Fix: User logout will remove session token\n* Fix: Various files related bugs\n* Fix: Force minimum node version 4.3 due to security issues in earlier version\n* Performance Improvement: Improved caching" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 2430, 857], "buggy_code_start_loc": [4, 2377, 857], "filenames": ["CHANGELOG.md", "spec/ParseUser.spec.js", "src/RestWrite.js"], "fixing_code_end_loc": [10, 2434, 862], "fixing_code_start_loc": [4, 2377, 858], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "9DE0F06D-5868-45AD-B21E-C5268BCC7F52", "versionEndExcluding": "4.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login."}, {"lang": "es", "value": "Parse Server es un backend de c\u00f3digo abierto que puede desplegarse en cualquier infraestructura que pueda ejecutar Node.js. Los desarrolladores pueden usar la API REST para registrar usuarios y tambi\u00e9n permitir a usuarios registrarse an\u00f3nimamente. Versiones anteriores a 4.5.1, cuando un usuario an\u00f3nimo es registrado por primera vez usando REST, el servidor creaba la sesi\u00f3n incorrectamente. En particular, el campo \"authProvider\" de la clase \"_Session\" en \"createdWith\" muestra que el usuario se ha registrado creando una contrase\u00f1a. Si un desarrollador depende posteriormente del campo \"createdWith\" para proporcionar un nivel de acceso diferente entre un usuario con contrase\u00f1a y un usuario an\u00f3nimo, el servidor clasifica incorrectamente el tipo de sesi\u00f3n como creada con un \"password\". El servidor no usa actualmente \"createdWith\" para tomar decisiones sobre las funciones internas, por lo que si un desarrollador no est\u00e1 usando \"createdWith\" directamente, no est\u00e1 afectado. La vulnerabilidad s\u00f3lo afecta a usuarios que dependen de \"createdWith\" al usarlo directamente. El problema est\u00e1 parcheado en Parse Server versi\u00f3n 4.5.1. Como soluci\u00f3n, no use el campo de sesi\u00f3n \"createdWith\" para tomar decisiones si se permite el acceso an\u00f3nimo."}], "evaluatorComment": null, "id": "CVE-2021-39138", "lastModified": "2022-08-12T18:01:28.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.5, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-19T16:15:12.483", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/releases/tag/4.5.1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, "type": "CWE-863"}
299
Determine whether the {function_name} code is vulnerable or not.
[ "## Parse Server Changelog", "### master", "[Full Changelog](https://github.com/parse-community/parse-server/compare/4.5.1...master)", "### 4.5.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.5.0...4.5.1)", "- SECURITY FIX: Fixes incorrect session property `authProvider: password` of anonymous users. When signing up an anonymous user, the session field `createdWith` indicates incorrectly that the session has been created using username and password with `authProvider: password`, instead of an anonymous sign-up with `authProvider: anonymous`. This fixes the issue by setting the correct `authProvider: anonymous` for future sign-ups of anonymous users. This fix does not fix incorrect `authProvider: password` for existing sessions of anonymous users. Consider this if your app logic depends on the `authProvider` field. (Corey Baker) [GHSA-23r4-5mxp-c7g5](https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5)", "\n### 4.5.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.4.0...4.5.0)", "__BREAKING CHANGES:__\n- FIX: Consistent casing for afterLiveQueryEvent. The afterLiveQueryEvent was introduced in 4.4.0 with inconsistent casing for the event names, which was fixed in 4.5.0. [#7023](https://github.com/parse-community/parse-server/pull/7023). Thanks to [dblythy](https://github.com/dblythy).\n___\n- FIX: Properly handle serverURL and publicServerUrl in Batch requests. [#7049](https://github.com/parse-community/parse-server/pull/7049). Thanks to [Zach Goldberg](https://github.com/ZachGoldberg).\n- IMPROVE: Prevent invalid column names (className and length). [#7053](https://github.com/parse-community/parse-server/pull/7053). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: GraphQL: Remove viewer from logout mutation. [#7029](https://github.com/parse-community/parse-server/pull/7029). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- IMPROVE: GraphQL: Optimize on Relation. [#7044](https://github.com/parse-community/parse-server/pull/7044). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW: Include sessionToken in onLiveQueryEvent. [#7043](https://github.com/parse-community/parse-server/pull/7043). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Definitions for accountLockout and passwordPolicy. [#7040](https://github.com/parse-community/parse-server/pull/7040). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Fix typo in server definitions for emailVerifyTokenReuseIfValid. [#7037](https://github.com/parse-community/parse-server/pull/7037). Thanks to [dblythy](https://github.com/dblythy).\n- SECURITY FIX: LDAP auth stores password in plain text. See [GHSA-4w46-w44m-3jq3](https://github.com/parse-community/parse-server/security/advisories/GHSA-4w46-w44m-3jq3) for more details about the vulnerability and [da905a3](https://github.com/parse-community/parse-server/commit/da905a357d062ab4fea727a21eac231acc2ed92a) for the fix. Thanks to [Fabian Strachanski](https://github.com/fastrde).\n- NEW: Reuse tokens if they haven't expired. [#7017](https://github.com/parse-community/parse-server/pull/7017). Thanks to [dblythy](https://github.com/dblythy).\n- NEW: Add LDAPS-support to LDAP-Authcontroller. [#7014](https://github.com/parse-community/parse-server/pull/7014). Thanks to [Fabian Strachanski](https://github.com/fastrde).\n- FIX: (beforeSave/afterSave): Return value instead of Parse.Op for nested fields. [#7005](https://github.com/parse-community/parse-server/pull/7005). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: (beforeSave): Skip Sanitizing Database results. [#7003](https://github.com/parse-community/parse-server/pull/7003). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Fix includeAll for querying a Pointer and Pointer array. [#7002](https://github.com/parse-community/parse-server/pull/7002). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: Add encryptionKey to src/options/index.js. [#6999](https://github.com/parse-community/parse-server/pull/6999). Thanks to [dblythy](https://github.com/dblythy).\n- IMPROVE: Update PostgresStorageAdapter.js. [#6989](https://github.com/parse-community/parse-server/pull/6989). Thanks to [Vitaly Tomilov](https://github.com/vitaly-t).", "### 4.4.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.3.0...4.4.0)\n- IMPROVE: Update PostgresStorageAdapter.js. [#6981](https://github.com/parse-community/parse-server/pull/6981). Thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n- NEW: skipWithMasterKey on Built-In Validator. [#6972](https://github.com/parse-community/parse-server/issues/6972). Thanks to [dblythy](https://github.com/dblythy).\n- NEW: Add fileKey rotation to GridFSBucketAdapter. [#6768](https://github.com/parse-community/parse-server/pull/6768). Thanks to [Corey Baker](https://github.com/cbaker6).\n- IMPROVE: Remove unused parameter in Cloud Function. [#6969](https://github.com/parse-community/parse-server/issues/6969). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: Validation Handler Update. [#6968](https://github.com/parse-community/parse-server/issues/6968). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: (directAccess): Properly handle response status. [#6966](https://github.com/parse-community/parse-server/issues/6966). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Remove hostnameMaxLen for Mongo URL. [#6693](https://github.com/parse-community/parse-server/issues/6693). Thanks to [markhoward02](https://github.com/markhoward02).\n- IMPROVE: Show a message if cloud functions are duplicated. [#6963](https://github.com/parse-community/parse-server/issues/6963). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Pass request.query to afterFind. [#6960](https://github.com/parse-community/parse-server/issues/6960). Thanks to [dblythy](https://github.com/dblythy).\n- SECURITY FIX: Patch session vulnerability over Live Query. See [GHSA-2xm2-xj2q-qgpj](https://github.com/parse-community/parse-server/security/advisories/GHSA-2xm2-xj2q-qgpj) for more details about the vulnerability and [78b59fb](https://github.com/parse-community/parse-server/commit/78b59fb26b1c36e3cdbd42ba9fec025003267f58) for the fix. Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo).\n- IMPROVE: LiveQueryEvent Error Logging Improvements. [#6951](https://github.com/parse-community/parse-server/issues/6951). Thanks to [dblythy](https://github.com/dblythy).\n- IMPROVE: Include stack in Cloud Code. [#6958](https://github.com/parse-community/parse-server/issues/6958). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: (jobs): Add Error Message to JobStatus Failure. [#6954](https://github.com/parse-community/parse-server/issues/6954). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- NEW: Create Cloud function afterLiveQueryEvent. [#6859](https://github.com/parse-community/parse-server/issues/6859). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Update vkontakte API to the latest version. [#6944](https://github.com/parse-community/parse-server/issues/6944). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo).\n- FIX: Use an empty object as default value of options for Google Sign in. [#6844](https://github.com/parse-community/parse-server/issues/6844). Thanks to [Kevin Kuang](https://github.com/kvnkuang).\n- FIX: Postgres: prepend className to unique indexes. [#6741](https://github.com/parse-community/parse-server/pull/6741). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: GraphQL: Transform input types also on user mutations. [#6934](https://github.com/parse-community/parse-server/pull/6934). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Set objectId into query for Email Validation. [#6930](https://github.com/parse-community/parse-server/pull/6930). Thanks to [Danaru](https://github.com/Danaru87).\n- FIX: GraphQL: Optimize queries, fixes some null returns (on object), fix stitched GraphQLUpload. [#6709](https://github.com/parse-community/parse-server/pull/6709). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Do not throw error if user provide a pointer like index onMongo. [#6923](https://github.com/parse-community/parse-server/pull/6923). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Hotfix instagram api. [#6922](https://github.com/parse-community/parse-server/issues/6922). Thanks to [Tim](https://github.com/timination).\n- FIX: (directAccess/cloud-code): Pass installationId with LogIn. [#6903](https://github.com/parse-community/parse-server/issues/6903). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Fix bcrypt binary incompatibility. [#6891](https://github.com/parse-community/parse-server/issues/6891). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- NEW: Keycloak auth adapter. [#6376](https://github.com/parse-community/parse-server/issues/6376). Thanks to [Rhuan](https://github.com/rhuanbarreto).\n- IMPROVE: Changed incorrect key name in apple auth adapter tests. [#6861](https://github.com/parse-community/parse-server/issues/6861). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- FIX: Fix mutating beforeSubscribe Query. [#6868](https://github.com/parse-community/parse-server/issues/6868). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Fix beforeLogin for users logging in with AuthData. [#6872](https://github.com/parse-community/parse-server/issues/6872). Thanks to [Kevin Kuang](https://github.com/kvnkuang).\n- FIX: Remove Facebook AccountKit auth. [#6870](https://github.com/parse-community/parse-server/issues/6870). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- FIX: Updated TOKEN_ISSUER to 'accounts.google.com'. [#6836](https://github.com/parse-community/parse-server/issues/6836). Thanks to [Arjun Vedak](https://github.com/arjun3396).\n- IMPROVE: Optimized deletion of class field from schema by using an index if available to do an index scan instead of a collection scan. [#6815](https://github.com/parse-community/parse-server/issues/6815). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- IMPROVE: Enable MongoDB transaction test for MongoDB >= 4.0.4 [#6827](https://github.com/parse-community/parse-server/pull/6827). Thanks to [Manuel](https://github.com/mtrezza).", "### 4.3.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.2.0...4.3.0)\n- PERFORMANCE: Optimizing pointer CLP query decoration done by DatabaseController#addPointerPermissions [#6747](https://github.com/parse-community/parse-server/pull/6747). Thanks to [mess-lelouch](https://github.com/mess-lelouch).\n- SECURITY: Fix security breach on GraphQL viewer [78239ac](https://github.com/parse-community/parse-server/commit/78239ac9071167fdf243c55ae4bc9a2c0b0d89aa), [secuity advisory](https://github.com/parse-community/parse-server/security/advisories/GHSA-236h-rqv8-8q73). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Save context not present if direct access enabled [#6764](https://github.com/parse-community/parse-server/pull/6764). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani).\n- NEW: Before Connect + Before Subscribe [#6793](https://github.com/parse-community/parse-server/pull/6793). Thanks to [dblythy](https://github.com/dblythy).\n- FIX: Add version to playground to fix CDN [#6804](https://github.com/parse-community/parse-server/pull/6804). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW (EXPERIMENTAL): Idempotency enforcement for client requests. This deduplicates requests where the client intends to send one request to Parse Server but due to network issues the server receives the request multiple times. **Caution, this is an experimental feature that may not be appropriate for production.** [#6748](https://github.com/parse-community/parse-server/issues/6748). Thanks to [Manuel Trezza](https://github.com/mtrezza).\n- FIX: Add production Google Auth Adapter instead of using the development url [#6734](https://github.com/parse-community/parse-server/pull/6734). Thanks to [SebC.](https://github.com/SebC99).\n- IMPROVE: Run Prettier JS Again Without requiring () on arrow functions [#6796](https://github.com/parse-community/parse-server/pull/6796). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: Run Prettier JS [#6795](https://github.com/parse-community/parse-server/pull/6795). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- IMPROVE: Replace bcrypt with @node-rs/bcrypt [#6794](https://github.com/parse-community/parse-server/pull/6794). Thanks to [LongYinan](https://github.com/Brooooooklyn).\n- IMPROVE: Make clear description of anonymous user [#6655](https://github.com/parse-community/parse-server/pull/6655). Thanks to [Jerome De Leon](https://github.com/JeromeDeLeon).\n- IMPROVE: Simplify GraphQL merge system to avoid js ref bugs [#6791](https://github.com/parse-community/parse-server/pull/6791). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW: Pass context in beforeDelete, afterDelete, beforeFind and Parse.Cloud.run [#6666](https://github.com/parse-community/parse-server/pull/6666). Thanks to [yog27ray](https://github.com/yog27ray).\n- NEW: Allow passing custom gql schema function to ParseServer#start options [#6762](https://github.com/parse-community/parse-server/pull/6762). Thanks to [Luca](https://github.com/lucatk).\n- NEW: Allow custom cors origin header [#6772](https://github.com/parse-community/parse-server/pull/6772). Thanks to [Kevin Yao](https://github.com/kzmeyao).\n- FIX: Fix context for cascade-saving and saving existing object [#6735](https://github.com/parse-community/parse-server/pull/6735). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Add file bucket encryption using fileKey [#6765](https://github.com/parse-community/parse-server/pull/6765). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: Removed gaze from dev dependencies and removed not working dev script [#6745](https://github.com/parse-community/parse-server/pull/6745). Thanks to [Vincent Semrau](https://github.com/vince1995).\n- IMPROVE: Upgrade graphql-tools to v6 [#6701](https://github.com/parse-community/parse-server/pull/6701). Thanks to [Yaacov Rydzinski](https://github.com/yaacovCR).\n- NEW: Support Metadata in GridFSAdapter [#6660](https://github.com/parse-community/parse-server/pull/6660). Thanks to [Diamond Lewis](https://github.com/dplewis).\n- NEW: Allow to unset file from graphql [#6651](https://github.com/parse-community/parse-server/pull/6651). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- NEW: Handle shutdown for RedisCacheAdapter [#6658](https://github.com/parse-community/parse-server/pull/6658). Thanks to [promisenxu](https://github.com/promisenxu).\n- FIX: Fix explain on user class [#6650](https://github.com/parse-community/parse-server/pull/6650). Thanks to [Manuel](https://github.com/mtrezza).\n- FIX: Fix read preference for aggregate [#6585](https://github.com/parse-community/parse-server/pull/6585). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Add context to Parse.Object.save [#6626](https://github.com/parse-community/parse-server/pull/6626). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Adding ssl config params to Postgres URI [#6580](https://github.com/parse-community/parse-server/pull/6580). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: Travis postgres update: removing unnecessary start of mongo-runner [#6594](https://github.com/parse-community/parse-server/pull/6594). Thanks to [Corey Baker](https://github.com/cbaker6).\n- FIX: ObjectId size for Pointer in Postgres [#6619](https://github.com/parse-community/parse-server/pull/6619). Thanks to [Corey Baker](https://github.com/cbaker6).\n- IMPROVE: Improve a test case [#6629](https://github.com/parse-community/parse-server/pull/6629). Thanks to [Gordon Sun](https://github.com/sunshineo).\n- NEW: Allow to resolve automatically Parse Type fields from Custom Schema [#6562](https://github.com/parse-community/parse-server/pull/6562). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Remove wrong console log in test [#6627](https://github.com/parse-community/parse-server/pull/6627). Thanks to [Gordon Sun](https://github.com/sunshineo).\n- IMPROVE: Graphql tools v5 [#6611](https://github.com/parse-community/parse-server/pull/6611). Thanks to [Yaacov Rydzinski](https://github.com/yaacovCR).\n- FIX: Catch JSON.parse and return 403 properly [#6589](https://github.com/parse-community/parse-server/pull/6589). Thanks to [Gordon Sun](https://github.com/sunshineo).\n- PERFORMANCE: Allow covering relation queries with minimal index [#6581](https://github.com/parse-community/parse-server/pull/6581). Thanks to [Noah Silas](https://github.com/noahsilas).\n- FIX: Fix Postgres group aggregation [#6522](https://github.com/parse-community/parse-server/pull/6522). Thanks to [Siddharth Ramesh](https://github.com/srameshr).\n- NEW: Allow set user mapped from JWT directly on request [#6411](https://github.com/parse-community/parse-server/pull/6411). Thanks to [Gordon Sun](https://github.com/sunshineo).", "### 4.2.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.1.0...4.2.0)", "__BREAKING CHANGES:__\n- CHANGE: The Sign-In with Apple authentication adapter parameter `client_id` has been changed to `clientId`. If using the Apple authentication adapter, this change requires to update the Parse Server configuration accordingly. See [#6523](https://github.com/parse-community/parse-server/pull/6523) for details.\n___\n- UPGRADE: Parse JS SDK to 2.12.0 [#6548](https://github.com/parse-community/parse-server/pull/6548)\n- NEW: Support Group aggregation on multiple columns for Postgres [#6483](https://github.com/parse-community/parse-server/pull/6483). Thanks to [Siddharth Ramesh](https://github.com/srameshr).\n- FIX: Improve test reliability by instructing Travis to only install one version of Postgres [#6490](https://github.com/parse-community/parse-server/pull/6490). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- FIX: Unknown type bug on overloaded types [#6494](https://github.com/parse-community/parse-server/pull/6494). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Improve reliability of 'SignIn with AppleID' [#6416](https://github.com/parse-community/parse-server/pull/6416). Thanks to [Andy King](https://github.com/andrewking0207).\n- FIX: Improve Travis reliability by separating Postgres & Mongo scripts [#6505](https://github.com/parse-community/parse-server/pull/6505). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- NEW: Apple SignIn support for multiple IDs [#6523](https://github.com/parse-community/parse-server/pull/6523). Thanks to [UnderratedDev](https://github.com/UnderratedDev).\n- NEW: Add support for new Instagram API [#6398](https://github.com/parse-community/parse-server/pull/6398). Thanks to [Maravilho Singa](https://github.com/maravilhosinga).\n- FIX: Updating Postgres/Postgis Call and Postgis to 3.0 [#6528](https://github.com/parse-community/parse-server/pull/6528). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- FIX: enableExpressErrorHandler logic [#6423](https://github.com/parse-community/parse-server/pull/6423). Thanks to [Nikolay Andryukhin](https://github.com/hybeats).\n- FIX: Change Order Enum Strategy for GraphQL [#6515](https://github.com/parse-community/parse-server/pull/6515). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Switch ACL to Relay Global Id for GraphQL [#6495](https://github.com/parse-community/parse-server/pull/6495). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Handle keys for pointer fields properly for GraphQL [#6499](https://github.com/parse-community/parse-server/pull/6499). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: GraphQL file mutation [#6507](https://github.com/parse-community/parse-server/pull/6507). Thanks to [Antoine Cormouls](https://github.com/Moumouls).\n- FIX: Aggregate geoNear with date query [#6540](https://github.com/parse-community/parse-server/pull/6540). Thanks to [Manuel](https://github.com/mtrezza).\n- NEW: Add file triggers and file meta data [#6344](https://github.com/parse-community/parse-server/pull/6344). Thanks to [stevestencil](https://github.com/stevestencil).\n- FIX: Improve local testing of postgres [#6531](https://github.com/parse-community/parse-server/pull/6531). Thanks to\n[Corey Baker](https://github.com/cbaker6).\n- NEW: Case insensitive username and email indexing and query planning for Postgres [#6506](https://github.com/parse-community/parse-server/issues/6441). Thanks to\n[Corey Baker](https://github.com/cbaker6).", "### 4.1.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.0.2...4.1.0)", "_SECURITY RELEASE_: see [advisory](https://github.com/parse-community/parse-server/security/advisories/GHSA-h4mf-75hf-67w4) for details\n- SECURITY FIX: Patch Regex vulnerabilities. See [3a3a5ee](https://github.com/parse-community/parse-server/commit/3a3a5eee5ffa48da1352423312cb767de14de269). Special thanks to [W0lfw00d](https://github.com/W0lfw00d) for identifying and [responsibly reporting](https://github.com/parse-community/parse-server/blob/master/SECURITY.md) the vulnerability. Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo) for the speedy fix.", "### 4.0.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.0.1...4.0.2)", "__BREAKING CHANGES:__\n1. Remove Support for Mongo 3.2 & 3.4. The new minimum supported version is Mongo 3.6.\n2. Change username and email validation to be case insensitive. This change should be transparent in most use cases. The validation behavior should now behave 'as expected'. See [#5634](https://github.com/parse-community/parse-server/pull/5634) for details.", "> __Special Note on Upgrading to Parse Server 4.0.0 and above__\n>\n> In addition to the breaking changes noted above, [#5634](https://github.com/parse-community/parse-server/pull/5634) introduces a two new case insensitive indexes on the `User` collection. Special care should be taken when upgrading to this version to ensure that:\n>\n> 1. The new indexes can be successfully created (see issue [#6465](https://github.com/parse-community/parse-server/issues/6465) for details on a potential issue for your installation).\n>\n> 2. Care is taken ensure that there is adequate compute capacity to create the index in the background while still servicing requests.", "- FIX: attempt to get travis to deploy to npmjs again. See [#6475](https://github.com/parse-community/parse-server/pull/6457). Thanks to [Arthur Cinader](https://github.com/acinader).", "### 4.0.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/4.0.0...4.0.1)\n- FIX: correct 'new' travis config to properly deploy. See [#6452](https://github.com/parse-community/parse-server/pull/6452). Thanks to [Arthur Cinader](https://github.com/acinader).\n- FIX: Better message on not allowed to protect default fields. See [#6439](https://github.com/parse-community/parse-server/pull/6439).Thanks to [Old Grandpa](https://github.com/BufferUnderflower)", "### 4.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.10.0...4.0.0)", "> __Special Note on Upgrading to Parse Server 4.0.0 and above__\n>\n> In addition to the breaking changes noted below, [#5634](https://github.com/parse-community/parse-server/pull/5634) introduces a two new case insensitive indexes on the `User` collection. Special care should be taken when upgrading to this version to ensure that:\n>\n> 1. The new indexes can be successfully created (see issue [#6465](https://github.com/parse-community/parse-server/issues/6465) for details on a potential issue for your installation).\n>\n> 2. Care is taken ensure that there is adequate compute capacity to create the index in the background while still servicing requests.", "- NEW: add hint option to Parse.Query [#6322](https://github.com/parse-community/parse-server/pull/6322). Thanks to [Steve Stencil](https://github.com/stevestencil)\n- FIX: CLP objectId size validation fix [#6332](https://github.com/parse-community/parse-server/pull/6332). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- FIX: Add volumes to Docker command [#6356](https://github.com/parse-community/parse-server/pull/6356). Thanks to [Kasra Bigdeli](https://github.com/githubsaturn)\n- NEW: GraphQL 3rd Party LoginWith Support [#6371](https://github.com/parse-community/parse-server/pull/6371). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: GraphQL Geo Queries [#6363](https://github.com/parse-community/parse-server/pull/6363). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: GraphQL Nested File Upload [#6372](https://github.com/parse-community/parse-server/pull/6372). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Granular CLP pointer permissions [#6352](https://github.com/parse-community/parse-server/pull/6352). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- FIX: Add missing colon for customPages [#6393](https://github.com/parse-community/parse-server/pull/6393). Thanks to [Jerome De Leon](https://github.com/JeromeDeLeon)\n- NEW: `afterLogin` cloud code hook [#6387](https://github.com/parse-community/parse-server/pull/6387). Thanks to [David Corona](https://github.com/davesters)\n- FIX: __BREAKING CHANGE__ Prevent new usernames or emails that clash with existing users' email or username if it only differs by case. For example, don't allow a new user with the name 'Jane' if we already have a user 'jane'. [#5634](https://github.com/parse-community/parse-server/pull/5634). Thanks to [Arthur Cinader](https://github.com/acinader)\n- FIX: Support Travis CI V2. [#6414](https://github.com/parse-community/parse-server/pull/6414). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Prevent crashing on websocket error. [#6418](https://github.com/parse-community/parse-server/pull/6418). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Allow protectedFields for Authenticated users and Public. [$6415](https://github.com/parse-community/parse-server/pull/6415). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- FIX: Correct bug in determining GraphQL pointer errors when mutating. [#6413](https://github.com/parse-community/parse-server/pull/6431). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Allow true GraphQL Schema Customization. [#6360](https://github.com/parse-community/parse-server/pull/6360). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- __BREAKING CHANGE__: Remove Support for Mongo version < 3.6 [#6445](https://github.com/parse-community/parse-server/pull/6445). Thanks to [Arthur Cinader](https://github.com/acinader)", "### 3.10.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.9.0...3.10.0)\n- FIX: correct and cover ordering queries in GraphQL [#6316](https://github.com/parse-community/parse-server/pull/6316). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL support for reset password email [#6301](https://github.com/parse-community/parse-server/pull/6301). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: Add default limit to GraphQL fetch [#6304](https://github.com/parse-community/parse-server/pull/6304). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- DOCS: use bash syntax highlighting [#6302](https://github.com/parse-community/parse-server/pull/6302). Thanks to [Jerome De Leon](https://github.com/JeromeDeLeon)\n- NEW: Add max log file option [#6296](https://github.com/parse-community/parse-server/pull/6296). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: support user supplied objectId [#6101](https://github.com/parse-community/parse-server/pull/6101). Thanks to [Ruhan](https://github.com/rhuanbarretos)\n- FIX: Add missing encodeURIComponent on username [#6278](https://github.com/parse-community/parse-server/pull/6278). Thanks to [Christopher Brookes](https://github.com/Klaitos)\n- NEW: update PostgresStorageAdapter.js to use async/await [#6275](https://github.com/parse-community/parse-server/pull/6275). Thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n- NEW: Support required fields on output type for GraphQL [#6279](https://github.com/parse-community/parse-server/pull/6279). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Support required fields for GraphQL [#6271](https://github.com/parse-community/parse-server/pull/6279). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- CHANGE: use mongodb 3.3.5 [#6263](https://github.com/parse-community/parse-server/pull/6263). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: GraphQL: DX Relational Where Query [#6255](https://github.com/parse-community/parse-server/pull/6255). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- CHANGE: test against Postgres 11 [#6260](https://github.com/parse-community/parse-server/pull/6260). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- CHANGE: test against Postgres 11 [#6260](https://github.com/parse-community/parse-server/pull/6260). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: GraphQL alias for mutations in classConfigs [#6258](https://github.com/parse-community/parse-server/pull/6258). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- NEW: GraphQL classConfig query alias [#6257](https://github.com/parse-community/parse-server/pull/6257). Thanks to [Old Grandpa](https://github.com/BufferUnderflower)\n- NEW: Allow validateFilename to return a string or Parse Error [#6246](https://github.com/parse-community/parse-server/pull/6246). Thanks to [Mike Patnode](https://github.com/mpatnode)\n- NEW: Relay Spec [#6089](https://github.com/parse-community/parse-server/pull/6089). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Set default ACL for GraphQL [#6249](https://github.com/parse-community/parse-server/pull/6249). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: LDAP auth Adapter [#6226](https://github.com/parse-community/parse-server/pull/6226). Thanks to [Julian Dax](https://github.com/brodo)\n- FIX: improve beforeFind to include Query info [#6237](https://github.com/parse-community/parse-server/pull/6237). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: improve websocket error handling [#6230](https://github.com/parse-community/parse-server/pull/6230). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: addition of an afterLogout trigger [#6217](https://github.com/parse-community/parse-server/pull/6217). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Initialize default logger [#6186](https://github.com/parse-community/parse-server/pull/6186). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Add funding link [#6192](https://github.com/parse-community/parse-server/pull/6192 ). Thanks to [Tom Fox](https://github.com/TomWFox)\n- FIX: installationId on LiveQuery connect [#6180](https://github.com/parse-community/parse-server/pull/6180). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Add exposing port in docker container [#6165](https://github.com/parse-community/parse-server/pull/6165). Thanks to [Priyash Patil](https://github.com/priyashpatil)\n- NEW: Support Google Play Games Service [#6147](https://github.com/parse-community/parse-server/pull/6147). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- DOC: Throw error when setting authData to null [#6154](https://github.com/parse-community/parse-server/pull/6154). Thanks to [Manuel](https://github.com/mtrezza)\n- CHANGE: Move filename validation out of the Router and into the FilesAdaptor [#6157](https://github.com/parse-community/parse-server/pull/6157). Thanks to [Mike Patnode](https://github.com/mpatnode)\n- NEW: Added warning for special URL sensitive characters for appId [#6159](https://github.com/parse-community/parse-server/pull/6159). Thanks to [Saimoom Safayet Akash](https://github.com/saimoomsafayet)\n- NEW: Support Apple Game Center Auth [#6143](https://github.com/parse-community/parse-server/pull/6143). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- CHANGE: test with Node 12 [#6133](https://github.com/parse-community/parse-server/pull/6133). Thanks to [Arthur Cinader](https://github.com/acinader)\n- FIX: prevent after find from firing when saving objects [#6127](https://github.com/parse-community/parse-server/pull/6127). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: GraphQL Mutations not returning updated information [6130](https://github.com/parse-community/parse-server/pull/6130). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- CHANGE: Cleanup Schema cache per request [#6216](https://github.com/parse-community/parse-server/pull/6216). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- DOC: Improve installation instructions [#6120](https://github.com/parse-community/parse-server/pull/6120). Thanks to [Andres Galante](https://github.com/andresgalante)\n- DOC: add code formatting to contributing guidelines [#6119](https://github.com/parse-community/parse-server/pull/6119). Thanks to [Andres Galante](https://github.com/andresgalante)\n- NEW: Add GraphQL ACL Type + Input [#5957](https://github.com/parse-community/parse-server/pull/5957). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- CHANGE: replace public key [#6099](https://github.com/parse-community/parse-server/pull/6099). Thanks to [Arthur Cinader](https://github.com/acinader)\n- NEW: Support microsoft authentication in GraphQL [#6051](https://github.com/parse-community/parse-server/pull/6051). Thanks to [Alann Maulana](https://github.com/alann-maulana)\n- NEW: Install parse-server 3.9.0 instead of 2.2 [#6069](https://github.com/parse-community/parse-server/pull/6069). Thanks to [Julian Dax](https://github.com/brodo)\n- NEW: Use #!/bin/bash instead of #!/bin/sh [#6062](https://github.com/parse-community/parse-server/pull/6062). Thanks to [Julian Dax](https://github.com/brodo)\n- DOC: Update GraphQL readme section [#6030](https://github.com/parse-community/parse-server/pull/6030). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "### 3.9.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.8.0...3.9.0)\n- NEW: Add allowHeaders to Options [#6044](https://github.com/parse-community/parse-server/pull/6044). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- CHANGE: Introduce ReadOptionsInput to GraphQL API [#6030](https://github.com/parse-community/parse-server/pull/6030). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Stream video with GridFSBucketAdapter (implements byte-range requests) [#6028](https://github.com/parse-community/parse-server/pull/6028). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Aggregate not matching null values [#6043](https://github.com/parse-community/parse-server/pull/6043). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Improve callCloudCode mutation to receive a CloudCodeFunction enum instead of a String in the GraphQL API [#6029](https://github.com/parse-community/parse-server/pull/6029). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- TEST: Add more tests to transactions [#6022](https://github.com/parse-community/parse-server/pull/6022). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Pointer constraint input type as ID in the GraphQL API [#6020](https://github.com/parse-community/parse-server/pull/6020). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- CHANGE: Remove underline from operators of the GraphQL API [#6024](https://github.com/parse-community/parse-server/pull/6024). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Make method async as expected in usage [#6025](https://github.com/parse-community/parse-server/pull/6025). Thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- DOC: Added breaking change note to 3.8 release [#6023](https://github.com/parse-community/parse-server/pull/6023). Thanks to [Manuel](https://github.com/mtrezza)\n- NEW: Added support for line auth [#6007](https://github.com/parse-community/parse-server/pull/6007). Thanks to [Saimoom Safayet Akash](https://github.com/saimoomsafayet)\n- FIX: Fix aggregate group id [#5994](https://github.com/parse-community/parse-server/pull/5994). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- CHANGE: Schema operations instead of generic operations in the GraphQL API [#5993](https://github.com/parse-community/parse-server/pull/5993). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- DOC: Fix changelog formatting[#6009](https://github.com/parse-community/parse-server/pull/6009). Thanks to [Tom Fox](https://github.com/TomWFox)\n- CHANGE: Rename objectId to id in the GraphQL API [#5985](https://github.com/parse-community/parse-server/pull/5985). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- FIX: Fix beforeLogin trigger when user has a file [#6001](https://github.com/parse-community/parse-server/pull/6001). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- DOC: Update GraphQL Docs with the latest changes [#5980](https://github.com/parse-community/parse-server/pull/5980). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "### 3.8.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.7.2...3.8.0)\n- NEW: Protected fields pointer-permissions support [#5951](https://github.com/parse-community/parse-server/pull/5951). Thanks to [Dobbias Nan](https://github.com/Dobbias)\n- NEW: GraphQL DX: Relation/Pointer [#5946](https://github.com/parse-community/parse-server/pull/5946). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Master Key Only Config Properties [#5953](https://github.com/parse-community/parse-server/pull/5954). Thanks to [Manuel](https://github.com/mtrezza)\n- FIX: Better validation when creating a Relation fields [#5922](https://github.com/parse-community/parse-server/pull/5922). Thanks to [Lucas Alencar](https://github.com/alencarlucas)\n- NEW: enable GraphQL file upload [#5944](https://github.com/parse-community/parse-server/pull/5944). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Handle shutdown on grid adapters [#5943](https://github.com/parse-community/parse-server/pull/5943). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Fix GraphQL max upload size [#5940](https://github.com/parse-community/parse-server/pull/5940). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Remove Buffer() deprecation notice [#5942](https://github.com/parse-community/parse-server/pull/5942). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Remove MongoDB unified topology deprecation notice from the grid adapter [#5941](https://github.com/parse-community/parse-server/pull/5941). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: add callback for serverCloseComplete [#5937](https://github.com/parse-community/parse-server/pull/5937). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- DOCS: Add Cloud Code guide to README [#5936](https://github.com/parse-community/parse-server/pull/5936). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Remove nested operations from GraphQL API [#5931](https://github.com/parse-community/parse-server/pull/5931). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Improve Live Query Monitoring [#5927](https://github.com/parse-community/parse-server/pull/5927). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: GraphQL: Fix undefined Array [#5296](https://github.com/parse-community/parse-server/pull/5926). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- NEW: Added array support for pointer-permissions [#5921](https://github.com/parse-community/parse-server/pull/5921). Thanks to [Dobbias Nan](https://github.com/Dobbias)\n- GraphQL: Renaming Types/Inputs [#5921](https://github.com/parse-community/parse-server/pull/5921). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: Lint no-prototype-builtins [#5920](https://github.com/parse-community/parse-server/pull/5920). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- GraphQL: Inline Fragment on Array Fields [#5908](https://github.com/parse-community/parse-server/pull/5908). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- DOCS: Add instructions to launch a compatible Docker Postgres [](). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- Fix: Undefined dot notation in matchKeyInQuery [#5917](https://github.com/parse-community/parse-server/pull/5917). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- Fix: Logger print JSON and Numbers [#5916](https://github.com/parse-community/parse-server/pull/5916). Thanks to [Diamond Lewis](https://github.com/dplewis)\n- GraphQL: Return specific Type on specific Mutation [#5893](https://github.com/parse-community/parse-server/pull/5893). Thanks to [Antoine Cormouls](https://github.com/Moumouls)\n- FIX: Apple sign-in authAdapter [#5891](https://github.com/parse-community/parse-server/pull/5891). Thanks to [SebC](https://github.com/SebC99).\n- DOCS: Add GraphQL beta notice [#5886](https://github.com/parse-community/parse-server/pull/5886). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- GraphQL: Remove \"password\" output field from _User class [#5889](https://github.com/parse-community/parse-server/pull/5889). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- GraphQL: Object constraints [#5715](https://github.com/parse-community/parse-server/pull/5715). Thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- DOCS: README top section overhaul + add sponsors [#5876](https://github.com/parse-community/parse-server/pull/5876). Thanks to [Tom Fox](https://github.com/TomWFox)\n- FIX: Return a Promise from classUpdate method [#5877](https://github.com/parse-community/parse-server/pull/5877). Thanks to [Lucas Alencar](https://github.com/alencarlucas)\n- FIX: Use UTC Month in aggregate tests [#5879](https://github.com/parse-community/parse-server/pull/5879). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Transaction was aborting before all promises have either resolved or rejected [#5878](https://github.com/parse-community/parse-server/pull/5878). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Use transactions for batch operation [#5849](https://github.com/parse-community/parse-server/pull/5849). Thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "#### Breaking Changes:\n- If you are running Parse Server on top of a MongoDB deployment which does not fit the [Retryable Writes Requirements](https://docs.mongodb.com/manual/core/retryable-writes/#prerequisites), you will have to add `retryWrites=false` to your connection string in order to upgrade to Parse Server 3.8.", "### 3.7.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.7.1...3.7.2)", "- FIX: Live Query was failing on release 3.7.1", "### 3.7.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.7.0...3.7.1)", "- FIX: Missing APN module\n- FIX: Set falsy values as default to schema fields [#5868](https://github.com/parse-community/parse-server/pull/5868), thanks to [Lucas Alencar](https://github.com/alencarlucas)\n- NEW: Implement WebSocketServer Adapter [#5866](https://github.com/parse-community/parse-server/pull/5866), thanks to [Diamond Lewis](https://github.com/dplewis)", "### 3.7.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.6.0...3.7.0)", "- FIX: Prevent linkWith sessionToken from generating new session [#5801](https://github.com/parse-community/parse-server/pull/5801), thanks to [Diamond Lewis](https://github.com/dplewis)\n- GraphQL: Improve session token error messages [#5753](https://github.com/parse-community/parse-server/pull/5753), thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- NEW: GraphQL { functions { call } } generic mutation [#5818](https://github.com/parse-community/parse-server/pull/5818), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL Custom Schema [#5821](https://github.com/parse-community/parse-server/pull/5821), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL custom schema on CLI [#5828](https://github.com/parse-community/parse-server/pull/5828), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL @mock directive [#5836](https://github.com/parse-community/parse-server/pull/5836), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: GraphQL _or operator not working [#5840](https://github.com/parse-community/parse-server/pull/5840), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Add \"count\" to CLP initial value [#5841](https://github.com/parse-community/parse-server/pull/5841), thanks to [Douglas Muraoka](https://github.com/douglasmuraoka)\n- NEW: Add ability to alter the response from the after save trigger [#5814](https://github.com/parse-community/parse-server/pull/5814), thanks to [BrunoMaurice](https://github.com/brunoMaurice)\n- FIX: Cache apple public key for the case it fails to fetch again [#5848](https://github.com/parse-community/parse-server/pull/5848), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: GraphQL Configuration Options [#5782](https://github.com/parse-community/parse-server/pull/5782), thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- NEW: Required fields and default values [#5835](https://github.com/parse-community/parse-server/pull/5835), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Postgres safely escape strings in nested objects [#5855](https://github.com/parse-community/parse-server/pull/5855), thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Support PhantAuth authentication [#5850](https://github.com/parse-community/parse-server/pull/5850), thanks to [Ivan SZKIBA](https://github.com/szkiba)\n- FIX: Remove uws package [#5860](https://github.com/parse-community/parse-server/pull/5860), thanks to [Zeal Murapa](https://github.com/GoGross)", "### 3.6.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.5.0...3.6.0)", "- SECURITY FIX: Address [Security Advisory](https://github.com/parse-community/parse-server/security/advisories/GHSA-8w3j-g983-8jh5) of a potential [Enumeration Attack](https://www.owasp.org/index.php/Testing_for_User_Enumeration_and_Guessable_User_Account_(OWASP-AT-002)#Description_of_the_Issue) [73b0f9a](https://github.com/parse-community/parse-server/commit/73b0f9a339b81f5d757725dc557955a7b670a3ec), big thanks to [Fabian Strachanski](https://github.com/fastrde) for identifying the problem, creating a fix and following the [vulnerability disclosure guidelines](https://github.com/parse-community/parse-server/blob/master/SECURITY.md#parse-community-vulnerability-disclosure-program)\n- NEW: Added rest option: excludeKeys [#5737](https://github.com/parse-community/parse-server/pull/5737), thanks to [Raschid J.F. Rafeally](https://github.com/RaschidJFR)\n- FIX: LiveQuery create event with fields [#5790](https://github.com/parse-community/parse-server/pull/5790), thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: Generate sessionToken with linkWith [#5799](https://github.com/parse-community/parse-server/pull/5799), thanks to [Diamond Lewis](https://github.com/dplewis)", "### 3.5.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.4...3.5.0)", "- NEW: GraphQL Support [#5674](https://github.com/parse-community/parse-server/pull/5674), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)", "[GraphQL Guide](https://github.com/parse-community/parse-server#graphql)", "- NEW: Sign in with Apple [#5694](https://github.com/parse-community/parse-server/pull/5694), thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: AppSecret to Facebook Auth [#5695](https://github.com/parse-community/parse-server/pull/5695), thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Postgres: Regex support foreign characters [#5598](https://github.com/parse-community/parse-server/pull/5598), thanks to [Jeff Gu Kang](https://github.com/JeffGuKang)\n- FIX: Winston Logger string interpolation [#5729](https://github.com/parse-community/parse-server/pull/5729), thanks to [Diamond Lewis](https://github.com/dplewis)", "### 3.4.4\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.3...3.4.4)", "Fix: Commit changes", "### 3.4.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.2...3.4.3)", "Fix: Use changes in master to travis configuration to enable pushing to npm and gh_pages. See diff for details.", "### 3.4.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.1...3.4.2)", "Fix: In my haste to get a [Security Fix](https://github.com/parse-community/parse-server/security/advisories/GHSA-2479-qvv7-47qq) out, I added [8709daf](https://github.com/parse-community/parse-server/commit/8709daf698ea69b59268cb66f0f7cee75b52daa5) to master instead of to 3.4.1. This commit fixes that. [Arthur Cinader](https://github.com/acinader)", "### 3.4.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.4.0...3.4.1)", "Security Fix: see Advisory: [GHSA-2479-qvv7-47q](https://github.com/parse-community/parse-server/security/advisories/GHSA-2479-qvv7-47qq) for details [8709daf](https://github.com/parse-community/parse-server/commit/8709daf698ea69b59268cb66f0f7cee75b52daa5). Big thanks to: [Benjamin Simonsson](https://github.com/BenniPlejd) for identifying the issue and promptly bringing it to the Parse Community's attention and also big thanks to the indefatigable [Diamond Lewis](https://github.com/dplewis) for crafting a failing test and then a solution within an hour of the report.", "### 3.4.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.3.0...3.4.0)\n- NEW: Aggregate supports group by date fields [#5538](https://github.com/parse-community/parse-server/pull/5538) thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: API for Read Preferences [#3963](https://github.com/parse-community/parse-server/pull/3963) thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- NEW: Add Redis options for LiveQuery [#5584](https://github.com/parse-community/parse-server/pull/5584) thanks to [Diamond Lewis](https://github.com/dplewis)\n- NEW: Add Direct Access option for Server Config [#5550](https://github.com/parse-community/parse-server/pull/5550) thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: updating mixed array in Postgres [#5552](https://github.com/parse-community/parse-server/pull/5552) thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: notEqualTo GeoPoint Query in Postgres [#5549](https://github.com/parse-community/parse-server/pull/5549), thanks to [Diamond Lewis](https://github.com/dplewis)\n- FIX: put the timestamp back in logs that was lost after Winston upgrade [#5571](https://github.com/parse-community/parse-server/pull/5571), thanks to [Steven Rowe](https://github.com/mrowe009) and [Arthur Cinader](https://github.com/acinader)\n- FIX: Validates permission before calling beforeSave [#5546](https://github.com/parse-community/parse-server/pull/5546), thanks to [Antonio Davi Macedo Coelho de Castro](https://github.com/davimacedo)\n- FIX: Remove userSensitiveFields default value. [#5588](https://github.com/parse-community/parse-server/pull/5588), thanks to [William George](https://github.com/awgeorge)\n- FIX: Decode Date JSON value in LiveQuery. [#5540](https://github.com/parse-community/parse-server/pull/5540), thanks to [ananfang](https://github.com/ananfang)", "\n### 3.3.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.3...3.3.0)\n- NEW: beforeLogin trigger with support for auth providers ([#5445](https://github.com/parse-community/parse-server/pull/5445)), thanks to [Omair Vaiyani](https://github.com/omairvaiyani)\n- NEW: RFC 7662 compliant OAuth2 auth adapter ([#4910](https://github.com/parse-community/parse-server/pull/4910)), thanks to [Müller Zsolt](https://github.com/zsmuller)\n- FIX: cannot change password when maxPasswordHistory is 1 ([#5191](https://github.com/parse-community/parse-server/pull/5191)), thanks to [Tulsi Sapkota](https://github.com/Tolsee)\n- FIX (Postgres): count being very slow on large Parse Classes' collections ([#5330](https://github.com/parse-community/parse-server/pull/5330)), thanks to [CoderickLamar](https://github.com/CoderickLamar)\n- FIX: using per-key basis queue ([#5420](https://github.com/parse-community/parse-server/pull/5420)), thanks to [Georges Jamous](https://github.com/georgesjamous)\n- FIX: issue on count with Geo constraints and mongo ([#5286](https://github.com/parse-community/parse-server/pull/5286)), thanks to [Julien Quéré](https://github.com/jlnquere)", "### 3.2.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.2...3.2.3)\n- Correct previous release with patch that is fully merged", "### 3.2.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.1...3.2.2)\n- Security fix to properly process userSensitiveFields when parse-server is started with\n ../lib/cli/parse-server [#5463](https://github.com/parse-community/parse-server/pull/5463\n )", "### 3.2.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.2.0...3.2.1)\n- Increment package.json version to match the deployment tag", "### 3.2.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.3...3.2.0)\n- NEW: Support accessing sensitive fields with an explicit ACL. Not documented yet, see [tests](https://github.com/parse-community/parse-server/blob/f2c332ea6a984808ad5b2e3ce34864a20724f72b/spec/UserPII.spec.js#L526) for examples\n- Upgrade Parse SDK JS to 2.3.1 [#5457](https://github.com/parse-community/parse-server/pull/5457)\n- Hides token contents in logStartupOptions if they arrive as a buffer [#6a9380](https://github.com/parse-community/parse-server/commit/6a93806c62205a56a8f4e3b8765848c552510337)\n- Support custom message for password requirements [#5399](https://github.com/parse-community/parse-server/pull/5399)\n- Support for Ajax password reset [#5332](https://github.com/parse-community/parse-server/pull/5332)\n- Postgres: Refuse to build unsafe JSON lists for contains [#5337](https://github.com/parse-community/parse-server/pull/5337)\n- Properly handle return values in beforeSave [#5228](https://github.com/parse-community/parse-server/pull/5228)\n- Fixes issue when querying user roles [#5276](https://github.com/parse-community/parse-server/pull/5276)\n- Fixes issue affecting update with CLP [#5269](https://github.com/parse-community/parse-server/pull/5269)", "### 3.1.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.2...3.1.3)", "- Postgres: Fixes support for global configuration\n- Postgres: Fixes support for numeric arrays\n- Postgres: Fixes issue affecting queries on empty arrays\n- LiveQuery: Adds support for transmitting the original object\n- Queries: Use estimated count if query is empty\n- Docker: Reduces the size of the docker image to 154Mb", "\n### 3.1.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.1...3.1.2)", "- Removes dev script, use TDD instead of server.\n- Removes nodemon and problematic dependencies.\n- Addressed event-stream security debacle.", "### 3.1.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.1.0...3.1.1)", "#### Improvements:\n* Fixes issue that would prevent users with large number of roles to resolve all of them [Antoine Cormouls](https://github.com/Moumouls) (#5131, #5132)\n* Fixes distinct query on special fields ([#5144](https://github.com/parse-community/parse-server/pull/5144))", "\n### 3.1.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/3.0.0...3.1.0)", "#### Breaking Changes:\n* Return success on sendPasswordResetEmail even if email not found. (#7fe4030)\n#### Security Fix:\n* Expire password reset tokens on email change (#5104)\n#### Improvements:\n* Live Query CLPs (#4387)\n* Reduces number of calls to injectDefaultSchema (#5107)\n* Remove runtime dependency on request (#5076)\n#### Bug fixes:\n* Fixes issue with vkontatke authentication (#4977)\n* Use the correct function when validating google auth tokens (#5018)\n* fix unexpected 'delete' trigger issue on LiveQuery (#5031)\n* Improves performance for roles and ACL's in live query server (#5126)", "\n### 3.0.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.4...3.0.0)", "`parse-server` 3.0.0 comes with brand new handlers for cloud code. It now fully supports promises and async / await.\nFor more informations, visit the v3.0.0 [migration guide](https://github.com/parse-community/parse-server/blob/master/3.0.0.md).", "#### Breaking changes:\n* Cloud Code handlers have a new interface based on promises.\n* response.success / response.error are removed in Cloud Code\n* Cloud Code runs with Parse-SDK 2.0\n* The aggregate now require aggregates to be passed in the form: `{\"pipeline\": [...]}` (REST Only)", "#### Improvements:\n* Adds Pipeline Operator to Aggregate Router.\n* Adds documentations for parse-server's adapters, constructors and more.\n* Adds ability to pass a context object between `beforeSave` and `afterSave` affecting the same object.", "#### Bug Fixes:\n* Fixes issue that would crash the server when mongo objects had undefined values [#4966](https://github.com/parse-community/parse-server/issues/4966)\n* Fixes issue that prevented ACL's from being used with `select` (see [#571](https://github.com/parse-community/Parse-SDK-JS/issues/571))", "#### Dependency updates:\n* [@parse/simple-mailgun-adapter@1.1.0](https://www.npmjs.com/package/@parse/simple-mailgun-adapter)\n* [mongodb@3.1.3](https://www.npmjs.com/package/mongodb)\n* [request@2.88.0](https://www.npmjs.com/package/request)", "##### Devevelopment Dependencies Updates:\n* [@parse/minami@1.0.0](https://www.npmjs.com/package/@parse/minami)\n* [deep-diff@1.0.2](https://www.npmjs.com/package/deep-diff)\n* [flow-bin@0.79.0](https://www.npmjs.com/package/flow-bin)\n* [jsdoc@3.5.5](https://www.npmjs.com/package/jsdoc)\n* [jsdoc-babel@0.4.0](https://www.npmjs.com/package/jsdoc-babel)", "### 2.8.4\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.3...2.8.4)", "#### Improvements:\n* Adds ability to forward errors to express handler (#4697)\n* Adds ability to increment the push badge with an arbitrary value (#4889)\n* Adds ability to preserve the file names when uploading (#4915)\n* `_User` now follow regular ACL policy. Letting administrator lock user out. (#4860) and (#4898)\n* Ensure dates are properly handled in aggregates (#4743)\n* Aggregates: Improved support for stages sharing the same name\n* Add includeAll option\n* Added verify password to users router and tests. (#4747)\n* Ensure read preference is never overriden, so DB config prevails (#4833)\n* add support for geoWithin.centerSphere queries via withJSON (#4825)\n* Allow sorting an object field (#4806)\n* Postgres: Don't merge JSON fields after save() to keep same behaviour as MongoDB (#4808) (#4815)", "#### Dependency updates\n* [commander@2.16.0](https://www.npmjs.com/package/commander)\n* [mongodb@3.1.1](https://www.npmjs.com/package/mongodb)\n* [pg-promise@8.4.5](https://www.npmjs.com/package/pg-promise)\n* [ws@6.0.0](https://www.npmjs.com/package/ws)\n* [bcrypt@3.0.0](https://www.npmjs.com/package/bcrypt)\n* [uws@10.148.1](https://www.npmjs.com/package/uws)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.2.0](https://www.npmjs.com/package/cross-env)\n* [eslint@5.0.0](https://www.npmjs.com/package/eslint)\n* [flow-bin@0.76.0](https://www.npmjs.com/package/flow-bin)\n* [mongodb-runner@4.0.0](https://www.npmjs.com/package/mongodb-runner)\n* [nodemon@1.18.1](https://www.npmjs.com/package/nodemon)\n* [nyc@12.0.2](https://www.npmjs.com/package/nyc)\n* [request-promise@4.2.2](https://www.npmjs.com/package/request-promise)\n* [supports-color@5.4.0](https://www.npmjs.com/package/supports-color)", "### 2.8.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.2...2.8.3)", "#### Improvements:", "* Adds support for JS SDK 2.0 job status header\n* Removes npm-git scripts as npm supports using git repositories that build, thanks to [Florent Vilmart](https://github.com/flovilmart)", "\n### 2.8.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.1...2.8.2)", "##### Bug Fixes:\n* Ensure legacy users without ACL's are not locked out, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements:\n* Use common HTTP agent to increase webhooks performance, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Adds withinPolygon support for Polygon objects, thanks to [Mads Bjerre](https://github.com/madsb)", "#### Dependency Updates:\n* [ws@5.2.0](https://www.npmjs.com/package/ws)\n* [commander@2.15.1](https://www.npmjs.com/package/commander)\n* [nodemon@1.17.5](https://www.npmjs.com/package/nodemon)", "##### Devevelopment Dependencies Updates:\n* [flow-bin@0.73.0](https://www.npmjs.com/package/flow-bin)\n* [cross-env@5.1.6](https://www.npmjs.com/package/cross-env)\n* [gaze@1.1.3](https://www.npmjs.com/package/gaze)\n* [deepcopy@1.0.0](https://www.npmjs.com/package/deepcopy)\n* [deep-diff@1.0.1](https://www.npmjs.com/package/deep-diff)", "\n### 2.8.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.1...2.8.0)", "Ensure all the files are properly exported to the final package.", "### 2.8.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.8.0...2.7.4)", "#### New Features\n* Adding Mongodb element to add `arrayMatches` the #4762 (#4766), thanks to [Jérémy Piednoel](https://github.com/jeremypiednoel)\n* Adds ability to Lockout users (#4749), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes:\n* Fixes issue when using afterFind with relations (#4752), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New query condition support to match all strings that starts with some other given strings (#3864), thanks to [Eduard Bosch Bertran](https://github.com/eduardbosch)\n* Allow creation of indices on default fields (#4738), thanks to [Claire Neveu](https://github.com/ClaireNeveu)\n* Purging empty class (#4676), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Postgres: Fixes issues comparing to zero or false (#4667), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Fix Aggregate Match Pointer (#4643), thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Improvements:\n* Allow Parse.Error when returning from Cloud Code (#4695), thanks to [Saulo Tauil](https://github.com/saulogt)\n* Fix typo: \"requrest\" -> \"request\" (#4761), thanks to [Joseph Frazier](https://github.com/josephfrazier)\n* Send version for Vkontakte API (#4725), thanks to [oleg](https://github.com/alekoleg)\n* Ensure we respond with invalid password even if email is unverified (#4708), thanks to [dblythy](https://github.com/dblythy)\n* Add _password_history to default sensitive data (#4699), thanks to [Jong Eun Lee](https://github.com/yomybaby)\n* Check for node version in postinstall script (#4657), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Remove FB Graph API version from URL to use the oldest non deprecated version, thanks to [SebC](https://github.com/SebC99)", "#### Dependency Updates:\n* [@parse/push-adapter@2.0.3](https://www.npmjs.com/package/@parse/push-adapter)\n* [@parse/simple-mailgun-adapter@1.0.2](https://www.npmjs.com/package/@parse/simple-mailgun-adapter)\n* [uws@10.148.0](https://www.npmjs.com/package/uws)\n* [body-parser@1.18.3](https://www.npmjs.com/package/body-parser)\n* [mime@2.3.1](https://www.npmjs.com/package/mime)\n* [request@2.85.0](https://www.npmjs.com/package/request)\n* [mongodb@3.0.7](https://www.npmjs.com/package/mongodb)\n* [bcrypt@2.0.1](https://www.npmjs.com/package/bcrypt)\n* [ws@5.1.1](https://www.npmjs.com/package/ws)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.1.5](https://www.npmjs.com/package/cross-env)\n* [flow-bin@0.71.0](https://www.npmjs.com/package/flow-bin)\n* [deep-diff@1.0.0](https://www.npmjs.com/package/deep-diff)\n* [nodemon@1.17.3](https://www.npmjs.com/package/nodemon)", "\n### 2.7.4\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.4...2.7.3)", "#### Bug Fixes:\n* Fixes an issue affecting polygon queries, thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Dependency Updates:\n* [pg-promise@8.2.1](https://www.npmjs.com/package/pg-promise)", "##### Development Dependencies Updates:\n* [nodemon@1.17.1](https://www.npmjs.com/package/nodemon)", "### 2.7.3\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.3...2.7.2)", "#### Improvements:\n* Improve documentation for LiveQuery options, thanks to [Arthur Cinader](https://github.com/acinader)\n* Improve documentation for using cloud code with docker, thanks to [Stephen Tuso](https://github.com/stephentuso)\n* Adds support for Facebook's AccountKit, thanks to [6thfdwp](https://github.com/6thfdwp)\n* Disable afterFind routines when running aggregates, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Improve support for distinct aggregations of nulls, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Regenreate the email verification token when requesting a new email, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)", "#### Bug Fixes:\n* Fix issue affecting readOnly masterKey and purge command, thanks to [AreyouHappy](https://github.com/AreyouHappy)\n* Fixes Issue unsetting in beforeSave doesn't allow object creation, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Fixes issue crashing server on invalid live query payload, thanks to [fridays](https://github.com/fridays)\n* Fixes issue affecting postgres storage adapter \"undefined property '__op'\", thanks to [Tyson Andre](https://github,com/TysonAndre)", "#### Dependency Updates:\n* [winston@2.4.1](https://www.npmjs.com/package/winston)\n* [pg-promise@8.2.0](https://www.npmjs.com/package/pg-promise)\n* [commander@2.15.0](https://www.npmjs.com/package/commander)\n* [lru-cache@4.1.2](https://www.npmjs.com/package/lru-cache)\n* [parse@1.11.1](https://www.npmjs.com/package/parse)\n* [ws@5.0.0](https://www.npmjs.com/package/ws)\n* [mongodb@3.0.4](https://www.npmjs.com/package/mongodb)\n* [lodash@4.17.5](https://www.npmjs.com/package/lodash)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.1.4](https://www.npmjs.com/package/cross-env)\n* [flow-bin@0.67.1](https://www.npmjs.com/package/flow-bin)\n* [jasmine@3.1.0](https://www.npmjs.com/package/jasmine)\n* [parse@1.11.1](https://www.npmjs.com/package/parse)\n* [babel-eslint@8.2.2](https://www.npmjs.com/package/babel-eslint)\n* [nodemon@1.15.0](https://www.npmjs.com/package/nodemon)", "### 2.7.2\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.2...2.7.1)", "#### Improvements:\n* Improved match aggregate\n* Do not mark the empty push as failed\n* Support pointer in aggregate query\n* Introduces flow types for storage\n* Postgres: Refactoring of Postgres Storage Adapter\n* Postgres: Support for multiple projection in aggregate\n* Postgres: performance optimizations\n* Adds infos about vulnerability disclosures\n* Adds ability to login with email when provided as username", "#### Bug Fixes\n* Scrub Passwords with URL Encoded Characters\n* Fixes issue affecting using sorting in beforeFind", "#### Dependency Updates:\n* [commander@2.13.0](https://www.npmjs.com/package/commander)\n* [semver@5.5.0](https://www.npmjs.com/package/semver)\n* [pg-promise@7.4.0](https://www.npmjs.com/package/pg-promise)\n* [ws@4.0.0](https://www.npmjs.com/package/ws)\n* [mime@2.2.0](https://www.npmjs.com/package/mime)\n* [parse@1.11.0](https://www.npmjs.com/package/parse)", "##### Devevelopment Dependencies Updates:\n* [nodemon@1.14.11](https://www.npmjs.com/package/nodemon)\n* [flow-bin@0.64.0](https://www.npmjs.com/package/flow-bin)\n* [jasmine@2.9.0](https://www.npmjs.com/package/jasmine)\n* [cross-env@5.1.3](https://www.npmjs.com/package/cross-env)", "### 2.7.1\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.1...2.7.0)", ":warning: Fixes a security issue affecting Class Level Permissions", "* Adds support for dot notation when using matchesKeyInQuery, thanks to [Henrik](https://github.com/bohemima) and [Arthur Cinader](https://github.com/acinader)", "### 2.7.0\n[Full Changelog](https://github.com/parse-community/parse-server/compare/2.7.0...2.6.5)", ":warning: This version contains an issue affecting Class Level Permissions on mongoDB. Please upgrade to 2.7.1.", "Starting parse-server 2.7.0, the minimun nodejs version is 6.11.4, please update your engines before updating parse-server", "#### New Features:\n* Aggregation endpoints, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Adds indexation options onto Schema endpoints, thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Bug fixes:\n* Fixes sessionTokens being overridden in 'find' (#4332), thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Proper `handleShutdown()` feature to close database connections (#4361), thanks to [CHANG, TZU-YEN](https://github.com/trylovetom)\n* Fixes issue affecting state of _PushStatus objects, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Fixes issue affecting calling password reset password pages with wrong appid, thanks to [Bryan de Leon](https://github.com/bryandel)\n* Fixes issue affecting duplicates _Sessions on successive logins, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements:\n* Updates contributing guides, and improves windows support, thanks to [Addison Elliott](https://github.com/addisonelliott)\n* Uses new official scoped packaged, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improves health checks responses, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Add password confirmation to choose_password, thanks to [Worathiti Manosroi](https://github.com/pungme)\n* Improve performance of relation queries, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [commander@2.12.1](https://www.npmjs.com/package/commander)\n* [ws@3.3.2](https://www.npmjs.com/package/ws)\n* [uws@9.14.0](https://www.npmjs.com/package/uws)\n* [pg-promise@7.3.2](https://www.npmjs.com/package/pg-promise)\n* [parse@1.10.2](https://www.npmjs.com/package/parse)\n* [pg-promise@7.3.1](https://www.npmjs.com/package/pg-promise)", "##### Devevelopment Dependencies Updates:\n* [cross-env@5.1.1](https://www.npmjs.com/package/cross-env)", "", "### 2.6.5\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.5...2.6.4)", "#### New Features:\n* Adds support for read-only masterKey, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Adds support for relative time queries (mongodb only), thanks to [Marvel Mathew](https://github.com/marvelm)", "#### Improvements:\n* Handle possible afterSave exception, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Add support for expiration interval in Push, thanks to [Marvel Mathew](https://github.com/marvelm)", "#### Bug Fixes:\n* The REST API key was improperly inferred from environment when using the CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.6.4\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.4...2.6.3)", "#### Improvements:\n* Improves management of configurations and default values, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Adds ability to start ParseServer with `ParseServer.start(options)`, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Adds request original IP to cloud code hooks, thanks to [Gustav Ahlberg](https://github.com/Gyran)\n* Corrects some outdated links, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Adds serverURL validation on startup, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Adds ability to login with POST requests alongside GET, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)\n* Adds ability to login with email, instead of username, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug Fixes:\n* Fixes issue affecting beforeSaves and increments, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)", "#### Dependency Updates:\n* [parse-server-push-adapter@2.0.2](https://www.npmjs.com/package/parse-server-push-adapter)\n* [semver@5.4.1](https://www.npmjs.com/package/semver)\n* [pg-promise@7.0.3](https://www.npmjs.com/package/pg-promise)\n* [mongodb@2.2.33](https://www.npmjs.com/package/mongodb)\n* [parse@1.10.1](https://www.npmjs.com/package/parse)\n* [express@4.16.0](https://www.npmjs.com/package/express)\n* [mime@1.4.1](https://www.npmjs.com/package/mime)\n* [parse-server-simple-mailgun-adapter@1.0.1](https://www.npmjs.com/package/parse-server-simple-mailgun-adapter)", "##### Devevelopment Dependencies Updates:\n* [babel-preset-env@1.6.1](https://www.npmjs.com/package/babel-preset-env)\n* [cross-env@5.1.0](https://www.npmjs.com/package/cross-env)\n* [mongodb-runner@3.6.1](https://www.npmjs.com/package/mongodb-runner)\n* [eslint-plugin-flowtype@2.39.1](https://www.npmjs.com/package/eslint-plugin-flowtype)\n* [eslint@4.9.0](https://www.npmjs.com/package/eslint)", "### 2.6.3\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.2...2.6.3)", "#### Improvements:\n* Queries on Pointer fields with `$in` and `$nin` now supports list of objectId's, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* LiveQueries on `$in` and `$nin` for pointer fields work as expected thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Also remove device token when APNS error is BadDeviceToken, thanks to [Mauricio Tollin](https://github.com/)\n* LRU cache is not available on the ParseServer object, thanks to [Tyler Brock](https://github.com/tbrock)\n* Error messages are more expressive, thanks to [Tyler Brock](https://github.com/tbrock)\n* Postgres: Properly handle undefined field values, thanks to [Diamond Lewis](https://github.com/dlewis)\n* Updating with two GeoPoints fails correctly, thanks to [Anthony Mosca](https://github.com/aontas)", "#### New Features:\n* Adds ability to set a maxLimit on server configuration for queries, thanks to [Chris Norris](https://github.com/)", "#### Bug fixes:\n* Fixes issue affecting reporting `_PushStatus` with misconfigured serverURL, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting deletion of class that doesn't exist, thanks to [Diamond Lewis](https://github.com/dlewis)", "#### Dependency Updates:\n* [winston@2.4.0](https://www.npmjs.com/package/winston)\n* [pg-promise@6.10.2](https://www.npmjs.com/package/pg-promise)\n* [winston-daily-rotate-file@1.6.0](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [request@2.83.0](https://www.npmjs.com/package/request)\n* [body-parser@1.18.2](https://www.npmjs.com/package/body-parser)", "##### Devevelopment Dependencies Updates:\n* [request-promise@4.2.2](https://www.npmjs.com/package/request-promise)\n* [eslint@4.7.1](https://www.npmjs.com/package/eslint)", "### 2.6.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.1...2.6.2)", "#### Improvements:\n* PushWorker/PushQueue channels are properly prefixed with the Parse applicationId, thanks to [Marvel Mathew](https://github.com/marvelm)\n* You can use Parse.Cloud.afterSave hooks on _PushStatus\n* You can use Parse.Cloud.onLiveQueryEvent to track the number of clients and subscriptions\n* Adds support for more fields from the Audience class.", "#### New Features:\n* Push: Adds ability to track sentPerUTC offset if your push scheduler supports it.\n* Push: Adds support for cleaning up invalid deviceTokens from _Installation (PARSE_SERVER_CLEANUP_INVALID_INSTALLATIONS=1).", "#### Dependency Updates:\n* [ws@3.2.0](https://www.npmjs.com/package/ws)\n* [pg-promise@6.5.3](https://www.npmjs.com/package/pg-promise)\n* [winston-daily-rotate-file@1.5.0](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [body-parser@1.18.1](https://www.npmjs.com/package/body-parser)", "##### Devevelopment Dependencies Updates:\n* [nodemon@1.12.1](https://www.npmjs.com/package/nodemon)\n* [mongodb-runner@3.6.0](https://www.npmjs.com/package/mongodb-runner)\n* [babel-eslint@8.0.0](https://www.npmjs.com/package/babel-eslint)", "### 2.6.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.6.0...2.6.1)", "#### Improvements:\n* Improves overall performance of the server, more particularly with large query results.\n* Improves performance of InMemoryCacheAdapter by removing serialization.\n* Improves logging performance by skipping necessary log calls.\n* Refactors object routers to simplify logic.\n* Adds automatic indexing on $text indexes, thanks to [Diamon Lewis](https://github.com/dplewis)", "#### New Features:\n* Push: Adds ability to send localized pushes according to the _Installation localeIdentifier\n* Push: proper support for scheduling push in user's locale time, thanks to [Marvel Mathew](https://github.com/marvelm)\n* LiveQuery: Adds ability to use LiveQuery with a masterKey, thanks to [Jeremy May](https://github.com/kenishi)", "#### Bug Fixes:\n* Fixes an issue that would duplicate Session objects per userId-installationId pair.\n* Fixes an issue affecting pointer permissions introduced in this release.\n* Fixes an issue that would prevent displaying audiences correctly in dashboard.\n* Fixes an issue affecting preventLoginWithUnverifiedEmail upon signups.", "#### Dependency Updates:\n* [pg-promise@6.3.2](https://www.npmjs.com/package/pg-promise)\n* [body-parser@1.18.0](https://www.npmjs.com/package/body-parser)\n* [nodemon@1.11.1](https://www.npmjs.com/package/nodemon)", "##### Devevelopment Dependencies Updates:\n* [babel-cli@6.26.0](https://www.npmjs.com/package/babel-cli)", "### 2.6.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.3...2.6.0)", "#### Breaking Changes:\n* [parse-server-s3-adapter@1.2.0](https://www.npmjs.com/package/parse-server-s3-adapter): A new deprecation notice is introduced with parse-server-s3-adapter's version 1.2.0. An upcoming release will remove passing key and password arguments. AWS credentials should be set using AWS best practices. See the [Deprecation Notice for AWS credentials]( https://github.com/parse-server-modules/parse-server-s3-adapter/blob/master/README.md#deprecation-notice----aws-credentials) section of the adapter's README.", "#### New Features\n* Polygon is fully supported as a type, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Query supports PolygonContains, thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Improvements\n* Postgres: Adds support nested contains and containedIn, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Postgres: Adds support for `null` in containsAll queries, thanks to [Diamond Lewis](https://github.com/dplewis)\n* Cloud Code: Request headers are passed to the cloud functions, thanks to [miguel-s](https://github.com/miguel-s)\n* Push: All push queries now filter only where deviceToken exists", "#### Bug Fixes:\n* Fixes issue affecting updates of _User objects when authData was passed.\n* Push: Pushing to an empty audience should now properly report a failed _PushStatus\n* Linking Users: Fixes issue affecting linking users with sessionToken only", "#### Dependency Updates:\n* [ws@3.1.0](https://www.npmjs.com/package/ws)\n* [mime@1.4.0](https://www.npmjs.com/package/mime)\n* [semver@5.4.0](https://www.npmjs.com/package/semver)\n* [uws@8.14.1](https://www.npmjs.com/package/uws)\n* [bcrypt@1.0.3](https://www.npmjs.com/package/bcrypt)\n* [mongodb@2.2.31](https://www.npmjs.com/package/mongodb)\n* [redis@2.8.0](https://www.npmjs.com/package/redis)\n* [pg-promise@6.3.1](https://www.npmjs.com/package/pg-promise)\n* [commander@2.11.0](https://www.npmjs.com/package/commander)", "##### Devevelopment Dependencies Updates:\n* [jasmine@2.8.0](https://www.npmjs.com/package/jasmine)\n* [babel-register@6.26.0](https://www.npmjs.com/package/babel-register)\n* [babel-core@6.26.0](https://www.npmjs.com/package/babel-core)\n* [cross-env@5.0.2](https://www.npmjs.com/package/cross-env)", "### 2.5.3\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.2...2.5.3)", "#### New Features:\n* badge property on android installations will now be set as on iOS (#3970), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug Fixes:\n* Fixes incorrect number parser for cache options", "### 2.5.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.1...2.5.2)", "#### Improvements:\n* Restores ability to run on node >= 4.6\n* Adds ability to configure cache from CLI\n* Removes runtime check for node >= 4.6", "### 2.5.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.5.0...2.5.1)", "#### New Features:\n* Adds ability to set default objectId size (#3950), thanks to [Steven Shipton](https://github.com/steven-supersolid)", "#### Improvements:\n* Uses LRU cache instead of InMemoryCache by default (#3979), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* iOS pushes are now using HTTP/2.0 instead of binary API (#3983), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [parse@1.10.0](https://www.npmjs.com/package/parse)\n* [pg-promise@6.3.0](https://www.npmjs.com/package/pg-promise)\n* [parse-server-s3-adapter@1.1.0](https://www.npmjs.com/package/parse-server-s3-adapter)\n* [parse-server-push-adapter@2.0.0](https://www.npmjs.com/package/parse-server-push-adapter)", "### 2.5.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.4.2...2.5.0)", "#### New Features:\n* Adds ability to run full text search (#3904), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Adds ability to run `$withinPolygon` queries (#3889), thanks to [Diamond Lewis](https://github.com/dplewis)\n* Adds ability to pass read preference per query with mongodb (#3865), thanks to [davimacedo](https://github.com/davimacedo)\n* beforeFind trigger now includes `isGet` for get queries (#3862), thanks to [davimacedo](https://github.com/davimacedo)\n* Adds endpoints for dashboard's audience API (#3861), thanks to [davimacedo](https://github.com/davimacedo)\n* Restores the job scheduling endpoints (#3927), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements:\n* Removes unnecessary warning when using maxTimeMs with mongodb, thanks to [Tyler Brock](https://github.com/tbrock)\n* Improves access control on system classes (#3916), thanks to [Worathiti Manosroi](https://github.com/pungme)\n* Adds bytes support in postgres (#3894), thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Bug Fixes:\n* Fixes issue with vkontakte adapter that would hang the request, thanks to [Denis Trofimov](https://github.com/denistrofimov)\n* Fixes issue affecting null relational data (#3924), thanks to [davimacedo](https://github.com/davimacedo)\n* Fixes issue affecting session token deletion (#3937), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting the serverInfo endpoint (#3933), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting beforeSave with dot-noted sub-documents (#3912), thanks to [IlyaDiallo](https://github.com/IlyaDiallo)\n* Fixes issue affecting emails being sent when using a 3rd party auth (#3882), thanks to [davimacedo](https://github.com/davimacedo)", "#### Dependency Updates:\n* [commander@2.10.0](https://www.npmjs.com/package/commander)\n* [pg-promise@5.9.7](https://www.npmjs.com/package/pg-promise)\n* [lru-cache@4.1.0](https://www.npmjs.com/package/lru-cache)\n* [mongodb@2.2.28](https://www.npmjs.com/package/mongodb)", "##### Devevelopment dependencies\n* [babel-core@6.25.0](https://www.npmjs.com/package/babel-core)\n* [cross-env@5.0.1](https://www.npmjs.com/package/cross-env)\n* [nyc@11.0.2](https://www.npmjs.com/package/nyc)", "### 2.4.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.4.1...2.4.2)", "#### New Features:\n* ParseQuery: Support for withinPolygon [#3866](https://github.com/parse-community/parse-server/pull/3866), thanks to [Diamond Lewis](https://github.com/dplewis)", "#### Improvements:\n* Postgres: Use transactions when deleting a class, [#3869](https://github.com/parse-community/parse-server/pull/3836), thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n* Postgres: Proper support for GeoPoint equality query, [#3874](https://github.com/parse-community/parse-server/pull/3836), thanks to [Diamond Lewis](https://github.com/dplewis)\n* beforeSave and liveQuery will be correctly triggered on email verification [#3851](https://github.com/parse-community/parse-server/pull/3851), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes:\n* Skip authData validation if it hasn't changed, on PUT requests [#3872](https://github.com/parse-community/parse-server/pull/3872), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [mongodb@2.2.27](https://www.npmjs.com/package/mongodb)\n* [pg-promise@5.7.2](https://www.npmjs.com/package/pg-promise)", "\n### 2.4.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.4.0...2.4.1)", "#### Bug fixes:\n* Fixes issue affecting relation updates ([#3835](https://github.com/parse-community/parse-server/pull/3835), [#3836](https://github.com/parse-community/parse-server/pull/3836)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issue affecting sending push notifications, thanks to [Felipe Andrade](https://github.com/felipemobile)\n* Session are always cleared when updating the passwords ([#3289](https://github.com/parse-community/parse-server/pull/3289), [#3821](https://github.com/parse-community/parse-server/pull/3821), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Dependency Updates:\n* [body-parser@1.17.2](https://www.npmjs.com/package/body-parser)\n* [pg-promise@5.7.1](https://www.npmjs.com/package/pg-promise)\n* [ws@3.0.0](https://www.npmjs.com/package/ws)", "\n### 2.4.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.8...2.4.0)", "Starting 2.4.0, parse-server is tested against node 6.10 and 7.10, mongodb 3.2 and 3.4.\nIf you experience issues with older versions, please [open a issue](https://github.com/parse-community/parse-server/issues).", "#### New Features:\n* Adds `count` Class Level Permission ([#3814](https://github.com/parse-community/parse-server/pull/3814)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Proper graceful shutdown support ([#3786](https://github.com/parse-community/parse-server/pull/3786)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Let parse-server store as `scheduled` Push Notifications with push_time (#3717, #3722), thanks to [Felipe Andrade](https://github.com/felipemobile)", "#### Improvements\n* Parse-Server images are built through docker hub, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Skip authData validation if it hasn't changed, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* [postgres] Improve performance when adding many new fields to the Schema ([#3740](https://github.com/parse-community/parse-server/pull/3740)), thanks to [Paulo Vítor S Reis](https://github.com/paulovitin)\n* Test maintenance, wordsmithing and nits ([#3744](https://github.com/parse-community/parse-server/pull/3744)), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Bug Fixes:\n* [postgres] Fixes issue affecting deleting multiple fields of a Schema ([#3734](https://github.com/parse-community/parse-server/pull/3734), [#3735](https://github.com/parse-community/parse-server/pull/3735)), thanks to [Paulo Vítor S Reis](https://github.com/paulovitin)\n* Fix issue affecting _PushStatus state ([#3808](https://github.com/parse-community/parse-server/pull/3808)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* requiresAuthentication Class Level Permission behaves correctly, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Email Verification related fields are not exposed ([#3681](https://github.com/parse-community/parse-server/pull/3681), [#3393](https://github.com/parse-community/parse-server/pull/3393), [#3432](https://github.com/parse-community/parse-server/pull/3432)), thanks to [Anthony Mosca](https://github.com/aontas)\n* HTTP query parameters are properly obfuscated in logs ([#3793](https://github.com/parse-community/parse-server/pull/3793), [#3789](https://github.com/parse-community/parse-server/pull/3789)), thanks to [@youngerong](https://github.com/youngerong)\n* Improve handling of `$near` operators in `$or` queries ([#3767](https://github.com/parse-community/parse-server/pull/3767), [#3798](https://github.com/parse-community/parse-server/pull/3798)), thanks to [Jack Wearden](https://github.com/NotBobTheBuilder)\n* Fix issue affecting arrays of pointers ([#3169](https://github.com/parse-community/parse-server/pull/3169)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix issue affecting overloaded query constraints ([#3723](https://github.com/parse-community/parse-server/pull/3723), [#3678](https://github.com/parse-community/parse-server/pull/3678)), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Properly catch unhandled rejections in _Installation updates ([#3795](https://github.com/parse-community/parse-server/pull/3795)), thanks to [kahoona77](https://github.com/kahoona77)", "#### Dependency Updates:", "* [uws@0.14.5](https://www.npmjs.com/package/uws)\n* [mime@1.3.6](https://www.npmjs.com/package/mime)\n* [mongodb@2.2.26](https://www.npmjs.com/package/mongodb)\n* [pg-promise@5.7.0](https://www.npmjs.com/package/pg-promise)\n* [semver@5.3.0](https://www.npmjs.com/package/semver)", "##### Devevelopment dependencies\n* [babel-cli@6.24.1](https://www.npmjs.com/package/babel-cli)\n* [babel-core@6.24.1](https://www.npmjs.com/package/babel-core)\n* [babel-preset-es2015@6.24.1](https://www.npmjs.com/package/babel-preset-es2015)\n* [babel-preset-stage-0@6.24.1](https://www.npmjs.com/package/babel-preset-stage-0)\n* [babel-register@6.24.1](https://www.npmjs.com/package/babel-register)\n* [cross-env@5.0.0](https://www.npmjs.com/package/cross-env)\n* [deep-diff@0.3.8](https://www.npmjs.com/package/deep-diff)\n* [gaze@1.1.2](https://www.npmjs.com/package/gaze)\n* [jasmine@2.6.0](https://www.npmjs.com/package/jasmine)\n* [jasmine-spec-reporter@4.1.0](https://www.npmjs.com/package/jasmine-spec-reporter)\n* [mongodb-runner@3.5.0](https://www.npmjs.com/package/mongodb-runner)\n* [nyc@10.3.2](https://www.npmjs.com/package/nyc)\n* [request-promise@4.2.1](https://www.npmjs.com/package/request-promise)", "\n### 2.3.8\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.7...2.3.8)", "#### New Features\n* Support for PG-Promise options, thanks to [ren dong](https://github.com/rendongsc)", "#### Improvements\n* Improves support for graceful shutdown, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improves configuration validation for Twitter Authentication, thanks to [Benjamin Wilson Friedman](https://github.com/montymxb)", "#### Bug Fixes\n* Fixes issue affecting GeoPoint __type with Postgres, thanks to [zhoul-HS](https://github.com/zhoul-HS)\n* Prevent user creation if username or password is empty, thanks to [Wissam Abirached](https://github.com/wabirached)", "#### Dependency Updates:\n* [cross-env@4.0.0 ](https://www.npmjs.com/package/cross-env)\n* [ws@2.2.3](https://www.npmjs.com/package/ws)\n* [babel-core@6.24.0](https://www.npmjs.com/package/babel-core)\n* [uws@0.14.0](https://www.npmjs.com/package/uws)\n* [babel-preset-es2015@6.24.0](https://www.npmjs.com/package/babel-preset-es2015)\n* [babel-plugin-syntax-flow@6.18.0](https://www.npmjs.com/package/babel-plugin-syntax-flow)\n* [babel-cli@6.24.0](https://www.npmjs.com/package/babel-cli)\n* [babel-register@6.24.0](https://www.npmjs.com/package/babel-register)\n* [winston-daily-rotate-file@1.4.6](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [mongodb@2.2.25](https://www.npmjs.com/package/mongodb)\n* [redis@2.7.0](https://www.npmjs.com/package/redis)\n* [pg-promise@5.6.4](https://www.npmjs.com/package/pg-promise)\n* [parse-server-push-adapter@1.3.0](https://www.npmjs.com/package/parse-server-push-adapter)", "### 2.3.7\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.6...2.3.7)", "#### New Features\n* New endpoint to resend verification email, thanks to [Xy Ziemba](https://github.com/xyziemba)", "#### Improvements\n* Add TTL option for Redis Cache Adapter, thanks to [Ryan Foster](https://github.com/f0ster)\n* Update Postgres Storage Adapter, thanks to [Vitaly Tomilov](https://github.com/vitaly-t)", "#### Bug Fixes\n* Add index on Role.name, fixes (#3579), thanks to [Natan Rolnik](https://github.com/natanrolnik)\n* Fix default value of userSensitiveFields, fixes (#3593), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Dependency Updates:\n* [body-parser@1.17.1](https://www.npmjs.com/package/body-parser)\n* [express@4.15.2](https://www.npmjs.com/package/express)\n* [request@2.81.0](https://www.npmjs.com/package/request)\n* [winston-daily-rotate-file@1.4.5](https://www.npmjs.com/package/winston-daily-rotate-file)\n* [ws@2.2.0](https://www.npmjs.com/package/ws)", "\n### 2.3.6\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.5...2.3.6)", "#### Improvements\n* Adds support for injecting a middleware for instumentation in the CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Alleviate mongodb bug with $or queries [SERVER-13732](https://jira.mongodb.org/browse/SERVER-13732), thanks to [Jack Wearden](https://github.com/NotBobTheBuilder)", "#### Bug Fixes\n* Fix issue affecting password policy and empty passwords, thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)\n* Fix issue when logging url in non string objects, thanks to [Paulo Vítor S Reis](https://github.com/paulovitin)", "#### Dependencies updates:\n* [ws@2.1.0](https://npmjs.com/package/ws)\n* [uws@0.13.0](https://npmjs.com/package/uws)\n* [pg-promise@5.6.2](https://npmjs.com/package/pg-promise)", "\n### 2.3.5\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.3...2.3.5)", "#### Bug Fixes\n* Allow empty client key\n(#3497), thanks to [Arthur Cinader](https://github.com/acinader)\n* Fix LiveQuery unsafe user\n(#3525), thanks to [David Starke](https://github.com/dstarke)\n* Use `flushdb` instead of `flushall` in RedisCacheAdapter\n(#3523), thanks to [Jeremy Louie](https://github.com/JeremyPlease)\n* Fix saving GeoPoints and Files in `_GlobalConfig` (Make sure we don't treat\ndot notation keys as topLevel atoms)\n(#3531), thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.3.3\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.2...2.3.3)", "#### Breaking Changes\n* **Minimum Node engine bumped to 4.6** (#3480), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug Fixes\n* Add logging on failure to create file (#3424), thanks to [Arthur Cinader](https://github.com/acinader)\n* Log Parse Errors so they are intelligible (#3431), thanks to [Arthur Cinader](https://github.com/acinader)\n* MongoDB $or Queries avoid SERVER-13732 bug (#3476), thanks to [Jack Wearden](https://github.com/NotBobTheBuilder)\n* Mongo object to Parse object date serialization - avoid re-serialization of iso of type Date (#3389), thanks to [nodechefMatt](https://github.com/nodechefMatt)", "#### Improvements\n* Ground preparations for push scalability (#3080), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Use uWS as optional dependency for ws server (#3231), thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.3.2\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.1...2.3.2)", "#### New features\n* Add parseFrameURL for masking user-facing pages (#3267), thanks to [Lenart Rudel](https://github.com/lenart)", "#### Bug fixes\n* Fix Parse-Server to work with winston-daily-rotate-1.4.2 (#3335), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Improvements\n* Add support for regex string for password policy validatorPattern setting (#3331), thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)\n* LiveQuery should match subobjects with dot notation (#3322), thanks to [David Starke](https://github.com/dstarke)\n* Reduce time to process high number of installations for push (#3264), thanks to [jeacott1](https://github.com/jeacott1)\n* Fix trivial typo in error message (#3238), thanks to [Arthur Cinader](https://github.com/acinader)", "### 2.3.1\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.3.0...2.3.1)", "A major issue was introduced when refactoring the authentication modules.\nThis release addresses only that issue.", "### 2.3.0\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.2.25...2.3.0)", "#### Breaking changes\n* Parse.Cloud.useMasterKey() is a no-op, please refer to (Cloud Code migration guide)[https://github.com/ParsePlatform/parse-server/wiki/Compatibility-with-Hosted-Parse#cloud-code]\n* Authentication helpers are now proper adapters, deprecates oauth option in favor of auth.\n* DEPRECATES: facebookAppIds, use `auth: { facebook: { appIds: [\"AAAAAAAAA\" ] } }`\n* `email` field is not returned anymore for `Parse.User` queries. (Provided only on the user itself if provided).", "#### New Features\n* Adds ability to restrict access through Class Level Permissions to only authenticated users [see docs](http://parseplatform.github.io/docs/ios/guide/#requires-authentication-permission-requires-parse-server---230)\n* Adds ability to strip sensitive data from `_User` responses, strips emails by default, thanks to [Arthur Cinader](https://github.com/acinader)\n* Adds password history support for password policies, thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)", "#### Improvements\n* Bump parse-server-s3-adapter to 1.0.6, thanks to [Arthur Cinader](https://github.com/acinader)\n* Using PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS let you create user sessions when passing {installationId: \"xxx-xxx\"} on signup in cloud code, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Add CLI option to pass `host` parameter when creating parse-server from CLI, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)", "#### Bug fixes\n* Ensure batch routes are only using posix paths, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Ensure falsy options from CLI are properly taken into account, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Fixes issues affecting calls to `matchesKeyInQuery` with pointers.\n* Ensure that `select` keys can be changed in triggers (beforeFind...), thanks to [Arthur Cinader](https://github.com/acinader)", "#### Housekeeping\n* Enables and enforces linting with eslint, thanks to [Arthur Cinader](https://github.com/acinader)", "### 2.2.25", "Postgres support requires v9.5", "#### New Features\n* Dockerizing Parse Server, thanks to [Kirill Kravinsky](https://github.com/woyorus)\n* Login with qq, wechat, weibo, thanks to [haifeizhang]()\n* Password policy, validation and expiration, thanks to [Bhaskar Reddy Yasa](https://github.com/bhaskaryasa)\n* Health check on /health, thanks to [Kirill Kravinsky](https://github.com/woyorus)\n* Reuse SchemaCache across requests option, thanks to [Steven Shipton](https://github.com/steven-supersolid)", "#### Improvements\n* Better support for CLI options, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Specity a database timeout with maxTimeMS, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Adds the username to reset password success pages, thanks to [Halim Qarroum](https://github.com/HQarroum)\n* Better support for Redis cache adapter, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Better coverage of Postgres, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)", "#### Bug Fixes\n* Fixes issue when sending push to multiple installations, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fixes issues with twitter authentication, thanks to [jonas-db](https://github.com/jonas-db)\n* Ignore createdAt fields update, thanks to [Yuki Takeichi](https://github.com/yuki-takeichi)\n* Improve support for array equality with LiveQuery, thanks to [David Poetzsch-Heffter](https://github.com/dpoetzsch)\n* Improve support for batch endpoint when serverURL and publicServerURL have different paths, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Support saving relation objects, thanks to [Yuki Takeichi](https://github.com/yuki-takeichi)", "### 2.2.24", "#### New Features\n* LiveQuery: Bring your own adapter (#2902), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* LiveQuery: Adds \"update\" operator to update a query subscription (#2935), thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Improvements\n* Better Postgres support, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Logs the function name when failing (#2963), thanks to [Michael Helvey](https://github.com/michaelhelvey)\n* CLI: forces closing the connections with SIGINT/SIGTERM (#2964), thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Reduce the number of calls to the `_SCHEMA` table (#2912), thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* LiveQuery: Support for Role ACL's, thanks to [Aaron Blondeau](https://github.com/aaron-blondeau-dose)", "#### Bug Fixes\n* Better support for checking application and client keys, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Google OAuth, better support for android and web logins, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.23", "* Run liveQuery server from CLI with a different port, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Support for Postgres databaseURI, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Support for Postgres options, thanks to [Kulshekhar Kabra](https://github.com/kulshekhar)\n* Improved support for google login (id_token and access_token), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improvements with VKontakte login, thanks to [Eugene Antropov](https://github.com/antigp)\n* Improved support for `select` and `include`, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes", "* Fix error when updating installation with useMasterKey (#2888), thanks to [Jeremy Louie](https://github.com/JeremyPlease)\n* Fix bug affecting usage of multiple `notEqualTo`, thanks to [Jeremy Louie](https://github.com/JeremyPlease)\n* Improved support for null values in arrays, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.22", "* Minimum nodejs engine is now 4.5", "#### New Features\n* New: CLI for parse-live-query-server, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Start parse-live-query-server for parse-server CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)", "#### Bug fixes\n* Fix: Include with pointers are not conflicting with get CLP anymore, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Removes dependency on babel-polyfill, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Support nested select calls, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Use native column selection instead of runtime, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: installationId header is properly used when updating `_Installation` objects, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: don't crash parse-server on improperly formatted live-query messages, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Passwords are properly stripped out of logs, thanks to [Arthur Cinader](https://github.com/acinader)\n* Fix: Lookup for email in username if email is not set, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.21", "* Fix: Reverts removal of babel-polyfill", "### 2.2.20", "* New: Adds CloudCode handler for `beforeFind`, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: RedisCacheAdapter for syncing schema, role and user caches across servers, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Latest master build available at `ParsePlatform/parse-server#latest`, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Better support for upgradeToRevocableSession with missing session token, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Removes babel-polyfill runtime dependency, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Cluster option now support a boolean value for automatically choosing the right number of processes, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Filenames now appear correctly, thanks to [Lama Chandrasena](https://github.com/lama-buddy)\n* Fix: `_acl` is properly updated, thanks to [Steven Shipton](https://github.com/steven-supersolid)", "Other fixes by [Mathias Rangel Wulff](https://github.com/mathiasrw)", "### 2.2.19", "* New: support for upgrading to revocable sessions, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: NullCacheAdapter for disabling caching, thanks to [Yuki Takeichi](https://github.com/yuki-takeichi)\n* New: Account lockout policy [#2601](https://github.com/ParsePlatform/parse-server/pull/2601), thanks to [Diwakar Cherukumilli](https://github.com/cherukumilli)\n* New: Jobs endpoint for defining and run jobs (no scheduling), thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Add --cluster option to the CLI, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Support for login with vk.com, thanks to [Nurdaulet Bolatov](https://github.com/nbolatov)\n* New: experimental support for postgres databases, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: parse-server doesn't call next() after successful responses, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Nested objects are properly includeed with Pointer Permissions on, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: null values in include calls are properly handled, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Schema validations now runs after beforeSave hooks, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: usersname and passwords are properly type checked, thanks to [Bam Wang](https://github.com/bamwang)\n* Fix: logging in info log would log also in error log, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: removes extaneous logging from ParseLiveQueryServer, thanks to [Flavio Torres](https://github.com/flavionegrao)\n* Fix: support for Range requests for files, thanks to [Brage G. Staven](https://github.com/Bragegs)", "### 2.2.18", "* Fix: Improve support for objects in push alert, thanks to [Antoine Lenoir](https://github.com/alenoir)\n* Fix; Prevent pointed from getting clobbered when they are changed in a beforeSave, thanks to [sud](https://github.com/sud80)\n* Fix: Improve support for \"Bytes\" type, thanks to [CongHoang](https://github.com/conghoang)\n* Fix: Better logging compatability with Parse.com, thanks to [Arthur Cinader](https://github.com/acinader)\n* New: Add Janrain Capture and Janrain Engage auth provider, thanks to [Andrew Lane](https://github.com/AndrewLane)\n* Improved: Include content length header in files response, thanks to [Steven Van Bael](https://github.com/vbsteven)\n* Improved: Support byte range header for files, thanks to [Brage G. Staven](https://github.com/Bragegs)\n* Improved: Validations for LinkedIn access_tokens, thanks to [Felix Dumit](https://github.com/felix-dumit)\n* Improved: Experimental postgres support, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Perf: Use native bcrypt implementation if available, thanks to [Florent Vilmart](https://github.com/flovilmart)", "\n### [2.2.17](https://github.com/ParsePlatform/parse-server/tree/2.2.17) (07/23/2016)\n[Full Changelog](https://github.com/ParsePlatform/parse-server/compare/2.2.16...2.2.17)", "* Cloud code logs [\\#2370](https://github.com/ParsePlatform/parse-server/pull/2370) ([flovilmart](https://github.com/flovilmart))\n* Make sure \\_PushStatus operations are run in order [\\#2367](https://github.com/ParsePlatform/parse-server/pull/2367) ([flovilmart](https://github.com/flovilmart))\n* Typo fix for error message when can't ensure uniqueness of user email addresses [\\#2360](https://github.com/ParsePlatform/parse-server/pull/2360) ([AndrewLane](https://github.com/AndrewLane))\n* LiveQuery constrains matching fix [\\#2357](https://github.com/ParsePlatform/parse-server/pull/2357) ([simonas-notcat](https://github.com/simonas-notcat))\n* Fix typo in logging for commander parseConfigFile [\\#2352](https://github.com/ParsePlatform/parse-server/pull/2352) ([AndrewLane](https://github.com/AndrewLane))\n* Fix minor typos in test names [\\#2351](https://github.com/ParsePlatform/parse-server/pull/2351) ([acinader](https://github.com/acinader))\n* Makes sure we don't strip authData or session token from users using masterKey [\\#2348](https://github.com/ParsePlatform/parse-server/pull/2348) ([flovilmart](https://github.com/flovilmart))\n* Run coverage with istanbul [\\#2340](https://github.com/ParsePlatform/parse-server/pull/2340) ([flovilmart](https://github.com/flovilmart))\n* Run next\\(\\) after successfully sending data to the client [\\#2338](https://github.com/ParsePlatform/parse-server/pull/2338) ([blacha](https://github.com/blacha))\n* Cache all the mongodb/version folder [\\#2336](https://github.com/ParsePlatform/parse-server/pull/2336) ([flovilmart](https://github.com/flovilmart))\n* updates usage of setting: emailVerifyTokenValidityDuration [\\#2331](https://github.com/ParsePlatform/parse-server/pull/2331) ([cherukumilli](https://github.com/cherukumilli))\n* Update Mongodb client to 2.2.4 [\\#2329](https://github.com/ParsePlatform/parse-server/pull/2329) ([flovilmart](https://github.com/flovilmart))\n* Allow usage of analytics adapter [\\#2327](https://github.com/ParsePlatform/parse-server/pull/2327) ([deashay](https://github.com/deashay))\n* Fix flaky tests [\\#2324](https://github.com/ParsePlatform/parse-server/pull/2324) ([flovilmart](https://github.com/flovilmart))\n* don't serve null authData values [\\#2320](https://github.com/ParsePlatform/parse-server/pull/2320) ([yuzeh](https://github.com/yuzeh))\n* Fix null relation problem [\\#2319](https://github.com/ParsePlatform/parse-server/pull/2319) ([flovilmart](https://github.com/flovilmart))\n* Clear the connectionPromise upon close or error [\\#2314](https://github.com/ParsePlatform/parse-server/pull/2314) ([flovilmart](https://github.com/flovilmart))\n* Report validation errors with correct error code [\\#2299](https://github.com/ParsePlatform/parse-server/pull/2299) ([flovilmart](https://github.com/flovilmart))\n* Parses correctly Parse.Files and Dates when sent to Cloud Code Functions [\\#2297](https://github.com/ParsePlatform/parse-server/pull/2297) ([flovilmart](https://github.com/flovilmart))\n* Adding proper generic Not Implemented. [\\#2292](https://github.com/ParsePlatform/parse-server/pull/2292) ([vitaly-t](https://github.com/vitaly-t))\n* Adds schema caching capabilities \\(5s by default\\) [\\#2286](https://github.com/ParsePlatform/parse-server/pull/2286) ([flovilmart](https://github.com/flovilmart))\n* add digits oauth provider [\\#2284](https://github.com/ParsePlatform/parse-server/pull/2284) ([ranhsd](https://github.com/ranhsd))\n* Improve installations query [\\#2281](https://github.com/ParsePlatform/parse-server/pull/2281) ([flovilmart](https://github.com/flovilmart))\n* Adding request headers to cloud functions fixes \\#1461 [\\#2274](https://github.com/ParsePlatform/parse-server/pull/2274) ([blacha](https://github.com/blacha))\n* Creates a new sessionToken when updating password [\\#2266](https://github.com/ParsePlatform/parse-server/pull/2266) ([flovilmart](https://github.com/flovilmart))\n* Add Gitter chat link to the README. [\\#2264](https://github.com/ParsePlatform/parse-server/pull/2264) ([nlutsenko](https://github.com/nlutsenko))\n* Restores ability to include non pointer keys [\\#2263](https://github.com/ParsePlatform/parse-server/pull/2263) ([flovilmart](https://github.com/flovilmart))\n* Allow next middleware handle error in handleParseErrors [\\#2260](https://github.com/ParsePlatform/parse-server/pull/2260) ([mejcz](https://github.com/mejcz))\n* Exposes the ClientSDK infos if available [\\#2259](https://github.com/ParsePlatform/parse-server/pull/2259) ([flovilmart](https://github.com/flovilmart))\n* Adds support for multiple twitter auths options [\\#2256](https://github.com/ParsePlatform/parse-server/pull/2256) ([flovilmart](https://github.com/flovilmart))\n* validate\\_purchase fix for SANDBOX requests [\\#2253](https://github.com/ParsePlatform/parse-server/pull/2253) ([valeryvaskabovich](https://github.com/valeryvaskabovich))", "### 2.2.16 (7/10/2016)", "* New: Expose InMemoryCacheAdapter publicly, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* New: Add ability to prevent login with unverified email, thanks to [Diwakar Cherukumilli](https://github.com/cherukumilli)\n* Improved: Better error message for incorrect type, thanks to [Andrew Lane](https://github.com/AndrewLane)\n* Improved: Better error message for permission denied, thanks to [Blayne Chard](https://github.com/blacha)\n* Improved: Update authData on login, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Improved: Ability to not check for old files on Parse.com, thanks to [OzgeAkin](https://github.com/OzgeAkin)\n* Fix: Issues with email adapter validation, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Issues with nested $or queries, thanks to [Florent Vilmart](https://github.com/flovilmart)", "### 2.2.15 (6/30/2016)", "* Fix: Type in description for Parse.Error.INVALID_QUERY, thanks to [Andrew Lane](https://github.com/AndrewLane)\n* Improvement: Stop requiring verifyUserEmails for password reset functionality, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Improvement: Kill without validation, thanks to [Drew Gross](https://github.com/drew-gross)\n* Fix: Deleting a file does not delete from fs.files, thanks to [David Keita](https://github.com/maninga)\n* Fix: Postgres stoage adapter fix, thanks to [Vitaly Tomilov](https://github.com/vitaly-t)\n* Fix: Results invalid session when providing an invalid session token, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: issue creating an anonymous user, thanks to [Hussam Moqhim](https://github.com/hmoqhim)\n* Fix: make http response serializable, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* New: Add postmark email adapter alternative [Glenn Reyes](https://github.com/glennreyes)", "### 2.2.14 (6/25/2016)", "* Hotfix: Fix Parse.Cloud.HTTPResponse serialization", "### 2.2.13 (6/12/2016)", "* Hotfix: Pin version of deepcopy", "### 2.2.12 (6/9/2016)", "* New: Custom error codes in cloud code response.error, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Fix: Crash in beforeSave when response is not an object, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Allow \"get\" on installations\n* Fix: Fix overly restrictive Class Level Permissions, thanks to [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Fix nested date parsing in Cloud Code, thanks to [Marco Cheung](https://github.com/Marco129)\n* Fix: Support very old file formats from Parse.com", "### 2.2.11 (5/31/2016)", "* Security: Censor user password in logs, thanks to [Marco Cheung](https://github.com/Marco129)\n* New: Add PARSE_SERVER_LOGS_FOLDER env var for setting log folder, thanks to [KartikeyaRokde](https://github.com/KartikeyaRokde)\n* New: Webhook key support, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Perf: Add cache adapter and default caching of certain objects, thanks to [Blayne Chard](https://github.com/blacha)\n* Improvement: Better error messages for schema type mismatches, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Improvement: Better error messages for reset password emails\n* Improvement: Webhook key support in CLI, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Remove read only fields when using beforeSave, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Use content type provided by JS SDK, thanks to [Blayne Chard](https://github.com/blacha) and [Florent Vilmart](https://github.com/flovilmart)\n* Fix: Tell the dashboard the stored push data is available, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Fix: Add support for HTTP Basic Auth, thanks to [Hussam Moqhim](https://github.com/hmoqhim)\n* Fix: Support for MongoDB version 3.2.6, (note: do not use MongoDB 3.2 with migrated apps that still have traffic on Parse.com), thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Prevent `pm2` from crashing when push notifications fail, thanks to [benishak](https://github.com/benishak)\n* Fix: Add full list of default _Installation fields, thanks to [Jeremy Pease](https://github.com/JeremyPlease)\n* Fix: Strip objectId out of hooks responses, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Fix external webhook response format, thanks to [Tyler Brock](https://github.com/TylerBrock)\n* Fix: Fix beforeSave when object is passed to `success`, thanks to [Madhav Bhagat](https://github.com/codebreach)\n* Fix: Remove use of deprecated APIs, thanks to [Emad Ehsan](https://github.com/emadehsan)\n* Fix: Crash when multiple Parse Servers on the same machine try to write to the same logs folder, thanks to [Steven Shipton](https://github.com/steven-supersolid)\n* Fix: Various issues with key names in `Parse.Object`s\n* Fix: Treat Bytes type properly\n* Fix: Caching bugs that caused writes by masterKey or other session token to not show up to users reading with a different session token\n* Fix: Pin mongo driver version, preventing a regression in version 2.1.19\n* Fix: Various issues with pointer fields not being treated properly\n* Fix: Issues with pointed getting un-fetched due to changes in beforeSave\n* Fix: Fixed crash when deleting classes that have CLPs", "### 2.2.10 (5/15/2016)", "* Fix: Write legacy ACLs to Mongo so that clients that still go through Parse.com can read them, thanks to [Tyler Brock](https://github.com/TylerBrock) and [carmenlau](https://github.com/carmenlau)\n* Fix: Querying installations with limit = 0 and count = 1 now works, thanks to [ssk7833](https://github.com/ssk7833)\n* Fix: Return correct error when violating unique index, thanks to [Marco Cheung](https://github.com/Marco129)\n* Fix: Allow unsetting user's email, thanks to [Marco Cheung](https://github.com/Marco129)\n* New: Support for Node 6.1", "### 2.2.9 (5/9/2016)", "* Fix: Fix a regression that caused Parse Server to crash when a null parameter is passed to a Cloud function", "### 2.2.8 (5/8/2016)", "* New: Support for Pointer Permissions\n* New: Expose logger in Cloud Code\n* New: Option to revoke sessions on password reset\n* New: Option to expire inactive sessions\n* Perf: Improvements in ACL checking query\n* Fix: Issues when sending pushes to list of devices that contains invalid values\n* Fix: Issues caused by using babel-polyfill outside of Parse Server, but in the same express app\n* Fix: Remove creation of extra session tokens\n* Fix: Return authData when querying with master key\n* Fix: Bugs when deleting webhooks\n* Fix: Ignore _RevocableSession header, which might be sent by the JS SDK\n* Fix: Issues with querying via URL params\n* Fix: Properly encode \"Date\" parameters to cloud code functions", "\n### 2.2.7 (4/15/2016)", "* Adds support for --verbose and verbose option when running ParseServer [\\#1414](https://github.com/ParsePlatform/parse-server/pull/1414) ([flovilmart](https://github.com/flovilmart))\n* Adds limit = 0 as a valid parameter for queries [\\#1493](https://github.com/ParsePlatform/parse-server/pull/1493) ([seijiakiyama](https://github.com/seijiakiyama))\n* Makes sure we preserve Installations when updating a token \\(\\#1475\\) [\\#1486](https://github.com/ParsePlatform/parse-server/pull/1486) ([flovilmart](https://github.com/flovilmart))\n* Hotfix for tests [\\#1503](https://github.com/ParsePlatform/parse-server/pull/1503) ([flovilmart](https://github.com/flovilmart))\n* Enable logs [\\#1502](https://github.com/ParsePlatform/parse-server/pull/1502) ([drew-gross](https://github.com/drew-gross))\n* Do some triple equals for great justice [\\#1499](https://github.com/ParsePlatform/parse-server/pull/1499) ([TylerBrock](https://github.com/TylerBrock))\n* Apply credential stripping to all untransforms for \\_User [\\#1498](https://github.com/ParsePlatform/parse-server/pull/1498) ([TylerBrock](https://github.com/TylerBrock))\n* Checking if object has defined key for Pointer constraints in liveQuery [\\#1487](https://github.com/ParsePlatform/parse-server/pull/1487) ([simonas-notcat](https://github.com/simonas-notcat))\n* Remove collection prefix and default mongo URI [\\#1479](https://github.com/ParsePlatform/parse-server/pull/1479) ([drew-gross](https://github.com/drew-gross))\n* Store collection prefix in mongo adapter, and clean up adapter interface [\\#1472](https://github.com/ParsePlatform/parse-server/pull/1472) ([drew-gross](https://github.com/drew-gross))\n* Move field deletion logic into mongo adapter [\\#1471](https://github.com/ParsePlatform/parse-server/pull/1471) ([drew-gross](https://github.com/drew-gross))\n* Adds support for Long and Double mongodb types \\(fixes \\#1316\\) [\\#1470](https://github.com/ParsePlatform/parse-server/pull/1470) ([flovilmart](https://github.com/flovilmart))\n* Schema.js database agnostic [\\#1468](https://github.com/ParsePlatform/parse-server/pull/1468) ([flovilmart](https://github.com/flovilmart))\n* Remove console.log [\\#1465](https://github.com/ParsePlatform/parse-server/pull/1465) ([drew-gross](https://github.com/drew-gross))\n* Push status nits [\\#1462](https://github.com/ParsePlatform/parse-server/pull/1462) ([flovilmart](https://github.com/flovilmart))\n* Fixes \\#1444 [\\#1451](https://github.com/ParsePlatform/parse-server/pull/1451) ([flovilmart](https://github.com/flovilmart))\n* Removing sessionToken and authData from \\_User objects included in a query [\\#1450](https://github.com/ParsePlatform/parse-server/pull/1450) ([simonas-notcat](https://github.com/simonas-notcat))\n* Move mongo field type logic into mongoadapter [\\#1432](https://github.com/ParsePlatform/parse-server/pull/1432) ([drew-gross](https://github.com/drew-gross))\n* Prevents \\_User lock out when setting ACL on signup or afterwards [\\#1429](https://github.com/ParsePlatform/parse-server/pull/1429) ([flovilmart](https://github.com/flovilmart))\n* Update .travis.yml [\\#1428](https://github.com/ParsePlatform/parse-server/pull/1428) ([flovilmart](https://github.com/flovilmart))\n* Adds relation fields to objects [\\#1424](https://github.com/ParsePlatform/parse-server/pull/1424) ([flovilmart](https://github.com/flovilmart))\n* Update .travis.yml [\\#1423](https://github.com/ParsePlatform/parse-server/pull/1423) ([flovilmart](https://github.com/flovilmart))\n* Sets the defaultSchemas keys in the SchemaCollection [\\#1421](https://github.com/ParsePlatform/parse-server/pull/1421) ([flovilmart](https://github.com/flovilmart))\n* Fixes \\#1417 [\\#1420](https://github.com/ParsePlatform/parse-server/pull/1420) ([drew-gross](https://github.com/drew-gross))\n* Untransform should treat Array's as nested objects [\\#1416](https://github.com/ParsePlatform/parse-server/pull/1416) ([blacha](https://github.com/blacha))\n* Adds X-Parse-Push-Status-Id header [\\#1412](https://github.com/ParsePlatform/parse-server/pull/1412) ([flovilmart](https://github.com/flovilmart))\n* Schema format cleanup [\\#1407](https://github.com/ParsePlatform/parse-server/pull/1407) ([drew-gross](https://github.com/drew-gross))\n* Updates the publicServerURL option [\\#1397](https://github.com/ParsePlatform/parse-server/pull/1397) ([flovilmart](https://github.com/flovilmart))\n* Fix exception with non-expiring session tokens. [\\#1386](https://github.com/ParsePlatform/parse-server/pull/1386) ([0x18B2EE](https://github.com/0x18B2EE))\n* Move mongo schema format related logic into mongo adapter [\\#1385](https://github.com/ParsePlatform/parse-server/pull/1385) ([drew-gross](https://github.com/drew-gross))\n* WIP: Huge performance improvement on roles queries [\\#1383](https://github.com/ParsePlatform/parse-server/pull/1383) ([flovilmart](https://github.com/flovilmart))\n* Removes GCS Adapter from provided adapters [\\#1339](https://github.com/ParsePlatform/parse-server/pull/1339) ([flovilmart](https://github.com/flovilmart))\n* DBController refactoring [\\#1228](https://github.com/ParsePlatform/parse-server/pull/1228) ([flovilmart](https://github.com/flovilmart))\n* Spotify authentication [\\#1226](https://github.com/ParsePlatform/parse-server/pull/1226) ([1nput0utput](https://github.com/1nput0utput))\n* Expose DatabaseAdapter to simplify application tests [\\#1121](https://github.com/ParsePlatform/parse-server/pull/1121) ([steven-supersolid](https://github.com/steven-supersolid))", "### 2.2.6 (4/5/2016)", "* Important Fix: Disables find on installation from clients [\\#1374](https://github.com/ParsePlatform/parse-server/pull/1374) ([flovilmart](https://github.com/flovilmart))\n* Adds missing options to the CLI [\\#1368](https://github.com/ParsePlatform/parse-server/pull/1368) ([flovilmart](https://github.com/flovilmart))\n* Removes only master on travis [\\#1367](https://github.com/ParsePlatform/parse-server/pull/1367) ([flovilmart](https://github.com/flovilmart))\n* Auth.\\_loadRoles should not query the same role twice. [\\#1366](https://github.com/ParsePlatform/parse-server/pull/1366) ([blacha](https://github.com/blacha))", "### 2.2.5 (4/4/2016)", "* Improves config loading and tests [\\#1363](https://github.com/ParsePlatform/parse-server/pull/1363) ([flovilmart](https://github.com/flovilmart))\n* Adds travis configuration to deploy NPM on new version tags [\\#1361](https://github.com/ParsePlatform/parse-server/pull/1361) ([gfosco](https://github.com/gfosco))\n* Inject the default schemas properties when loading it [\\#1357](https://github.com/ParsePlatform/parse-server/pull/1357) ([flovilmart](https://github.com/flovilmart))\n* Adds console transport when testing with VERBOSE=1 [\\#1351](https://github.com/ParsePlatform/parse-server/pull/1351) ([flovilmart](https://github.com/flovilmart))\n* Make notEqual work on relations [\\#1350](https://github.com/ParsePlatform/parse-server/pull/1350) ([flovilmart](https://github.com/flovilmart))\n* Accept only bool for $exists in LiveQuery [\\#1315](https://github.com/ParsePlatform/parse-server/pull/1315) ([drew-gross](https://github.com/drew-gross))\n* Adds more options when using CLI/config [\\#1305](https://github.com/ParsePlatform/parse-server/pull/1305) ([flovilmart](https://github.com/flovilmart))\n* Update error message [\\#1297](https://github.com/ParsePlatform/parse-server/pull/1297) ([drew-gross](https://github.com/drew-gross))\n* Properly let masterKey add fields [\\#1291](https://github.com/ParsePlatform/parse-server/pull/1291) ([flovilmart](https://github.com/flovilmart))\n* Point to \\#1271 as how to write a good issue report [\\#1290](https://github.com/ParsePlatform/parse-server/pull/1290) ([drew-gross](https://github.com/drew-gross))\n* Adds ability to override mount with publicServerURL for production uses [\\#1287](https://github.com/ParsePlatform/parse-server/pull/1287) ([flovilmart](https://github.com/flovilmart))\n* Single object queries to use include and keys [\\#1280](https://github.com/ParsePlatform/parse-server/pull/1280) ([jeremyjackson89](https://github.com/jeremyjackson89))\n* Improves report for Push error in logs and \\_PushStatus [\\#1269](https://github.com/ParsePlatform/parse-server/pull/1269) ([flovilmart](https://github.com/flovilmart))\n* Removes all stdout/err logs while testing [\\#1268](https://github.com/ParsePlatform/parse-server/pull/1268) ([flovilmart](https://github.com/flovilmart))\n* Matching queries with doesNotExist constraint [\\#1250](https://github.com/ParsePlatform/parse-server/pull/1250) ([andrecardoso](https://github.com/andrecardoso))\n* Added session length option for session tokens to server configuration [\\#997](https://github.com/ParsePlatform/parse-server/pull/997) ([Kenishi](https://github.com/Kenishi))\n* Regression test for \\#1259 [\\#1286](https://github.com/ParsePlatform/parse-server/pull/1286) ([drew-gross](https://github.com/drew-gross))\n* Regression test for \\#871 [\\#1283](https://github.com/ParsePlatform/parse-server/pull/1283) ([drew-gross](https://github.com/drew-gross))\n* Add a test to repro \\#701 [\\#1281](https://github.com/ParsePlatform/parse-server/pull/1281) ([drew-gross](https://github.com/drew-gross))\n* Fix for \\#1334: using relative cloud code files broken [\\#1353](https://github.com/ParsePlatform/parse-server/pull/1353) ([airdrummingfool](https://github.com/airdrummingfool))\n* Fix Issue/1288 [\\#1346](https://github.com/ParsePlatform/parse-server/pull/1346) ([flovilmart](https://github.com/flovilmart))\n* Fixes \\#1271 [\\#1295](https://github.com/ParsePlatform/parse-server/pull/1295) ([drew-gross](https://github.com/drew-gross))\n* Fixes issue \\#1302 [\\#1314](https://github.com/ParsePlatform/parse-server/pull/1314) ([flovilmart](https://github.com/flovilmart))\n* Fixes bug related to include in queries [\\#1312](https://github.com/ParsePlatform/parse-server/pull/1312) ([flovilmart](https://github.com/flovilmart))", "\n### 2.2.4 (3/29/2016)", "* Hotfix: fixed imports issue for S3Adapter, GCSAdapter, FileSystemAdapter [\\#1263](https://github.com/ParsePlatform/parse-server/pull/1263) ([drew-gross](https://github.com/drew-gross)\n* Fix: Clean null authData values on _User update [\\#1199](https://github.com/ParsePlatform/parse-server/pull/1199) ([yuzeh](https://github.com/yuzeh))", "### 2.2.3 (3/29/2016)", "* Fixed bug with invalid email verification link on email update. [\\#1253](https://github.com/ParsePlatform/parse-server/pull/1253) ([kzielonka](https://github.com/kzielonka))\n* Badge update supports increment as well as Increment [\\#1248](https://github.com/ParsePlatform/parse-server/pull/1248) ([flovilmart](https://github.com/flovilmart))\n* Config/Push Tested with the dashboard. [\\#1235](https://github.com/ParsePlatform/parse-server/pull/1235) ([drew-gross](https://github.com/drew-gross))\n* Better logging with winston [\\#1234](https://github.com/ParsePlatform/parse-server/pull/1234) ([flovilmart](https://github.com/flovilmart))\n* Make GlobalConfig work like parse.com [\\#1210](https://github.com/ParsePlatform/parse-server/pull/1210) ([framp](https://github.com/framp))\n* Improve flattening of results from pushAdapter [\\#1204](https://github.com/ParsePlatform/parse-server/pull/1204) ([flovilmart](https://github.com/flovilmart))\n* Push adapters are provided by external packages [\\#1195](https://github.com/ParsePlatform/parse-server/pull/1195) ([flovilmart](https://github.com/flovilmart))\n* Fix flaky test [\\#1188](https://github.com/ParsePlatform/parse-server/pull/1188) ([drew-gross](https://github.com/drew-gross))\n* Fixes problem affecting finding array pointers [\\#1185](https://github.com/ParsePlatform/parse-server/pull/1185) ([flovilmart](https://github.com/flovilmart))\n* Moves Files adapters to external packages [\\#1172](https://github.com/ParsePlatform/parse-server/pull/1172) ([flovilmart](https://github.com/flovilmart))\n* Mark push as enabled in serverInfo endpoint [\\#1164](https://github.com/ParsePlatform/parse-server/pull/1164) ([drew-gross](https://github.com/drew-gross))\n* Document email adapter [\\#1144](https://github.com/ParsePlatform/parse-server/pull/1144) ([drew-gross](https://github.com/drew-gross))\n* Reset password fix [\\#1133](https://github.com/ParsePlatform/parse-server/pull/1133) ([carmenlau](https://github.com/carmenlau))", "### 2.2.2 (3/23/2016)", "* Important Fix: Mounts createLiveQueryServer, fix babel induced problem [\\#1153](https://github.com/ParsePlatform/parse-server/pull/1153) (flovilmart)\n* Move ParseServer to it's own file [\\#1166](https://github.com/ParsePlatform/parse-server/pull/1166) (flovilmart)\n* Update README.md * remove deploy buttons * replace with community links [\\#1139](https://github.com/ParsePlatform/parse-server/pull/1139) (drew-gross)\n* Adds bootstrap.sh [\\#1138](https://github.com/ParsePlatform/parse-server/pull/1138) (flovilmart)\n* Fix: Do not override username [\\#1142](https://github.com/ParsePlatform/parse-server/pull/1142) (flovilmart)\n* Fix: Add pushId back to GCM payload [\\#1168](https://github.com/ParsePlatform/parse-server/pull/1168) (wangmengyan95)", "### 2.2.1 (3/22/2016)", "* New: Add FileSystemAdapter file adapter [\\#1098](https://github.com/ParsePlatform/parse-server/pull/1098) (dtsolis)\n* New: Enabled CLP editing [\\#1128](https://github.com/ParsePlatform/parse-server/pull/1128) (drew-gross)\n* Improvement: Reduces the number of connections to mongo created [\\#1111](https://github.com/ParsePlatform/parse-server/pull/1111) (flovilmart)\n* Improvement: Make ParseServer a class [\\#980](https://github.com/ParsePlatform/parse-server/pull/980) (flovilmart)\n* Fix: Adds support for plain object in $add, $addUnique, $remove [\\#1114](https://github.com/ParsePlatform/parse-server/pull/1114) (flovilmart)\n* Fix: Generates default CLP, freezes objects [\\#1132](https://github.com/ParsePlatform/parse-server/pull/1132) (flovilmart)\n* Fix: Properly sets installationId on creating session with 3rd party auth [\\#1110](https://github.com/ParsePlatform/parse-server/pull/1110) (flovilmart)", "### 2.2.0 (3/18/2016)", "* New Feature: Real-time functionality with Live Queries! [\\#1092](https://github.com/ParsePlatform/parse-server/pull/1092) (wangmengyan95)\n* Improvement: Push Status API [\\#1004](https://github.com/ParsePlatform/parse-server/pull/1004) (flovilmart)\n* Improvement: Allow client operations on Roles [\\#1068](https://github.com/ParsePlatform/parse-server/pull/1068) (flovilmart)\n* Improvement: Add URI encoding to mongo auth parameters [\\#986](https://github.com/ParsePlatform/parse-server/pull/986) (bgw)\n* Improvement: Adds support for apps key in config file, but only support single app for now [\\#979](https://github.com/ParsePlatform/parse-server/pull/979) (flovilmart)\n* Documentation: Getting Started and Configuring Parse Server [\\#988](https://github.com/ParsePlatform/parse-server/pull/988) (hramos)\n* Fix: Various edge cases with REST API [\\#1066](https://github.com/ParsePlatform/parse-server/pull/1066) (flovilmart)\n* Fix: Makes sure the location in results has the proper objectId [\\#1065](https://github.com/ParsePlatform/parse-server/pull/1065) (flovilmart)\n* Fix: Third-party auth is properly removed when unlinked [\\#1081](https://github.com/ParsePlatform/parse-server/pull/1081) (flovilmart)\n* Fix: Clear the session-user cache when changing \\_User objects [\\#1072](https://github.com/ParsePlatform/parse-server/pull/1072) (gfosco)\n* Fix: Bug related to subqueries on unfetched objects [\\#1046](https://github.com/ParsePlatform/parse-server/pull/1046) (flovilmart)\n* Fix: Properly urlencode parameters for email validation and password reset [\\#1001](https://github.com/ParsePlatform/parse-server/pull/1001) (flovilmart)\n* Fix: Better sanitization/decoding of object data for afterSave triggers [\\#992](https://github.com/ParsePlatform/parse-server/pull/992) (flovilmart)\n* Fix: Changes default encoding for httpRequest [\\#892](https://github.com/ParsePlatform/parse-server/pull/892) (flovilmart)", "### 2.1.6 (3/11/2016)", "* Improvement: Full query support for badge Increment \\(\\#931\\) [\\#983](https://github.com/ParsePlatform/parse-server/pull/983) (flovilmart)\n* Improvement: Shutdown standalone parse server gracefully [\\#958](https://github.com/ParsePlatform/parse-server/pull/958) (raulr)\n* Improvement: Add database options to ParseServer constructor and pass to MongoStorageAdapter [\\#956](https://github.com/ParsePlatform/parse-server/pull/956) (steven-supersolid)\n* Improvement: AuthData logic refactor [\\#952](https://github.com/ParsePlatform/parse-server/pull/952) (flovilmart)\n* Improvement: Changed FileLoggerAdapterSpec to fail gracefully on Windows [\\#946](https://github.com/ParsePlatform/parse-server/pull/946) (aneeshd16)\n* Improvement: Add new schema collection type and replace all usages of direct mongo collection for schema operations. [\\#943](https://github.com/ParsePlatform/parse-server/pull/943) (nlutsenko)\n* Improvement: Adds CLP API to Schema router [\\#898](https://github.com/ParsePlatform/parse-server/pull/898) (flovilmart)\n* Fix: Cleans up authData null keys on login for android crash [\\#978](https://github.com/ParsePlatform/parse-server/pull/978) (flovilmart)\n* Fix: Do master query for before/afterSaveHook [\\#959](https://github.com/ParsePlatform/parse-server/pull/959) (wangmengyan95)\n* Fix: re-add shebang [\\#944](https://github.com/ParsePlatform/parse-server/pull/944) (flovilmart)\n* Fix: Added test command for Windows support [\\#886](https://github.com/ParsePlatform/parse-server/pull/886) (aneeshd16)", "### 2.1.5 (3/9/2016)", "* New: FileAdapter for Google Cloud Storage [\\#708](https://github.com/ParsePlatform/parse-server/pull/708) (mcdonamp)\n* Improvement: Minimize extra schema queries in some scenarios. [\\#919](https://github.com/ParsePlatform/parse-server/pull/919) (Marco129)\n* Improvement: Move DatabaseController and Schema fully to adaptive mongo collection. [\\#909](https://github.com/ParsePlatform/parse-server/pull/909) (nlutsenko)\n* Improvement: Cleanup PushController/PushRouter, remove raw mongo collection access. [\\#903](https://github.com/ParsePlatform/parse-server/pull/903) (nlutsenko)\n* Improvement: Increment badge the right way [\\#902](https://github.com/ParsePlatform/parse-server/pull/902) (flovilmart)\n* Improvement: Migrate ParseGlobalConfig to new database storage API. [\\#901](https://github.com/ParsePlatform/parse-server/pull/901) (nlutsenko)\n* Improvement: Improve delete flow for non-existent \\_Join collection [\\#881](https://github.com/ParsePlatform/parse-server/pull/881) (Marco129)\n* Improvement: Adding a role scenario test for issue 827 [\\#878](https://github.com/ParsePlatform/parse-server/pull/878) (gfosco)\n* Improvement: Test empty authData block on login for \\#413 [\\#863](https://github.com/ParsePlatform/parse-server/pull/863) (gfosco)\n* Improvement: Modified the npm dev script to support Windows [\\#846](https://github.com/ParsePlatform/parse-server/pull/846) (aneeshd16)\n* Improvement: Move HooksController to use MongoCollection instead of direct Mongo access. [\\#844](https://github.com/ParsePlatform/parse-server/pull/844) (nlutsenko)\n* Improvement: Adds public\\_html and views for packaging [\\#839](https://github.com/ParsePlatform/parse-server/pull/839) (flovilmart)\n* Improvement: Better support for windows builds [\\#831](https://github.com/ParsePlatform/parse-server/pull/831) (flovilmart)\n* Improvement: Convert Schema.js to ES6 class. [\\#826](https://github.com/ParsePlatform/parse-server/pull/826) (nlutsenko)\n* Improvement: Remove duplicated instructions [\\#816](https://github.com/ParsePlatform/parse-server/pull/816) (hramos)\n* Improvement: Completely migrate SchemasRouter to new MongoCollection API. [\\#794](https://github.com/ParsePlatform/parse-server/pull/794) (nlutsenko)\n* Fix: Do not require where clause in $dontSelect condition on queries. [\\#925](https://github.com/ParsePlatform/parse-server/pull/925) (nlutsenko)\n* Fix: Make sure that ACLs propagate to before/after save hooks. [\\#924](https://github.com/ParsePlatform/parse-server/pull/924) (nlutsenko)\n* Fix: Support params option in Parse.Cloud.httpRequest. [\\#912](https://github.com/ParsePlatform/parse-server/pull/912) (carmenlau)\n* Fix: Fix flaky Parse.GeoPoint test. [\\#908](https://github.com/ParsePlatform/parse-server/pull/908) (nlutsenko)\n* Fix: Handle legacy \\_client\\_permissions key in \\_SCHEMA. [\\#900](https://github.com/ParsePlatform/parse-server/pull/900) (drew-gross)\n* Fix: Fixes bug when querying equalTo on objectId and relation [\\#887](https://github.com/ParsePlatform/parse-server/pull/887) (flovilmart)\n* Fix: Allow crossdomain on filesRouter [\\#876](https://github.com/ParsePlatform/parse-server/pull/876) (flovilmart)\n* Fix: Remove limit when counting results. [\\#867](https://github.com/ParsePlatform/parse-server/pull/867) (gfosco)\n* Fix: beforeSave changes should propagate to the response [\\#865](https://github.com/ParsePlatform/parse-server/pull/865) (gfosco)\n* Fix: Delete relation field when \\_Join collection not exist [\\#864](https://github.com/ParsePlatform/parse-server/pull/864) (Marco129)\n* Fix: Related query on non-existing column [\\#861](https://github.com/ParsePlatform/parse-server/pull/861) (gfosco)\n* Fix: Update markdown in .github/ISSUE\\_TEMPLATE.md [\\#859](https://github.com/ParsePlatform/parse-server/pull/859) (igorshubovych)\n* Fix: Issue with creating wrong \\_Session for Facebook login [\\#857](https://github.com/ParsePlatform/parse-server/pull/857) (tobernguyen)\n* Fix: Leak warnings in tests, use mongodb-runner from node\\_modules [\\#843](https://github.com/ParsePlatform/parse-server/pull/843) (drew-gross)\n* Fix: Reversed roles lookup [\\#841](https://github.com/ParsePlatform/parse-server/pull/841) (flovilmart)\n* Fix: Improves loading of Push Adapter, fix loading of S3Adapter [\\#833](https://github.com/ParsePlatform/parse-server/pull/833) (flovilmart)\n* Fix: Add field to system schema [\\#828](https://github.com/ParsePlatform/parse-server/pull/828) (Marco129)", "### 2.1.4 (3/3/2016)", "* New: serverInfo endpoint that returns server version and info about the server's features\n* Improvement: Add support for badges on iOS\n* Improvement: Improve failure handling in cloud code http requests\n* Improvement: Add support for queries on pointers and relations\n* Improvement: Add support for multiple $in clauses in a query\n* Improvement: Add allowClientClassCreation config option\n* Improvement: Allow atomically setting subdocument keys\n* Improvement: Allow arbitrarily deeply nested roles\n* Improvement: Set proper content-type in S3 File Adapter\n* Improvement: S3 adapter auto-creates buckets\n* Improvement: Better error messages for many errors\n* Performance: Improved algorithm for validating client keys\n* Experimental: Parse Hooks and Hooks API\n* Experimental: Email verification and password reset emails\n* Experimental: Improve compatability of logs feature with Parse.com\n* Fix: Fix for attempting to delete missing classes via schemas API\n* Fix: Allow creation of system classes via schemas API\n* Fix: Allow missing where cause in $select\n* Fix: Improve handling of invalid object ids\n* Fix: Replace query overwriting existing query\n* Fix: Propagate installationId in cloud code triggers\n* Fix: Session expiresAt is now a Date instead of a string\n* Fix: Fix count queries\n* Fix: Disallow _Role objects without names or without ACL\n* Fix: Better handling of invalid types submitted\n* Fix: beforeSave will not be triggered for attempts to save with invalid authData\n* Fix: Fix duplicate device token issues on Android\n* Fix: Allow empty authData on signup\n* Fix: Allow Master Key Headers (CORS)\n* Fix: Fix bugs if JavaScript key was not provided in server configuration\n* Fix: Parse Files on objects can now be stored without URLs\n* Fix: allow both objectId or installationId when modifying installation\n* Fix: Command line works better when not given options", "### 2.1.3 (2/24/2016)", "* Feature: Add initial support for in-app purchases\n* Feature: Better error messages when attempting to run the server on a port that is already in use or without a server URL\n* Feature: Allow customization of max file size\n* Performance: Faster saves if not using beforeSave triggers\n* Fix: Send session token in response to current user endpoint\n* Fix: Remove triggers for _Session collection\n* Fix: Improve compatability of cloud code beforeSave hook for newly created object\n* Fix: ACL creation for master key only objects\n* Fix: Allow uploading files without Content-Type\n* Fix: Add features to http request to match Parse.com\n* Fix: Bugs in development script when running from locations other than project root\n* Fix: Can pass query constraints in URL\n* Fix: Objects with legacy \"_tombstone\" key now don't cause issues.\n* Fix: Allow nested keys in objects to begin with underscores\n* Fix: Allow correct headers for CORS", "### 2.1.2 (2/19/2016)", "* Change: The S3 file adapter constructor requires a bucket name\n* Fix: Parse Query should throw if improperly encoded\n* Fix: Issue where roles were not used in some requests\n* Fix: serverURL will no longer default to api.parse.com/1", "### 2.1.1 (2/18/2016)", "* Experimental: Schemas API support for DELETE operations\n* Fix: Session token issue fetching Users\n* Fix: Facebook auth validation\n* Fix: Invalid error when deleting missing session", "### 2.1.0 (2/17/2016)", "* Feature: Support for additional OAuth providers\n* Feature: Ability to implement custom OAuth providers\n* Feature: Support for deleting Parse Files\n* Feature: Allow querying roles\n* Feature: Support for logs, extensible via Log Adapter\n* Feature: New Push Adapter for sending push notifications through OneSignal\n* Feature: Tighter default security for Users\n* Feature: Pass parameters to cloud code in query string\n* Feature: Disable anonymous users via configuration.\n* Experimental: Schemas API support for PUT operations\n* Fix: Prevent installation ID from being added to User\n* Fix: Becoming a user works properly with sessions\n* Fix: Including multiple object when some object are unavailable will get all the objects that are available\n* Fix: Invalid URL for Parse Files\n* Fix: Making a query without a limit now returns 100 results\n* Fix: Expose installation id in cloud code\n* Fix: Correct username for Anonymous users\n* Fix: Session token issue after fetching user\n* Fix: Issues during install process\n* Fix: Issue with Unity SDK sending _noBody", "### 2.0.8 (2/11/2016)", "* Add: support for Android and iOS push notifications\n* Experimental: cloud code validation hooks (can mark as non-experimental after we have docs)\n* Experimental: support for schemas API (GET and POST only)\n* Experimental: support for Parse Config (GET and POST only)\n* Fix: Querying objects with equality constraint on array column\n* Fix: User logout will remove session token\n* Fix: Various files related bugs\n* Fix: Force minimum node version 4.3 due to security issues in earlier version\n* Performance Improvement: Improved caching" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 2430, 857], "buggy_code_start_loc": [4, 2377, 857], "filenames": ["CHANGELOG.md", "spec/ParseUser.spec.js", "src/RestWrite.js"], "fixing_code_end_loc": [10, 2434, 862], "fixing_code_start_loc": [4, 2377, 858], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "9DE0F06D-5868-45AD-B21E-C5268BCC7F52", "versionEndExcluding": "4.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login."}, {"lang": "es", "value": "Parse Server es un backend de c\u00f3digo abierto que puede desplegarse en cualquier infraestructura que pueda ejecutar Node.js. Los desarrolladores pueden usar la API REST para registrar usuarios y tambi\u00e9n permitir a usuarios registrarse an\u00f3nimamente. Versiones anteriores a 4.5.1, cuando un usuario an\u00f3nimo es registrado por primera vez usando REST, el servidor creaba la sesi\u00f3n incorrectamente. En particular, el campo \"authProvider\" de la clase \"_Session\" en \"createdWith\" muestra que el usuario se ha registrado creando una contrase\u00f1a. Si un desarrollador depende posteriormente del campo \"createdWith\" para proporcionar un nivel de acceso diferente entre un usuario con contrase\u00f1a y un usuario an\u00f3nimo, el servidor clasifica incorrectamente el tipo de sesi\u00f3n como creada con un \"password\". El servidor no usa actualmente \"createdWith\" para tomar decisiones sobre las funciones internas, por lo que si un desarrollador no est\u00e1 usando \"createdWith\" directamente, no est\u00e1 afectado. La vulnerabilidad s\u00f3lo afecta a usuarios que dependen de \"createdWith\" al usarlo directamente. El problema est\u00e1 parcheado en Parse Server versi\u00f3n 4.5.1. Como soluci\u00f3n, no use el campo de sesi\u00f3n \"createdWith\" para tomar decisiones si se permite el acceso an\u00f3nimo."}], "evaluatorComment": null, "id": "CVE-2021-39138", "lastModified": "2022-08-12T18:01:28.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.5, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-19T16:15:12.483", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/releases/tag/4.5.1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, "type": "CWE-863"}
299
Determine whether the {function_name} code is vulnerable or not.
[ "// This is a port of the test suite:\n// hungry/js/test/parse_user_test.js\n//\n// Things that we didn't port:\n// Tests that involve revocable sessions.\n// Tests that involve sending password reset emails.", "'use strict';", "const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default;\nconst request = require('../lib/request');\nconst passwordCrypto = require('../lib/password');\nconst Config = require('../lib/Config');\nconst cryptoUtils = require('../lib/cryptoUtils');", "function verifyACL(user) {\n const ACL = user.getACL();\n expect(ACL.getReadAccess(user)).toBe(true);\n expect(ACL.getWriteAccess(user)).toBe(true);\n expect(ACL.getPublicReadAccess()).toBe(true);\n expect(ACL.getPublicWriteAccess()).toBe(false);\n const perms = ACL.permissionsById;\n expect(Object.keys(perms).length).toBe(2);\n expect(perms[user.id].read).toBe(true);\n expect(perms[user.id].write).toBe(true);\n expect(perms['*'].read).toBe(true);\n expect(perms['*'].write).not.toBe(true);\n}", "describe('Parse.User testing', () => {\n it('user sign up class method', async done => {\n const user = await Parse.User.signUp('asdf', 'zxcv');\n ok(user.getSessionToken());\n done();\n });", " it('user sign up instance method', async () => {\n const user = new Parse.User();\n user.setPassword('asdf');\n user.setUsername('zxcv');\n await user.signUp();\n ok(user.getSessionToken());\n });", " it('user login wrong username', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n try {\n await Parse.User.logIn('non_existent_user', 'asdf3');\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n done();\n }\n });", " it('user login wrong password', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n try {\n await Parse.User.logIn('asdf', 'asdfWrong');\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n done();\n }\n });", " it('user login with non-string username with REST API', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/login',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n _method: 'GET',\n username: { $regex: '^asd' },\n password: 'zxcv',\n },\n })\n .then(res => {\n fail(`no request should succeed: ${JSON.stringify(res)}`);\n done();\n })\n .catch(err => {\n expect(err.status).toBe(404);\n expect(err.text).toMatch('{\"code\":101,\"error\":\"Invalid username/password.\"}');\n done();\n });\n });", " it('user login with non-string username with REST API (again)', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/login',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n _method: 'GET',\n username: 'asdf',\n password: { $regex: '^zx' },\n },\n })\n .then(res => {\n fail(`no request should succeed: ${JSON.stringify(res)}`);\n done();\n })\n .catch(err => {\n expect(err.status).toBe(404);\n expect(err.text).toMatch('{\"code\":101,\"error\":\"Invalid username/password.\"}');\n done();\n });\n });", " it('user login using POST with REST API', async done => {\n await Parse.User.signUp('some_user', 'some_password');\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/login',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n body: {\n username: 'some_user',\n password: 'some_password',\n },\n })\n .then(res => {\n expect(res.data.username).toBe('some_user');\n done();\n })\n .catch(err => {\n fail(`no request should fail: ${JSON.stringify(err)}`);\n done();\n });\n });", " it('user login', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n const user = await Parse.User.logIn('asdf', 'zxcv');\n equal(user.get('username'), 'asdf');\n verifyACL(user);\n done();\n });", " it('should respect ACL without locking user out', done => {\n const user = new Parse.User();\n const ACL = new Parse.ACL();\n ACL.setPublicReadAccess(false);\n ACL.setPublicWriteAccess(false);\n user.setUsername('asdf');\n user.setPassword('zxcv');\n user.setACL(ACL);\n user\n .signUp()\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n equal(user.get('username'), 'asdf');\n const ACL = user.getACL();\n expect(ACL.getReadAccess(user)).toBe(true);\n expect(ACL.getWriteAccess(user)).toBe(true);\n expect(ACL.getPublicReadAccess()).toBe(false);\n expect(ACL.getPublicWriteAccess()).toBe(false);\n const perms = ACL.permissionsById;\n expect(Object.keys(perms).length).toBe(1);\n expect(perms[user.id].read).toBe(true);\n expect(perms[user.id].write).toBe(true);\n expect(perms['*']).toBeUndefined();\n // Try to lock out user\n const newACL = new Parse.ACL();\n newACL.setReadAccess(user.id, false);\n newACL.setWriteAccess(user.id, false);\n user.setACL(newACL);\n return user.save();\n })\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n equal(user.get('username'), 'asdf');\n const ACL = user.getACL();\n expect(ACL.getReadAccess(user)).toBe(true);\n expect(ACL.getWriteAccess(user)).toBe(true);\n expect(ACL.getPublicReadAccess()).toBe(false);\n expect(ACL.getPublicWriteAccess()).toBe(false);\n const perms = ACL.permissionsById;\n expect(Object.keys(perms).length).toBe(1);\n expect(perms[user.id].read).toBe(true);\n expect(perms[user.id].write).toBe(true);\n expect(perms['*']).toBeUndefined();\n done();\n })\n .catch(() => {\n fail('Should not fail');\n done();\n });\n });", " it('should let masterKey lockout user', done => {\n const user = new Parse.User();\n const ACL = new Parse.ACL();\n ACL.setPublicReadAccess(false);\n ACL.setPublicWriteAccess(false);\n user.setUsername('asdf');\n user.setPassword('zxcv');\n user.setACL(ACL);\n user\n .signUp()\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n equal(user.get('username'), 'asdf');\n // Lock the user down\n const ACL = new Parse.ACL();\n user.setACL(ACL);\n return user.save(null, { useMasterKey: true });\n })\n .then(() => {\n expect(user.getACL().getPublicReadAccess()).toBe(false);\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(done.fail)\n .catch(err => {\n expect(err.message).toBe('Invalid username/password.');\n expect(err.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n done();\n });\n });", " it_only_db('mongo')('should let legacy users without ACL login', async () => {\n const databaseURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase';\n const adapter = new MongoStorageAdapter({\n collectionPrefix: 'test_',\n uri: databaseURI,\n });\n await adapter.connect();\n await adapter.database.dropDatabase();\n delete adapter.connectionPromise;", " const user = new Parse.User();\n await user.signUp({\n username: 'newUser',\n password: 'password',\n });", " const collection = await adapter._adaptiveCollection('_User');\n await collection.insertOne({\n // the hashed password is 'password' hashed\n _hashed_password: '$2b$10$mJ2ca2UbCM9hlojYHZxkQe8pyEXe5YMg0nMdvP4AJBeqlTEZJ6/Uu',\n _session_token: 'xxx',\n email: 'xxx@a.b',\n username: 'oldUser',\n emailVerified: true,\n _email_verify_token: 'yyy',\n });", " // get the 2 users\n const users = await collection.find();\n expect(users.length).toBe(2);", " const aUser = await Parse.User.logIn('oldUser', 'password');\n expect(aUser).not.toBeUndefined();", " const newUser = await Parse.User.logIn('newUser', 'password');\n expect(newUser).not.toBeUndefined();\n });", " it('should be let masterKey lock user out with authData', async () => {\n const response = await request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'value',\n authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' } },\n },\n });\n const body = response.data;\n const objectId = body.objectId;\n const sessionToken = body.sessionToken;\n expect(sessionToken).toBeDefined();\n expect(objectId).toBeDefined();\n const user = new Parse.User();\n user.id = objectId;\n const ACL = new Parse.ACL();\n user.setACL(ACL);\n await user.save(null, { useMasterKey: true });\n // update the user\n const options = {\n method: 'POST',\n url: `http://localhost:8378/1/classes/_User/`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'otherValue',\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n };\n const res = await request(options);\n expect(res.data.objectId).not.toEqual(objectId);\n });", " it('user login with files', done => {\n const file = new Parse.File('yolo.txt', [1, 2, 3], 'text/plain');\n file\n .save()\n .then(file => {\n return Parse.User.signUp('asdf', 'zxcv', { file: file });\n })\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n const fileAgain = user.get('file');\n ok(fileAgain.name());\n ok(fileAgain.url());\n done();\n })\n .catch(err => {\n jfail(err);\n done();\n });\n });", " it('become sends token back', done => {\n let user = null;\n let sessionToken = null;", " Parse.User.signUp('Jason', 'Parse', { code: 'red' })\n .then(newUser => {\n user = newUser;\n expect(user.get('code'), 'red');", " sessionToken = newUser.getSessionToken();\n expect(sessionToken).toBeDefined();", " return Parse.User.become(sessionToken);\n })\n .then(newUser => {\n expect(newUser.id).toEqual(user.id);\n expect(newUser.get('username'), 'Jason');\n expect(newUser.get('code'), 'red');\n expect(newUser.getSessionToken()).toEqual(sessionToken);\n })\n .then(\n () => {\n done();\n },\n error => {\n jfail(error);\n done();\n }\n );\n });", " it('become', done => {\n let user = null;\n let sessionToken = null;", " Promise.resolve()\n .then(function () {\n return Parse.User.signUp('Jason', 'Parse', { code: 'red' });\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);", " user = newUser;\n sessionToken = newUser.getSessionToken();\n ok(sessionToken);", " return Parse.User.logOut();\n })\n .then(() => {\n ok(!Parse.User.current());", " return Parse.User.become(sessionToken);\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);", " ok(newUser);\n equal(newUser.id, user.id);\n equal(newUser.get('username'), 'Jason');\n equal(newUser.get('code'), 'red');", " return Parse.User.logOut();\n })\n .then(() => {\n ok(!Parse.User.current());", " return Parse.User.become('somegarbage');\n })\n .then(\n function () {\n // This should have failed actually.\n ok(false, \"Shouldn't have been able to log in with garbage session token.\");\n },\n function (error) {\n ok(error);\n // Handle the error.\n return Promise.resolve();\n }\n )\n .then(\n function () {\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('should not call beforeLogin with become', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(() => {\n hit++;\n });", " await Parse.User._logInWith('facebook');\n const sessionToken = Parse.User.current().getSessionToken();\n await Parse.User.become(sessionToken);\n expect(hit).toBe(0);\n done();\n });", " it('cannot save non-authed user', async done => {\n let user = new Parse.User();\n user.set({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n let userAgain = await user.signUp();\n equal(userAgain, user);\n const query = new Parse.Query(Parse.User);\n const userNotAuthed = await query.get(user.id);\n user = new Parse.User();\n user.set({\n username: 'hacker',\n password: 'password',\n });\n userAgain = await user.signUp();\n equal(userAgain, user);\n userNotAuthed.set('username', 'changed');\n userNotAuthed.save().then(fail, err => {\n expect(err.code).toEqual(Parse.Error.SESSION_MISSING);\n done();\n });\n });", " it('cannot delete non-authed user', async done => {\n let user = new Parse.User();\n await user.signUp({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n const query = new Parse.Query(Parse.User);\n const userNotAuthed = await query.get(user.id);\n user = new Parse.User();\n const userAgain = await user.signUp({\n username: 'hacker',\n password: 'password',\n });\n equal(userAgain, user);\n userNotAuthed.set('username', 'changed');\n try {\n await userNotAuthed.destroy();\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n done();\n }\n });", " it('cannot saveAll with non-authed user', async done => {\n let user = new Parse.User();\n await user.signUp({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n const query = new Parse.Query(Parse.User);\n const userNotAuthed = await query.get(user.id);\n user = new Parse.User();\n await user.signUp({\n username: 'hacker',\n password: 'password',\n });\n const userNotAuthedNotChanged = await query.get(user.id);\n userNotAuthed.set('username', 'changed');\n const object = new TestObject();\n await object.save({\n user: userNotAuthedNotChanged,\n });\n const item1 = new TestObject();\n await item1.save({\n number: 0,\n });\n item1.set('number', 1);\n const item2 = new TestObject();\n item2.set('number', 2);\n try {\n await Parse.Object.saveAll([item1, item2, userNotAuthed]);\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n done();\n }\n });", " it('never locks himself up', async () => {\n const user = new Parse.User();\n await user.signUp({\n username: 'username',\n password: 'password',\n });\n user.setACL(new Parse.ACL());\n await user.save();\n await user.fetch();\n expect(user.getACL().getReadAccess(user)).toBe(true);\n expect(user.getACL().getWriteAccess(user)).toBe(true);\n const publicReadACL = new Parse.ACL();\n publicReadACL.setPublicReadAccess(true);", " // Create an administrator role with a single admin user\n const role = new Parse.Role('admin', publicReadACL);\n const admin = new Parse.User();\n await admin.signUp({\n username: 'admin',\n password: 'admin',\n });\n role.getUsers().add(admin);\n await role.save(null, { useMasterKey: true });", " // Grant the admins write rights on the user\n const acl = user.getACL();\n acl.setRoleWriteAccess(role, true);\n acl.setRoleReadAccess(role, true);", " // Update with the masterKey just to be sure\n await user.save({ ACL: acl }, { useMasterKey: true });", " // Try to update from admin... should all work fine\n await user.save({ key: 'fromAdmin' }, { sessionToken: admin.getSessionToken() });\n await user.fetch();\n expect(user.toJSON().key).toEqual('fromAdmin');", " // Try to save when logged out (public)\n let failed = false;\n try {\n // Ensure no session token is sent\n await Parse.User.logOut();\n await user.save({ key: 'fromPublic' });\n } catch (e) {\n failed = true;\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n expect({ failed }).toEqual({ failed: true });", " // Try to save with a random user, should fail\n failed = false;\n const anyUser = new Parse.User();\n await anyUser.signUp({\n username: 'randomUser',\n password: 'password',\n });\n try {\n await user.save({ key: 'fromAnyUser' });\n } catch (e) {\n failed = true;\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n expect({ failed }).toEqual({ failed: true });\n });", " it('current user', done => {\n const user = new Parse.User();\n user.set('password', 'asdf');\n user.set('email', 'asdf@example.com');\n user.set('username', 'zxcv');\n user\n .signUp()\n .then(() => {\n const currentUser = Parse.User.current();\n equal(user.id, currentUser.id);\n ok(user.getSessionToken());", " const currentUserAgain = Parse.User.current();\n // should be the same object\n equal(currentUser, currentUserAgain);", " // test logging out the current user\n return Parse.User.logOut();\n })\n .then(() => {\n equal(Parse.User.current(), null);\n done();\n });\n });", " it('user.isCurrent', done => {\n const user1 = new Parse.User();\n const user2 = new Parse.User();\n const user3 = new Parse.User();", " user1.set('username', 'a');\n user2.set('username', 'b');\n user3.set('username', 'c');", " user1.set('password', 'password');\n user2.set('password', 'password');\n user3.set('password', 'password');", " user1\n .signUp()\n .then(() => {\n equal(user1.isCurrent(), true);\n equal(user2.isCurrent(), false);\n equal(user3.isCurrent(), false);\n return user2.signUp();\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), true);\n equal(user3.isCurrent(), false);\n return user3.signUp();\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), false);\n equal(user3.isCurrent(), true);\n return Parse.User.logIn('a', 'password');\n })\n .then(() => {\n equal(user1.isCurrent(), true);\n equal(user2.isCurrent(), false);\n equal(user3.isCurrent(), false);\n return Parse.User.logIn('b', 'password');\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), true);\n equal(user3.isCurrent(), false);\n return Parse.User.logIn('b', 'password');\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), true);\n equal(user3.isCurrent(), false);\n return Parse.User.logOut();\n })\n .then(() => {\n equal(user2.isCurrent(), false);\n done();\n });\n });", " it('user associations', async done => {\n const child = new TestObject();\n await child.save();\n const user = new Parse.User();\n user.set('password', 'asdf');\n user.set('email', 'asdf@example.com');\n user.set('username', 'zxcv');\n user.set('child', child);\n await user.signUp();\n const object = new TestObject();\n object.set('user', user);\n await object.save();\n const query = new Parse.Query(TestObject);\n const objectAgain = await query.get(object.id);\n const userAgain = objectAgain.get('user');\n await userAgain.fetch();\n equal(user.id, userAgain.id);\n equal(userAgain.get('child').id, child.id);\n done();\n });", " it('user queries', async done => {\n const user = new Parse.User();\n user.set('password', 'asdf');\n user.set('email', 'asdf@example.com');\n user.set('username', 'zxcv');\n await user.signUp();\n const query = new Parse.Query(Parse.User);\n const userAgain = await query.get(user.id);\n equal(userAgain.id, user.id);\n const users = await query.find();\n equal(users.length, 1);\n equal(users[0].id, user.id);\n ok(userAgain.get('email'), 'asdf@example.com');\n done();\n });", " function signUpAll(list, optionsOrCallback) {\n let promise = Promise.resolve();\n list.forEach(user => {\n promise = promise.then(function () {\n return user.signUp();\n });\n });\n promise = promise.then(function () {\n return list;\n });\n return promise.then(optionsOrCallback);\n }", " it('contained in user array queries', async done => {\n const USERS = 4;\n const MESSAGES = 5;", " // Make a list of users.\n const userList = range(USERS).map(function (i) {\n const user = new Parse.User();\n user.set('password', 'user_num_' + i);\n user.set('email', 'user_num_' + i + '@example.com');\n user.set('username', 'xinglblog_num_' + i);\n return user;\n });", " signUpAll(userList, async function (users) {\n // Make a list of messages.\n if (!users || users.length != USERS) {\n fail('signupAll failed');\n done();\n return;\n }\n const messageList = range(MESSAGES).map(function (i) {\n const message = new TestObject();\n message.set('to', users[(i + 1) % USERS]);\n message.set('from', users[i % USERS]);\n return message;\n });", " // Save all the messages.\n await Parse.Object.saveAll(messageList);", " // Assemble an \"in\" list.\n const inList = [users[0], users[3], users[3]]; // Intentional dupe\n const query = new Parse.Query(TestObject);\n query.containedIn('from', inList);\n const results = await query.find();\n equal(results.length, 3);\n done();\n });\n });", " it(\"saving a user signs them up but doesn't log them in\", async done => {\n const user = new Parse.User();\n await user.save({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n equal(Parse.User.current(), null);\n done();\n });", " it('user updates', async done => {\n const user = new Parse.User();\n await user.signUp({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });", " user.set('username', 'test');\n await user.save();\n equal(Object.keys(user.attributes).length, 6);\n ok(user.attributes['username']);\n ok(user.attributes['email']);\n await user.destroy();\n const query = new Parse.Query(Parse.User);\n try {\n await query.get(user.id);\n done.fail();\n } catch (error) {\n // The user should no longer exist.\n equal(error.code, Parse.Error.OBJECT_NOT_FOUND);\n done();\n }\n });", " it('count users', async done => {\n const james = new Parse.User();\n james.set('username', 'james');\n james.set('password', 'mypass');\n await james.signUp();\n const kevin = new Parse.User();\n kevin.set('username', 'kevin');\n kevin.set('password', 'mypass');\n await kevin.signUp();\n const query = new Parse.Query(Parse.User);\n const count = await query.count();\n equal(count, 2);\n done();\n });", " it('user sign up with container class', async done => {\n await Parse.User.signUp('ilya', 'mypass', { array: ['hello'] });\n done();\n });", " it('user modified while saving', done => {\n Parse.Object.disableSingleInstance();\n const user = new Parse.User();\n user.set('username', 'alice');\n user.set('password', 'password');\n user.signUp().then(function (userAgain) {\n equal(userAgain.get('username'), 'bob');\n ok(userAgain.dirty('username'));\n const query = new Parse.Query(Parse.User);\n query.get(user.id).then(freshUser => {\n equal(freshUser.id, user.id);\n equal(freshUser.get('username'), 'alice');\n done();\n });\n });\n // Jump a frame so the signup call is properly sent\n // This is due to the fact that now, we use real promises\n process.nextTick(() => {\n ok(user.set('username', 'bob'));\n });\n });", " it('user modified while saving with unsaved child', done => {\n Parse.Object.disableSingleInstance();\n const user = new Parse.User();\n user.set('username', 'alice');\n user.set('password', 'password');\n user.set('child', new TestObject());\n user.signUp().then(userAgain => {\n equal(userAgain.get('username'), 'bob');\n // Should be dirty, but it depends on batch support.\n // ok(userAgain.dirty(\"username\"));\n const query = new Parse.Query(Parse.User);\n query.get(user.id).then(freshUser => {\n equal(freshUser.id, user.id);\n // Should be alice, but it depends on batch support.\n equal(freshUser.get('username'), 'bob');\n done();\n });\n });\n ok(user.set('username', 'bob'));\n });", " it('user loaded from localStorage from signup', async done => {\n const alice = await Parse.User.signUp('alice', 'password');\n ok(alice.id, 'Alice should have an objectId');\n ok(alice.getSessionToken(), 'Alice should have a session token');\n equal(alice.get('password'), undefined, 'Alice should not have a password');", " // Simulate the environment getting reset.\n Parse.User._currentUser = null;\n Parse.User._currentUserMatchesDisk = false;", " const aliceAgain = Parse.User.current();\n equal(aliceAgain.get('username'), 'alice');\n equal(aliceAgain.id, alice.id, 'currentUser should have objectId');\n ok(aliceAgain.getSessionToken(), 'currentUser should have a sessionToken');\n equal(alice.get('password'), undefined, 'currentUser should not have password');\n done();\n });", " it('user loaded from localStorage from login', done => {\n let id;\n Parse.User.signUp('alice', 'password')\n .then(alice => {\n id = alice.id;\n return Parse.User.logOut();\n })\n .then(() => {\n return Parse.User.logIn('alice', 'password');\n })\n .then(() => {\n // Force the current user to read from disk\n delete Parse.User._currentUser;\n delete Parse.User._currentUserMatchesDisk;", " const userFromDisk = Parse.User.current();\n equal(userFromDisk.get('password'), undefined, 'password should not be in attributes');\n equal(userFromDisk.id, id, 'id should be set');\n ok(userFromDisk.getSessionToken(), 'currentUser should have a sessionToken');\n done();\n });\n });", " it('saving user after browser refresh', done => {\n let id;", " Parse.User.signUp('alice', 'password', null)\n .then(function (alice) {\n id = alice.id;\n return Parse.User.logOut();\n })\n .then(() => {\n return Parse.User.logIn('alice', 'password');\n })\n .then(function () {\n // Simulate browser refresh by force-reloading user from localStorage\n Parse.User._clearCache();", " // Test that this save works correctly\n return Parse.User.current().save({ some_field: 1 });\n })\n .then(\n function () {\n // Check the user in memory just after save operation\n const userInMemory = Parse.User.current();", " equal(\n userInMemory.getUsername(),\n 'alice',\n 'saving user should not remove existing fields'\n );", " equal(userInMemory.get('some_field'), 1, 'saving user should save specified field');", " equal(\n userInMemory.get('password'),\n undefined,\n 'password should not be in attributes after saving user'\n );", " equal(\n userInMemory.get('objectId'),\n undefined,\n 'objectId should not be in attributes after saving user'\n );", " equal(\n userInMemory.get('_id'),\n undefined,\n '_id should not be in attributes after saving user'\n );", " equal(userInMemory.id, id, 'id should be set');", " expect(userInMemory.updatedAt instanceof Date).toBe(true);", " ok(userInMemory.createdAt instanceof Date);", " ok(userInMemory.getSessionToken(), 'user should have a sessionToken after saving');", " // Force the current user to read from localStorage, and check again\n delete Parse.User._currentUser;\n delete Parse.User._currentUserMatchesDisk;\n const userFromDisk = Parse.User.current();", " equal(\n userFromDisk.getUsername(),\n 'alice',\n 'userFromDisk should have previously existing fields'\n );", " equal(userFromDisk.get('some_field'), 1, 'userFromDisk should have saved field');", " equal(\n userFromDisk.get('password'),\n undefined,\n 'password should not be in attributes of userFromDisk'\n );", " equal(\n userFromDisk.get('objectId'),\n undefined,\n 'objectId should not be in attributes of userFromDisk'\n );", " equal(\n userFromDisk.get('_id'),\n undefined,\n '_id should not be in attributes of userFromDisk'\n );", " equal(userFromDisk.id, id, 'id should be set on userFromDisk');", " ok(userFromDisk.updatedAt instanceof Date);", " ok(userFromDisk.createdAt instanceof Date);", " ok(userFromDisk.getSessionToken(), 'userFromDisk should have a sessionToken');", " done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('user with missing username', async done => {\n const user = new Parse.User();\n user.set('password', 'foo');\n try {\n await user.signUp();\n done.fail();\n } catch (error) {\n equal(error.code, Parse.Error.OTHER_CAUSE);\n done();\n }\n });", " it('user with missing password', async done => {\n const user = new Parse.User();\n user.set('username', 'foo');\n try {\n await user.signUp();\n done.fail();\n } catch (error) {\n equal(error.code, Parse.Error.OTHER_CAUSE);\n done();\n }\n });", " it('user stupid subclassing', async done => {\n const SuperUser = Parse.Object.extend('User');\n const user = new SuperUser();\n user.set('username', 'bob');\n user.set('password', 'welcome');\n ok(user instanceof Parse.User, 'Subclassing User should have worked');\n await user.signUp();\n done();\n });", " it('user signup class method uses subclassing', async done => {\n const SuperUser = Parse.User.extend({\n secret: function () {\n return 1337;\n },\n });", " const user = await Parse.User.signUp('bob', 'welcome');\n ok(user instanceof SuperUser, 'Subclassing User should have worked');\n equal(user.secret(), 1337);\n done();\n });", " it('user on disk gets updated after save', async done => {\n Parse.User.extend({\n isSuper: function () {\n return true;\n },\n });", " const user = await Parse.User.signUp('bob', 'welcome');\n await user.save('secret', 1337);\n delete Parse.User._currentUser;\n delete Parse.User._currentUserMatchesDisk;", " const userFromDisk = Parse.User.current();\n equal(userFromDisk.get('secret'), 1337);\n ok(userFromDisk.isSuper(), 'The subclass should have been used');\n done();\n });", " it(\"current user isn't dirty\", async done => {\n const user = await Parse.User.signUp('andrew', 'oppa', {\n style: 'gangnam',\n });\n ok(!user.dirty('style'), 'The user just signed up.');\n Parse.User._currentUser = null;\n Parse.User._currentUserMatchesDisk = false;\n const userAgain = Parse.User.current();\n ok(!userAgain.dirty('style'), 'The user was just read from disk.');\n done();\n });", " const getMockFacebookProviderWithIdToken = function (id, token) {\n return {\n authData: {\n id: id,\n access_token: token,\n expiration_date: new Date().toJSON(),\n },\n shouldError: false,\n loggedOut: false,\n synchronizedUserId: null,\n synchronizedAuthToken: null,\n synchronizedExpiration: null,", " authenticate: function (options) {\n if (this.shouldError) {\n options.error(this, 'An error occurred');\n } else if (this.shouldCancel) {\n options.error(this, null);\n } else {\n options.success(this, this.authData);\n }\n },\n restoreAuthentication: function (authData) {\n if (!authData) {\n this.synchronizedUserId = null;\n this.synchronizedAuthToken = null;\n this.synchronizedExpiration = null;\n return true;\n }\n this.synchronizedUserId = authData.id;\n this.synchronizedAuthToken = authData.access_token;\n this.synchronizedExpiration = authData.expiration_date;\n return true;\n },\n getAuthType: function () {\n return 'facebook';\n },\n deauthenticate: function () {\n this.loggedOut = true;\n this.restoreAuthentication(null);\n },\n };\n };", " // Note that this mocks out client-side Facebook action rather than\n // server-side.\n const getMockFacebookProvider = function () {\n return getMockFacebookProviderWithIdToken('8675309', 'jenny');\n };", " const getMockMyOauthProvider = function () {\n return {\n authData: {\n id: '12345',\n access_token: '12345',\n expiration_date: new Date().toJSON(),\n },\n shouldError: false,\n loggedOut: false,\n synchronizedUserId: null,\n synchronizedAuthToken: null,\n synchronizedExpiration: null,", " authenticate: function (options) {\n if (this.shouldError) {\n options.error(this, 'An error occurred');\n } else if (this.shouldCancel) {\n options.error(this, null);\n } else {\n options.success(this, this.authData);\n }\n },\n restoreAuthentication: function (authData) {\n if (!authData) {\n this.synchronizedUserId = null;\n this.synchronizedAuthToken = null;\n this.synchronizedExpiration = null;\n return true;\n }\n this.synchronizedUserId = authData.id;\n this.synchronizedAuthToken = authData.access_token;\n this.synchronizedExpiration = authData.expiration_date;\n return true;\n },\n getAuthType: function () {\n return 'myoauth';\n },\n deauthenticate: function () {\n this.loggedOut = true;\n this.restoreAuthentication(null);\n },\n };\n };", " Parse.User.extend({\n extended: function () {\n return true;\n },\n });", " it('log in with provider', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n done();\n });", " it('can not set authdata to null', async () => {\n try {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n user.set('authData', null);\n await user.save();\n fail();\n } catch (e) {\n expect(e.message).toBe('This authentication method is unsupported.');\n }\n });", " it('ignore setting authdata to undefined', async () => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n user.set('authData', undefined);\n await user.save();\n let authData = user.get('authData');\n expect(authData).toBe(undefined);\n await user.fetch();\n authData = user.get('authData');\n expect(authData.facebook.id).toBeDefined();\n });", " it('user authData should be available in cloudcode (#2342)', async done => {\n Parse.Cloud.define('checkLogin', req => {\n expect(req.user).not.toBeUndefined();\n expect(Parse.FacebookUtils.isLinked(req.user)).toBe(true);\n return 'ok';\n });", " const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');", " Parse.Cloud.run('checkLogin').then(done, done);\n });", " it('log in with provider and update token', async done => {\n const provider = getMockFacebookProvider();\n const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token');\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n Parse.User._registerAuthenticationProvider(secondProvider);\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n expect(secondProvider.synchronizedAuthToken).toEqual('jenny_valid_token');\n // Make sure we can login with the new token again\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n done();\n });", " it('returns authData when authed and logged in with provider (regression test for #1498)', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n const userQuery = new Parse.Query(Parse.User);\n userQuery.get(user.id).then(user => {\n expect(user.get('authData')).not.toBeUndefined();\n done();\n });\n });", " it('only creates a single session for an installation / user pair (#2885)', async done => {\n Parse.Object.disableSingleInstance();\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User.logInWith('facebook');\n await Parse.User.logInWith('facebook');\n const user = await Parse.User.logInWith('facebook');\n const sessionToken = user.getSessionToken();\n const query = new Parse.Query('_Session');\n return query\n .find({ useMasterKey: true })\n .then(results => {\n expect(results.length).toBe(1);\n expect(results[0].get('sessionToken')).toBe(sessionToken);\n expect(results[0].get('createdWith')).toEqual({\n action: 'login',\n authProvider: 'facebook',\n });\n done();\n })\n .catch(done.fail);\n });", " it('log in with provider with files', done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const file = new Parse.File('yolo.txt', [1, 2, 3], 'text/plain');\n file\n .save()\n .then(file => {\n const user = new Parse.User();\n user.set('file', file);\n return user._linkWith('facebook', {});\n })\n .then(user => {\n expect(user._isLinked('facebook')).toBeTruthy();\n return Parse.User._logInWith('facebook', {});\n })\n .then(user => {\n const fileAgain = user.get('file');\n expect(fileAgain.name()).toMatch(/yolo.txt$/);\n expect(fileAgain.url()).toMatch(/yolo.txt$/);\n })\n .then(() => {\n done();\n })\n .catch(done.fail);\n });", " it('log in with provider twice', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');", " Parse.User.logOut().then(async () => {\n ok(provider.loggedOut);\n provider.loggedOut = false;\n const innerModel = await Parse.User._logInWith('facebook');\n ok(innerModel instanceof Parse.User, 'Model should be a Parse.User');\n ok(innerModel === Parse.User.current(), 'Returned model should be the current user');\n ok(provider.authData.id === provider.synchronizedUserId);\n ok(provider.authData.access_token === provider.synchronizedAuthToken);\n ok(innerModel._isLinked('facebook'), 'User should be linked to facebook');\n ok(innerModel.existed(), 'User should not be newly-created');\n done();\n }, done.fail);\n });", " it('log in with provider failed', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldError = true;\n Parse.User._registerAuthenticationProvider(provider);\n try {\n await Parse.User._logInWith('facebook');\n done.fail();\n } catch (error) {\n ok(error, 'Error should be non-null');\n done();\n }\n });", " it('log in with provider cancelled', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldCancel = true;\n Parse.User._registerAuthenticationProvider(provider);\n try {\n await Parse.User._logInWith('facebook');\n done.fail();\n } catch (error) {\n ok(error === null, 'Error should be null');\n done();\n }\n });", " it('login with provider should not call beforeSave trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n Parse.User.logOut().then(async () => {\n Parse.Cloud.beforeSave(Parse.User, function (req, res) {\n res.error(\"Before save shouldn't be called on login\");\n });\n await Parse.User._logInWith('facebook');\n done();\n });\n });", " it('signup with provider should not call beforeLogin trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(() => {\n hit++;\n });", " await Parse.User._logInWith('facebook');\n expect(hit).toBe(0);\n done();\n });", " it('login with provider should call beforeLogin trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(req => {\n hit++;\n expect(req.object.get('authData')).toBeDefined();\n expect(req.object.get('name')).toBe('tupac shakur');\n });\n await Parse.User._logInWith('facebook');\n await Parse.User.current().save({ name: 'tupac shakur' });\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n expect(hit).toBe(1);\n done();\n });", " it('incorrect login with provider should not call beforeLogin trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(() => {\n hit++;\n });\n await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n provider.shouldError = true;\n try {\n await Parse.User._logInWith('facebook');\n } catch (e) {\n expect(e).toBeDefined();\n }\n expect(hit).toBe(0);\n done();\n });", " it('login with provider should be blockable by beforeLogin', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(req => {\n hit++;\n if (req.object.get('isBanned')) {\n throw new Error('banned account');\n }\n });\n await Parse.User._logInWith('facebook');\n await Parse.User.current().save({ isBanned: true });\n await Parse.User.logOut();", " try {\n await Parse.User._logInWith('facebook');\n throw new Error('should not have continued login.');\n } catch (e) {\n expect(e.message).toBe('banned account');\n }", " expect(hit).toBe(1);\n done();\n });", " it('login with provider should be blockable by beforeLogin even when the user has a attached file', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(req => {\n hit++;\n if (req.object.get('isBanned')) {\n throw new Error('banned account');\n }\n });", " const user = await Parse.User._logInWith('facebook');\n const base64 = 'aHR0cHM6Ly9naXRodWIuY29tL2t2bmt1YW5n';\n const file = new Parse.File('myfile.txt', { base64 });\n await file.save();\n await user.save({ isBanned: true, file });\n await Parse.User.logOut();", " try {\n await Parse.User._logInWith('facebook');\n throw new Error('should not have continued login.');\n } catch (e) {\n expect(e.message).toBe('banned account');\n }", " expect(hit).toBe(1);\n done();\n });", " it('logout with provider should call afterLogout trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let userId;\n Parse.Cloud.afterLogout(req => {\n expect(req.object.className).toEqual('_Session');\n expect(req.object.id).toBeDefined();\n const user = req.object.get('user');\n expect(user).toBeDefined();\n userId = user.id;\n });\n const user = await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n expect(user.id).toBe(userId);\n done();\n });", " it('link with provider', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n const model = await user._linkWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked');\n done();\n });", " // What this means is, only one Parse User can be linked to a\n // particular Facebook account.\n it('link with provider for already linked user', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProviderToAlreadyLinkedUser');\n user.set('password', 'mypass');\n await user.signUp();\n const model = await user._linkWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked.');\n const user2 = new Parse.User();\n user2.set('username', 'testLinkWithProviderToAlreadyLinkedUser2');\n user2.set('password', 'mypass');\n await user2.signUp();\n try {\n await user2._linkWith('facebook');\n done.fail();\n } catch (error) {\n expect(error.code).toEqual(Parse.Error.ACCOUNT_ALREADY_LINKED);\n done();\n }\n });", " it('link with provider should return sessionToken', async () => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n const query = new Parse.Query(Parse.User);\n const u2 = await query.get(user.id);\n const model = await u2._linkWith('facebook', {}, { useMasterKey: true });\n expect(u2.getSessionToken()).toBeDefined();\n expect(model.getSessionToken()).toBeDefined();\n expect(u2.getSessionToken()).toBe(model.getSessionToken());\n });", " it('link with provider via sessionToken should not create new sessionToken (Regression #5799)', async () => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProviderNoOverride');\n user.set('password', 'mypass');\n await user.signUp();\n const sessionToken = user.getSessionToken();", " await user._linkWith('facebook', {}, { sessionToken });\n expect(sessionToken).toBe(user.getSessionToken());", " expect(user._isLinked(provider)).toBe(true);\n await user._unlinkFrom(provider, { sessionToken });\n expect(user._isLinked(provider)).toBe(false);", " const become = await Parse.User.become(sessionToken);\n expect(sessionToken).toBe(become.getSessionToken());\n });", " it('link with provider failed', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldError = true;\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n try {\n await user._linkWith('facebook');\n done.fail();\n } catch (error) {\n ok(error, 'Linking should fail');\n ok(!user._isLinked('facebook'), 'User should not be linked to facebook');\n done();\n }\n });", " it('link with provider cancelled', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldCancel = true;\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n try {\n await user._linkWith('facebook');\n done.fail();\n } catch (error) {\n ok(!error, 'Linking should be cancelled');\n ok(!user._isLinked('facebook'), 'User should not be linked to facebook');\n done();\n }\n });", " it('unlink with provider', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User.');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook.');\n await model._unlinkFrom('facebook');\n ok(!model._isLinked('facebook'), 'User should not be linked.');\n ok(!provider.synchronizedUserId, 'User id should be cleared.');\n ok(!provider.synchronizedAuthToken, 'Auth token should be cleared.');\n ok(!provider.synchronizedExpiration, 'Expiration should be cleared.');\n done();\n });", " it('unlink and link', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');", " await model._unlinkFrom('facebook');\n ok(!model._isLinked('facebook'), 'User should not be linked to facebook');\n ok(!provider.synchronizedUserId, 'User id should be cleared');\n ok(!provider.synchronizedAuthToken, 'Auth token should be cleared');\n ok(!provider.synchronizedExpiration, 'Expiration should be cleared');", " await model._linkWith('facebook');\n ok(provider.synchronizedUserId, 'User id should have a value');\n ok(provider.synchronizedAuthToken, 'Auth token should have a value');\n ok(provider.synchronizedExpiration, 'Expiration should have a value');\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n done();\n });", " it('link multiple providers', async done => {\n const provider = getMockFacebookProvider();\n const mockProvider = getMockMyOauthProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n Parse.User._registerAuthenticationProvider(mockProvider);\n const objectId = model.id;\n await model._linkWith('myoauth');\n expect(model.id).toEqual(objectId);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n ok(model._isLinked('myoauth'), 'User should be linked to myoauth');\n done();\n });", " it('link multiple providers and updates token', async done => {\n const provider = getMockFacebookProvider();\n const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token');", " const mockProvider = getMockMyOauthProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n Parse.User._registerAuthenticationProvider(mockProvider);\n const objectId = model.id;\n await model._linkWith('myoauth');\n Parse.User._registerAuthenticationProvider(secondProvider);\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n const user = await Parse.User._logInWith('myoauth');\n expect(user.id).toBe(objectId);\n done();\n });", " it('link multiple providers and update token', async done => {\n const provider = getMockFacebookProvider();\n const mockProvider = getMockMyOauthProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n Parse.User._registerAuthenticationProvider(mockProvider);\n const objectId = model.id;\n await model._linkWith('myoauth');\n expect(model.id).toEqual(objectId);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n ok(model._isLinked('myoauth'), 'User should be linked to myoauth');\n await model._linkWith('facebook');\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n ok(model._isLinked('myoauth'), 'User should be linked to myoauth');\n done();\n });", " it('should fail linking with existing', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n const user = new Parse.User();\n user.setUsername('user');\n user.setPassword('password');\n await user.signUp();\n // try to link here\n try {\n await user._linkWith('facebook');\n done.fail();\n } catch (e) {\n done();\n }\n });", " it('should fail linking with existing through REST', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n const userId = model.id;\n Parse.User.logOut().then(() => {\n request({\n method: 'POST',\n url: Parse.serverURL + '/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: { authData: { facebook: provider.authData } },\n }).then(response => {\n const body = response.data;\n // make sure the location header is properly set\n expect(userId).not.toBeUndefined();\n expect(body.objectId).toEqual(userId);\n expect(response.headers.location).toEqual(Parse.serverURL + '/users/' + userId);\n done();\n });\n });\n });", " it('should allow login with old authData token', done => {\n const provider = {\n authData: {\n id: '12345',\n access_token: 'token',\n },\n restoreAuthentication: function () {\n return true;\n },\n deauthenticate: function () {\n provider.authData = {};\n },\n authenticate: function (options) {\n options.success(this, provider.authData);\n },\n getAuthType: function () {\n return 'shortLivedAuth';\n },\n };\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('token');\n Parse.User._registerAuthenticationProvider(provider);\n Parse.User._logInWith('shortLivedAuth', {})\n .then(() => {\n // Simulate a remotely expired token (like a short lived one)\n // In this case, we want success as it was valid once.\n // If the client needs an updated one, do lock the user out\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('otherToken');\n return Parse.User._logInWith('shortLivedAuth', {});\n })\n .then(\n () => {\n done();\n },\n err => {\n done.fail(err);\n }\n );\n });", " it('should allow PUT request with stale auth Data', done => {\n const provider = {\n authData: {\n id: '12345',\n access_token: 'token',\n },\n restoreAuthentication: function () {\n return true;\n },\n deauthenticate: function () {\n provider.authData = {};\n },\n authenticate: function (options) {\n options.success(this, provider.authData);\n },\n getAuthType: function () {\n return 'shortLivedAuth';\n },\n };\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('token');\n Parse.User._registerAuthenticationProvider(provider);\n Parse.User._logInWith('shortLivedAuth', {})\n .then(() => {\n // Simulate a remotely expired token (like a short lived one)\n // In this case, we want success as it was valid once.\n // If the client needs an updated one, do lock the user out\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('otherToken');\n return request({\n method: 'PUT',\n url: Parse.serverURL + '/users/' + Parse.User.current().id,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Javascript-Key': Parse.javaScriptKey,\n 'X-Parse-Session-Token': Parse.User.current().getSessionToken(),\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'value', // update a key\n authData: {\n // pass the original auth data\n shortLivedAuth: {\n id: '12345',\n access_token: 'token',\n },\n },\n },\n });\n })\n .then(\n () => {\n done();\n },\n err => {\n done.fail(err);\n }\n );\n });", " it('should properly error when password is missing', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n user.set('username', 'myUser');\n user.set('email', 'foo@example.com');\n user\n .save()\n .then(() => {\n return Parse.User.logOut();\n })\n .then(() => {\n return Parse.User.logIn('myUser', 'password');\n })\n .then(\n () => {\n fail('should not succeed');\n done();\n },\n err => {\n expect(err.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n expect(err.message).toEqual('Invalid username/password.');\n done();\n }\n );\n });", " it('should have authData in beforeSave and afterSave', async done => {\n Parse.Cloud.beforeSave('_User', request => {\n const authData = request.object.get('authData');\n expect(authData).not.toBeUndefined();\n if (authData) {\n expect(authData.facebook.id).toEqual('8675309');\n expect(authData.facebook.access_token).toEqual('jenny');\n } else {\n fail('authData should be set');\n }\n });", " Parse.Cloud.afterSave('_User', request => {\n const authData = request.object.get('authData');\n expect(authData).not.toBeUndefined();\n if (authData) {\n expect(authData.facebook.id).toEqual('8675309');\n expect(authData.facebook.access_token).toEqual('jenny');\n } else {\n fail('authData should be set');\n }\n });", " const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n done();\n });", " it('set password then change password', done => {\n Parse.User.signUp('bob', 'barker')\n .then(bob => {\n bob.setPassword('meower');\n return bob.save();\n })\n .then(() => {\n return Parse.User.logIn('bob', 'meower');\n })\n .then(\n bob => {\n expect(bob.getUsername()).toEqual('bob');\n done();\n },\n e => {\n console.log(e);\n fail();\n }\n );\n });", " it('authenticated check', async done => {\n const user = new Parse.User();\n user.set('username', 'darkhelmet');\n user.set('password', 'onetwothreefour');\n ok(!user.authenticated());\n await user.signUp(null);\n ok(user.authenticated());\n done();\n });", " it('log in with explicit facebook auth data', async done => {\n await Parse.FacebookUtils.logIn({\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n });\n done();\n });", " it('log in async with explicit facebook auth data', done => {\n Parse.FacebookUtils.logIn({\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(\n function () {\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('link with explicit facebook auth data', async done => {\n const user = await Parse.User.signUp('mask', 'open sesame');\n Parse.FacebookUtils.link(user, {\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(done, error => {\n jfail(error);\n done();\n });\n });", " it('link async with explicit facebook auth data', async done => {\n const user = await Parse.User.signUp('mask', 'open sesame');\n Parse.FacebookUtils.link(user, {\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(\n function () {\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('async methods', done => {\n const data = { foo: 'bar' };", " Parse.User.signUp('finn', 'human', data)\n .then(function (user) {\n equal(Parse.User.current(), user);\n equal(user.get('foo'), 'bar');\n return Parse.User.logOut();\n })\n .then(function () {\n return Parse.User.logIn('finn', 'human');\n })\n .then(function (user) {\n equal(user, Parse.User.current());\n equal(user.get('foo'), 'bar');\n return Parse.User.logOut();\n })\n .then(function () {\n const user = new Parse.User();\n user.set('username', 'jake');\n user.set('password', 'dog');\n user.set('foo', 'baz');\n return user.signUp();\n })\n .then(function (user) {\n equal(user, Parse.User.current());\n equal(user.get('foo'), 'baz');\n user = new Parse.User();\n user.set('username', 'jake');\n user.set('password', 'dog');\n return user.logIn();\n })\n .then(function (user) {\n equal(user, Parse.User.current());\n equal(user.get('foo'), 'baz');\n const userAgain = new Parse.User();\n userAgain.id = user.id;\n return userAgain.fetch();\n })\n .then(function (userAgain) {\n equal(userAgain.get('foo'), 'baz');\n done();\n });\n });", " it(\"querying for users doesn't get session tokens\", done => {\n Parse.User.signUp('finn', 'human', { foo: 'bar' })\n .then(function () {\n return Parse.User.logOut();\n })\n .then(() => {\n const user = new Parse.User();\n user.set('username', 'jake');\n user.set('password', 'dog');\n user.set('foo', 'baz');\n return user.signUp();\n })\n .then(function () {\n return Parse.User.logOut();\n })\n .then(() => {\n const query = new Parse.Query(Parse.User);\n return query.find({ sessionToken: null });\n })\n .then(\n function (users) {\n equal(users.length, 2);\n users.forEach(user => {\n expect(user.getSessionToken()).toBeUndefined();\n ok(!user.getSessionToken(), 'user should not have a session token.');\n });\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('querying for users only gets the expected fields', done => {\n Parse.User.signUp('finn', 'human', { foo: 'bar' }).then(() => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/users',\n }).then(response => {\n const b = response.data;\n expect(b.results.length).toEqual(1);\n const user = b.results[0];\n expect(Object.keys(user).length).toEqual(6);\n done();\n });\n });\n });", " it(\"retrieve user data from fetch, make sure the session token hasn't changed\", done => {\n const user = new Parse.User();\n user.setPassword('asdf');\n user.setUsername('zxcv');\n let currentSessionToken = '';\n Promise.resolve()\n .then(function () {\n return user.signUp();\n })\n .then(function () {\n currentSessionToken = user.getSessionToken();\n return user.fetch();\n })\n .then(\n function (u) {\n expect(currentSessionToken).toEqual(u.getSessionToken());\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('user save should fail with invalid email', done => {\n const user = new Parse.User();\n user.set('username', 'teste');\n user.set('password', 'test');\n user.set('email', 'invalid');\n user.signUp().then(\n () => {\n fail('Should not have been able to save.');\n done();\n },\n error => {\n expect(error.code).toEqual(125);\n done();\n }\n );\n });", " it('user signup should error if email taken', done => {\n const user = new Parse.User();\n user.set('username', 'test1');\n user.set('password', 'test');\n user.set('email', 'test@test.com');\n user\n .signUp()\n .then(() => {\n const user2 = new Parse.User();\n user2.set('username', 'test2');\n user2.set('password', 'test');\n user2.set('email', 'test@test.com');\n return user2.signUp();\n })\n .then(\n () => {\n fail('Should not have been able to sign up.');\n done();\n },\n () => {\n done();\n }\n );\n });", " describe('case insensitive signup not allowed', () => {\n it('signup should fail with duplicate case insensitive username with basic setter', async () => {\n const user = new Parse.User();\n user.set('username', 'test1');\n user.set('password', 'test');\n await user.signUp();", " const user2 = new Parse.User();\n user2.set('username', 'Test1');\n user2.set('password', 'test');\n await expectAsync(user2.signUp()).toBeRejectedWith(\n new Parse.Error(Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.')\n );\n });", " it('signup should fail with duplicate case insensitive username with field specific setter', async () => {\n const user = new Parse.User();\n user.setUsername('test1');\n user.setPassword('test');\n await user.signUp();", " const user2 = new Parse.User();\n user2.setUsername('Test1');\n user2.setPassword('test');\n await expectAsync(user2.signUp()).toBeRejectedWith(\n new Parse.Error(Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.')\n );\n });", " it('signup should fail with duplicate case insensitive email', async () => {\n const user = new Parse.User();\n user.setUsername('test1');\n user.setPassword('test');\n user.setEmail('test@example.com');\n await user.signUp();", " const user2 = new Parse.User();\n user2.setUsername('test2');\n user2.setPassword('test');\n user2.setEmail('Test@Example.Com');\n await expectAsync(user2.signUp()).toBeRejectedWith(\n new Parse.Error(Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.')\n );\n });", " it('edit should fail with duplicate case insensitive email', async () => {\n const user = new Parse.User();\n user.setUsername('test1');\n user.setPassword('test');\n user.setEmail('test@example.com');\n await user.signUp();", " const user2 = new Parse.User();\n user2.setUsername('test2');\n user2.setPassword('test');\n user2.setEmail('Foo@Example.Com');\n await user2.signUp();", " user2.setEmail('Test@Example.Com');\n await expectAsync(user2.save()).toBeRejectedWith(\n new Parse.Error(Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.')\n );\n });", " describe('anonymous users', () => {\n beforeEach(() => {\n const insensitiveCollisions = [\n 'abcdefghijklmnop',\n 'Abcdefghijklmnop',\n 'ABcdefghijklmnop',\n 'ABCdefghijklmnop',\n 'ABCDefghijklmnop',\n 'ABCDEfghijklmnop',\n 'ABCDEFghijklmnop',\n 'ABCDEFGhijklmnop',\n 'ABCDEFGHijklmnop',\n 'ABCDEFGHIjklmnop',\n 'ABCDEFGHIJklmnop',\n 'ABCDEFGHIJKlmnop',\n 'ABCDEFGHIJKLmnop',\n 'ABCDEFGHIJKLMnop',\n 'ABCDEFGHIJKLMnop',\n 'ABCDEFGHIJKLMNop',\n 'ABCDEFGHIJKLMNOp',\n 'ABCDEFGHIJKLMNOP',\n ];", " // need a bunch of spare random strings per api request\n spyOn(cryptoUtils, 'randomString').and.returnValues(...insensitiveCollisions);\n });", " it('should not fail on case insensitive matches', async () => {\n const user1 = await Parse.AnonymousUtils.logIn();\n const username1 = user1.get('username');", " const user2 = await Parse.AnonymousUtils.logIn();\n const username2 = user2.get('username');", " expect(username1).not.toBeUndefined();\n expect(username2).not.toBeUndefined();\n expect(username1.toLowerCase()).toBe('abcdefghijklmnop');\n expect(username2.toLowerCase()).toBe('abcdefghijklmnop');\n expect(username2).not.toBe(username1);\n expect(username2.toLowerCase()).toBe(username1.toLowerCase()); // this is redundant :).\n });\n });\n });", " it('user cannot update email to existing user', done => {\n const user = new Parse.User();\n user.set('username', 'test1');\n user.set('password', 'test');\n user.set('email', 'test@test.com');\n user\n .signUp()\n .then(() => {\n const user2 = new Parse.User();\n user2.set('username', 'test2');\n user2.set('password', 'test');\n return user2.signUp();\n })\n .then(user2 => {\n user2.set('email', 'test@test.com');\n return user2.save();\n })\n .then(\n () => {\n fail('Should not have been able to sign up.');\n done();\n },\n () => {\n done();\n }\n );\n });", " it('unset user email', done => {\n const user = new Parse.User();\n user.set('username', 'test');\n user.set('password', 'test');\n user.set('email', 'test@test.com');\n user\n .signUp()\n .then(() => {\n user.unset('email');\n return user.save();\n })\n .then(() => {\n return Parse.User.logIn('test', 'test');\n })\n .then(user => {\n expect(user.getEmail()).toBeUndefined();\n done();\n });\n });", " it('create session from user', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n method: 'POST',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n expect(typeof b.sessionToken).toEqual('string');\n expect(typeof b.createdWith).toEqual('object');\n expect(b.createdWith.action).toEqual('create');\n expect(typeof b.user).toEqual('object');\n expect(b.user.objectId).toEqual(user.id);\n done();\n });\n });\n });\n", " it('user get session from token on signup', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n }).then(response => {\n const b = response.data;\n expect(typeof b.sessionToken).toEqual('string');\n expect(typeof b.createdWith).toEqual('object');\n expect(b.createdWith.action).toEqual('signup');\n expect(typeof b.user).toEqual('object');\n expect(b.user.objectId).toEqual(user.id);\n done();\n });\n });\n });", " it('user get session from token on login', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.logOut().then(() => {\n return Parse.User.logIn('finn', 'human');\n });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n }).then(response => {\n const b = response.data;\n expect(typeof b.sessionToken).toEqual('string');\n expect(typeof b.createdWith).toEqual('object');\n expect(b.createdWith.action).toEqual('login');\n expect(typeof b.user).toEqual('object');\n expect(b.user.objectId).toEqual(user.id);\n done();\n });\n });", " });", " it('user update session with other field', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n }).then(response => {\n const b = response.data;\n request({\n method: 'PUT',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + b.objectId,\n body: JSON.stringify({ foo: 'bar' }),\n }).then(() => {\n done();\n });\n });\n });\n });", " it('cannot update session if invalid or no session token', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n }).then(response => {\n const b = response.data;\n request({\n method: 'PUT',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': 'foo',\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n url: 'http://localhost:8378/1/sessions/' + b.objectId,\n body: JSON.stringify({ foo: 'bar' }),\n }).then(fail, response => {\n const b = response.data;\n expect(b.error).toBe('Invalid session token');\n request({\n method: 'PUT',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + b.objectId,\n body: JSON.stringify({ foo: 'bar' }),\n }).then(fail, response => {\n const b = response.data;\n expect(b.error).toBe('Session token required.');\n done();\n });\n });\n });\n });\n });", " it('get session only for current user', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('test1', 'test', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.signUp('test2', 'test', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n expect(b.results.length).toEqual(1);\n expect(typeof b.results[0].user).toEqual('object');\n expect(b.results[0].user.objectId).toEqual(user.id);\n done();\n });\n });\n });", " it('delete session by object', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('test1', 'test', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.signUp('test2', 'test', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n let objId;\n try {\n expect(b.results.length).toEqual(1);\n objId = b.results[0].objectId;\n } catch (e) {\n jfail(e);\n done();\n return;\n }\n request({\n method: 'DELETE',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + objId,\n }).then(() => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(fail, response => {\n const b = response.data;\n expect(b.code).toEqual(209);\n expect(b.error).toBe('Invalid session token');\n done();\n });\n });\n });\n });\n });", " it('cannot delete session if no sessionToken', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('test1', 'test', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.signUp('test2', 'test', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n expect(b.results.length).toEqual(1);\n const objId = b.results[0].objectId;\n request({\n method: 'DELETE',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + objId,\n }).then(fail, response => {\n const b = response.data;\n expect(b.code).toEqual(209);\n expect(b.error).toBe('Invalid session token');\n done();\n });\n });\n });\n });", " it('password format matches hosted parse', done => {\n const hashed = '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie';\n passwordCrypto.compare('test', hashed).then(\n pass => {\n expect(pass).toBe(true);\n done();\n },\n () => {\n fail('Password format did not match.');\n done();\n }\n );\n });", " it('changing password clears sessions', done => {\n let sessionToken = null;", " Promise.resolve()\n .then(function () {\n return Parse.User.signUp('fosco', 'parse');\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);\n sessionToken = newUser.getSessionToken();\n ok(sessionToken);\n newUser.set('password', 'facebook');\n return newUser.save();\n })\n .then(function () {\n return Parse.User.become(sessionToken);\n })\n .then(\n function () {\n fail('Session should have been invalidated');\n done();\n },\n function (err) {\n expect(err.code).toBe(Parse.Error.INVALID_SESSION_TOKEN);\n expect(err.message).toBe('Invalid session token');\n done();\n }\n );\n });", " it('test parse user become', done => {\n let sessionToken = null;\n Promise.resolve()\n .then(function () {\n return Parse.User.signUp('flessard', 'folo', { foo: 1 });\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);\n sessionToken = newUser.getSessionToken();\n ok(sessionToken);\n newUser.set('foo', 2);\n return newUser.save();\n })\n .then(function () {\n return Parse.User.become(sessionToken);\n })\n .then(\n function (newUser) {\n equal(newUser.get('foo'), 2);\n done();\n },\n function () {\n fail('The session should still be valid');\n done();\n }\n );\n });", " it('ensure logout works', done => {\n let user = null;\n let sessionToken = null;", " Promise.resolve()\n .then(function () {\n return Parse.User.signUp('log', 'out');\n })\n .then(newUser => {\n user = newUser;\n sessionToken = user.getSessionToken();\n return Parse.User.logOut();\n })\n .then(() => {\n user.set('foo', 'bar');\n return user.save(null, { sessionToken: sessionToken });\n })\n .then(\n () => {\n fail('Save should have failed.');\n done();\n },\n e => {\n expect(e.code).toEqual(Parse.Error.INVALID_SESSION_TOKEN);\n done();\n }\n );\n });", " it('support user/password signup with empty authData block', done => {\n // The android SDK can send an empty authData object along with username and password.\n Parse.User.signUp('artof', 'thedeal', { authData: {} }).then(\n () => {\n done();\n },\n () => {\n fail('Signup should have succeeded.');\n done();\n }\n );\n });", " it('session expiresAt correct format', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n url: 'http://localhost:8378/1/classes/_Session',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n },\n }).then(response => {\n const body = response.data;\n expect(body.results[0].expiresAt.__type).toEqual('Date');\n done();\n });\n });", " it('Invalid session tokens are rejected', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n url: 'http://localhost:8378/1/classes/AClass',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Rest-API-Key': 'rest',\n 'X-Parse-Session-Token': 'text',\n },\n }).then(fail, response => {\n const body = response.data;\n expect(body.code).toBe(209);\n expect(body.error).toBe('Invalid session token');\n done();\n });\n });", " it_exclude_dbs(['postgres'])(\n 'should cleanup null authData keys (regression test for #935)',\n done => {\n const database = Config.get(Parse.applicationId).database;\n database\n .create(\n '_User',\n {\n username: 'user',\n _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',\n _auth_data_facebook: null,\n },\n {}\n )\n .then(() => {\n return request({\n url: 'http://localhost:8378/1/login?username=user&password=test',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n },\n }).then(res => res.data);\n })\n .then(user => {\n const authData = user.authData;\n expect(user.username).toEqual('user');\n expect(authData).toBeUndefined();\n done();\n })\n .catch(() => {\n fail('this should not fail');\n done();\n });\n }\n );", " it_exclude_dbs(['postgres'])('should not serve null authData keys', done => {\n const database = Config.get(Parse.applicationId).database;\n database\n .create(\n '_User',\n {\n username: 'user',\n _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',\n _auth_data_facebook: null,\n },\n {}\n )\n .then(() => {\n return new Parse.Query(Parse.User)\n .equalTo('username', 'user')\n .first({ useMasterKey: true });\n })\n .then(user => {\n const authData = user.get('authData');\n expect(user.get('username')).toEqual('user');\n expect(authData).toBeUndefined();\n done();\n })\n .catch(() => {\n fail('this should not fail');\n done();\n });\n });", " it('should cleanup null authData keys ParseUser update (regression test for #1198, #2252)', done => {\n Parse.Cloud.beforeSave('_User', req => {\n req.object.set('foo', 'bar');\n });", " let originalSessionToken;\n let originalUserId;\n // Simulate anonymous user save\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n })\n .then(response => response.data)\n .then(user => {\n originalSessionToken = user.sessionToken;\n originalUserId = user.objectId;\n // Simulate registration\n return request({\n method: 'PUT',\n url: 'http://localhost:8378/1/classes/_User/' + user.objectId,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: { anonymous: null },\n username: 'user',\n password: 'password',\n },\n }).then(response => {\n return response.data;\n });\n })\n .then(user => {\n expect(typeof user).toEqual('object');\n expect(user.authData).toBeUndefined();\n expect(user.sessionToken).not.toBeUndefined();\n // Session token should have changed\n expect(user.sessionToken).not.toEqual(originalSessionToken);\n // test that the sessionToken is valid\n return request({\n url: 'http://localhost:8378/1/users/me',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n }).then(response => {\n const body = response.data;\n expect(body.username).toEqual('user');\n expect(body.objectId).toEqual(originalUserId);\n done();\n });\n })\n .catch(err => {\n fail('no request should fail: ' + JSON.stringify(err));\n done();\n });\n });", " it('should send email when upgrading from anon', done => {\n let emailCalled = false;\n let emailOptions;\n const emailAdapter = {\n sendVerificationEmail: options => {\n emailOptions = options;\n emailCalled = true;\n },\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };\n reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n });\n // Simulate anonymous user save\n return request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n })\n .then(response => {\n const user = response.data;\n return request({\n method: 'PUT',\n url: 'http://localhost:8378/1/classes/_User/' + user.objectId,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: { anonymous: null },\n username: 'user',\n email: 'user@email.com',\n password: 'password',\n },\n });\n })\n .then(() => {\n expect(emailCalled).toBe(true);\n expect(emailOptions).not.toBeUndefined();\n expect(emailOptions.user.get('email')).toEqual('user@email.com');\n done();\n })\n .catch(err => {\n jfail(err);\n fail('no request should fail: ' + JSON.stringify(err));\n done();\n });\n });", " it('should not send email when email is not a string', async done => {\n let emailCalled = false;\n let emailOptions;\n const emailAdapter = {\n sendVerificationEmail: options => {\n emailOptions = options;\n emailCalled = true;\n },\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };\n await reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n });\n const user = new Parse.User();\n user.set('username', 'asdf@jkl.com');\n user.set('password', 'zxcv');\n user.set('email', 'asdf@jkl.com');\n await user.signUp();\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/requestPasswordReset',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n email: { $regex: '^asd' },\n },\n })\n .then(res => {\n fail('no request should succeed: ' + JSON.stringify(res));\n done();\n })\n .catch(err => {\n expect(emailCalled).toBeTruthy();\n expect(emailOptions).toBeDefined();\n expect(err.status).toBe(400);\n expect(err.text).toMatch('{\"code\":125,\"error\":\"you must provide a valid email string\"}');\n done();\n });\n });", " it('should aftersave with full object', done => {\n let hit = 0;\n Parse.Cloud.afterSave('_User', (req, res) => {\n hit++;\n expect(req.object.get('username')).toEqual('User');\n res.success();\n });\n const user = new Parse.User();\n user.setUsername('User');\n user.setPassword('pass');\n user\n .signUp()\n .then(() => {\n user.set('hello', 'world');\n return user.save();\n })\n .then(() => {\n expect(hit).toBe(2);\n done();\n });\n });", " it('changes to a user should update the cache', done => {\n Parse.Cloud.define('testUpdatedUser', req => {\n expect(req.user.get('han')).toEqual('solo');\n return {};\n });\n const user = new Parse.User();\n user.setUsername('harrison');\n user.setPassword('ford');\n user\n .signUp()\n .then(() => {\n user.set('han', 'solo');\n return user.save();\n })\n .then(() => {\n return Parse.Cloud.run('testUpdatedUser');\n })\n .then(\n () => {\n done();\n },\n () => {\n fail('Should not have failed.');\n done();\n }\n );\n });", " it('should fail to become user with expired token', done => {\n let token;\n Parse.User.signUp('auser', 'somepass', null)\n .then(() =>\n request({\n method: 'GET',\n url: 'http://localhost:8378/1/classes/_Session',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n },\n })\n )\n .then(response => {\n const body = response.data;\n const id = body.results[0].objectId;\n const expiresAt = new Date(new Date().setYear(2015));\n token = body.results[0].sessionToken;\n return request({\n method: 'PUT',\n url: 'http://localhost:8378/1/classes/_Session/' + id,\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n 'Content-Type': 'application/json',\n },\n body: {\n expiresAt: { __type: 'Date', iso: expiresAt.toISOString() },\n },\n });\n })\n .then(() => Parse.User.become(token))\n .then(\n () => {\n fail('Should not have succeded');\n done();\n },\n error => {\n expect(error.code).toEqual(209);\n expect(error.message).toEqual('Session token is expired.');\n done();\n }\n )\n .catch(done.fail);\n });", " it('should not create extraneous session tokens', done => {\n const config = Config.get(Parse.applicationId);\n config.database\n .loadSchema()\n .then(s => {\n // Lock down the _User class for creation\n return s.addClassIfNotExists('_User', {}, { create: {} });\n })\n .then(() => {\n const user = new Parse.User();\n return user.save({ username: 'user', password: 'pass' });\n })\n .then(\n () => {\n fail('should not be able to save the user');\n },\n () => {\n return Promise.resolve();\n }\n )\n .then(() => {\n const q = new Parse.Query('_Session');\n return q.find({ useMasterKey: true });\n })\n .then(\n res => {\n // We should have no session created\n expect(res.length).toBe(0);\n done();\n },\n () => {\n fail('should not fail');\n done();\n }\n );\n });", " it('should not overwrite username when unlinking facebook user (regression test for #1532)', async done => {\n Parse.Object.disableSingleInstance();\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n let user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n await user._linkWith('facebook');\n expect(user.get('username')).toEqual('testLinkWithProvider');\n expect(Parse.FacebookUtils.isLinked(user)).toBeTruthy();\n await user._unlinkFrom('facebook');\n user = await user.fetch();\n expect(user.get('username')).toEqual('testLinkWithProvider');\n expect(Parse.FacebookUtils.isLinked(user)).toBeFalsy();\n done();\n });", " it('should revoke sessions when converting anonymous user to \"normal\" user', done => {\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n }).then(response => {\n const body = response.data;\n Parse.User.become(body.sessionToken).then(user => {\n const obj = new Parse.Object('TestObject');\n obj.setACL(new Parse.ACL(user));\n return obj\n .save()\n .then(() => {\n // Change password, revoking session\n user.set('username', 'no longer anonymous');\n user.set('password', 'password');\n return user.save();\n })\n .then(() => {\n // Session token should have been recycled\n expect(body.sessionToken).not.toEqual(user.getSessionToken());\n })\n .then(() => obj.fetch())\n .then(() => {\n done();\n })\n .catch(() => {\n fail('should not fail');\n done();\n });\n });\n });\n });", " it('should not revoke session tokens if the server is configures to not revoke session tokens', done => {\n reconfigureServer({ revokeSessionOnPasswordReset: false }).then(() => {\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n }).then(response => {\n const body = response.data;\n Parse.User.become(body.sessionToken).then(user => {\n const obj = new Parse.Object('TestObject');\n obj.setACL(new Parse.ACL(user));\n return (\n obj\n .save()\n .then(() => {\n // Change password, revoking session\n user.set('username', 'no longer anonymous');\n user.set('password', 'password');\n return user.save();\n })\n .then(() => obj.fetch())\n // fetch should succeed as we still have our session token\n .then(done, fail)\n );\n });\n });\n });\n });", " it('should not fail querying non existing relations', done => {\n const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n });\n user\n .signUp()\n .then(() => {\n return Parse.User.current().relation('relation').query().find();\n })\n .then(res => {\n expect(res.length).toBe(0);\n done();\n })\n .catch(err => {\n fail(JSON.stringify(err));\n done();\n });\n });", " it('should not allow updates to emailVerified', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() => {\n return Parse.User.current().set('emailVerified', true).save();\n })\n .then(() => {\n fail('Should not be able to update emailVerified');\n done();\n })\n .catch(err => {\n expect(err.message).toBe(\"Clients aren't allowed to manually update email verification.\");\n done();\n });\n });", " it('should not retrieve hidden fields on GET users/me (#3432)', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() =>\n request({\n method: 'GET',\n url: 'http://localhost:8378/1/users/me',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': Parse.User.current().getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n })\n )\n .then(response => {\n const res = response.data;\n expect(res.emailVerified).toBe(false);\n expect(res._email_verify_token).toBeUndefined();\n done();\n })\n .catch(done.fail);\n });", " it('should not retrieve hidden fields on GET users/id (#3432)', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() =>\n request({\n method: 'GET',\n url: 'http://localhost:8378/1/users/' + Parse.User.current().id,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n })\n )\n .then(response => {\n const res = response.data;\n expect(res.emailVerified).toBe(false);\n expect(res._email_verify_token).toBeUndefined();\n done();\n })\n .catch(err => {\n fail(JSON.stringify(err));\n done();\n });\n });", " it('should not retrieve hidden fields on login (#3432)', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() =>\n request({\n url: 'http://localhost:8378/1/login?email=test@email.com&username=hello&password=world',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n })\n )\n .then(response => {\n const res = response.data;\n expect(res.emailVerified).toBe(false);\n expect(res._email_verify_token).toBeUndefined();\n done();\n })\n .catch(err => {\n fail(JSON.stringify(err));\n done();\n });\n });", " it('should not allow updates to hidden fields', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() => {\n return Parse.User.current().set('_email_verify_token', 'bad').save();\n })\n .then(() => {\n fail('Should not be able to update email verification token');\n done();\n })\n .catch(err => {\n expect(err).toBeDefined();\n done();\n });\n });", " it('should revoke sessions when setting paswword with masterKey (#3289)', done => {\n let user;\n Parse.User.signUp('username', 'password')\n .then(newUser => {\n user = newUser;\n user.set('password', 'newPassword');\n return user.save(null, { useMasterKey: true });\n })\n .then(() => {\n const query = new Parse.Query('_Session');\n query.equalTo('user', user);\n return query.find({ useMasterKey: true });\n })\n .then(results => {\n expect(results.length).toBe(0);\n done();\n }, done.fail);\n });", " xit('should not send a verification email if the user signed up using oauth', done => {\n let emailCalledCount = 0;\n const emailAdapter = {\n sendVerificationEmail: () => {\n emailCalledCount++;\n return Promise.resolve();\n },\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };\n reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n });\n const user = new Parse.User();\n user.set('email', 'email1@host.com');\n Parse.FacebookUtils.link(user, {\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(user => {\n user.set('email', 'email2@host.com');\n user.save().then(() => {\n expect(emailCalledCount).toBe(0);\n done();\n });\n });\n }).pend('this test fails. See: https://github.com/parse-community/parse-server/issues/5097');", " it('should be able to update user with authData passed', done => {\n let objectId;\n let sessionToken;", " function validate(block) {\n return request({\n url: `http://localhost:8378/1/classes/_User/${objectId}`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'X-Parse-Session-Token': sessionToken,\n },\n }).then(response => block(response.data));\n }", " request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'value',\n authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' } },\n },\n })\n .then(response => {\n const body = response.data;\n objectId = body.objectId;\n sessionToken = body.sessionToken;\n expect(sessionToken).toBeDefined();\n expect(objectId).toBeDefined();\n return validate(user => {\n // validate that keys are set on creation\n expect(user.key).toBe('value');\n });\n })\n .then(() => {\n // update the user\n const options = {\n method: 'PUT',\n url: `http://localhost:8378/1/classes/_User/${objectId}`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'X-Parse-Session-Token': sessionToken,\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'otherValue',\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n };\n return request(options);\n })\n .then(() => {\n return validate(user => {\n // validate that keys are set on update\n expect(user.key).toBe('otherValue');\n });\n })\n .then(() => {\n done();\n })\n .then(done)\n .catch(done.fail);\n });", " it('can login with email', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n qs: { email: 'yo@lo.com', password: 'yolopass' },\n };\n return request(options);\n })\n .then(done)\n .catch(done.fail);\n });", " it('cannot login with email and invalid password', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n method: 'POST',\n url: `http://localhost:8378/1/login`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: { email: 'yo@lo.com', password: 'yolopass2' },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(() => done());\n });", " it('can login with email through query string', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo.com&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done)\n .catch(done.fail);\n });", " it('can login when both email and username are passed', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo.com&username=yolo&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done)\n .catch(done.fail);\n });", " it(\"fails to login when username doesn't match email\", done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo.com&username=yolo2&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('Invalid username/password.');\n done();\n });\n });", " it(\"fails to login when email doesn't match username\", done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo2.com&username=yolo&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('Invalid username/password.');\n done();\n });\n });", " it('fails to login when email and username are not provided', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('username/email is required.');\n done();\n });\n });", " it('allows login when providing email as username', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n return Parse.User.logIn('yo@lo.com', 'yolopass');\n })\n .then(user => {\n expect(user.get('username')).toBe('yolo');\n })\n .then(done)\n .catch(done.fail);\n });", " it('handles properly when 2 users share username / email pairs', done => {\n const user = new Parse.User({\n username: 'yo@loname.com',\n password: 'yolopass',\n email: 'yo@lo.com',\n });\n const user2 = new Parse.User({\n username: 'yo@lo.com',\n email: 'yo@loname.com',\n password: 'yolopass2', // different passwords\n });", " Parse.Object.saveAll([user, user2])\n .then(() => {\n return Parse.User.logIn('yo@loname.com', 'yolopass');\n })\n .then(user => {\n // the username takes precedence over the email,\n // so we get the user with username as passed in\n expect(user.get('username')).toBe('yo@loname.com');\n })\n .then(done)\n .catch(done.fail);\n });", " it('handles properly when 2 users share username / email pairs, counterpart', done => {\n const user = new Parse.User({\n username: 'yo@loname.com',\n password: 'yolopass',\n email: 'yo@lo.com',\n });\n const user2 = new Parse.User({\n username: 'yo@lo.com',\n email: 'yo@loname.com',\n password: 'yolopass2', // different passwords\n });", " Parse.Object.saveAll([user, user2])\n .then(() => {\n return Parse.User.logIn('yo@loname.com', 'yolopass2');\n })\n .then(done.fail)\n .catch(err => {\n expect(err.message).toEqual('Invalid username/password.');\n done();\n });\n });", " it('fails to login when password is not provided', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?username=yolo`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('password is required.');\n done();\n });\n });", " it('does not duplicate session when logging in multiple times #3451', done => {\n const user = new Parse.User();\n user\n .signUp({\n username: 'yolo',\n password: 'yolo',\n email: 'yo@lo.com',\n })\n .then(() => {\n const token = user.getSessionToken();\n let promise = Promise.resolve();\n let count = 0;\n while (count < 5) {\n promise = promise.then(() => {\n return Parse.User.logIn('yolo', 'yolo').then(res => {\n // ensure a new session token is generated at each login\n expect(res.getSessionToken()).not.toBe(token);\n });\n });\n count++;\n }\n return promise;\n })\n .then(() => {\n // wait because session destruction is not synchronous\n return new Promise(resolve => {\n setTimeout(resolve, 100);\n });\n })\n .then(() => {\n const query = new Parse.Query('_Session');\n return query.find({ useMasterKey: true });\n })\n .then(results => {\n // only one session in the end\n expect(results.length).toBe(1);\n })\n .then(done, done.fail);\n });", " it('should throw OBJECT_NOT_FOUND instead of SESSION_MISSING when using masterKey', async () => {\n // create a fake user (just so we simulate an object not found)\n const non_existent_user = Parse.User.createWithoutData('fake_id');\n try {\n await non_existent_user.destroy({ useMasterKey: true });\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n }\n try {\n await non_existent_user.save({}, { useMasterKey: true });\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n }\n try {\n await non_existent_user.save();\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n try {\n await non_existent_user.destroy();\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n });", " describe('issue #4897', () => {\n it_only_db('mongo')('should be able to login with a legacy user (no ACL)', async () => {\n // This issue is a side effect of the locked users and legacy users which don't have ACL's\n // In this scenario, a legacy user wasn't be able to login as there's no ACL on it\n const database = Config.get(Parse.applicationId).database;\n const collection = await database.adapter._adaptiveCollection('_User');\n await collection.insertOne({\n _id: 'ABCDEF1234',\n name: '<some_name>',\n email: '<some_email>',\n username: '<some_username>',\n _hashed_password: '<some_password>',\n _auth_data_facebook: {\n id: '8675309',\n access_token: 'jenny',\n },\n sessionToken: '<some_session_token>',\n });\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook', {});\n expect(model.id).toBe('ABCDEF1234');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n });\n });\n});", "describe('Security Advisory GHSA-8w3j-g983-8jh5', function () {\n it_only_db('mongo')(\n 'should validate credentials first and check if account already linked afterwards ()',\n async done => {\n // Add User to Database with authData\n const database = Config.get(Parse.applicationId).database;\n const collection = await database.adapter._adaptiveCollection('_User');\n await collection.insertOne({\n _id: 'ABCDEF1234',\n name: '<some_name>',\n email: '<some_email>',\n username: '<some_username>',\n _hashed_password: '<some_password>',\n _auth_data_custom: {\n id: 'linkedID', // Already linked userid\n },\n sessionToken: '<some_session_token>',\n });\n const provider = {\n getAuthType: () => 'custom',\n restoreAuthentication: () => true,\n }; // AuthProvider checks if password is 'password'\n Parse.User._registerAuthenticationProvider(provider);", " // Try to link second user with wrong password\n try {\n const user = await Parse.AnonymousUtils.logIn();\n await user._linkWith(provider.getAuthType(), {\n authData: { id: 'linkedID', password: 'wrong' },\n });\n } catch (error) {\n // This should throw Parse.Error.SESSION_MISSING and not Parse.Error.ACCOUNT_ALREADY_LINKED\n expect(error.code).toEqual(Parse.Error.SESSION_MISSING);\n done();\n return;\n }\n fail();\n done();\n }\n );\n it_only_db('mongo')('should ignore authData field', async () => {\n // Add User to Database with authData\n const database = Config.get(Parse.applicationId).database;\n const collection = await database.adapter._adaptiveCollection('_User');\n await collection.insertOne({\n _id: '1234ABCDEF',\n name: '<some_name>',\n email: '<some_email>',\n username: '<some_username>',\n _hashed_password: '<some_password>',\n _auth_data_custom: {\n id: 'linkedID',\n },\n sessionToken: '<some_session_token>',\n authData: null, // should ignore\n });\n const provider = {\n getAuthType: () => 'custom',\n restoreAuthentication: () => true,\n };\n Parse.User._registerAuthenticationProvider(provider);\n const query = new Parse.Query(Parse.User);\n const user = await query.get('1234ABCDEF', { useMasterKey: true });\n expect(user.get('authData')).toEqual({ custom: { id: 'linkedID' } });\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 2430, 857], "buggy_code_start_loc": [4, 2377, 857], "filenames": ["CHANGELOG.md", "spec/ParseUser.spec.js", "src/RestWrite.js"], "fixing_code_end_loc": [10, 2434, 862], "fixing_code_start_loc": [4, 2377, 858], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "9DE0F06D-5868-45AD-B21E-C5268BCC7F52", "versionEndExcluding": "4.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login."}, {"lang": "es", "value": "Parse Server es un backend de c\u00f3digo abierto que puede desplegarse en cualquier infraestructura que pueda ejecutar Node.js. Los desarrolladores pueden usar la API REST para registrar usuarios y tambi\u00e9n permitir a usuarios registrarse an\u00f3nimamente. Versiones anteriores a 4.5.1, cuando un usuario an\u00f3nimo es registrado por primera vez usando REST, el servidor creaba la sesi\u00f3n incorrectamente. En particular, el campo \"authProvider\" de la clase \"_Session\" en \"createdWith\" muestra que el usuario se ha registrado creando una contrase\u00f1a. Si un desarrollador depende posteriormente del campo \"createdWith\" para proporcionar un nivel de acceso diferente entre un usuario con contrase\u00f1a y un usuario an\u00f3nimo, el servidor clasifica incorrectamente el tipo de sesi\u00f3n como creada con un \"password\". El servidor no usa actualmente \"createdWith\" para tomar decisiones sobre las funciones internas, por lo que si un desarrollador no est\u00e1 usando \"createdWith\" directamente, no est\u00e1 afectado. La vulnerabilidad s\u00f3lo afecta a usuarios que dependen de \"createdWith\" al usarlo directamente. El problema est\u00e1 parcheado en Parse Server versi\u00f3n 4.5.1. Como soluci\u00f3n, no use el campo de sesi\u00f3n \"createdWith\" para tomar decisiones si se permite el acceso an\u00f3nimo."}], "evaluatorComment": null, "id": "CVE-2021-39138", "lastModified": "2022-08-12T18:01:28.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.5, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-19T16:15:12.483", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/releases/tag/4.5.1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, "type": "CWE-863"}
299
Determine whether the {function_name} code is vulnerable or not.
[ "// This is a port of the test suite:\n// hungry/js/test/parse_user_test.js\n//\n// Things that we didn't port:\n// Tests that involve revocable sessions.\n// Tests that involve sending password reset emails.", "'use strict';", "const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default;\nconst request = require('../lib/request');\nconst passwordCrypto = require('../lib/password');\nconst Config = require('../lib/Config');\nconst cryptoUtils = require('../lib/cryptoUtils');", "function verifyACL(user) {\n const ACL = user.getACL();\n expect(ACL.getReadAccess(user)).toBe(true);\n expect(ACL.getWriteAccess(user)).toBe(true);\n expect(ACL.getPublicReadAccess()).toBe(true);\n expect(ACL.getPublicWriteAccess()).toBe(false);\n const perms = ACL.permissionsById;\n expect(Object.keys(perms).length).toBe(2);\n expect(perms[user.id].read).toBe(true);\n expect(perms[user.id].write).toBe(true);\n expect(perms['*'].read).toBe(true);\n expect(perms['*'].write).not.toBe(true);\n}", "describe('Parse.User testing', () => {\n it('user sign up class method', async done => {\n const user = await Parse.User.signUp('asdf', 'zxcv');\n ok(user.getSessionToken());\n done();\n });", " it('user sign up instance method', async () => {\n const user = new Parse.User();\n user.setPassword('asdf');\n user.setUsername('zxcv');\n await user.signUp();\n ok(user.getSessionToken());\n });", " it('user login wrong username', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n try {\n await Parse.User.logIn('non_existent_user', 'asdf3');\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n done();\n }\n });", " it('user login wrong password', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n try {\n await Parse.User.logIn('asdf', 'asdfWrong');\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n done();\n }\n });", " it('user login with non-string username with REST API', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/login',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n _method: 'GET',\n username: { $regex: '^asd' },\n password: 'zxcv',\n },\n })\n .then(res => {\n fail(`no request should succeed: ${JSON.stringify(res)}`);\n done();\n })\n .catch(err => {\n expect(err.status).toBe(404);\n expect(err.text).toMatch('{\"code\":101,\"error\":\"Invalid username/password.\"}');\n done();\n });\n });", " it('user login with non-string username with REST API (again)', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/login',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n _method: 'GET',\n username: 'asdf',\n password: { $regex: '^zx' },\n },\n })\n .then(res => {\n fail(`no request should succeed: ${JSON.stringify(res)}`);\n done();\n })\n .catch(err => {\n expect(err.status).toBe(404);\n expect(err.text).toMatch('{\"code\":101,\"error\":\"Invalid username/password.\"}');\n done();\n });\n });", " it('user login using POST with REST API', async done => {\n await Parse.User.signUp('some_user', 'some_password');\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/login',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n body: {\n username: 'some_user',\n password: 'some_password',\n },\n })\n .then(res => {\n expect(res.data.username).toBe('some_user');\n done();\n })\n .catch(err => {\n fail(`no request should fail: ${JSON.stringify(err)}`);\n done();\n });\n });", " it('user login', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n const user = await Parse.User.logIn('asdf', 'zxcv');\n equal(user.get('username'), 'asdf');\n verifyACL(user);\n done();\n });", " it('should respect ACL without locking user out', done => {\n const user = new Parse.User();\n const ACL = new Parse.ACL();\n ACL.setPublicReadAccess(false);\n ACL.setPublicWriteAccess(false);\n user.setUsername('asdf');\n user.setPassword('zxcv');\n user.setACL(ACL);\n user\n .signUp()\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n equal(user.get('username'), 'asdf');\n const ACL = user.getACL();\n expect(ACL.getReadAccess(user)).toBe(true);\n expect(ACL.getWriteAccess(user)).toBe(true);\n expect(ACL.getPublicReadAccess()).toBe(false);\n expect(ACL.getPublicWriteAccess()).toBe(false);\n const perms = ACL.permissionsById;\n expect(Object.keys(perms).length).toBe(1);\n expect(perms[user.id].read).toBe(true);\n expect(perms[user.id].write).toBe(true);\n expect(perms['*']).toBeUndefined();\n // Try to lock out user\n const newACL = new Parse.ACL();\n newACL.setReadAccess(user.id, false);\n newACL.setWriteAccess(user.id, false);\n user.setACL(newACL);\n return user.save();\n })\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n equal(user.get('username'), 'asdf');\n const ACL = user.getACL();\n expect(ACL.getReadAccess(user)).toBe(true);\n expect(ACL.getWriteAccess(user)).toBe(true);\n expect(ACL.getPublicReadAccess()).toBe(false);\n expect(ACL.getPublicWriteAccess()).toBe(false);\n const perms = ACL.permissionsById;\n expect(Object.keys(perms).length).toBe(1);\n expect(perms[user.id].read).toBe(true);\n expect(perms[user.id].write).toBe(true);\n expect(perms['*']).toBeUndefined();\n done();\n })\n .catch(() => {\n fail('Should not fail');\n done();\n });\n });", " it('should let masterKey lockout user', done => {\n const user = new Parse.User();\n const ACL = new Parse.ACL();\n ACL.setPublicReadAccess(false);\n ACL.setPublicWriteAccess(false);\n user.setUsername('asdf');\n user.setPassword('zxcv');\n user.setACL(ACL);\n user\n .signUp()\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n equal(user.get('username'), 'asdf');\n // Lock the user down\n const ACL = new Parse.ACL();\n user.setACL(ACL);\n return user.save(null, { useMasterKey: true });\n })\n .then(() => {\n expect(user.getACL().getPublicReadAccess()).toBe(false);\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(done.fail)\n .catch(err => {\n expect(err.message).toBe('Invalid username/password.');\n expect(err.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n done();\n });\n });", " it_only_db('mongo')('should let legacy users without ACL login', async () => {\n const databaseURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase';\n const adapter = new MongoStorageAdapter({\n collectionPrefix: 'test_',\n uri: databaseURI,\n });\n await adapter.connect();\n await adapter.database.dropDatabase();\n delete adapter.connectionPromise;", " const user = new Parse.User();\n await user.signUp({\n username: 'newUser',\n password: 'password',\n });", " const collection = await adapter._adaptiveCollection('_User');\n await collection.insertOne({\n // the hashed password is 'password' hashed\n _hashed_password: '$2b$10$mJ2ca2UbCM9hlojYHZxkQe8pyEXe5YMg0nMdvP4AJBeqlTEZJ6/Uu',\n _session_token: 'xxx',\n email: 'xxx@a.b',\n username: 'oldUser',\n emailVerified: true,\n _email_verify_token: 'yyy',\n });", " // get the 2 users\n const users = await collection.find();\n expect(users.length).toBe(2);", " const aUser = await Parse.User.logIn('oldUser', 'password');\n expect(aUser).not.toBeUndefined();", " const newUser = await Parse.User.logIn('newUser', 'password');\n expect(newUser).not.toBeUndefined();\n });", " it('should be let masterKey lock user out with authData', async () => {\n const response = await request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'value',\n authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' } },\n },\n });\n const body = response.data;\n const objectId = body.objectId;\n const sessionToken = body.sessionToken;\n expect(sessionToken).toBeDefined();\n expect(objectId).toBeDefined();\n const user = new Parse.User();\n user.id = objectId;\n const ACL = new Parse.ACL();\n user.setACL(ACL);\n await user.save(null, { useMasterKey: true });\n // update the user\n const options = {\n method: 'POST',\n url: `http://localhost:8378/1/classes/_User/`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'otherValue',\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n };\n const res = await request(options);\n expect(res.data.objectId).not.toEqual(objectId);\n });", " it('user login with files', done => {\n const file = new Parse.File('yolo.txt', [1, 2, 3], 'text/plain');\n file\n .save()\n .then(file => {\n return Parse.User.signUp('asdf', 'zxcv', { file: file });\n })\n .then(() => {\n return Parse.User.logIn('asdf', 'zxcv');\n })\n .then(user => {\n const fileAgain = user.get('file');\n ok(fileAgain.name());\n ok(fileAgain.url());\n done();\n })\n .catch(err => {\n jfail(err);\n done();\n });\n });", " it('become sends token back', done => {\n let user = null;\n let sessionToken = null;", " Parse.User.signUp('Jason', 'Parse', { code: 'red' })\n .then(newUser => {\n user = newUser;\n expect(user.get('code'), 'red');", " sessionToken = newUser.getSessionToken();\n expect(sessionToken).toBeDefined();", " return Parse.User.become(sessionToken);\n })\n .then(newUser => {\n expect(newUser.id).toEqual(user.id);\n expect(newUser.get('username'), 'Jason');\n expect(newUser.get('code'), 'red');\n expect(newUser.getSessionToken()).toEqual(sessionToken);\n })\n .then(\n () => {\n done();\n },\n error => {\n jfail(error);\n done();\n }\n );\n });", " it('become', done => {\n let user = null;\n let sessionToken = null;", " Promise.resolve()\n .then(function () {\n return Parse.User.signUp('Jason', 'Parse', { code: 'red' });\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);", " user = newUser;\n sessionToken = newUser.getSessionToken();\n ok(sessionToken);", " return Parse.User.logOut();\n })\n .then(() => {\n ok(!Parse.User.current());", " return Parse.User.become(sessionToken);\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);", " ok(newUser);\n equal(newUser.id, user.id);\n equal(newUser.get('username'), 'Jason');\n equal(newUser.get('code'), 'red');", " return Parse.User.logOut();\n })\n .then(() => {\n ok(!Parse.User.current());", " return Parse.User.become('somegarbage');\n })\n .then(\n function () {\n // This should have failed actually.\n ok(false, \"Shouldn't have been able to log in with garbage session token.\");\n },\n function (error) {\n ok(error);\n // Handle the error.\n return Promise.resolve();\n }\n )\n .then(\n function () {\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('should not call beforeLogin with become', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(() => {\n hit++;\n });", " await Parse.User._logInWith('facebook');\n const sessionToken = Parse.User.current().getSessionToken();\n await Parse.User.become(sessionToken);\n expect(hit).toBe(0);\n done();\n });", " it('cannot save non-authed user', async done => {\n let user = new Parse.User();\n user.set({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n let userAgain = await user.signUp();\n equal(userAgain, user);\n const query = new Parse.Query(Parse.User);\n const userNotAuthed = await query.get(user.id);\n user = new Parse.User();\n user.set({\n username: 'hacker',\n password: 'password',\n });\n userAgain = await user.signUp();\n equal(userAgain, user);\n userNotAuthed.set('username', 'changed');\n userNotAuthed.save().then(fail, err => {\n expect(err.code).toEqual(Parse.Error.SESSION_MISSING);\n done();\n });\n });", " it('cannot delete non-authed user', async done => {\n let user = new Parse.User();\n await user.signUp({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n const query = new Parse.Query(Parse.User);\n const userNotAuthed = await query.get(user.id);\n user = new Parse.User();\n const userAgain = await user.signUp({\n username: 'hacker',\n password: 'password',\n });\n equal(userAgain, user);\n userNotAuthed.set('username', 'changed');\n try {\n await userNotAuthed.destroy();\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n done();\n }\n });", " it('cannot saveAll with non-authed user', async done => {\n let user = new Parse.User();\n await user.signUp({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n const query = new Parse.Query(Parse.User);\n const userNotAuthed = await query.get(user.id);\n user = new Parse.User();\n await user.signUp({\n username: 'hacker',\n password: 'password',\n });\n const userNotAuthedNotChanged = await query.get(user.id);\n userNotAuthed.set('username', 'changed');\n const object = new TestObject();\n await object.save({\n user: userNotAuthedNotChanged,\n });\n const item1 = new TestObject();\n await item1.save({\n number: 0,\n });\n item1.set('number', 1);\n const item2 = new TestObject();\n item2.set('number', 2);\n try {\n await Parse.Object.saveAll([item1, item2, userNotAuthed]);\n done.fail();\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n done();\n }\n });", " it('never locks himself up', async () => {\n const user = new Parse.User();\n await user.signUp({\n username: 'username',\n password: 'password',\n });\n user.setACL(new Parse.ACL());\n await user.save();\n await user.fetch();\n expect(user.getACL().getReadAccess(user)).toBe(true);\n expect(user.getACL().getWriteAccess(user)).toBe(true);\n const publicReadACL = new Parse.ACL();\n publicReadACL.setPublicReadAccess(true);", " // Create an administrator role with a single admin user\n const role = new Parse.Role('admin', publicReadACL);\n const admin = new Parse.User();\n await admin.signUp({\n username: 'admin',\n password: 'admin',\n });\n role.getUsers().add(admin);\n await role.save(null, { useMasterKey: true });", " // Grant the admins write rights on the user\n const acl = user.getACL();\n acl.setRoleWriteAccess(role, true);\n acl.setRoleReadAccess(role, true);", " // Update with the masterKey just to be sure\n await user.save({ ACL: acl }, { useMasterKey: true });", " // Try to update from admin... should all work fine\n await user.save({ key: 'fromAdmin' }, { sessionToken: admin.getSessionToken() });\n await user.fetch();\n expect(user.toJSON().key).toEqual('fromAdmin');", " // Try to save when logged out (public)\n let failed = false;\n try {\n // Ensure no session token is sent\n await Parse.User.logOut();\n await user.save({ key: 'fromPublic' });\n } catch (e) {\n failed = true;\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n expect({ failed }).toEqual({ failed: true });", " // Try to save with a random user, should fail\n failed = false;\n const anyUser = new Parse.User();\n await anyUser.signUp({\n username: 'randomUser',\n password: 'password',\n });\n try {\n await user.save({ key: 'fromAnyUser' });\n } catch (e) {\n failed = true;\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n expect({ failed }).toEqual({ failed: true });\n });", " it('current user', done => {\n const user = new Parse.User();\n user.set('password', 'asdf');\n user.set('email', 'asdf@example.com');\n user.set('username', 'zxcv');\n user\n .signUp()\n .then(() => {\n const currentUser = Parse.User.current();\n equal(user.id, currentUser.id);\n ok(user.getSessionToken());", " const currentUserAgain = Parse.User.current();\n // should be the same object\n equal(currentUser, currentUserAgain);", " // test logging out the current user\n return Parse.User.logOut();\n })\n .then(() => {\n equal(Parse.User.current(), null);\n done();\n });\n });", " it('user.isCurrent', done => {\n const user1 = new Parse.User();\n const user2 = new Parse.User();\n const user3 = new Parse.User();", " user1.set('username', 'a');\n user2.set('username', 'b');\n user3.set('username', 'c');", " user1.set('password', 'password');\n user2.set('password', 'password');\n user3.set('password', 'password');", " user1\n .signUp()\n .then(() => {\n equal(user1.isCurrent(), true);\n equal(user2.isCurrent(), false);\n equal(user3.isCurrent(), false);\n return user2.signUp();\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), true);\n equal(user3.isCurrent(), false);\n return user3.signUp();\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), false);\n equal(user3.isCurrent(), true);\n return Parse.User.logIn('a', 'password');\n })\n .then(() => {\n equal(user1.isCurrent(), true);\n equal(user2.isCurrent(), false);\n equal(user3.isCurrent(), false);\n return Parse.User.logIn('b', 'password');\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), true);\n equal(user3.isCurrent(), false);\n return Parse.User.logIn('b', 'password');\n })\n .then(() => {\n equal(user1.isCurrent(), false);\n equal(user2.isCurrent(), true);\n equal(user3.isCurrent(), false);\n return Parse.User.logOut();\n })\n .then(() => {\n equal(user2.isCurrent(), false);\n done();\n });\n });", " it('user associations', async done => {\n const child = new TestObject();\n await child.save();\n const user = new Parse.User();\n user.set('password', 'asdf');\n user.set('email', 'asdf@example.com');\n user.set('username', 'zxcv');\n user.set('child', child);\n await user.signUp();\n const object = new TestObject();\n object.set('user', user);\n await object.save();\n const query = new Parse.Query(TestObject);\n const objectAgain = await query.get(object.id);\n const userAgain = objectAgain.get('user');\n await userAgain.fetch();\n equal(user.id, userAgain.id);\n equal(userAgain.get('child').id, child.id);\n done();\n });", " it('user queries', async done => {\n const user = new Parse.User();\n user.set('password', 'asdf');\n user.set('email', 'asdf@example.com');\n user.set('username', 'zxcv');\n await user.signUp();\n const query = new Parse.Query(Parse.User);\n const userAgain = await query.get(user.id);\n equal(userAgain.id, user.id);\n const users = await query.find();\n equal(users.length, 1);\n equal(users[0].id, user.id);\n ok(userAgain.get('email'), 'asdf@example.com');\n done();\n });", " function signUpAll(list, optionsOrCallback) {\n let promise = Promise.resolve();\n list.forEach(user => {\n promise = promise.then(function () {\n return user.signUp();\n });\n });\n promise = promise.then(function () {\n return list;\n });\n return promise.then(optionsOrCallback);\n }", " it('contained in user array queries', async done => {\n const USERS = 4;\n const MESSAGES = 5;", " // Make a list of users.\n const userList = range(USERS).map(function (i) {\n const user = new Parse.User();\n user.set('password', 'user_num_' + i);\n user.set('email', 'user_num_' + i + '@example.com');\n user.set('username', 'xinglblog_num_' + i);\n return user;\n });", " signUpAll(userList, async function (users) {\n // Make a list of messages.\n if (!users || users.length != USERS) {\n fail('signupAll failed');\n done();\n return;\n }\n const messageList = range(MESSAGES).map(function (i) {\n const message = new TestObject();\n message.set('to', users[(i + 1) % USERS]);\n message.set('from', users[i % USERS]);\n return message;\n });", " // Save all the messages.\n await Parse.Object.saveAll(messageList);", " // Assemble an \"in\" list.\n const inList = [users[0], users[3], users[3]]; // Intentional dupe\n const query = new Parse.Query(TestObject);\n query.containedIn('from', inList);\n const results = await query.find();\n equal(results.length, 3);\n done();\n });\n });", " it(\"saving a user signs them up but doesn't log them in\", async done => {\n const user = new Parse.User();\n await user.save({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });\n equal(Parse.User.current(), null);\n done();\n });", " it('user updates', async done => {\n const user = new Parse.User();\n await user.signUp({\n password: 'asdf',\n email: 'asdf@example.com',\n username: 'zxcv',\n });", " user.set('username', 'test');\n await user.save();\n equal(Object.keys(user.attributes).length, 6);\n ok(user.attributes['username']);\n ok(user.attributes['email']);\n await user.destroy();\n const query = new Parse.Query(Parse.User);\n try {\n await query.get(user.id);\n done.fail();\n } catch (error) {\n // The user should no longer exist.\n equal(error.code, Parse.Error.OBJECT_NOT_FOUND);\n done();\n }\n });", " it('count users', async done => {\n const james = new Parse.User();\n james.set('username', 'james');\n james.set('password', 'mypass');\n await james.signUp();\n const kevin = new Parse.User();\n kevin.set('username', 'kevin');\n kevin.set('password', 'mypass');\n await kevin.signUp();\n const query = new Parse.Query(Parse.User);\n const count = await query.count();\n equal(count, 2);\n done();\n });", " it('user sign up with container class', async done => {\n await Parse.User.signUp('ilya', 'mypass', { array: ['hello'] });\n done();\n });", " it('user modified while saving', done => {\n Parse.Object.disableSingleInstance();\n const user = new Parse.User();\n user.set('username', 'alice');\n user.set('password', 'password');\n user.signUp().then(function (userAgain) {\n equal(userAgain.get('username'), 'bob');\n ok(userAgain.dirty('username'));\n const query = new Parse.Query(Parse.User);\n query.get(user.id).then(freshUser => {\n equal(freshUser.id, user.id);\n equal(freshUser.get('username'), 'alice');\n done();\n });\n });\n // Jump a frame so the signup call is properly sent\n // This is due to the fact that now, we use real promises\n process.nextTick(() => {\n ok(user.set('username', 'bob'));\n });\n });", " it('user modified while saving with unsaved child', done => {\n Parse.Object.disableSingleInstance();\n const user = new Parse.User();\n user.set('username', 'alice');\n user.set('password', 'password');\n user.set('child', new TestObject());\n user.signUp().then(userAgain => {\n equal(userAgain.get('username'), 'bob');\n // Should be dirty, but it depends on batch support.\n // ok(userAgain.dirty(\"username\"));\n const query = new Parse.Query(Parse.User);\n query.get(user.id).then(freshUser => {\n equal(freshUser.id, user.id);\n // Should be alice, but it depends on batch support.\n equal(freshUser.get('username'), 'bob');\n done();\n });\n });\n ok(user.set('username', 'bob'));\n });", " it('user loaded from localStorage from signup', async done => {\n const alice = await Parse.User.signUp('alice', 'password');\n ok(alice.id, 'Alice should have an objectId');\n ok(alice.getSessionToken(), 'Alice should have a session token');\n equal(alice.get('password'), undefined, 'Alice should not have a password');", " // Simulate the environment getting reset.\n Parse.User._currentUser = null;\n Parse.User._currentUserMatchesDisk = false;", " const aliceAgain = Parse.User.current();\n equal(aliceAgain.get('username'), 'alice');\n equal(aliceAgain.id, alice.id, 'currentUser should have objectId');\n ok(aliceAgain.getSessionToken(), 'currentUser should have a sessionToken');\n equal(alice.get('password'), undefined, 'currentUser should not have password');\n done();\n });", " it('user loaded from localStorage from login', done => {\n let id;\n Parse.User.signUp('alice', 'password')\n .then(alice => {\n id = alice.id;\n return Parse.User.logOut();\n })\n .then(() => {\n return Parse.User.logIn('alice', 'password');\n })\n .then(() => {\n // Force the current user to read from disk\n delete Parse.User._currentUser;\n delete Parse.User._currentUserMatchesDisk;", " const userFromDisk = Parse.User.current();\n equal(userFromDisk.get('password'), undefined, 'password should not be in attributes');\n equal(userFromDisk.id, id, 'id should be set');\n ok(userFromDisk.getSessionToken(), 'currentUser should have a sessionToken');\n done();\n });\n });", " it('saving user after browser refresh', done => {\n let id;", " Parse.User.signUp('alice', 'password', null)\n .then(function (alice) {\n id = alice.id;\n return Parse.User.logOut();\n })\n .then(() => {\n return Parse.User.logIn('alice', 'password');\n })\n .then(function () {\n // Simulate browser refresh by force-reloading user from localStorage\n Parse.User._clearCache();", " // Test that this save works correctly\n return Parse.User.current().save({ some_field: 1 });\n })\n .then(\n function () {\n // Check the user in memory just after save operation\n const userInMemory = Parse.User.current();", " equal(\n userInMemory.getUsername(),\n 'alice',\n 'saving user should not remove existing fields'\n );", " equal(userInMemory.get('some_field'), 1, 'saving user should save specified field');", " equal(\n userInMemory.get('password'),\n undefined,\n 'password should not be in attributes after saving user'\n );", " equal(\n userInMemory.get('objectId'),\n undefined,\n 'objectId should not be in attributes after saving user'\n );", " equal(\n userInMemory.get('_id'),\n undefined,\n '_id should not be in attributes after saving user'\n );", " equal(userInMemory.id, id, 'id should be set');", " expect(userInMemory.updatedAt instanceof Date).toBe(true);", " ok(userInMemory.createdAt instanceof Date);", " ok(userInMemory.getSessionToken(), 'user should have a sessionToken after saving');", " // Force the current user to read from localStorage, and check again\n delete Parse.User._currentUser;\n delete Parse.User._currentUserMatchesDisk;\n const userFromDisk = Parse.User.current();", " equal(\n userFromDisk.getUsername(),\n 'alice',\n 'userFromDisk should have previously existing fields'\n );", " equal(userFromDisk.get('some_field'), 1, 'userFromDisk should have saved field');", " equal(\n userFromDisk.get('password'),\n undefined,\n 'password should not be in attributes of userFromDisk'\n );", " equal(\n userFromDisk.get('objectId'),\n undefined,\n 'objectId should not be in attributes of userFromDisk'\n );", " equal(\n userFromDisk.get('_id'),\n undefined,\n '_id should not be in attributes of userFromDisk'\n );", " equal(userFromDisk.id, id, 'id should be set on userFromDisk');", " ok(userFromDisk.updatedAt instanceof Date);", " ok(userFromDisk.createdAt instanceof Date);", " ok(userFromDisk.getSessionToken(), 'userFromDisk should have a sessionToken');", " done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('user with missing username', async done => {\n const user = new Parse.User();\n user.set('password', 'foo');\n try {\n await user.signUp();\n done.fail();\n } catch (error) {\n equal(error.code, Parse.Error.OTHER_CAUSE);\n done();\n }\n });", " it('user with missing password', async done => {\n const user = new Parse.User();\n user.set('username', 'foo');\n try {\n await user.signUp();\n done.fail();\n } catch (error) {\n equal(error.code, Parse.Error.OTHER_CAUSE);\n done();\n }\n });", " it('user stupid subclassing', async done => {\n const SuperUser = Parse.Object.extend('User');\n const user = new SuperUser();\n user.set('username', 'bob');\n user.set('password', 'welcome');\n ok(user instanceof Parse.User, 'Subclassing User should have worked');\n await user.signUp();\n done();\n });", " it('user signup class method uses subclassing', async done => {\n const SuperUser = Parse.User.extend({\n secret: function () {\n return 1337;\n },\n });", " const user = await Parse.User.signUp('bob', 'welcome');\n ok(user instanceof SuperUser, 'Subclassing User should have worked');\n equal(user.secret(), 1337);\n done();\n });", " it('user on disk gets updated after save', async done => {\n Parse.User.extend({\n isSuper: function () {\n return true;\n },\n });", " const user = await Parse.User.signUp('bob', 'welcome');\n await user.save('secret', 1337);\n delete Parse.User._currentUser;\n delete Parse.User._currentUserMatchesDisk;", " const userFromDisk = Parse.User.current();\n equal(userFromDisk.get('secret'), 1337);\n ok(userFromDisk.isSuper(), 'The subclass should have been used');\n done();\n });", " it(\"current user isn't dirty\", async done => {\n const user = await Parse.User.signUp('andrew', 'oppa', {\n style: 'gangnam',\n });\n ok(!user.dirty('style'), 'The user just signed up.');\n Parse.User._currentUser = null;\n Parse.User._currentUserMatchesDisk = false;\n const userAgain = Parse.User.current();\n ok(!userAgain.dirty('style'), 'The user was just read from disk.');\n done();\n });", " const getMockFacebookProviderWithIdToken = function (id, token) {\n return {\n authData: {\n id: id,\n access_token: token,\n expiration_date: new Date().toJSON(),\n },\n shouldError: false,\n loggedOut: false,\n synchronizedUserId: null,\n synchronizedAuthToken: null,\n synchronizedExpiration: null,", " authenticate: function (options) {\n if (this.shouldError) {\n options.error(this, 'An error occurred');\n } else if (this.shouldCancel) {\n options.error(this, null);\n } else {\n options.success(this, this.authData);\n }\n },\n restoreAuthentication: function (authData) {\n if (!authData) {\n this.synchronizedUserId = null;\n this.synchronizedAuthToken = null;\n this.synchronizedExpiration = null;\n return true;\n }\n this.synchronizedUserId = authData.id;\n this.synchronizedAuthToken = authData.access_token;\n this.synchronizedExpiration = authData.expiration_date;\n return true;\n },\n getAuthType: function () {\n return 'facebook';\n },\n deauthenticate: function () {\n this.loggedOut = true;\n this.restoreAuthentication(null);\n },\n };\n };", " // Note that this mocks out client-side Facebook action rather than\n // server-side.\n const getMockFacebookProvider = function () {\n return getMockFacebookProviderWithIdToken('8675309', 'jenny');\n };", " const getMockMyOauthProvider = function () {\n return {\n authData: {\n id: '12345',\n access_token: '12345',\n expiration_date: new Date().toJSON(),\n },\n shouldError: false,\n loggedOut: false,\n synchronizedUserId: null,\n synchronizedAuthToken: null,\n synchronizedExpiration: null,", " authenticate: function (options) {\n if (this.shouldError) {\n options.error(this, 'An error occurred');\n } else if (this.shouldCancel) {\n options.error(this, null);\n } else {\n options.success(this, this.authData);\n }\n },\n restoreAuthentication: function (authData) {\n if (!authData) {\n this.synchronizedUserId = null;\n this.synchronizedAuthToken = null;\n this.synchronizedExpiration = null;\n return true;\n }\n this.synchronizedUserId = authData.id;\n this.synchronizedAuthToken = authData.access_token;\n this.synchronizedExpiration = authData.expiration_date;\n return true;\n },\n getAuthType: function () {\n return 'myoauth';\n },\n deauthenticate: function () {\n this.loggedOut = true;\n this.restoreAuthentication(null);\n },\n };\n };", " Parse.User.extend({\n extended: function () {\n return true;\n },\n });", " it('log in with provider', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n done();\n });", " it('can not set authdata to null', async () => {\n try {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n user.set('authData', null);\n await user.save();\n fail();\n } catch (e) {\n expect(e.message).toBe('This authentication method is unsupported.');\n }\n });", " it('ignore setting authdata to undefined', async () => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n user.set('authData', undefined);\n await user.save();\n let authData = user.get('authData');\n expect(authData).toBe(undefined);\n await user.fetch();\n authData = user.get('authData');\n expect(authData.facebook.id).toBeDefined();\n });", " it('user authData should be available in cloudcode (#2342)', async done => {\n Parse.Cloud.define('checkLogin', req => {\n expect(req.user).not.toBeUndefined();\n expect(Parse.FacebookUtils.isLinked(req.user)).toBe(true);\n return 'ok';\n });", " const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');", " Parse.Cloud.run('checkLogin').then(done, done);\n });", " it('log in with provider and update token', async done => {\n const provider = getMockFacebookProvider();\n const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token');\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n Parse.User._registerAuthenticationProvider(secondProvider);\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n expect(secondProvider.synchronizedAuthToken).toEqual('jenny_valid_token');\n // Make sure we can login with the new token again\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n done();\n });", " it('returns authData when authed and logged in with provider (regression test for #1498)', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n const userQuery = new Parse.Query(Parse.User);\n userQuery.get(user.id).then(user => {\n expect(user.get('authData')).not.toBeUndefined();\n done();\n });\n });", " it('only creates a single session for an installation / user pair (#2885)', async done => {\n Parse.Object.disableSingleInstance();\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User.logInWith('facebook');\n await Parse.User.logInWith('facebook');\n const user = await Parse.User.logInWith('facebook');\n const sessionToken = user.getSessionToken();\n const query = new Parse.Query('_Session');\n return query\n .find({ useMasterKey: true })\n .then(results => {\n expect(results.length).toBe(1);\n expect(results[0].get('sessionToken')).toBe(sessionToken);\n expect(results[0].get('createdWith')).toEqual({\n action: 'login',\n authProvider: 'facebook',\n });\n done();\n })\n .catch(done.fail);\n });", " it('log in with provider with files', done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const file = new Parse.File('yolo.txt', [1, 2, 3], 'text/plain');\n file\n .save()\n .then(file => {\n const user = new Parse.User();\n user.set('file', file);\n return user._linkWith('facebook', {});\n })\n .then(user => {\n expect(user._isLinked('facebook')).toBeTruthy();\n return Parse.User._logInWith('facebook', {});\n })\n .then(user => {\n const fileAgain = user.get('file');\n expect(fileAgain.name()).toMatch(/yolo.txt$/);\n expect(fileAgain.url()).toMatch(/yolo.txt$/);\n })\n .then(() => {\n done();\n })\n .catch(done.fail);\n });", " it('log in with provider twice', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');", " Parse.User.logOut().then(async () => {\n ok(provider.loggedOut);\n provider.loggedOut = false;\n const innerModel = await Parse.User._logInWith('facebook');\n ok(innerModel instanceof Parse.User, 'Model should be a Parse.User');\n ok(innerModel === Parse.User.current(), 'Returned model should be the current user');\n ok(provider.authData.id === provider.synchronizedUserId);\n ok(provider.authData.access_token === provider.synchronizedAuthToken);\n ok(innerModel._isLinked('facebook'), 'User should be linked to facebook');\n ok(innerModel.existed(), 'User should not be newly-created');\n done();\n }, done.fail);\n });", " it('log in with provider failed', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldError = true;\n Parse.User._registerAuthenticationProvider(provider);\n try {\n await Parse.User._logInWith('facebook');\n done.fail();\n } catch (error) {\n ok(error, 'Error should be non-null');\n done();\n }\n });", " it('log in with provider cancelled', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldCancel = true;\n Parse.User._registerAuthenticationProvider(provider);\n try {\n await Parse.User._logInWith('facebook');\n done.fail();\n } catch (error) {\n ok(error === null, 'Error should be null');\n done();\n }\n });", " it('login with provider should not call beforeSave trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n Parse.User.logOut().then(async () => {\n Parse.Cloud.beforeSave(Parse.User, function (req, res) {\n res.error(\"Before save shouldn't be called on login\");\n });\n await Parse.User._logInWith('facebook');\n done();\n });\n });", " it('signup with provider should not call beforeLogin trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(() => {\n hit++;\n });", " await Parse.User._logInWith('facebook');\n expect(hit).toBe(0);\n done();\n });", " it('login with provider should call beforeLogin trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(req => {\n hit++;\n expect(req.object.get('authData')).toBeDefined();\n expect(req.object.get('name')).toBe('tupac shakur');\n });\n await Parse.User._logInWith('facebook');\n await Parse.User.current().save({ name: 'tupac shakur' });\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n expect(hit).toBe(1);\n done();\n });", " it('incorrect login with provider should not call beforeLogin trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(() => {\n hit++;\n });\n await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n provider.shouldError = true;\n try {\n await Parse.User._logInWith('facebook');\n } catch (e) {\n expect(e).toBeDefined();\n }\n expect(hit).toBe(0);\n done();\n });", " it('login with provider should be blockable by beforeLogin', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(req => {\n hit++;\n if (req.object.get('isBanned')) {\n throw new Error('banned account');\n }\n });\n await Parse.User._logInWith('facebook');\n await Parse.User.current().save({ isBanned: true });\n await Parse.User.logOut();", " try {\n await Parse.User._logInWith('facebook');\n throw new Error('should not have continued login.');\n } catch (e) {\n expect(e.message).toBe('banned account');\n }", " expect(hit).toBe(1);\n done();\n });", " it('login with provider should be blockable by beforeLogin even when the user has a attached file', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let hit = 0;\n Parse.Cloud.beforeLogin(req => {\n hit++;\n if (req.object.get('isBanned')) {\n throw new Error('banned account');\n }\n });", " const user = await Parse.User._logInWith('facebook');\n const base64 = 'aHR0cHM6Ly9naXRodWIuY29tL2t2bmt1YW5n';\n const file = new Parse.File('myfile.txt', { base64 });\n await file.save();\n await user.save({ isBanned: true, file });\n await Parse.User.logOut();", " try {\n await Parse.User._logInWith('facebook');\n throw new Error('should not have continued login.');\n } catch (e) {\n expect(e.message).toBe('banned account');\n }", " expect(hit).toBe(1);\n done();\n });", " it('logout with provider should call afterLogout trigger', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);", " let userId;\n Parse.Cloud.afterLogout(req => {\n expect(req.object.className).toEqual('_Session');\n expect(req.object.id).toBeDefined();\n const user = req.object.get('user');\n expect(user).toBeDefined();\n userId = user.id;\n });\n const user = await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n expect(user.id).toBe(userId);\n done();\n });", " it('link with provider', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n const model = await user._linkWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked');\n done();\n });", " // What this means is, only one Parse User can be linked to a\n // particular Facebook account.\n it('link with provider for already linked user', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProviderToAlreadyLinkedUser');\n user.set('password', 'mypass');\n await user.signUp();\n const model = await user._linkWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked.');\n const user2 = new Parse.User();\n user2.set('username', 'testLinkWithProviderToAlreadyLinkedUser2');\n user2.set('password', 'mypass');\n await user2.signUp();\n try {\n await user2._linkWith('facebook');\n done.fail();\n } catch (error) {\n expect(error.code).toEqual(Parse.Error.ACCOUNT_ALREADY_LINKED);\n done();\n }\n });", " it('link with provider should return sessionToken', async () => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n const query = new Parse.Query(Parse.User);\n const u2 = await query.get(user.id);\n const model = await u2._linkWith('facebook', {}, { useMasterKey: true });\n expect(u2.getSessionToken()).toBeDefined();\n expect(model.getSessionToken()).toBeDefined();\n expect(u2.getSessionToken()).toBe(model.getSessionToken());\n });", " it('link with provider via sessionToken should not create new sessionToken (Regression #5799)', async () => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProviderNoOverride');\n user.set('password', 'mypass');\n await user.signUp();\n const sessionToken = user.getSessionToken();", " await user._linkWith('facebook', {}, { sessionToken });\n expect(sessionToken).toBe(user.getSessionToken());", " expect(user._isLinked(provider)).toBe(true);\n await user._unlinkFrom(provider, { sessionToken });\n expect(user._isLinked(provider)).toBe(false);", " const become = await Parse.User.become(sessionToken);\n expect(sessionToken).toBe(become.getSessionToken());\n });", " it('link with provider failed', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldError = true;\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n try {\n await user._linkWith('facebook');\n done.fail();\n } catch (error) {\n ok(error, 'Linking should fail');\n ok(!user._isLinked('facebook'), 'User should not be linked to facebook');\n done();\n }\n });", " it('link with provider cancelled', async done => {\n const provider = getMockFacebookProvider();\n provider.shouldCancel = true;\n Parse.User._registerAuthenticationProvider(provider);\n const user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n try {\n await user._linkWith('facebook');\n done.fail();\n } catch (error) {\n ok(!error, 'Linking should be cancelled');\n ok(!user._isLinked('facebook'), 'User should not be linked to facebook');\n done();\n }\n });", " it('unlink with provider', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User.');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook.');\n await model._unlinkFrom('facebook');\n ok(!model._isLinked('facebook'), 'User should not be linked.');\n ok(!provider.synchronizedUserId, 'User id should be cleared.');\n ok(!provider.synchronizedAuthToken, 'Auth token should be cleared.');\n ok(!provider.synchronizedExpiration, 'Expiration should be cleared.');\n done();\n });", " it('unlink and link', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');", " await model._unlinkFrom('facebook');\n ok(!model._isLinked('facebook'), 'User should not be linked to facebook');\n ok(!provider.synchronizedUserId, 'User id should be cleared');\n ok(!provider.synchronizedAuthToken, 'Auth token should be cleared');\n ok(!provider.synchronizedExpiration, 'Expiration should be cleared');", " await model._linkWith('facebook');\n ok(provider.synchronizedUserId, 'User id should have a value');\n ok(provider.synchronizedAuthToken, 'Auth token should have a value');\n ok(provider.synchronizedExpiration, 'Expiration should have a value');\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n done();\n });", " it('link multiple providers', async done => {\n const provider = getMockFacebookProvider();\n const mockProvider = getMockMyOauthProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n Parse.User._registerAuthenticationProvider(mockProvider);\n const objectId = model.id;\n await model._linkWith('myoauth');\n expect(model.id).toEqual(objectId);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n ok(model._isLinked('myoauth'), 'User should be linked to myoauth');\n done();\n });", " it('link multiple providers and updates token', async done => {\n const provider = getMockFacebookProvider();\n const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token');", " const mockProvider = getMockMyOauthProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n Parse.User._registerAuthenticationProvider(mockProvider);\n const objectId = model.id;\n await model._linkWith('myoauth');\n Parse.User._registerAuthenticationProvider(secondProvider);\n await Parse.User.logOut();\n await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n const user = await Parse.User._logInWith('myoauth');\n expect(user.id).toBe(objectId);\n done();\n });", " it('link multiple providers and update token', async done => {\n const provider = getMockFacebookProvider();\n const mockProvider = getMockMyOauthProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used the subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n Parse.User._registerAuthenticationProvider(mockProvider);\n const objectId = model.id;\n await model._linkWith('myoauth');\n expect(model.id).toEqual(objectId);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n ok(model._isLinked('myoauth'), 'User should be linked to myoauth');\n await model._linkWith('facebook');\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n ok(model._isLinked('myoauth'), 'User should be linked to myoauth');\n done();\n });", " it('should fail linking with existing', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n await Parse.User.logOut();\n const user = new Parse.User();\n user.setUsername('user');\n user.setPassword('password');\n await user.signUp();\n // try to link here\n try {\n await user._linkWith('facebook');\n done.fail();\n } catch (e) {\n done();\n }\n });", " it('should fail linking with existing through REST', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook');\n const userId = model.id;\n Parse.User.logOut().then(() => {\n request({\n method: 'POST',\n url: Parse.serverURL + '/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: { authData: { facebook: provider.authData } },\n }).then(response => {\n const body = response.data;\n // make sure the location header is properly set\n expect(userId).not.toBeUndefined();\n expect(body.objectId).toEqual(userId);\n expect(response.headers.location).toEqual(Parse.serverURL + '/users/' + userId);\n done();\n });\n });\n });", " it('should allow login with old authData token', done => {\n const provider = {\n authData: {\n id: '12345',\n access_token: 'token',\n },\n restoreAuthentication: function () {\n return true;\n },\n deauthenticate: function () {\n provider.authData = {};\n },\n authenticate: function (options) {\n options.success(this, provider.authData);\n },\n getAuthType: function () {\n return 'shortLivedAuth';\n },\n };\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('token');\n Parse.User._registerAuthenticationProvider(provider);\n Parse.User._logInWith('shortLivedAuth', {})\n .then(() => {\n // Simulate a remotely expired token (like a short lived one)\n // In this case, we want success as it was valid once.\n // If the client needs an updated one, do lock the user out\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('otherToken');\n return Parse.User._logInWith('shortLivedAuth', {});\n })\n .then(\n () => {\n done();\n },\n err => {\n done.fail(err);\n }\n );\n });", " it('should allow PUT request with stale auth Data', done => {\n const provider = {\n authData: {\n id: '12345',\n access_token: 'token',\n },\n restoreAuthentication: function () {\n return true;\n },\n deauthenticate: function () {\n provider.authData = {};\n },\n authenticate: function (options) {\n options.success(this, provider.authData);\n },\n getAuthType: function () {\n return 'shortLivedAuth';\n },\n };\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('token');\n Parse.User._registerAuthenticationProvider(provider);\n Parse.User._logInWith('shortLivedAuth', {})\n .then(() => {\n // Simulate a remotely expired token (like a short lived one)\n // In this case, we want success as it was valid once.\n // If the client needs an updated one, do lock the user out\n defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('otherToken');\n return request({\n method: 'PUT',\n url: Parse.serverURL + '/users/' + Parse.User.current().id,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Javascript-Key': Parse.javaScriptKey,\n 'X-Parse-Session-Token': Parse.User.current().getSessionToken(),\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'value', // update a key\n authData: {\n // pass the original auth data\n shortLivedAuth: {\n id: '12345',\n access_token: 'token',\n },\n },\n },\n });\n })\n .then(\n () => {\n done();\n },\n err => {\n done.fail(err);\n }\n );\n });", " it('should properly error when password is missing', async done => {\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const user = await Parse.User._logInWith('facebook');\n user.set('username', 'myUser');\n user.set('email', 'foo@example.com');\n user\n .save()\n .then(() => {\n return Parse.User.logOut();\n })\n .then(() => {\n return Parse.User.logIn('myUser', 'password');\n })\n .then(\n () => {\n fail('should not succeed');\n done();\n },\n err => {\n expect(err.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n expect(err.message).toEqual('Invalid username/password.');\n done();\n }\n );\n });", " it('should have authData in beforeSave and afterSave', async done => {\n Parse.Cloud.beforeSave('_User', request => {\n const authData = request.object.get('authData');\n expect(authData).not.toBeUndefined();\n if (authData) {\n expect(authData.facebook.id).toEqual('8675309');\n expect(authData.facebook.access_token).toEqual('jenny');\n } else {\n fail('authData should be set');\n }\n });", " Parse.Cloud.afterSave('_User', request => {\n const authData = request.object.get('authData');\n expect(authData).not.toBeUndefined();\n if (authData) {\n expect(authData.facebook.id).toEqual('8675309');\n expect(authData.facebook.access_token).toEqual('jenny');\n } else {\n fail('authData should be set');\n }\n });", " const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n await Parse.User._logInWith('facebook');\n done();\n });", " it('set password then change password', done => {\n Parse.User.signUp('bob', 'barker')\n .then(bob => {\n bob.setPassword('meower');\n return bob.save();\n })\n .then(() => {\n return Parse.User.logIn('bob', 'meower');\n })\n .then(\n bob => {\n expect(bob.getUsername()).toEqual('bob');\n done();\n },\n e => {\n console.log(e);\n fail();\n }\n );\n });", " it('authenticated check', async done => {\n const user = new Parse.User();\n user.set('username', 'darkhelmet');\n user.set('password', 'onetwothreefour');\n ok(!user.authenticated());\n await user.signUp(null);\n ok(user.authenticated());\n done();\n });", " it('log in with explicit facebook auth data', async done => {\n await Parse.FacebookUtils.logIn({\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n });\n done();\n });", " it('log in async with explicit facebook auth data', done => {\n Parse.FacebookUtils.logIn({\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(\n function () {\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('link with explicit facebook auth data', async done => {\n const user = await Parse.User.signUp('mask', 'open sesame');\n Parse.FacebookUtils.link(user, {\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(done, error => {\n jfail(error);\n done();\n });\n });", " it('link async with explicit facebook auth data', async done => {\n const user = await Parse.User.signUp('mask', 'open sesame');\n Parse.FacebookUtils.link(user, {\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(\n function () {\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('async methods', done => {\n const data = { foo: 'bar' };", " Parse.User.signUp('finn', 'human', data)\n .then(function (user) {\n equal(Parse.User.current(), user);\n equal(user.get('foo'), 'bar');\n return Parse.User.logOut();\n })\n .then(function () {\n return Parse.User.logIn('finn', 'human');\n })\n .then(function (user) {\n equal(user, Parse.User.current());\n equal(user.get('foo'), 'bar');\n return Parse.User.logOut();\n })\n .then(function () {\n const user = new Parse.User();\n user.set('username', 'jake');\n user.set('password', 'dog');\n user.set('foo', 'baz');\n return user.signUp();\n })\n .then(function (user) {\n equal(user, Parse.User.current());\n equal(user.get('foo'), 'baz');\n user = new Parse.User();\n user.set('username', 'jake');\n user.set('password', 'dog');\n return user.logIn();\n })\n .then(function (user) {\n equal(user, Parse.User.current());\n equal(user.get('foo'), 'baz');\n const userAgain = new Parse.User();\n userAgain.id = user.id;\n return userAgain.fetch();\n })\n .then(function (userAgain) {\n equal(userAgain.get('foo'), 'baz');\n done();\n });\n });", " it(\"querying for users doesn't get session tokens\", done => {\n Parse.User.signUp('finn', 'human', { foo: 'bar' })\n .then(function () {\n return Parse.User.logOut();\n })\n .then(() => {\n const user = new Parse.User();\n user.set('username', 'jake');\n user.set('password', 'dog');\n user.set('foo', 'baz');\n return user.signUp();\n })\n .then(function () {\n return Parse.User.logOut();\n })\n .then(() => {\n const query = new Parse.Query(Parse.User);\n return query.find({ sessionToken: null });\n })\n .then(\n function (users) {\n equal(users.length, 2);\n users.forEach(user => {\n expect(user.getSessionToken()).toBeUndefined();\n ok(!user.getSessionToken(), 'user should not have a session token.');\n });\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('querying for users only gets the expected fields', done => {\n Parse.User.signUp('finn', 'human', { foo: 'bar' }).then(() => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/users',\n }).then(response => {\n const b = response.data;\n expect(b.results.length).toEqual(1);\n const user = b.results[0];\n expect(Object.keys(user).length).toEqual(6);\n done();\n });\n });\n });", " it(\"retrieve user data from fetch, make sure the session token hasn't changed\", done => {\n const user = new Parse.User();\n user.setPassword('asdf');\n user.setUsername('zxcv');\n let currentSessionToken = '';\n Promise.resolve()\n .then(function () {\n return user.signUp();\n })\n .then(function () {\n currentSessionToken = user.getSessionToken();\n return user.fetch();\n })\n .then(\n function (u) {\n expect(currentSessionToken).toEqual(u.getSessionToken());\n done();\n },\n function (error) {\n ok(false, error);\n done();\n }\n );\n });", " it('user save should fail with invalid email', done => {\n const user = new Parse.User();\n user.set('username', 'teste');\n user.set('password', 'test');\n user.set('email', 'invalid');\n user.signUp().then(\n () => {\n fail('Should not have been able to save.');\n done();\n },\n error => {\n expect(error.code).toEqual(125);\n done();\n }\n );\n });", " it('user signup should error if email taken', done => {\n const user = new Parse.User();\n user.set('username', 'test1');\n user.set('password', 'test');\n user.set('email', 'test@test.com');\n user\n .signUp()\n .then(() => {\n const user2 = new Parse.User();\n user2.set('username', 'test2');\n user2.set('password', 'test');\n user2.set('email', 'test@test.com');\n return user2.signUp();\n })\n .then(\n () => {\n fail('Should not have been able to sign up.');\n done();\n },\n () => {\n done();\n }\n );\n });", " describe('case insensitive signup not allowed', () => {\n it('signup should fail with duplicate case insensitive username with basic setter', async () => {\n const user = new Parse.User();\n user.set('username', 'test1');\n user.set('password', 'test');\n await user.signUp();", " const user2 = new Parse.User();\n user2.set('username', 'Test1');\n user2.set('password', 'test');\n await expectAsync(user2.signUp()).toBeRejectedWith(\n new Parse.Error(Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.')\n );\n });", " it('signup should fail with duplicate case insensitive username with field specific setter', async () => {\n const user = new Parse.User();\n user.setUsername('test1');\n user.setPassword('test');\n await user.signUp();", " const user2 = new Parse.User();\n user2.setUsername('Test1');\n user2.setPassword('test');\n await expectAsync(user2.signUp()).toBeRejectedWith(\n new Parse.Error(Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.')\n );\n });", " it('signup should fail with duplicate case insensitive email', async () => {\n const user = new Parse.User();\n user.setUsername('test1');\n user.setPassword('test');\n user.setEmail('test@example.com');\n await user.signUp();", " const user2 = new Parse.User();\n user2.setUsername('test2');\n user2.setPassword('test');\n user2.setEmail('Test@Example.Com');\n await expectAsync(user2.signUp()).toBeRejectedWith(\n new Parse.Error(Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.')\n );\n });", " it('edit should fail with duplicate case insensitive email', async () => {\n const user = new Parse.User();\n user.setUsername('test1');\n user.setPassword('test');\n user.setEmail('test@example.com');\n await user.signUp();", " const user2 = new Parse.User();\n user2.setUsername('test2');\n user2.setPassword('test');\n user2.setEmail('Foo@Example.Com');\n await user2.signUp();", " user2.setEmail('Test@Example.Com');\n await expectAsync(user2.save()).toBeRejectedWith(\n new Parse.Error(Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.')\n );\n });", " describe('anonymous users', () => {\n beforeEach(() => {\n const insensitiveCollisions = [\n 'abcdefghijklmnop',\n 'Abcdefghijklmnop',\n 'ABcdefghijklmnop',\n 'ABCdefghijklmnop',\n 'ABCDefghijklmnop',\n 'ABCDEfghijklmnop',\n 'ABCDEFghijklmnop',\n 'ABCDEFGhijklmnop',\n 'ABCDEFGHijklmnop',\n 'ABCDEFGHIjklmnop',\n 'ABCDEFGHIJklmnop',\n 'ABCDEFGHIJKlmnop',\n 'ABCDEFGHIJKLmnop',\n 'ABCDEFGHIJKLMnop',\n 'ABCDEFGHIJKLMnop',\n 'ABCDEFGHIJKLMNop',\n 'ABCDEFGHIJKLMNOp',\n 'ABCDEFGHIJKLMNOP',\n ];", " // need a bunch of spare random strings per api request\n spyOn(cryptoUtils, 'randomString').and.returnValues(...insensitiveCollisions);\n });", " it('should not fail on case insensitive matches', async () => {\n const user1 = await Parse.AnonymousUtils.logIn();\n const username1 = user1.get('username');", " const user2 = await Parse.AnonymousUtils.logIn();\n const username2 = user2.get('username');", " expect(username1).not.toBeUndefined();\n expect(username2).not.toBeUndefined();\n expect(username1.toLowerCase()).toBe('abcdefghijklmnop');\n expect(username2.toLowerCase()).toBe('abcdefghijklmnop');\n expect(username2).not.toBe(username1);\n expect(username2.toLowerCase()).toBe(username1.toLowerCase()); // this is redundant :).\n });\n });\n });", " it('user cannot update email to existing user', done => {\n const user = new Parse.User();\n user.set('username', 'test1');\n user.set('password', 'test');\n user.set('email', 'test@test.com');\n user\n .signUp()\n .then(() => {\n const user2 = new Parse.User();\n user2.set('username', 'test2');\n user2.set('password', 'test');\n return user2.signUp();\n })\n .then(user2 => {\n user2.set('email', 'test@test.com');\n return user2.save();\n })\n .then(\n () => {\n fail('Should not have been able to sign up.');\n done();\n },\n () => {\n done();\n }\n );\n });", " it('unset user email', done => {\n const user = new Parse.User();\n user.set('username', 'test');\n user.set('password', 'test');\n user.set('email', 'test@test.com');\n user\n .signUp()\n .then(() => {\n user.unset('email');\n return user.save();\n })\n .then(() => {\n return Parse.User.logIn('test', 'test');\n })\n .then(user => {\n expect(user.getEmail()).toBeUndefined();\n done();\n });\n });", " it('create session from user', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n method: 'POST',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n expect(typeof b.sessionToken).toEqual('string');\n expect(typeof b.createdWith).toEqual('object');\n expect(b.createdWith.action).toEqual('create');\n expect(typeof b.user).toEqual('object');\n expect(b.user.objectId).toEqual(user.id);\n done();\n });\n });\n });\n", " it('user get session from token on signup', async () => {\n const user = await Parse.User.signUp('finn', 'human', { foo: 'bar' });\n const response = await request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n });\n const data = response.data;\n expect(typeof data.sessionToken).toEqual('string');\n expect(typeof data.createdWith).toEqual('object');\n expect(data.createdWith.action).toEqual('signup');\n expect(data.createdWith.authProvider).toEqual('password');\n expect(typeof data.user).toEqual('object');\n expect(data.user.objectId).toEqual(user.id);\n });", " it('user get session from token on username/password login', async () => {\n await Parse.User.signUp('finn', 'human', { foo: 'bar' });\n await Parse.User.logOut();\n const user = await Parse.User.logIn('finn', 'human');\n const response = await request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n });\n const data = response.data;\n expect(typeof data.sessionToken).toEqual('string');\n expect(typeof data.createdWith).toEqual('object');\n expect(data.createdWith.action).toEqual('login');\n expect(data.createdWith.authProvider).toEqual('password');\n expect(typeof data.user).toEqual('object');\n expect(data.user.objectId).toEqual(user.id);\n });", " it('user get session from token on anonymous login', async () => {\n const user = await Parse.AnonymousUtils.logIn();\n const response = await request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n });\n const data = response.data;\n expect(typeof data.sessionToken).toEqual('string');\n expect(typeof data.createdWith).toEqual('object');\n expect(data.createdWith.action).toEqual('login');\n expect(data.createdWith.authProvider).toEqual('anonymous');\n expect(typeof data.user).toEqual('object');\n expect(data.user.objectId).toEqual(user.id);", " });", " it('user update session with other field', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n }).then(response => {\n const b = response.data;\n request({\n method: 'PUT',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + b.objectId,\n body: JSON.stringify({ foo: 'bar' }),\n }).then(() => {\n done();\n });\n });\n });\n });", " it('cannot update session if invalid or no session token', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('finn', 'human', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/me',\n }).then(response => {\n const b = response.data;\n request({\n method: 'PUT',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': 'foo',\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n url: 'http://localhost:8378/1/sessions/' + b.objectId,\n body: JSON.stringify({ foo: 'bar' }),\n }).then(fail, response => {\n const b = response.data;\n expect(b.error).toBe('Invalid session token');\n request({\n method: 'PUT',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + b.objectId,\n body: JSON.stringify({ foo: 'bar' }),\n }).then(fail, response => {\n const b = response.data;\n expect(b.error).toBe('Session token required.');\n done();\n });\n });\n });\n });\n });", " it('get session only for current user', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('test1', 'test', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.signUp('test2', 'test', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n expect(b.results.length).toEqual(1);\n expect(typeof b.results[0].user).toEqual('object');\n expect(b.results[0].user.objectId).toEqual(user.id);\n done();\n });\n });\n });", " it('delete session by object', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('test1', 'test', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.signUp('test2', 'test', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n let objId;\n try {\n expect(b.results.length).toEqual(1);\n objId = b.results[0].objectId;\n } catch (e) {\n jfail(e);\n done();\n return;\n }\n request({\n method: 'DELETE',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + objId,\n }).then(() => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(fail, response => {\n const b = response.data;\n expect(b.code).toEqual(209);\n expect(b.error).toBe('Invalid session token');\n done();\n });\n });\n });\n });\n });", " it('cannot delete session if no sessionToken', done => {\n Promise.resolve()\n .then(() => {\n return Parse.User.signUp('test1', 'test', { foo: 'bar' });\n })\n .then(() => {\n return Parse.User.signUp('test2', 'test', { foo: 'bar' });\n })\n .then(user => {\n request({\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Session-Token': user.getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions',\n }).then(response => {\n const b = response.data;\n expect(b.results.length).toEqual(1);\n const objId = b.results[0].objectId;\n request({\n method: 'DELETE',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-REST-API-Key': 'rest',\n },\n url: 'http://localhost:8378/1/sessions/' + objId,\n }).then(fail, response => {\n const b = response.data;\n expect(b.code).toEqual(209);\n expect(b.error).toBe('Invalid session token');\n done();\n });\n });\n });\n });", " it('password format matches hosted parse', done => {\n const hashed = '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie';\n passwordCrypto.compare('test', hashed).then(\n pass => {\n expect(pass).toBe(true);\n done();\n },\n () => {\n fail('Password format did not match.');\n done();\n }\n );\n });", " it('changing password clears sessions', done => {\n let sessionToken = null;", " Promise.resolve()\n .then(function () {\n return Parse.User.signUp('fosco', 'parse');\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);\n sessionToken = newUser.getSessionToken();\n ok(sessionToken);\n newUser.set('password', 'facebook');\n return newUser.save();\n })\n .then(function () {\n return Parse.User.become(sessionToken);\n })\n .then(\n function () {\n fail('Session should have been invalidated');\n done();\n },\n function (err) {\n expect(err.code).toBe(Parse.Error.INVALID_SESSION_TOKEN);\n expect(err.message).toBe('Invalid session token');\n done();\n }\n );\n });", " it('test parse user become', done => {\n let sessionToken = null;\n Promise.resolve()\n .then(function () {\n return Parse.User.signUp('flessard', 'folo', { foo: 1 });\n })\n .then(function (newUser) {\n equal(Parse.User.current(), newUser);\n sessionToken = newUser.getSessionToken();\n ok(sessionToken);\n newUser.set('foo', 2);\n return newUser.save();\n })\n .then(function () {\n return Parse.User.become(sessionToken);\n })\n .then(\n function (newUser) {\n equal(newUser.get('foo'), 2);\n done();\n },\n function () {\n fail('The session should still be valid');\n done();\n }\n );\n });", " it('ensure logout works', done => {\n let user = null;\n let sessionToken = null;", " Promise.resolve()\n .then(function () {\n return Parse.User.signUp('log', 'out');\n })\n .then(newUser => {\n user = newUser;\n sessionToken = user.getSessionToken();\n return Parse.User.logOut();\n })\n .then(() => {\n user.set('foo', 'bar');\n return user.save(null, { sessionToken: sessionToken });\n })\n .then(\n () => {\n fail('Save should have failed.');\n done();\n },\n e => {\n expect(e.code).toEqual(Parse.Error.INVALID_SESSION_TOKEN);\n done();\n }\n );\n });", " it('support user/password signup with empty authData block', done => {\n // The android SDK can send an empty authData object along with username and password.\n Parse.User.signUp('artof', 'thedeal', { authData: {} }).then(\n () => {\n done();\n },\n () => {\n fail('Signup should have succeeded.');\n done();\n }\n );\n });", " it('session expiresAt correct format', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n url: 'http://localhost:8378/1/classes/_Session',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n },\n }).then(response => {\n const body = response.data;\n expect(body.results[0].expiresAt.__type).toEqual('Date');\n done();\n });\n });", " it('Invalid session tokens are rejected', async done => {\n await Parse.User.signUp('asdf', 'zxcv');\n request({\n url: 'http://localhost:8378/1/classes/AClass',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Rest-API-Key': 'rest',\n 'X-Parse-Session-Token': 'text',\n },\n }).then(fail, response => {\n const body = response.data;\n expect(body.code).toBe(209);\n expect(body.error).toBe('Invalid session token');\n done();\n });\n });", " it_exclude_dbs(['postgres'])(\n 'should cleanup null authData keys (regression test for #935)',\n done => {\n const database = Config.get(Parse.applicationId).database;\n database\n .create(\n '_User',\n {\n username: 'user',\n _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',\n _auth_data_facebook: null,\n },\n {}\n )\n .then(() => {\n return request({\n url: 'http://localhost:8378/1/login?username=user&password=test',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n },\n }).then(res => res.data);\n })\n .then(user => {\n const authData = user.authData;\n expect(user.username).toEqual('user');\n expect(authData).toBeUndefined();\n done();\n })\n .catch(() => {\n fail('this should not fail');\n done();\n });\n }\n );", " it_exclude_dbs(['postgres'])('should not serve null authData keys', done => {\n const database = Config.get(Parse.applicationId).database;\n database\n .create(\n '_User',\n {\n username: 'user',\n _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',\n _auth_data_facebook: null,\n },\n {}\n )\n .then(() => {\n return new Parse.Query(Parse.User)\n .equalTo('username', 'user')\n .first({ useMasterKey: true });\n })\n .then(user => {\n const authData = user.get('authData');\n expect(user.get('username')).toEqual('user');\n expect(authData).toBeUndefined();\n done();\n })\n .catch(() => {\n fail('this should not fail');\n done();\n });\n });", " it('should cleanup null authData keys ParseUser update (regression test for #1198, #2252)', done => {\n Parse.Cloud.beforeSave('_User', req => {\n req.object.set('foo', 'bar');\n });", " let originalSessionToken;\n let originalUserId;\n // Simulate anonymous user save\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n })\n .then(response => response.data)\n .then(user => {\n originalSessionToken = user.sessionToken;\n originalUserId = user.objectId;\n // Simulate registration\n return request({\n method: 'PUT',\n url: 'http://localhost:8378/1/classes/_User/' + user.objectId,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: { anonymous: null },\n username: 'user',\n password: 'password',\n },\n }).then(response => {\n return response.data;\n });\n })\n .then(user => {\n expect(typeof user).toEqual('object');\n expect(user.authData).toBeUndefined();\n expect(user.sessionToken).not.toBeUndefined();\n // Session token should have changed\n expect(user.sessionToken).not.toEqual(originalSessionToken);\n // test that the sessionToken is valid\n return request({\n url: 'http://localhost:8378/1/users/me',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n }).then(response => {\n const body = response.data;\n expect(body.username).toEqual('user');\n expect(body.objectId).toEqual(originalUserId);\n done();\n });\n })\n .catch(err => {\n fail('no request should fail: ' + JSON.stringify(err));\n done();\n });\n });", " it('should send email when upgrading from anon', done => {\n let emailCalled = false;\n let emailOptions;\n const emailAdapter = {\n sendVerificationEmail: options => {\n emailOptions = options;\n emailCalled = true;\n },\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };\n reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n });\n // Simulate anonymous user save\n return request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n })\n .then(response => {\n const user = response.data;\n return request({\n method: 'PUT',\n url: 'http://localhost:8378/1/classes/_User/' + user.objectId,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: { anonymous: null },\n username: 'user',\n email: 'user@email.com',\n password: 'password',\n },\n });\n })\n .then(() => {\n expect(emailCalled).toBe(true);\n expect(emailOptions).not.toBeUndefined();\n expect(emailOptions.user.get('email')).toEqual('user@email.com');\n done();\n })\n .catch(err => {\n jfail(err);\n fail('no request should fail: ' + JSON.stringify(err));\n done();\n });\n });", " it('should not send email when email is not a string', async done => {\n let emailCalled = false;\n let emailOptions;\n const emailAdapter = {\n sendVerificationEmail: options => {\n emailOptions = options;\n emailCalled = true;\n },\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };\n await reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n });\n const user = new Parse.User();\n user.set('username', 'asdf@jkl.com');\n user.set('password', 'zxcv');\n user.set('email', 'asdf@jkl.com');\n await user.signUp();\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/requestPasswordReset',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': user.sessionToken,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n email: { $regex: '^asd' },\n },\n })\n .then(res => {\n fail('no request should succeed: ' + JSON.stringify(res));\n done();\n })\n .catch(err => {\n expect(emailCalled).toBeTruthy();\n expect(emailOptions).toBeDefined();\n expect(err.status).toBe(400);\n expect(err.text).toMatch('{\"code\":125,\"error\":\"you must provide a valid email string\"}');\n done();\n });\n });", " it('should aftersave with full object', done => {\n let hit = 0;\n Parse.Cloud.afterSave('_User', (req, res) => {\n hit++;\n expect(req.object.get('username')).toEqual('User');\n res.success();\n });\n const user = new Parse.User();\n user.setUsername('User');\n user.setPassword('pass');\n user\n .signUp()\n .then(() => {\n user.set('hello', 'world');\n return user.save();\n })\n .then(() => {\n expect(hit).toBe(2);\n done();\n });\n });", " it('changes to a user should update the cache', done => {\n Parse.Cloud.define('testUpdatedUser', req => {\n expect(req.user.get('han')).toEqual('solo');\n return {};\n });\n const user = new Parse.User();\n user.setUsername('harrison');\n user.setPassword('ford');\n user\n .signUp()\n .then(() => {\n user.set('han', 'solo');\n return user.save();\n })\n .then(() => {\n return Parse.Cloud.run('testUpdatedUser');\n })\n .then(\n () => {\n done();\n },\n () => {\n fail('Should not have failed.');\n done();\n }\n );\n });", " it('should fail to become user with expired token', done => {\n let token;\n Parse.User.signUp('auser', 'somepass', null)\n .then(() =>\n request({\n method: 'GET',\n url: 'http://localhost:8378/1/classes/_Session',\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n },\n })\n )\n .then(response => {\n const body = response.data;\n const id = body.results[0].objectId;\n const expiresAt = new Date(new Date().setYear(2015));\n token = body.results[0].sessionToken;\n return request({\n method: 'PUT',\n url: 'http://localhost:8378/1/classes/_Session/' + id,\n headers: {\n 'X-Parse-Application-Id': 'test',\n 'X-Parse-Master-Key': 'test',\n 'Content-Type': 'application/json',\n },\n body: {\n expiresAt: { __type: 'Date', iso: expiresAt.toISOString() },\n },\n });\n })\n .then(() => Parse.User.become(token))\n .then(\n () => {\n fail('Should not have succeded');\n done();\n },\n error => {\n expect(error.code).toEqual(209);\n expect(error.message).toEqual('Session token is expired.');\n done();\n }\n )\n .catch(done.fail);\n });", " it('should not create extraneous session tokens', done => {\n const config = Config.get(Parse.applicationId);\n config.database\n .loadSchema()\n .then(s => {\n // Lock down the _User class for creation\n return s.addClassIfNotExists('_User', {}, { create: {} });\n })\n .then(() => {\n const user = new Parse.User();\n return user.save({ username: 'user', password: 'pass' });\n })\n .then(\n () => {\n fail('should not be able to save the user');\n },\n () => {\n return Promise.resolve();\n }\n )\n .then(() => {\n const q = new Parse.Query('_Session');\n return q.find({ useMasterKey: true });\n })\n .then(\n res => {\n // We should have no session created\n expect(res.length).toBe(0);\n done();\n },\n () => {\n fail('should not fail');\n done();\n }\n );\n });", " it('should not overwrite username when unlinking facebook user (regression test for #1532)', async done => {\n Parse.Object.disableSingleInstance();\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n let user = new Parse.User();\n user.set('username', 'testLinkWithProvider');\n user.set('password', 'mypass');\n await user.signUp();\n await user._linkWith('facebook');\n expect(user.get('username')).toEqual('testLinkWithProvider');\n expect(Parse.FacebookUtils.isLinked(user)).toBeTruthy();\n await user._unlinkFrom('facebook');\n user = await user.fetch();\n expect(user.get('username')).toEqual('testLinkWithProvider');\n expect(Parse.FacebookUtils.isLinked(user)).toBeFalsy();\n done();\n });", " it('should revoke sessions when converting anonymous user to \"normal\" user', done => {\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n }).then(response => {\n const body = response.data;\n Parse.User.become(body.sessionToken).then(user => {\n const obj = new Parse.Object('TestObject');\n obj.setACL(new Parse.ACL(user));\n return obj\n .save()\n .then(() => {\n // Change password, revoking session\n user.set('username', 'no longer anonymous');\n user.set('password', 'password');\n return user.save();\n })\n .then(() => {\n // Session token should have been recycled\n expect(body.sessionToken).not.toEqual(user.getSessionToken());\n })\n .then(() => obj.fetch())\n .then(() => {\n done();\n })\n .catch(() => {\n fail('should not fail');\n done();\n });\n });\n });\n });", " it('should not revoke session tokens if the server is configures to not revoke session tokens', done => {\n reconfigureServer({ revokeSessionOnPasswordReset: false }).then(() => {\n request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n }).then(response => {\n const body = response.data;\n Parse.User.become(body.sessionToken).then(user => {\n const obj = new Parse.Object('TestObject');\n obj.setACL(new Parse.ACL(user));\n return (\n obj\n .save()\n .then(() => {\n // Change password, revoking session\n user.set('username', 'no longer anonymous');\n user.set('password', 'password');\n return user.save();\n })\n .then(() => obj.fetch())\n // fetch should succeed as we still have our session token\n .then(done, fail)\n );\n });\n });\n });\n });", " it('should not fail querying non existing relations', done => {\n const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n });\n user\n .signUp()\n .then(() => {\n return Parse.User.current().relation('relation').query().find();\n })\n .then(res => {\n expect(res.length).toBe(0);\n done();\n })\n .catch(err => {\n fail(JSON.stringify(err));\n done();\n });\n });", " it('should not allow updates to emailVerified', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() => {\n return Parse.User.current().set('emailVerified', true).save();\n })\n .then(() => {\n fail('Should not be able to update emailVerified');\n done();\n })\n .catch(err => {\n expect(err.message).toBe(\"Clients aren't allowed to manually update email verification.\");\n done();\n });\n });", " it('should not retrieve hidden fields on GET users/me (#3432)', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() =>\n request({\n method: 'GET',\n url: 'http://localhost:8378/1/users/me',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-Session-Token': Parse.User.current().getSessionToken(),\n 'X-Parse-REST-API-Key': 'rest',\n },\n })\n )\n .then(response => {\n const res = response.data;\n expect(res.emailVerified).toBe(false);\n expect(res._email_verify_token).toBeUndefined();\n done();\n })\n .catch(done.fail);\n });", " it('should not retrieve hidden fields on GET users/id (#3432)', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() =>\n request({\n method: 'GET',\n url: 'http://localhost:8378/1/users/' + Parse.User.current().id,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n })\n )\n .then(response => {\n const res = response.data;\n expect(res.emailVerified).toBe(false);\n expect(res._email_verify_token).toBeUndefined();\n done();\n })\n .catch(err => {\n fail(JSON.stringify(err));\n done();\n });\n });", " it('should not retrieve hidden fields on login (#3432)', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() =>\n request({\n url: 'http://localhost:8378/1/login?email=test@email.com&username=hello&password=world',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n })\n )\n .then(response => {\n const res = response.data;\n expect(res.emailVerified).toBe(false);\n expect(res._email_verify_token).toBeUndefined();\n done();\n })\n .catch(err => {\n fail(JSON.stringify(err));\n done();\n });\n });", " it('should not allow updates to hidden fields', done => {\n const emailAdapter = {\n sendVerificationEmail: () => {},\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };", " const user = new Parse.User();\n user.set({\n username: 'hello',\n password: 'world',\n email: 'test@email.com',\n });", " reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n })\n .then(() => {\n return user.signUp();\n })\n .then(() => {\n return Parse.User.current().set('_email_verify_token', 'bad').save();\n })\n .then(() => {\n fail('Should not be able to update email verification token');\n done();\n })\n .catch(err => {\n expect(err).toBeDefined();\n done();\n });\n });", " it('should revoke sessions when setting paswword with masterKey (#3289)', done => {\n let user;\n Parse.User.signUp('username', 'password')\n .then(newUser => {\n user = newUser;\n user.set('password', 'newPassword');\n return user.save(null, { useMasterKey: true });\n })\n .then(() => {\n const query = new Parse.Query('_Session');\n query.equalTo('user', user);\n return query.find({ useMasterKey: true });\n })\n .then(results => {\n expect(results.length).toBe(0);\n done();\n }, done.fail);\n });", " xit('should not send a verification email if the user signed up using oauth', done => {\n let emailCalledCount = 0;\n const emailAdapter = {\n sendVerificationEmail: () => {\n emailCalledCount++;\n return Promise.resolve();\n },\n sendPasswordResetEmail: () => Promise.resolve(),\n sendMail: () => Promise.resolve(),\n };\n reconfigureServer({\n appName: 'unused',\n verifyUserEmails: true,\n emailAdapter: emailAdapter,\n publicServerURL: 'http://localhost:8378/1',\n });\n const user = new Parse.User();\n user.set('email', 'email1@host.com');\n Parse.FacebookUtils.link(user, {\n id: '8675309',\n access_token: 'jenny',\n expiration_date: new Date().toJSON(),\n }).then(user => {\n user.set('email', 'email2@host.com');\n user.save().then(() => {\n expect(emailCalledCount).toBe(0);\n done();\n });\n });\n }).pend('this test fails. See: https://github.com/parse-community/parse-server/issues/5097');", " it('should be able to update user with authData passed', done => {\n let objectId;\n let sessionToken;", " function validate(block) {\n return request({\n url: `http://localhost:8378/1/classes/_User/${objectId}`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'X-Parse-Session-Token': sessionToken,\n },\n }).then(response => block(response.data));\n }", " request({\n method: 'POST',\n url: 'http://localhost:8378/1/classes/_User',\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'value',\n authData: { anonymous: { id: '00000000-0000-0000-0000-000000000001' } },\n },\n })\n .then(response => {\n const body = response.data;\n objectId = body.objectId;\n sessionToken = body.sessionToken;\n expect(sessionToken).toBeDefined();\n expect(objectId).toBeDefined();\n return validate(user => {\n // validate that keys are set on creation\n expect(user.key).toBe('value');\n });\n })\n .then(() => {\n // update the user\n const options = {\n method: 'PUT',\n url: `http://localhost:8378/1/classes/_User/${objectId}`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'X-Parse-Session-Token': sessionToken,\n 'Content-Type': 'application/json',\n },\n body: {\n key: 'otherValue',\n authData: {\n anonymous: { id: '00000000-0000-0000-0000-000000000001' },\n },\n },\n };\n return request(options);\n })\n .then(() => {\n return validate(user => {\n // validate that keys are set on update\n expect(user.key).toBe('otherValue');\n });\n })\n .then(() => {\n done();\n })\n .then(done)\n .catch(done.fail);\n });", " it('can login with email', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n qs: { email: 'yo@lo.com', password: 'yolopass' },\n };\n return request(options);\n })\n .then(done)\n .catch(done.fail);\n });", " it('cannot login with email and invalid password', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n method: 'POST',\n url: `http://localhost:8378/1/login`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n 'Content-Type': 'application/json',\n },\n body: { email: 'yo@lo.com', password: 'yolopass2' },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(() => done());\n });", " it('can login with email through query string', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo.com&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done)\n .catch(done.fail);\n });", " it('can login when both email and username are passed', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo.com&username=yolo&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done)\n .catch(done.fail);\n });", " it(\"fails to login when username doesn't match email\", done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo.com&username=yolo2&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('Invalid username/password.');\n done();\n });\n });", " it(\"fails to login when email doesn't match username\", done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?email=yo@lo2.com&username=yolo&password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('Invalid username/password.');\n done();\n });\n });", " it('fails to login when email and username are not provided', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?password=yolopass`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('username/email is required.');\n done();\n });\n });", " it('allows login when providing email as username', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n return Parse.User.logIn('yo@lo.com', 'yolopass');\n })\n .then(user => {\n expect(user.get('username')).toBe('yolo');\n })\n .then(done)\n .catch(done.fail);\n });", " it('handles properly when 2 users share username / email pairs', done => {\n const user = new Parse.User({\n username: 'yo@loname.com',\n password: 'yolopass',\n email: 'yo@lo.com',\n });\n const user2 = new Parse.User({\n username: 'yo@lo.com',\n email: 'yo@loname.com',\n password: 'yolopass2', // different passwords\n });", " Parse.Object.saveAll([user, user2])\n .then(() => {\n return Parse.User.logIn('yo@loname.com', 'yolopass');\n })\n .then(user => {\n // the username takes precedence over the email,\n // so we get the user with username as passed in\n expect(user.get('username')).toBe('yo@loname.com');\n })\n .then(done)\n .catch(done.fail);\n });", " it('handles properly when 2 users share username / email pairs, counterpart', done => {\n const user = new Parse.User({\n username: 'yo@loname.com',\n password: 'yolopass',\n email: 'yo@lo.com',\n });\n const user2 = new Parse.User({\n username: 'yo@lo.com',\n email: 'yo@loname.com',\n password: 'yolopass2', // different passwords\n });", " Parse.Object.saveAll([user, user2])\n .then(() => {\n return Parse.User.logIn('yo@loname.com', 'yolopass2');\n })\n .then(done.fail)\n .catch(err => {\n expect(err.message).toEqual('Invalid username/password.');\n done();\n });\n });", " it('fails to login when password is not provided', done => {\n const user = new Parse.User();\n user\n .save({\n username: 'yolo',\n password: 'yolopass',\n email: 'yo@lo.com',\n })\n .then(() => {\n const options = {\n url: `http://localhost:8378/1/login?username=yolo`,\n headers: {\n 'X-Parse-Application-Id': Parse.applicationId,\n 'X-Parse-REST-API-Key': 'rest',\n },\n };\n return request(options);\n })\n .then(done.fail)\n .catch(err => {\n expect(err.data.error).toEqual('password is required.');\n done();\n });\n });", " it('does not duplicate session when logging in multiple times #3451', done => {\n const user = new Parse.User();\n user\n .signUp({\n username: 'yolo',\n password: 'yolo',\n email: 'yo@lo.com',\n })\n .then(() => {\n const token = user.getSessionToken();\n let promise = Promise.resolve();\n let count = 0;\n while (count < 5) {\n promise = promise.then(() => {\n return Parse.User.logIn('yolo', 'yolo').then(res => {\n // ensure a new session token is generated at each login\n expect(res.getSessionToken()).not.toBe(token);\n });\n });\n count++;\n }\n return promise;\n })\n .then(() => {\n // wait because session destruction is not synchronous\n return new Promise(resolve => {\n setTimeout(resolve, 100);\n });\n })\n .then(() => {\n const query = new Parse.Query('_Session');\n return query.find({ useMasterKey: true });\n })\n .then(results => {\n // only one session in the end\n expect(results.length).toBe(1);\n })\n .then(done, done.fail);\n });", " it('should throw OBJECT_NOT_FOUND instead of SESSION_MISSING when using masterKey', async () => {\n // create a fake user (just so we simulate an object not found)\n const non_existent_user = Parse.User.createWithoutData('fake_id');\n try {\n await non_existent_user.destroy({ useMasterKey: true });\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n }\n try {\n await non_existent_user.save({}, { useMasterKey: true });\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.OBJECT_NOT_FOUND);\n }\n try {\n await non_existent_user.save();\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n try {\n await non_existent_user.destroy();\n throw '';\n } catch (e) {\n expect(e.code).toBe(Parse.Error.SESSION_MISSING);\n }\n });", " describe('issue #4897', () => {\n it_only_db('mongo')('should be able to login with a legacy user (no ACL)', async () => {\n // This issue is a side effect of the locked users and legacy users which don't have ACL's\n // In this scenario, a legacy user wasn't be able to login as there's no ACL on it\n const database = Config.get(Parse.applicationId).database;\n const collection = await database.adapter._adaptiveCollection('_User');\n await collection.insertOne({\n _id: 'ABCDEF1234',\n name: '<some_name>',\n email: '<some_email>',\n username: '<some_username>',\n _hashed_password: '<some_password>',\n _auth_data_facebook: {\n id: '8675309',\n access_token: 'jenny',\n },\n sessionToken: '<some_session_token>',\n });\n const provider = getMockFacebookProvider();\n Parse.User._registerAuthenticationProvider(provider);\n const model = await Parse.User._logInWith('facebook', {});\n expect(model.id).toBe('ABCDEF1234');\n ok(model instanceof Parse.User, 'Model should be a Parse.User');\n strictEqual(Parse.User.current(), model);\n ok(model.extended(), 'Should have used subclass.');\n strictEqual(provider.authData.id, provider.synchronizedUserId);\n strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);\n strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);\n ok(model._isLinked('facebook'), 'User should be linked to facebook');\n });\n });\n});", "describe('Security Advisory GHSA-8w3j-g983-8jh5', function () {\n it_only_db('mongo')(\n 'should validate credentials first and check if account already linked afterwards ()',\n async done => {\n // Add User to Database with authData\n const database = Config.get(Parse.applicationId).database;\n const collection = await database.adapter._adaptiveCollection('_User');\n await collection.insertOne({\n _id: 'ABCDEF1234',\n name: '<some_name>',\n email: '<some_email>',\n username: '<some_username>',\n _hashed_password: '<some_password>',\n _auth_data_custom: {\n id: 'linkedID', // Already linked userid\n },\n sessionToken: '<some_session_token>',\n });\n const provider = {\n getAuthType: () => 'custom',\n restoreAuthentication: () => true,\n }; // AuthProvider checks if password is 'password'\n Parse.User._registerAuthenticationProvider(provider);", " // Try to link second user with wrong password\n try {\n const user = await Parse.AnonymousUtils.logIn();\n await user._linkWith(provider.getAuthType(), {\n authData: { id: 'linkedID', password: 'wrong' },\n });\n } catch (error) {\n // This should throw Parse.Error.SESSION_MISSING and not Parse.Error.ACCOUNT_ALREADY_LINKED\n expect(error.code).toEqual(Parse.Error.SESSION_MISSING);\n done();\n return;\n }\n fail();\n done();\n }\n );\n it_only_db('mongo')('should ignore authData field', async () => {\n // Add User to Database with authData\n const database = Config.get(Parse.applicationId).database;\n const collection = await database.adapter._adaptiveCollection('_User');\n await collection.insertOne({\n _id: '1234ABCDEF',\n name: '<some_name>',\n email: '<some_email>',\n username: '<some_username>',\n _hashed_password: '<some_password>',\n _auth_data_custom: {\n id: 'linkedID',\n },\n sessionToken: '<some_session_token>',\n authData: null, // should ignore\n });\n const provider = {\n getAuthType: () => 'custom',\n restoreAuthentication: () => true,\n };\n Parse.User._registerAuthenticationProvider(provider);\n const query = new Parse.Query(Parse.User);\n const user = await query.get('1234ABCDEF', { useMasterKey: true });\n expect(user.get('authData')).toEqual({ custom: { id: 'linkedID' } });\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 2430, 857], "buggy_code_start_loc": [4, 2377, 857], "filenames": ["CHANGELOG.md", "spec/ParseUser.spec.js", "src/RestWrite.js"], "fixing_code_end_loc": [10, 2434, 862], "fixing_code_start_loc": [4, 2377, 858], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "9DE0F06D-5868-45AD-B21E-C5268BCC7F52", "versionEndExcluding": "4.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login."}, {"lang": "es", "value": "Parse Server es un backend de c\u00f3digo abierto que puede desplegarse en cualquier infraestructura que pueda ejecutar Node.js. Los desarrolladores pueden usar la API REST para registrar usuarios y tambi\u00e9n permitir a usuarios registrarse an\u00f3nimamente. Versiones anteriores a 4.5.1, cuando un usuario an\u00f3nimo es registrado por primera vez usando REST, el servidor creaba la sesi\u00f3n incorrectamente. En particular, el campo \"authProvider\" de la clase \"_Session\" en \"createdWith\" muestra que el usuario se ha registrado creando una contrase\u00f1a. Si un desarrollador depende posteriormente del campo \"createdWith\" para proporcionar un nivel de acceso diferente entre un usuario con contrase\u00f1a y un usuario an\u00f3nimo, el servidor clasifica incorrectamente el tipo de sesi\u00f3n como creada con un \"password\". El servidor no usa actualmente \"createdWith\" para tomar decisiones sobre las funciones internas, por lo que si un desarrollador no est\u00e1 usando \"createdWith\" directamente, no est\u00e1 afectado. La vulnerabilidad s\u00f3lo afecta a usuarios que dependen de \"createdWith\" al usarlo directamente. El problema est\u00e1 parcheado en Parse Server versi\u00f3n 4.5.1. Como soluci\u00f3n, no use el campo de sesi\u00f3n \"createdWith\" para tomar decisiones si se permite el acceso an\u00f3nimo."}], "evaluatorComment": null, "id": "CVE-2021-39138", "lastModified": "2022-08-12T18:01:28.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.5, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-19T16:15:12.483", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/releases/tag/4.5.1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, "type": "CWE-863"}
299
Determine whether the {function_name} code is vulnerable or not.
[ "// A RestWrite encapsulates everything we need to run an operation\n// that writes to the database.\n// This could be either a \"create\" or an \"update\".", "var SchemaController = require('./Controllers/SchemaController');\nvar deepcopy = require('deepcopy');", "const Auth = require('./Auth');\nvar cryptoUtils = require('./cryptoUtils');\nvar passwordCrypto = require('./password');\nvar Parse = require('parse/node');\nvar triggers = require('./triggers');\nvar ClientSDK = require('./ClientSDK');\nimport RestQuery from './RestQuery';\nimport _ from 'lodash';\nimport logger from './logger';", "// query and data are both provided in REST API format. So data\n// types are encoded by plain old objects.\n// If query is null, this is a \"create\" and the data in data should be\n// created.\n// Otherwise this is an \"update\" - the object matching the query\n// should get updated with data.\n// RestWrite will handle objectId, createdAt, and updatedAt for\n// everything. It also knows to use triggers and special modifications\n// for the _User class.\nfunction RestWrite(config, auth, className, query, data, originalData, clientSDK, context, action) {\n if (auth.isReadOnly) {\n throw new Parse.Error(\n Parse.Error.OPERATION_FORBIDDEN,\n 'Cannot perform a write operation when using readOnlyMasterKey'\n );\n }\n this.config = config;\n this.auth = auth;\n this.className = className;\n this.clientSDK = clientSDK;\n this.storage = {};\n this.runOptions = {};\n this.context = context || {};", " if (action) {\n this.runOptions.action = action;\n }", " if (!query) {\n if (this.config.allowCustomObjectId) {\n if (Object.prototype.hasOwnProperty.call(data, 'objectId') && !data.objectId) {\n throw new Parse.Error(\n Parse.Error.MISSING_OBJECT_ID,\n 'objectId must not be empty, null or undefined'\n );\n }\n } else {\n if (data.objectId) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'objectId is an invalid field name.');\n }\n if (data.id) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'id is an invalid field name.');\n }\n }\n }", " // When the operation is complete, this.response may have several\n // fields.\n // response: the actual data to be returned\n // status: the http status code. if not present, treated like a 200\n // location: the location header. if not present, no location header\n this.response = null;", " // Processing this operation may mutate our data, so we operate on a\n // copy\n this.query = deepcopy(query);\n this.data = deepcopy(data);\n // We never change originalData, so we do not need a deep copy\n this.originalData = originalData;", " // The timestamp we'll use for this whole operation\n this.updatedAt = Parse._encode(new Date()).iso;", " // Shared SchemaController to be reused to reduce the number of loadSchema() calls per request\n // Once set the schemaData should be immutable\n this.validSchemaController = null;\n}", "// A convenient method to perform all the steps of processing the\n// write, in order.\n// Returns a promise for a {response, status, location} object.\n// status and location are optional.\nRestWrite.prototype.execute = function () {\n return Promise.resolve()\n .then(() => {\n return this.getUserAndRoleACL();\n })\n .then(() => {\n return this.validateClientClassCreation();\n })\n .then(() => {\n return this.handleInstallation();\n })\n .then(() => {\n return this.handleSession();\n })\n .then(() => {\n return this.validateAuthData();\n })\n .then(() => {\n return this.runBeforeSaveTrigger();\n })\n .then(() => {\n return this.deleteEmailResetTokenIfNeeded();\n })\n .then(() => {\n return this.validateSchema();\n })\n .then(schemaController => {\n this.validSchemaController = schemaController;\n return this.setRequiredFieldsIfNeeded();\n })\n .then(() => {\n return this.transformUser();\n })\n .then(() => {\n return this.expandFilesForExistingObjects();\n })\n .then(() => {\n return this.destroyDuplicatedSessions();\n })\n .then(() => {\n return this.runDatabaseOperation();\n })\n .then(() => {\n return this.createSessionTokenIfNeeded();\n })\n .then(() => {\n return this.handleFollowup();\n })\n .then(() => {\n return this.runAfterSaveTrigger();\n })\n .then(() => {\n return this.cleanUserAuthData();\n })\n .then(() => {\n return this.response;\n });\n};", "// Uses the Auth object to get the list of roles, adds the user id\nRestWrite.prototype.getUserAndRoleACL = function () {\n if (this.auth.isMaster) {\n return Promise.resolve();\n }", " this.runOptions.acl = ['*'];", " if (this.auth.user) {\n return this.auth.getUserRoles().then(roles => {\n this.runOptions.acl = this.runOptions.acl.concat(roles, [this.auth.user.id]);\n return;\n });\n } else {\n return Promise.resolve();\n }\n};", "// Validates this operation against the allowClientClassCreation config.\nRestWrite.prototype.validateClientClassCreation = function () {\n if (\n this.config.allowClientClassCreation === false &&\n !this.auth.isMaster &&\n SchemaController.systemClasses.indexOf(this.className) === -1\n ) {\n return this.config.database\n .loadSchema()\n .then(schemaController => schemaController.hasClass(this.className))\n .then(hasClass => {\n if (hasClass !== true) {\n throw new Parse.Error(\n Parse.Error.OPERATION_FORBIDDEN,\n 'This user is not allowed to access ' + 'non-existent class: ' + this.className\n );\n }\n });\n } else {\n return Promise.resolve();\n }\n};", "// Validates this operation against the schema.\nRestWrite.prototype.validateSchema = function () {\n return this.config.database.validateObject(\n this.className,\n this.data,\n this.query,\n this.runOptions\n );\n};", "// Runs any beforeSave triggers against this operation.\n// Any change leads to our data being mutated.\nRestWrite.prototype.runBeforeSaveTrigger = function () {\n if (this.response) {\n return;\n }", " // Avoid doing any setup for triggers if there is no 'beforeSave' trigger for this class.\n if (\n !triggers.triggerExists(this.className, triggers.Types.beforeSave, this.config.applicationId)\n ) {\n return Promise.resolve();\n }", " // Cloud code gets a bit of extra data for its objects\n var extraData = { className: this.className };\n if (this.query && this.query.objectId) {\n extraData.objectId = this.query.objectId;\n }", " let originalObject = null;\n const updatedObject = this.buildUpdatedObject(extraData);\n if (this.query && this.query.objectId) {\n // This is an update for existing object.\n originalObject = triggers.inflate(extraData, this.originalData);\n }", " return Promise.resolve()\n .then(() => {\n // Before calling the trigger, validate the permissions for the save operation\n let databasePromise = null;\n if (this.query) {\n // Validate for updating\n databasePromise = this.config.database.update(\n this.className,\n this.query,\n this.data,\n this.runOptions,\n true,\n true\n );\n } else {\n // Validate for creating\n databasePromise = this.config.database.create(\n this.className,\n this.data,\n this.runOptions,\n true\n );\n }\n // In the case that there is no permission for the operation, it throws an error\n return databasePromise.then(result => {\n if (!result || result.length <= 0) {\n throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.');\n }\n });\n })\n .then(() => {\n return triggers.maybeRunTrigger(\n triggers.Types.beforeSave,\n this.auth,\n updatedObject,\n originalObject,\n this.config,\n this.context\n );\n })\n .then(response => {\n if (response && response.object) {\n this.storage.fieldsChangedByTrigger = _.reduce(\n response.object,\n (result, value, key) => {\n if (!_.isEqual(this.data[key], value)) {\n result.push(key);\n }\n return result;\n },\n []\n );\n this.data = response.object;\n // We should delete the objectId for an update write\n if (this.query && this.query.objectId) {\n delete this.data.objectId;\n }\n }\n });\n};", "RestWrite.prototype.runBeforeLoginTrigger = async function (userData) {\n // Avoid doing any setup for triggers if there is no 'beforeLogin' trigger\n if (\n !triggers.triggerExists(this.className, triggers.Types.beforeLogin, this.config.applicationId)\n ) {\n return;\n }", " // Cloud code gets a bit of extra data for its objects\n const extraData = { className: this.className };", " // Expand file objects\n this.config.filesController.expandFilesInObject(this.config, userData);", " const user = triggers.inflate(extraData, userData);", " // no need to return a response\n await triggers.maybeRunTrigger(\n triggers.Types.beforeLogin,\n this.auth,\n user,\n null,\n this.config,\n this.context\n );\n};", "RestWrite.prototype.setRequiredFieldsIfNeeded = function () {\n if (this.data) {\n return this.validSchemaController.getAllClasses().then(allClasses => {\n const schema = allClasses.find(oneClass => oneClass.className === this.className);\n const setRequiredFieldIfNeeded = (fieldName, setDefault) => {\n if (\n this.data[fieldName] === undefined ||\n this.data[fieldName] === null ||\n this.data[fieldName] === '' ||\n (typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete')\n ) {\n if (\n setDefault &&\n schema.fields[fieldName] &&\n schema.fields[fieldName].defaultValue !== null &&\n schema.fields[fieldName].defaultValue !== undefined &&\n (this.data[fieldName] === undefined ||\n (typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete'))\n ) {\n this.data[fieldName] = schema.fields[fieldName].defaultValue;\n this.storage.fieldsChangedByTrigger = this.storage.fieldsChangedByTrigger || [];\n if (this.storage.fieldsChangedByTrigger.indexOf(fieldName) < 0) {\n this.storage.fieldsChangedByTrigger.push(fieldName);\n }\n } else if (schema.fields[fieldName] && schema.fields[fieldName].required === true) {\n throw new Parse.Error(Parse.Error.VALIDATION_ERROR, `${fieldName} is required`);\n }\n }\n };", " // Add default fields\n this.data.updatedAt = this.updatedAt;\n if (!this.query) {\n this.data.createdAt = this.updatedAt;", " // Only assign new objectId if we are creating new object\n if (!this.data.objectId) {\n this.data.objectId = cryptoUtils.newObjectId(this.config.objectIdSize);\n }\n if (schema) {\n Object.keys(schema.fields).forEach(fieldName => {\n setRequiredFieldIfNeeded(fieldName, true);\n });\n }\n } else if (schema) {\n Object.keys(this.data).forEach(fieldName => {\n setRequiredFieldIfNeeded(fieldName, false);\n });\n }\n });\n }\n return Promise.resolve();\n};", "// Transforms auth data for a user object.\n// Does nothing if this isn't a user object.\n// Returns a promise for when we're done if it can't finish this tick.\nRestWrite.prototype.validateAuthData = function () {\n if (this.className !== '_User') {\n return;\n }", " if (!this.query && !this.data.authData) {\n if (typeof this.data.username !== 'string' || _.isEmpty(this.data.username)) {\n throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'bad or missing username');\n }\n if (typeof this.data.password !== 'string' || _.isEmpty(this.data.password)) {\n throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'password is required');\n }\n }", " if (\n (this.data.authData && !Object.keys(this.data.authData).length) ||\n !Object.prototype.hasOwnProperty.call(this.data, 'authData')\n ) {\n // Handle saving authData to {} or if authData doesn't exist\n return;\n } else if (Object.prototype.hasOwnProperty.call(this.data, 'authData') && !this.data.authData) {\n // Handle saving authData to null\n throw new Parse.Error(\n Parse.Error.UNSUPPORTED_SERVICE,\n 'This authentication method is unsupported.'\n );\n }", " var authData = this.data.authData;\n var providers = Object.keys(authData);\n if (providers.length > 0) {\n const canHandleAuthData = providers.reduce((canHandle, provider) => {\n var providerAuthData = authData[provider];\n var hasToken = providerAuthData && providerAuthData.id;\n return canHandle && (hasToken || providerAuthData == null);\n }, true);\n if (canHandleAuthData) {\n return this.handleAuthData(authData);\n }\n }\n throw new Parse.Error(\n Parse.Error.UNSUPPORTED_SERVICE,\n 'This authentication method is unsupported.'\n );\n};", "RestWrite.prototype.handleAuthDataValidation = function (authData) {\n const validations = Object.keys(authData).map(provider => {\n if (authData[provider] === null) {\n return Promise.resolve();\n }\n const validateAuthData = this.config.authDataManager.getValidatorForProvider(provider);\n if (!validateAuthData) {\n throw new Parse.Error(\n Parse.Error.UNSUPPORTED_SERVICE,\n 'This authentication method is unsupported.'\n );\n }\n return validateAuthData(authData[provider]);\n });\n return Promise.all(validations);\n};", "RestWrite.prototype.findUsersWithAuthData = function (authData) {\n const providers = Object.keys(authData);\n const query = providers\n .reduce((memo, provider) => {\n if (!authData[provider]) {\n return memo;\n }\n const queryKey = `authData.${provider}.id`;\n const query = {};\n query[queryKey] = authData[provider].id;\n memo.push(query);\n return memo;\n }, [])\n .filter(q => {\n return typeof q !== 'undefined';\n });", " let findPromise = Promise.resolve([]);\n if (query.length > 0) {\n findPromise = this.config.database.find(this.className, { $or: query }, {});\n }", " return findPromise;\n};", "RestWrite.prototype.filteredObjectsByACL = function (objects) {\n if (this.auth.isMaster) {\n return objects;\n }\n return objects.filter(object => {\n if (!object.ACL) {\n return true; // legacy users that have no ACL field on them\n }\n // Regular users that have been locked out.\n return object.ACL && Object.keys(object.ACL).length > 0;\n });\n};", "RestWrite.prototype.handleAuthData = function (authData) {\n let results;\n return this.findUsersWithAuthData(authData).then(async r => {\n results = this.filteredObjectsByACL(r);", " if (results.length == 1) {\n this.storage['authProvider'] = Object.keys(authData).join(',');", " const userResult = results[0];\n const mutatedAuthData = {};\n Object.keys(authData).forEach(provider => {\n const providerData = authData[provider];\n const userAuthData = userResult.authData[provider];\n if (!_.isEqual(providerData, userAuthData)) {\n mutatedAuthData[provider] = providerData;\n }\n });\n const hasMutatedAuthData = Object.keys(mutatedAuthData).length !== 0;\n let userId;\n if (this.query && this.query.objectId) {\n userId = this.query.objectId;\n } else if (this.auth && this.auth.user && this.auth.user.id) {\n userId = this.auth.user.id;\n }\n if (!userId || userId === userResult.objectId) {\n // no user making the call\n // OR the user making the call is the right one\n // Login with auth data\n delete results[0].password;", " // need to set the objectId first otherwise location has trailing undefined\n this.data.objectId = userResult.objectId;", " if (!this.query || !this.query.objectId) {\n // this a login call, no userId passed\n this.response = {\n response: userResult,\n location: this.location(),\n };\n // Run beforeLogin hook before storing any updates\n // to authData on the db; changes to userResult\n // will be ignored.\n await this.runBeforeLoginTrigger(deepcopy(userResult));\n }", " // If we didn't change the auth data, just keep going\n if (!hasMutatedAuthData) {\n return;\n }\n // We have authData that is updated on login\n // that can happen when token are refreshed,\n // We should update the token and let the user in\n // We should only check the mutated keys\n return this.handleAuthDataValidation(mutatedAuthData).then(async () => {\n // IF we have a response, we'll skip the database operation / beforeSave / afterSave etc...\n // we need to set it up there.\n // We are supposed to have a response only on LOGIN with authData, so we skip those\n // If we're not logging in, but just updating the current user, we can safely skip that part\n if (this.response) {\n // Assign the new authData in the response\n Object.keys(mutatedAuthData).forEach(provider => {\n this.response.response.authData[provider] = mutatedAuthData[provider];\n });", " // Run the DB update directly, as 'master'\n // Just update the authData part\n // Then we're good for the user, early exit of sorts\n return this.config.database.update(\n this.className,\n { objectId: this.data.objectId },\n { authData: mutatedAuthData },\n {}\n );\n }\n });\n } else if (userId) {\n // Trying to update auth data but users\n // are different\n if (userResult.objectId !== userId) {\n throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');\n }\n // No auth data was mutated, just keep going\n if (!hasMutatedAuthData) {\n return;\n }\n }\n }\n return this.handleAuthDataValidation(authData).then(() => {\n if (results.length > 1) {\n // More than 1 user with the passed id's\n throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');\n }\n });\n });\n};", "// The non-third-party parts of User transformation\nRestWrite.prototype.transformUser = function () {\n var promise = Promise.resolve();", " if (this.className !== '_User') {\n return promise;\n }", " if (!this.auth.isMaster && 'emailVerified' in this.data) {\n const error = `Clients aren't allowed to manually update email verification.`;\n throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);\n }", " // Do not cleanup session if objectId is not set\n if (this.query && this.objectId()) {\n // If we're updating a _User object, we need to clear out the cache for that user. Find all their\n // session tokens, and remove them from the cache.\n promise = new RestQuery(this.config, Auth.master(this.config), '_Session', {\n user: {\n __type: 'Pointer',\n className: '_User',\n objectId: this.objectId(),\n },\n })\n .execute()\n .then(results => {\n results.results.forEach(session =>\n this.config.cacheController.user.del(session.sessionToken)\n );\n });\n }", " return promise\n .then(() => {\n // Transform the password\n if (this.data.password === undefined) {\n // ignore only if undefined. should proceed if empty ('')\n return Promise.resolve();\n }", " if (this.query) {\n this.storage['clearSessions'] = true;\n // Generate a new session only if the user requested\n if (!this.auth.isMaster) {\n this.storage['generateNewSession'] = true;\n }\n }", " return this._validatePasswordPolicy().then(() => {\n return passwordCrypto.hash(this.data.password).then(hashedPassword => {\n this.data._hashed_password = hashedPassword;\n delete this.data.password;\n });\n });\n })\n .then(() => {\n return this._validateUserName();\n })\n .then(() => {\n return this._validateEmail();\n });\n};", "RestWrite.prototype._validateUserName = function () {\n // Check for username uniqueness\n if (!this.data.username) {\n if (!this.query) {\n this.data.username = cryptoUtils.randomString(25);\n this.responseShouldHaveUsername = true;\n }\n return Promise.resolve();\n }\n /*\n Usernames should be unique when compared case insensitively", " Users should be able to make case sensitive usernames and\n login using the case they entered. I.e. 'Snoopy' should preclude\n 'snoopy' as a valid username.\n */\n return this.config.database\n .find(\n this.className,\n {\n username: this.data.username,\n objectId: { $ne: this.objectId() },\n },\n { limit: 1, caseInsensitive: true },\n {},\n this.validSchemaController\n )\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.USERNAME_TAKEN,\n 'Account already exists for this username.'\n );\n }\n return;\n });\n};", "/*\n As with usernames, Parse should not allow case insensitive collisions of email.\n unlike with usernames (which can have case insensitive collisions in the case of\n auth adapters), emails should never have a case insensitive collision.", " This behavior can be enforced through a properly configured index see:\n https://docs.mongodb.com/manual/core/index-case-insensitive/#create-a-case-insensitive-index\n which could be implemented instead of this code based validation.", " Given that this lookup should be a relatively low use case and that the case sensitive\n unique index will be used by the db for the query, this is an adequate solution.\n*/\nRestWrite.prototype._validateEmail = function () {\n if (!this.data.email || this.data.email.__op === 'Delete') {\n return Promise.resolve();\n }\n // Validate basic email address format\n if (!this.data.email.match(/^.+@.+$/)) {\n return Promise.reject(\n new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'Email address format is invalid.')\n );\n }\n // Case insensitive match, see note above function.\n return this.config.database\n .find(\n this.className,\n {\n email: this.data.email,\n objectId: { $ne: this.objectId() },\n },\n { limit: 1, caseInsensitive: true },\n {},\n this.validSchemaController\n )\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.EMAIL_TAKEN,\n 'Account already exists for this email address.'\n );\n }\n if (\n !this.data.authData ||\n !Object.keys(this.data.authData).length ||\n (Object.keys(this.data.authData).length === 1 &&\n Object.keys(this.data.authData)[0] === 'anonymous')\n ) {\n // We updated the email, send a new validation\n this.storage['sendVerificationEmail'] = true;\n this.config.userController.setEmailVerifyToken(this.data);\n }\n });\n};", "RestWrite.prototype._validatePasswordPolicy = function () {\n if (!this.config.passwordPolicy) return Promise.resolve();\n return this._validatePasswordRequirements().then(() => {\n return this._validatePasswordHistory();\n });\n};", "RestWrite.prototype._validatePasswordRequirements = function () {\n // check if the password conforms to the defined password policy if configured\n // If we specified a custom error in our configuration use it.\n // Example: \"Passwords must include a Capital Letter, Lowercase Letter, and a number.\"\n //\n // This is especially useful on the generic \"password reset\" page,\n // as it allows the programmer to communicate specific requirements instead of:\n // a. making the user guess whats wrong\n // b. making a custom password reset page that shows the requirements\n const policyError = this.config.passwordPolicy.validationError\n ? this.config.passwordPolicy.validationError\n : 'Password does not meet the Password Policy requirements.';\n const containsUsernameError = 'Password cannot contain your username.';", " // check whether the password meets the password strength requirements\n if (\n (this.config.passwordPolicy.patternValidator &&\n !this.config.passwordPolicy.patternValidator(this.data.password)) ||\n (this.config.passwordPolicy.validatorCallback &&\n !this.config.passwordPolicy.validatorCallback(this.data.password))\n ) {\n return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, policyError));\n }", " // check whether password contain username\n if (this.config.passwordPolicy.doNotAllowUsername === true) {\n if (this.data.username) {\n // username is not passed during password reset\n if (this.data.password.indexOf(this.data.username) >= 0)\n return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError));\n } else {\n // retrieve the User object using objectId during password reset\n return this.config.database.find('_User', { objectId: this.objectId() }).then(results => {\n if (results.length != 1) {\n throw undefined;\n }\n if (this.data.password.indexOf(results[0].username) >= 0)\n return Promise.reject(\n new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)\n );\n return Promise.resolve();\n });\n }\n }\n return Promise.resolve();\n};", "RestWrite.prototype._validatePasswordHistory = function () {\n // check whether password is repeating from specified history\n if (this.query && this.config.passwordPolicy.maxPasswordHistory) {\n return this.config.database\n .find(\n '_User',\n { objectId: this.objectId() },\n { keys: ['_password_history', '_hashed_password'] }\n )\n .then(results => {\n if (results.length != 1) {\n throw undefined;\n }\n const user = results[0];\n let oldPasswords = [];\n if (user._password_history)\n oldPasswords = _.take(\n user._password_history,\n this.config.passwordPolicy.maxPasswordHistory - 1\n );\n oldPasswords.push(user.password);\n const newPassword = this.data.password;\n // compare the new password hash with all old password hashes\n const promises = oldPasswords.map(function (hash) {\n return passwordCrypto.compare(newPassword, hash).then(result => {\n if (result)\n // reject if there is a match\n return Promise.reject('REPEAT_PASSWORD');\n return Promise.resolve();\n });\n });\n // wait for all comparisons to complete\n return Promise.all(promises)\n .then(() => {\n return Promise.resolve();\n })\n .catch(err => {\n if (err === 'REPEAT_PASSWORD')\n // a match was found\n return Promise.reject(\n new Parse.Error(\n Parse.Error.VALIDATION_ERROR,\n `New password should not be the same as last ${this.config.passwordPolicy.maxPasswordHistory} passwords.`\n )\n );\n throw err;\n });\n });\n }\n return Promise.resolve();\n};", "RestWrite.prototype.createSessionTokenIfNeeded = function () {\n if (this.className !== '_User') {\n return;\n }\n // Don't generate session for updating user (this.query is set) unless authData exists\n if (this.query && !this.data.authData) {\n return;\n }\n // Don't generate new sessionToken if linking via sessionToken\n if (this.auth.user && this.data.authData) {\n return;\n }\n if (\n !this.storage['authProvider'] && // signup call, with\n this.config.preventLoginWithUnverifiedEmail && // no login without verification\n this.config.verifyUserEmails\n ) {\n // verification is on\n return; // do not create the session token in that case!\n }\n return this.createSessionToken();\n};", "RestWrite.prototype.createSessionToken = async function () {\n // cloud installationId from Cloud Code,\n // never create session tokens from there.\n if (this.auth.installationId && this.auth.installationId === 'cloud') {\n return;", "", " }", " const { sessionData, createSession } = Auth.createSession(this.config, {\n userId: this.objectId(),\n createdWith: {\n action: this.storage['authProvider'] ? 'login' : 'signup',\n authProvider: this.storage['authProvider'] || 'password',\n },\n installationId: this.auth.installationId,\n });", " if (this.response && this.response.response) {\n this.response.response.sessionToken = sessionData.sessionToken;\n }", " return createSession();\n};", "// Delete email reset tokens if user is changing password or email.\nRestWrite.prototype.deleteEmailResetTokenIfNeeded = function () {\n if (this.className !== '_User' || this.query === null) {\n // null query means create\n return;\n }", " if ('password' in this.data || 'email' in this.data) {\n const addOps = {\n _perishable_token: { __op: 'Delete' },\n _perishable_token_expires_at: { __op: 'Delete' },\n };\n this.data = Object.assign(this.data, addOps);\n }\n};", "RestWrite.prototype.destroyDuplicatedSessions = function () {\n // Only for _Session, and at creation time\n if (this.className != '_Session' || this.query) {\n return;\n }\n // Destroy the sessions in 'Background'\n const { user, installationId, sessionToken } = this.data;\n if (!user || !installationId) {\n return;\n }\n if (!user.objectId) {\n return;\n }\n this.config.database.destroy(\n '_Session',\n {\n user,\n installationId,\n sessionToken: { $ne: sessionToken },\n },\n {},\n this.validSchemaController\n );\n};", "// Handles any followup logic\nRestWrite.prototype.handleFollowup = function () {\n if (this.storage && this.storage['clearSessions'] && this.config.revokeSessionOnPasswordReset) {\n var sessionQuery = {\n user: {\n __type: 'Pointer',\n className: '_User',\n objectId: this.objectId(),\n },\n };\n delete this.storage['clearSessions'];\n return this.config.database\n .destroy('_Session', sessionQuery)\n .then(this.handleFollowup.bind(this));\n }", " if (this.storage && this.storage['generateNewSession']) {\n delete this.storage['generateNewSession'];\n return this.createSessionToken().then(this.handleFollowup.bind(this));\n }", " if (this.storage && this.storage['sendVerificationEmail']) {\n delete this.storage['sendVerificationEmail'];\n // Fire and forget!\n this.config.userController.sendVerificationEmail(this.data);\n return this.handleFollowup.bind(this);\n }\n};", "// Handles the _Session class specialness.\n// Does nothing if this isn't an _Session object.\nRestWrite.prototype.handleSession = function () {\n if (this.response || this.className !== '_Session') {\n return;\n }", " if (!this.auth.user && !this.auth.isMaster) {\n throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token required.');\n }", " // TODO: Verify proper error to throw\n if (this.data.ACL) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'Cannot set ' + 'ACL on a Session.');\n }", " if (this.query) {\n if (this.data.user && !this.auth.isMaster && this.data.user.objectId != this.auth.user.id) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME);\n } else if (this.data.installationId) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME);\n } else if (this.data.sessionToken) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME);\n }\n }", " if (!this.query && !this.auth.isMaster) {\n const additionalSessionData = {};\n for (var key in this.data) {\n if (key === 'objectId' || key === 'user') {\n continue;\n }\n additionalSessionData[key] = this.data[key];\n }", " const { sessionData, createSession } = Auth.createSession(this.config, {\n userId: this.auth.user.id,\n createdWith: {\n action: 'create',\n },\n additionalSessionData,\n });", " return createSession().then(results => {\n if (!results.response) {\n throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'Error creating session.');\n }\n sessionData['objectId'] = results.response['objectId'];\n this.response = {\n status: 201,\n location: results.location,\n response: sessionData,\n };\n });\n }\n};", "// Handles the _Installation class specialness.\n// Does nothing if this isn't an installation object.\n// If an installation is found, this can mutate this.query and turn a create\n// into an update.\n// Returns a promise for when we're done if it can't finish this tick.\nRestWrite.prototype.handleInstallation = function () {\n if (this.response || this.className !== '_Installation') {\n return;\n }", " if (\n !this.query &&\n !this.data.deviceToken &&\n !this.data.installationId &&\n !this.auth.installationId\n ) {\n throw new Parse.Error(\n 135,\n 'at least one ID field (deviceToken, installationId) ' + 'must be specified in this operation'\n );\n }", " // If the device token is 64 characters long, we assume it is for iOS\n // and lowercase it.\n if (this.data.deviceToken && this.data.deviceToken.length == 64) {\n this.data.deviceToken = this.data.deviceToken.toLowerCase();\n }", " // We lowercase the installationId if present\n if (this.data.installationId) {\n this.data.installationId = this.data.installationId.toLowerCase();\n }", " let installationId = this.data.installationId;", " // If data.installationId is not set and we're not master, we can lookup in auth\n if (!installationId && !this.auth.isMaster) {\n installationId = this.auth.installationId;\n }", " if (installationId) {\n installationId = installationId.toLowerCase();\n }", " // Updating _Installation but not updating anything critical\n if (this.query && !this.data.deviceToken && !installationId && !this.data.deviceType) {\n return;\n }", " var promise = Promise.resolve();", " var idMatch; // Will be a match on either objectId or installationId\n var objectIdMatch;\n var installationIdMatch;\n var deviceTokenMatches = [];", " // Instead of issuing 3 reads, let's do it with one OR.\n const orQueries = [];\n if (this.query && this.query.objectId) {\n orQueries.push({\n objectId: this.query.objectId,\n });\n }\n if (installationId) {\n orQueries.push({\n installationId: installationId,\n });\n }\n if (this.data.deviceToken) {\n orQueries.push({ deviceToken: this.data.deviceToken });\n }", " if (orQueries.length == 0) {\n return;\n }", " promise = promise\n .then(() => {\n return this.config.database.find(\n '_Installation',\n {\n $or: orQueries,\n },\n {}\n );\n })\n .then(results => {\n results.forEach(result => {\n if (this.query && this.query.objectId && result.objectId == this.query.objectId) {\n objectIdMatch = result;\n }\n if (result.installationId == installationId) {\n installationIdMatch = result;\n }\n if (result.deviceToken == this.data.deviceToken) {\n deviceTokenMatches.push(result);\n }\n });", " // Sanity checks when running a query\n if (this.query && this.query.objectId) {\n if (!objectIdMatch) {\n throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found for update.');\n }\n if (\n this.data.installationId &&\n objectIdMatch.installationId &&\n this.data.installationId !== objectIdMatch.installationId\n ) {\n throw new Parse.Error(136, 'installationId may not be changed in this ' + 'operation');\n }\n if (\n this.data.deviceToken &&\n objectIdMatch.deviceToken &&\n this.data.deviceToken !== objectIdMatch.deviceToken &&\n !this.data.installationId &&\n !objectIdMatch.installationId\n ) {\n throw new Parse.Error(136, 'deviceToken may not be changed in this ' + 'operation');\n }\n if (\n this.data.deviceType &&\n this.data.deviceType &&\n this.data.deviceType !== objectIdMatch.deviceType\n ) {\n throw new Parse.Error(136, 'deviceType may not be changed in this ' + 'operation');\n }\n }", " if (this.query && this.query.objectId && objectIdMatch) {\n idMatch = objectIdMatch;\n }", " if (installationId && installationIdMatch) {\n idMatch = installationIdMatch;\n }\n // need to specify deviceType only if it's new\n if (!this.query && !this.data.deviceType && !idMatch) {\n throw new Parse.Error(135, 'deviceType must be specified in this operation');\n }\n })\n .then(() => {\n if (!idMatch) {\n if (!deviceTokenMatches.length) {\n return;\n } else if (\n deviceTokenMatches.length == 1 &&\n (!deviceTokenMatches[0]['installationId'] || !installationId)\n ) {\n // Single match on device token but none on installationId, and either\n // the passed object or the match is missing an installationId, so we\n // can just return the match.\n return deviceTokenMatches[0]['objectId'];\n } else if (!this.data.installationId) {\n throw new Parse.Error(\n 132,\n 'Must specify installationId when deviceToken ' +\n 'matches multiple Installation objects'\n );\n } else {\n // Multiple device token matches and we specified an installation ID,\n // or a single match where both the passed and matching objects have\n // an installation ID. Try cleaning out old installations that match\n // the deviceToken, and return nil to signal that a new object should\n // be created.\n var delQuery = {\n deviceToken: this.data.deviceToken,\n installationId: {\n $ne: installationId,\n },\n };\n if (this.data.appIdentifier) {\n delQuery['appIdentifier'] = this.data.appIdentifier;\n }\n this.config.database.destroy('_Installation', delQuery).catch(err => {\n if (err.code == Parse.Error.OBJECT_NOT_FOUND) {\n // no deletions were made. Can be ignored.\n return;\n }\n // rethrow the error\n throw err;\n });\n return;\n }\n } else {\n if (deviceTokenMatches.length == 1 && !deviceTokenMatches[0]['installationId']) {\n // Exactly one device token match and it doesn't have an installation\n // ID. This is the one case where we want to merge with the existing\n // object.\n const delQuery = { objectId: idMatch.objectId };\n return this.config.database\n .destroy('_Installation', delQuery)\n .then(() => {\n return deviceTokenMatches[0]['objectId'];\n })\n .catch(err => {\n if (err.code == Parse.Error.OBJECT_NOT_FOUND) {\n // no deletions were made. Can be ignored\n return;\n }\n // rethrow the error\n throw err;\n });\n } else {\n if (this.data.deviceToken && idMatch.deviceToken != this.data.deviceToken) {\n // We're setting the device token on an existing installation, so\n // we should try cleaning out old installations that match this\n // device token.\n const delQuery = {\n deviceToken: this.data.deviceToken,\n };\n // We have a unique install Id, use that to preserve\n // the interesting installation\n if (this.data.installationId) {\n delQuery['installationId'] = {\n $ne: this.data.installationId,\n };\n } else if (\n idMatch.objectId &&\n this.data.objectId &&\n idMatch.objectId == this.data.objectId\n ) {\n // we passed an objectId, preserve that instalation\n delQuery['objectId'] = {\n $ne: idMatch.objectId,\n };\n } else {\n // What to do here? can't really clean up everything...\n return idMatch.objectId;\n }\n if (this.data.appIdentifier) {\n delQuery['appIdentifier'] = this.data.appIdentifier;\n }\n this.config.database.destroy('_Installation', delQuery).catch(err => {\n if (err.code == Parse.Error.OBJECT_NOT_FOUND) {\n // no deletions were made. Can be ignored.\n return;\n }\n // rethrow the error\n throw err;\n });\n }\n // In non-merge scenarios, just return the installation match id\n return idMatch.objectId;\n }\n }\n })\n .then(objId => {\n if (objId) {\n this.query = { objectId: objId };\n delete this.data.objectId;\n delete this.data.createdAt;\n }\n // TODO: Validate ops (add/remove on channels, $inc on badge, etc.)\n });\n return promise;\n};", "// If we short-circuted the object response - then we need to make sure we expand all the files,\n// since this might not have a query, meaning it won't return the full result back.\n// TODO: (nlutsenko) This should die when we move to per-class based controllers on _Session/_User\nRestWrite.prototype.expandFilesForExistingObjects = function () {\n // Check whether we have a short-circuited response - only then run expansion.\n if (this.response && this.response.response) {\n this.config.filesController.expandFilesInObject(this.config, this.response.response);\n }\n};", "RestWrite.prototype.runDatabaseOperation = function () {\n if (this.response) {\n return;\n }", " if (this.className === '_Role') {\n this.config.cacheController.role.clear();\n }", " if (this.className === '_User' && this.query && this.auth.isUnauthenticated()) {\n throw new Parse.Error(\n Parse.Error.SESSION_MISSING,\n `Cannot modify user ${this.query.objectId}.`\n );\n }", " if (this.className === '_Product' && this.data.download) {\n this.data.downloadName = this.data.download.name;\n }", " // TODO: Add better detection for ACL, ensuring a user can't be locked from\n // their own user record.\n if (this.data.ACL && this.data.ACL['*unresolved']) {\n throw new Parse.Error(Parse.Error.INVALID_ACL, 'Invalid ACL.');\n }", " if (this.query) {\n // Force the user to not lockout\n // Matched with parse.com\n if (this.className === '_User' && this.data.ACL && this.auth.isMaster !== true) {\n this.data.ACL[this.query.objectId] = { read: true, write: true };\n }\n // update password timestamp if user password is being changed\n if (\n this.className === '_User' &&\n this.data._hashed_password &&\n this.config.passwordPolicy &&\n this.config.passwordPolicy.maxPasswordAge\n ) {\n this.data._password_changed_at = Parse._encode(new Date());\n }\n // Ignore createdAt when update\n delete this.data.createdAt;", " let defer = Promise.resolve();\n // if password history is enabled then save the current password to history\n if (\n this.className === '_User' &&\n this.data._hashed_password &&\n this.config.passwordPolicy &&\n this.config.passwordPolicy.maxPasswordHistory\n ) {\n defer = this.config.database\n .find(\n '_User',\n { objectId: this.objectId() },\n { keys: ['_password_history', '_hashed_password'] }\n )\n .then(results => {\n if (results.length != 1) {\n throw undefined;\n }\n const user = results[0];\n let oldPasswords = [];\n if (user._password_history) {\n oldPasswords = _.take(\n user._password_history,\n this.config.passwordPolicy.maxPasswordHistory\n );\n }\n //n-1 passwords go into history including last password\n while (\n oldPasswords.length > Math.max(0, this.config.passwordPolicy.maxPasswordHistory - 2)\n ) {\n oldPasswords.shift();\n }\n oldPasswords.push(user.password);\n this.data._password_history = oldPasswords;\n });\n }", " return defer.then(() => {\n // Run an update\n return this.config.database\n .update(\n this.className,\n this.query,\n this.data,\n this.runOptions,\n false,\n false,\n this.validSchemaController\n )\n .then(response => {\n response.updatedAt = this.updatedAt;\n this._updateResponseWithData(response, this.data);\n this.response = { response };\n });\n });\n } else {\n // Set the default ACL and password timestamp for the new _User\n if (this.className === '_User') {\n var ACL = this.data.ACL;\n // default public r/w ACL\n if (!ACL) {\n ACL = {};\n ACL['*'] = { read: true, write: false };\n }\n // make sure the user is not locked down\n ACL[this.data.objectId] = { read: true, write: true };\n this.data.ACL = ACL;\n // password timestamp to be used when password expiry policy is enforced\n if (this.config.passwordPolicy && this.config.passwordPolicy.maxPasswordAge) {\n this.data._password_changed_at = Parse._encode(new Date());\n }\n }", " // Run a create\n return this.config.database\n .create(this.className, this.data, this.runOptions, false, this.validSchemaController)\n .catch(error => {\n if (this.className !== '_User' || error.code !== Parse.Error.DUPLICATE_VALUE) {\n throw error;\n }", " // Quick check, if we were able to infer the duplicated field name\n if (error && error.userInfo && error.userInfo.duplicated_field === 'username') {\n throw new Parse.Error(\n Parse.Error.USERNAME_TAKEN,\n 'Account already exists for this username.'\n );\n }", " if (error && error.userInfo && error.userInfo.duplicated_field === 'email') {\n throw new Parse.Error(\n Parse.Error.EMAIL_TAKEN,\n 'Account already exists for this email address.'\n );\n }", " // If this was a failed user creation due to username or email already taken, we need to\n // check whether it was username or email and return the appropriate error.\n // Fallback to the original method\n // TODO: See if we can later do this without additional queries by using named indexes.\n return this.config.database\n .find(\n this.className,\n {\n username: this.data.username,\n objectId: { $ne: this.objectId() },\n },\n { limit: 1 }\n )\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.USERNAME_TAKEN,\n 'Account already exists for this username.'\n );\n }\n return this.config.database.find(\n this.className,\n { email: this.data.email, objectId: { $ne: this.objectId() } },\n { limit: 1 }\n );\n })\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.EMAIL_TAKEN,\n 'Account already exists for this email address.'\n );\n }\n throw new Parse.Error(\n Parse.Error.DUPLICATE_VALUE,\n 'A duplicate value for a field with unique values was provided'\n );\n });\n })\n .then(response => {\n response.objectId = this.data.objectId;\n response.createdAt = this.data.createdAt;", " if (this.responseShouldHaveUsername) {\n response.username = this.data.username;\n }\n this._updateResponseWithData(response, this.data);\n this.response = {\n status: 201,\n response,\n location: this.location(),\n };\n });\n }\n};", "// Returns nothing - doesn't wait for the trigger.\nRestWrite.prototype.runAfterSaveTrigger = function () {\n if (!this.response || !this.response.response) {\n return;\n }", " // Avoid doing any setup for triggers if there is no 'afterSave' trigger for this class.\n const hasAfterSaveHook = triggers.triggerExists(\n this.className,\n triggers.Types.afterSave,\n this.config.applicationId\n );\n const hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className);\n if (!hasAfterSaveHook && !hasLiveQuery) {\n return Promise.resolve();\n }", " var extraData = { className: this.className };\n if (this.query && this.query.objectId) {\n extraData.objectId = this.query.objectId;\n }", " // Build the original object, we only do this for a update write.\n let originalObject;\n if (this.query && this.query.objectId) {\n originalObject = triggers.inflate(extraData, this.originalData);\n }", " // Build the inflated object, different from beforeSave, originalData is not empty\n // since developers can change data in the beforeSave.\n const updatedObject = this.buildUpdatedObject(extraData);\n updatedObject._handleSaveResponse(this.response.response, this.response.status || 200);", " this.config.database.loadSchema().then(schemaController => {\n // Notifiy LiveQueryServer if possible\n const perms = schemaController.getClassLevelPermissions(updatedObject.className);\n this.config.liveQueryController.onAfterSave(\n updatedObject.className,\n updatedObject,\n originalObject,\n perms\n );\n });", " // Run afterSave trigger\n return triggers\n .maybeRunTrigger(\n triggers.Types.afterSave,\n this.auth,\n updatedObject,\n originalObject,\n this.config,\n this.context\n )\n .then(result => {\n if (result && typeof result === 'object') {\n this.response.response = result;\n }\n })\n .catch(function (err) {\n logger.warn('afterSave caught an error', err);\n });\n};", "// A helper to figure out what location this operation happens at.\nRestWrite.prototype.location = function () {\n var middle = this.className === '_User' ? '/users/' : '/classes/' + this.className + '/';\n const mount = this.config.mount || this.config.serverURL;\n return mount + middle + this.data.objectId;\n};", "// A helper to get the object id for this operation.\n// Because it could be either on the query or on the data\nRestWrite.prototype.objectId = function () {\n return this.data.objectId || this.query.objectId;\n};", "// Returns a copy of the data and delete bad keys (_auth_data, _hashed_password...)\nRestWrite.prototype.sanitizedData = function () {\n const data = Object.keys(this.data).reduce((data, key) => {\n // Regexp comes from Parse.Object.prototype.validate\n if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {\n delete data[key];\n }\n return data;\n }, deepcopy(this.data));\n return Parse._decode(undefined, data);\n};", "// Returns an updated copy of the object\nRestWrite.prototype.buildUpdatedObject = function (extraData) {\n const updatedObject = triggers.inflate(extraData, this.originalData);\n Object.keys(this.data).reduce(function (data, key) {\n if (key.indexOf('.') > 0) {\n if (typeof data[key].__op === 'string') {\n updatedObject.set(key, data[key]);\n } else {\n // subdocument key with dot notation { 'x.y': v } => { 'x': { 'y' : v } })\n const splittedKey = key.split('.');\n const parentProp = splittedKey[0];\n let parentVal = updatedObject.get(parentProp);\n if (typeof parentVal !== 'object') {\n parentVal = {};\n }\n parentVal[splittedKey[1]] = data[key];\n updatedObject.set(parentProp, parentVal);\n }\n delete data[key];\n }\n return data;\n }, deepcopy(this.data));", " updatedObject.set(this.sanitizedData());\n return updatedObject;\n};", "RestWrite.prototype.cleanUserAuthData = function () {\n if (this.response && this.response.response && this.className === '_User') {\n const user = this.response.response;\n if (user.authData) {\n Object.keys(user.authData).forEach(provider => {\n if (user.authData[provider] === null) {\n delete user.authData[provider];\n }\n });\n if (Object.keys(user.authData).length == 0) {\n delete user.authData;\n }\n }\n }\n};", "RestWrite.prototype._updateResponseWithData = function (response, data) {\n if (_.isEmpty(this.storage.fieldsChangedByTrigger)) {\n return response;\n }\n const clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK);\n this.storage.fieldsChangedByTrigger.forEach(fieldName => {\n const dataValue = data[fieldName];", " if (!Object.prototype.hasOwnProperty.call(response, fieldName)) {\n response[fieldName] = dataValue;\n }", " // Strips operations from responses\n if (response[fieldName] && response[fieldName].__op) {\n delete response[fieldName];\n if (clientSupportsDelete && dataValue.__op == 'Delete') {\n response[fieldName] = dataValue;\n }\n }\n });\n return response;\n};", "export default RestWrite;\nmodule.exports = RestWrite;" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 2430, 857], "buggy_code_start_loc": [4, 2377, 857], "filenames": ["CHANGELOG.md", "spec/ParseUser.spec.js", "src/RestWrite.js"], "fixing_code_end_loc": [10, 2434, 862], "fixing_code_start_loc": [4, 2377, 858], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "9DE0F06D-5868-45AD-B21E-C5268BCC7F52", "versionEndExcluding": "4.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login."}, {"lang": "es", "value": "Parse Server es un backend de c\u00f3digo abierto que puede desplegarse en cualquier infraestructura que pueda ejecutar Node.js. Los desarrolladores pueden usar la API REST para registrar usuarios y tambi\u00e9n permitir a usuarios registrarse an\u00f3nimamente. Versiones anteriores a 4.5.1, cuando un usuario an\u00f3nimo es registrado por primera vez usando REST, el servidor creaba la sesi\u00f3n incorrectamente. En particular, el campo \"authProvider\" de la clase \"_Session\" en \"createdWith\" muestra que el usuario se ha registrado creando una contrase\u00f1a. Si un desarrollador depende posteriormente del campo \"createdWith\" para proporcionar un nivel de acceso diferente entre un usuario con contrase\u00f1a y un usuario an\u00f3nimo, el servidor clasifica incorrectamente el tipo de sesi\u00f3n como creada con un \"password\". El servidor no usa actualmente \"createdWith\" para tomar decisiones sobre las funciones internas, por lo que si un desarrollador no est\u00e1 usando \"createdWith\" directamente, no est\u00e1 afectado. La vulnerabilidad s\u00f3lo afecta a usuarios que dependen de \"createdWith\" al usarlo directamente. El problema est\u00e1 parcheado en Parse Server versi\u00f3n 4.5.1. Como soluci\u00f3n, no use el campo de sesi\u00f3n \"createdWith\" para tomar decisiones si se permite el acceso an\u00f3nimo."}], "evaluatorComment": null, "id": "CVE-2021-39138", "lastModified": "2022-08-12T18:01:28.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.5, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-19T16:15:12.483", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/releases/tag/4.5.1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, "type": "CWE-863"}
299
Determine whether the {function_name} code is vulnerable or not.
[ "// A RestWrite encapsulates everything we need to run an operation\n// that writes to the database.\n// This could be either a \"create\" or an \"update\".", "var SchemaController = require('./Controllers/SchemaController');\nvar deepcopy = require('deepcopy');", "const Auth = require('./Auth');\nvar cryptoUtils = require('./cryptoUtils');\nvar passwordCrypto = require('./password');\nvar Parse = require('parse/node');\nvar triggers = require('./triggers');\nvar ClientSDK = require('./ClientSDK');\nimport RestQuery from './RestQuery';\nimport _ from 'lodash';\nimport logger from './logger';", "// query and data are both provided in REST API format. So data\n// types are encoded by plain old objects.\n// If query is null, this is a \"create\" and the data in data should be\n// created.\n// Otherwise this is an \"update\" - the object matching the query\n// should get updated with data.\n// RestWrite will handle objectId, createdAt, and updatedAt for\n// everything. It also knows to use triggers and special modifications\n// for the _User class.\nfunction RestWrite(config, auth, className, query, data, originalData, clientSDK, context, action) {\n if (auth.isReadOnly) {\n throw new Parse.Error(\n Parse.Error.OPERATION_FORBIDDEN,\n 'Cannot perform a write operation when using readOnlyMasterKey'\n );\n }\n this.config = config;\n this.auth = auth;\n this.className = className;\n this.clientSDK = clientSDK;\n this.storage = {};\n this.runOptions = {};\n this.context = context || {};", " if (action) {\n this.runOptions.action = action;\n }", " if (!query) {\n if (this.config.allowCustomObjectId) {\n if (Object.prototype.hasOwnProperty.call(data, 'objectId') && !data.objectId) {\n throw new Parse.Error(\n Parse.Error.MISSING_OBJECT_ID,\n 'objectId must not be empty, null or undefined'\n );\n }\n } else {\n if (data.objectId) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'objectId is an invalid field name.');\n }\n if (data.id) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'id is an invalid field name.');\n }\n }\n }", " // When the operation is complete, this.response may have several\n // fields.\n // response: the actual data to be returned\n // status: the http status code. if not present, treated like a 200\n // location: the location header. if not present, no location header\n this.response = null;", " // Processing this operation may mutate our data, so we operate on a\n // copy\n this.query = deepcopy(query);\n this.data = deepcopy(data);\n // We never change originalData, so we do not need a deep copy\n this.originalData = originalData;", " // The timestamp we'll use for this whole operation\n this.updatedAt = Parse._encode(new Date()).iso;", " // Shared SchemaController to be reused to reduce the number of loadSchema() calls per request\n // Once set the schemaData should be immutable\n this.validSchemaController = null;\n}", "// A convenient method to perform all the steps of processing the\n// write, in order.\n// Returns a promise for a {response, status, location} object.\n// status and location are optional.\nRestWrite.prototype.execute = function () {\n return Promise.resolve()\n .then(() => {\n return this.getUserAndRoleACL();\n })\n .then(() => {\n return this.validateClientClassCreation();\n })\n .then(() => {\n return this.handleInstallation();\n })\n .then(() => {\n return this.handleSession();\n })\n .then(() => {\n return this.validateAuthData();\n })\n .then(() => {\n return this.runBeforeSaveTrigger();\n })\n .then(() => {\n return this.deleteEmailResetTokenIfNeeded();\n })\n .then(() => {\n return this.validateSchema();\n })\n .then(schemaController => {\n this.validSchemaController = schemaController;\n return this.setRequiredFieldsIfNeeded();\n })\n .then(() => {\n return this.transformUser();\n })\n .then(() => {\n return this.expandFilesForExistingObjects();\n })\n .then(() => {\n return this.destroyDuplicatedSessions();\n })\n .then(() => {\n return this.runDatabaseOperation();\n })\n .then(() => {\n return this.createSessionTokenIfNeeded();\n })\n .then(() => {\n return this.handleFollowup();\n })\n .then(() => {\n return this.runAfterSaveTrigger();\n })\n .then(() => {\n return this.cleanUserAuthData();\n })\n .then(() => {\n return this.response;\n });\n};", "// Uses the Auth object to get the list of roles, adds the user id\nRestWrite.prototype.getUserAndRoleACL = function () {\n if (this.auth.isMaster) {\n return Promise.resolve();\n }", " this.runOptions.acl = ['*'];", " if (this.auth.user) {\n return this.auth.getUserRoles().then(roles => {\n this.runOptions.acl = this.runOptions.acl.concat(roles, [this.auth.user.id]);\n return;\n });\n } else {\n return Promise.resolve();\n }\n};", "// Validates this operation against the allowClientClassCreation config.\nRestWrite.prototype.validateClientClassCreation = function () {\n if (\n this.config.allowClientClassCreation === false &&\n !this.auth.isMaster &&\n SchemaController.systemClasses.indexOf(this.className) === -1\n ) {\n return this.config.database\n .loadSchema()\n .then(schemaController => schemaController.hasClass(this.className))\n .then(hasClass => {\n if (hasClass !== true) {\n throw new Parse.Error(\n Parse.Error.OPERATION_FORBIDDEN,\n 'This user is not allowed to access ' + 'non-existent class: ' + this.className\n );\n }\n });\n } else {\n return Promise.resolve();\n }\n};", "// Validates this operation against the schema.\nRestWrite.prototype.validateSchema = function () {\n return this.config.database.validateObject(\n this.className,\n this.data,\n this.query,\n this.runOptions\n );\n};", "// Runs any beforeSave triggers against this operation.\n// Any change leads to our data being mutated.\nRestWrite.prototype.runBeforeSaveTrigger = function () {\n if (this.response) {\n return;\n }", " // Avoid doing any setup for triggers if there is no 'beforeSave' trigger for this class.\n if (\n !triggers.triggerExists(this.className, triggers.Types.beforeSave, this.config.applicationId)\n ) {\n return Promise.resolve();\n }", " // Cloud code gets a bit of extra data for its objects\n var extraData = { className: this.className };\n if (this.query && this.query.objectId) {\n extraData.objectId = this.query.objectId;\n }", " let originalObject = null;\n const updatedObject = this.buildUpdatedObject(extraData);\n if (this.query && this.query.objectId) {\n // This is an update for existing object.\n originalObject = triggers.inflate(extraData, this.originalData);\n }", " return Promise.resolve()\n .then(() => {\n // Before calling the trigger, validate the permissions for the save operation\n let databasePromise = null;\n if (this.query) {\n // Validate for updating\n databasePromise = this.config.database.update(\n this.className,\n this.query,\n this.data,\n this.runOptions,\n true,\n true\n );\n } else {\n // Validate for creating\n databasePromise = this.config.database.create(\n this.className,\n this.data,\n this.runOptions,\n true\n );\n }\n // In the case that there is no permission for the operation, it throws an error\n return databasePromise.then(result => {\n if (!result || result.length <= 0) {\n throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.');\n }\n });\n })\n .then(() => {\n return triggers.maybeRunTrigger(\n triggers.Types.beforeSave,\n this.auth,\n updatedObject,\n originalObject,\n this.config,\n this.context\n );\n })\n .then(response => {\n if (response && response.object) {\n this.storage.fieldsChangedByTrigger = _.reduce(\n response.object,\n (result, value, key) => {\n if (!_.isEqual(this.data[key], value)) {\n result.push(key);\n }\n return result;\n },\n []\n );\n this.data = response.object;\n // We should delete the objectId for an update write\n if (this.query && this.query.objectId) {\n delete this.data.objectId;\n }\n }\n });\n};", "RestWrite.prototype.runBeforeLoginTrigger = async function (userData) {\n // Avoid doing any setup for triggers if there is no 'beforeLogin' trigger\n if (\n !triggers.triggerExists(this.className, triggers.Types.beforeLogin, this.config.applicationId)\n ) {\n return;\n }", " // Cloud code gets a bit of extra data for its objects\n const extraData = { className: this.className };", " // Expand file objects\n this.config.filesController.expandFilesInObject(this.config, userData);", " const user = triggers.inflate(extraData, userData);", " // no need to return a response\n await triggers.maybeRunTrigger(\n triggers.Types.beforeLogin,\n this.auth,\n user,\n null,\n this.config,\n this.context\n );\n};", "RestWrite.prototype.setRequiredFieldsIfNeeded = function () {\n if (this.data) {\n return this.validSchemaController.getAllClasses().then(allClasses => {\n const schema = allClasses.find(oneClass => oneClass.className === this.className);\n const setRequiredFieldIfNeeded = (fieldName, setDefault) => {\n if (\n this.data[fieldName] === undefined ||\n this.data[fieldName] === null ||\n this.data[fieldName] === '' ||\n (typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete')\n ) {\n if (\n setDefault &&\n schema.fields[fieldName] &&\n schema.fields[fieldName].defaultValue !== null &&\n schema.fields[fieldName].defaultValue !== undefined &&\n (this.data[fieldName] === undefined ||\n (typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete'))\n ) {\n this.data[fieldName] = schema.fields[fieldName].defaultValue;\n this.storage.fieldsChangedByTrigger = this.storage.fieldsChangedByTrigger || [];\n if (this.storage.fieldsChangedByTrigger.indexOf(fieldName) < 0) {\n this.storage.fieldsChangedByTrigger.push(fieldName);\n }\n } else if (schema.fields[fieldName] && schema.fields[fieldName].required === true) {\n throw new Parse.Error(Parse.Error.VALIDATION_ERROR, `${fieldName} is required`);\n }\n }\n };", " // Add default fields\n this.data.updatedAt = this.updatedAt;\n if (!this.query) {\n this.data.createdAt = this.updatedAt;", " // Only assign new objectId if we are creating new object\n if (!this.data.objectId) {\n this.data.objectId = cryptoUtils.newObjectId(this.config.objectIdSize);\n }\n if (schema) {\n Object.keys(schema.fields).forEach(fieldName => {\n setRequiredFieldIfNeeded(fieldName, true);\n });\n }\n } else if (schema) {\n Object.keys(this.data).forEach(fieldName => {\n setRequiredFieldIfNeeded(fieldName, false);\n });\n }\n });\n }\n return Promise.resolve();\n};", "// Transforms auth data for a user object.\n// Does nothing if this isn't a user object.\n// Returns a promise for when we're done if it can't finish this tick.\nRestWrite.prototype.validateAuthData = function () {\n if (this.className !== '_User') {\n return;\n }", " if (!this.query && !this.data.authData) {\n if (typeof this.data.username !== 'string' || _.isEmpty(this.data.username)) {\n throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'bad or missing username');\n }\n if (typeof this.data.password !== 'string' || _.isEmpty(this.data.password)) {\n throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'password is required');\n }\n }", " if (\n (this.data.authData && !Object.keys(this.data.authData).length) ||\n !Object.prototype.hasOwnProperty.call(this.data, 'authData')\n ) {\n // Handle saving authData to {} or if authData doesn't exist\n return;\n } else if (Object.prototype.hasOwnProperty.call(this.data, 'authData') && !this.data.authData) {\n // Handle saving authData to null\n throw new Parse.Error(\n Parse.Error.UNSUPPORTED_SERVICE,\n 'This authentication method is unsupported.'\n );\n }", " var authData = this.data.authData;\n var providers = Object.keys(authData);\n if (providers.length > 0) {\n const canHandleAuthData = providers.reduce((canHandle, provider) => {\n var providerAuthData = authData[provider];\n var hasToken = providerAuthData && providerAuthData.id;\n return canHandle && (hasToken || providerAuthData == null);\n }, true);\n if (canHandleAuthData) {\n return this.handleAuthData(authData);\n }\n }\n throw new Parse.Error(\n Parse.Error.UNSUPPORTED_SERVICE,\n 'This authentication method is unsupported.'\n );\n};", "RestWrite.prototype.handleAuthDataValidation = function (authData) {\n const validations = Object.keys(authData).map(provider => {\n if (authData[provider] === null) {\n return Promise.resolve();\n }\n const validateAuthData = this.config.authDataManager.getValidatorForProvider(provider);\n if (!validateAuthData) {\n throw new Parse.Error(\n Parse.Error.UNSUPPORTED_SERVICE,\n 'This authentication method is unsupported.'\n );\n }\n return validateAuthData(authData[provider]);\n });\n return Promise.all(validations);\n};", "RestWrite.prototype.findUsersWithAuthData = function (authData) {\n const providers = Object.keys(authData);\n const query = providers\n .reduce((memo, provider) => {\n if (!authData[provider]) {\n return memo;\n }\n const queryKey = `authData.${provider}.id`;\n const query = {};\n query[queryKey] = authData[provider].id;\n memo.push(query);\n return memo;\n }, [])\n .filter(q => {\n return typeof q !== 'undefined';\n });", " let findPromise = Promise.resolve([]);\n if (query.length > 0) {\n findPromise = this.config.database.find(this.className, { $or: query }, {});\n }", " return findPromise;\n};", "RestWrite.prototype.filteredObjectsByACL = function (objects) {\n if (this.auth.isMaster) {\n return objects;\n }\n return objects.filter(object => {\n if (!object.ACL) {\n return true; // legacy users that have no ACL field on them\n }\n // Regular users that have been locked out.\n return object.ACL && Object.keys(object.ACL).length > 0;\n });\n};", "RestWrite.prototype.handleAuthData = function (authData) {\n let results;\n return this.findUsersWithAuthData(authData).then(async r => {\n results = this.filteredObjectsByACL(r);", " if (results.length == 1) {\n this.storage['authProvider'] = Object.keys(authData).join(',');", " const userResult = results[0];\n const mutatedAuthData = {};\n Object.keys(authData).forEach(provider => {\n const providerData = authData[provider];\n const userAuthData = userResult.authData[provider];\n if (!_.isEqual(providerData, userAuthData)) {\n mutatedAuthData[provider] = providerData;\n }\n });\n const hasMutatedAuthData = Object.keys(mutatedAuthData).length !== 0;\n let userId;\n if (this.query && this.query.objectId) {\n userId = this.query.objectId;\n } else if (this.auth && this.auth.user && this.auth.user.id) {\n userId = this.auth.user.id;\n }\n if (!userId || userId === userResult.objectId) {\n // no user making the call\n // OR the user making the call is the right one\n // Login with auth data\n delete results[0].password;", " // need to set the objectId first otherwise location has trailing undefined\n this.data.objectId = userResult.objectId;", " if (!this.query || !this.query.objectId) {\n // this a login call, no userId passed\n this.response = {\n response: userResult,\n location: this.location(),\n };\n // Run beforeLogin hook before storing any updates\n // to authData on the db; changes to userResult\n // will be ignored.\n await this.runBeforeLoginTrigger(deepcopy(userResult));\n }", " // If we didn't change the auth data, just keep going\n if (!hasMutatedAuthData) {\n return;\n }\n // We have authData that is updated on login\n // that can happen when token are refreshed,\n // We should update the token and let the user in\n // We should only check the mutated keys\n return this.handleAuthDataValidation(mutatedAuthData).then(async () => {\n // IF we have a response, we'll skip the database operation / beforeSave / afterSave etc...\n // we need to set it up there.\n // We are supposed to have a response only on LOGIN with authData, so we skip those\n // If we're not logging in, but just updating the current user, we can safely skip that part\n if (this.response) {\n // Assign the new authData in the response\n Object.keys(mutatedAuthData).forEach(provider => {\n this.response.response.authData[provider] = mutatedAuthData[provider];\n });", " // Run the DB update directly, as 'master'\n // Just update the authData part\n // Then we're good for the user, early exit of sorts\n return this.config.database.update(\n this.className,\n { objectId: this.data.objectId },\n { authData: mutatedAuthData },\n {}\n );\n }\n });\n } else if (userId) {\n // Trying to update auth data but users\n // are different\n if (userResult.objectId !== userId) {\n throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');\n }\n // No auth data was mutated, just keep going\n if (!hasMutatedAuthData) {\n return;\n }\n }\n }\n return this.handleAuthDataValidation(authData).then(() => {\n if (results.length > 1) {\n // More than 1 user with the passed id's\n throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');\n }\n });\n });\n};", "// The non-third-party parts of User transformation\nRestWrite.prototype.transformUser = function () {\n var promise = Promise.resolve();", " if (this.className !== '_User') {\n return promise;\n }", " if (!this.auth.isMaster && 'emailVerified' in this.data) {\n const error = `Clients aren't allowed to manually update email verification.`;\n throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);\n }", " // Do not cleanup session if objectId is not set\n if (this.query && this.objectId()) {\n // If we're updating a _User object, we need to clear out the cache for that user. Find all their\n // session tokens, and remove them from the cache.\n promise = new RestQuery(this.config, Auth.master(this.config), '_Session', {\n user: {\n __type: 'Pointer',\n className: '_User',\n objectId: this.objectId(),\n },\n })\n .execute()\n .then(results => {\n results.results.forEach(session =>\n this.config.cacheController.user.del(session.sessionToken)\n );\n });\n }", " return promise\n .then(() => {\n // Transform the password\n if (this.data.password === undefined) {\n // ignore only if undefined. should proceed if empty ('')\n return Promise.resolve();\n }", " if (this.query) {\n this.storage['clearSessions'] = true;\n // Generate a new session only if the user requested\n if (!this.auth.isMaster) {\n this.storage['generateNewSession'] = true;\n }\n }", " return this._validatePasswordPolicy().then(() => {\n return passwordCrypto.hash(this.data.password).then(hashedPassword => {\n this.data._hashed_password = hashedPassword;\n delete this.data.password;\n });\n });\n })\n .then(() => {\n return this._validateUserName();\n })\n .then(() => {\n return this._validateEmail();\n });\n};", "RestWrite.prototype._validateUserName = function () {\n // Check for username uniqueness\n if (!this.data.username) {\n if (!this.query) {\n this.data.username = cryptoUtils.randomString(25);\n this.responseShouldHaveUsername = true;\n }\n return Promise.resolve();\n }\n /*\n Usernames should be unique when compared case insensitively", " Users should be able to make case sensitive usernames and\n login using the case they entered. I.e. 'Snoopy' should preclude\n 'snoopy' as a valid username.\n */\n return this.config.database\n .find(\n this.className,\n {\n username: this.data.username,\n objectId: { $ne: this.objectId() },\n },\n { limit: 1, caseInsensitive: true },\n {},\n this.validSchemaController\n )\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.USERNAME_TAKEN,\n 'Account already exists for this username.'\n );\n }\n return;\n });\n};", "/*\n As with usernames, Parse should not allow case insensitive collisions of email.\n unlike with usernames (which can have case insensitive collisions in the case of\n auth adapters), emails should never have a case insensitive collision.", " This behavior can be enforced through a properly configured index see:\n https://docs.mongodb.com/manual/core/index-case-insensitive/#create-a-case-insensitive-index\n which could be implemented instead of this code based validation.", " Given that this lookup should be a relatively low use case and that the case sensitive\n unique index will be used by the db for the query, this is an adequate solution.\n*/\nRestWrite.prototype._validateEmail = function () {\n if (!this.data.email || this.data.email.__op === 'Delete') {\n return Promise.resolve();\n }\n // Validate basic email address format\n if (!this.data.email.match(/^.+@.+$/)) {\n return Promise.reject(\n new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'Email address format is invalid.')\n );\n }\n // Case insensitive match, see note above function.\n return this.config.database\n .find(\n this.className,\n {\n email: this.data.email,\n objectId: { $ne: this.objectId() },\n },\n { limit: 1, caseInsensitive: true },\n {},\n this.validSchemaController\n )\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.EMAIL_TAKEN,\n 'Account already exists for this email address.'\n );\n }\n if (\n !this.data.authData ||\n !Object.keys(this.data.authData).length ||\n (Object.keys(this.data.authData).length === 1 &&\n Object.keys(this.data.authData)[0] === 'anonymous')\n ) {\n // We updated the email, send a new validation\n this.storage['sendVerificationEmail'] = true;\n this.config.userController.setEmailVerifyToken(this.data);\n }\n });\n};", "RestWrite.prototype._validatePasswordPolicy = function () {\n if (!this.config.passwordPolicy) return Promise.resolve();\n return this._validatePasswordRequirements().then(() => {\n return this._validatePasswordHistory();\n });\n};", "RestWrite.prototype._validatePasswordRequirements = function () {\n // check if the password conforms to the defined password policy if configured\n // If we specified a custom error in our configuration use it.\n // Example: \"Passwords must include a Capital Letter, Lowercase Letter, and a number.\"\n //\n // This is especially useful on the generic \"password reset\" page,\n // as it allows the programmer to communicate specific requirements instead of:\n // a. making the user guess whats wrong\n // b. making a custom password reset page that shows the requirements\n const policyError = this.config.passwordPolicy.validationError\n ? this.config.passwordPolicy.validationError\n : 'Password does not meet the Password Policy requirements.';\n const containsUsernameError = 'Password cannot contain your username.';", " // check whether the password meets the password strength requirements\n if (\n (this.config.passwordPolicy.patternValidator &&\n !this.config.passwordPolicy.patternValidator(this.data.password)) ||\n (this.config.passwordPolicy.validatorCallback &&\n !this.config.passwordPolicy.validatorCallback(this.data.password))\n ) {\n return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, policyError));\n }", " // check whether password contain username\n if (this.config.passwordPolicy.doNotAllowUsername === true) {\n if (this.data.username) {\n // username is not passed during password reset\n if (this.data.password.indexOf(this.data.username) >= 0)\n return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError));\n } else {\n // retrieve the User object using objectId during password reset\n return this.config.database.find('_User', { objectId: this.objectId() }).then(results => {\n if (results.length != 1) {\n throw undefined;\n }\n if (this.data.password.indexOf(results[0].username) >= 0)\n return Promise.reject(\n new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)\n );\n return Promise.resolve();\n });\n }\n }\n return Promise.resolve();\n};", "RestWrite.prototype._validatePasswordHistory = function () {\n // check whether password is repeating from specified history\n if (this.query && this.config.passwordPolicy.maxPasswordHistory) {\n return this.config.database\n .find(\n '_User',\n { objectId: this.objectId() },\n { keys: ['_password_history', '_hashed_password'] }\n )\n .then(results => {\n if (results.length != 1) {\n throw undefined;\n }\n const user = results[0];\n let oldPasswords = [];\n if (user._password_history)\n oldPasswords = _.take(\n user._password_history,\n this.config.passwordPolicy.maxPasswordHistory - 1\n );\n oldPasswords.push(user.password);\n const newPassword = this.data.password;\n // compare the new password hash with all old password hashes\n const promises = oldPasswords.map(function (hash) {\n return passwordCrypto.compare(newPassword, hash).then(result => {\n if (result)\n // reject if there is a match\n return Promise.reject('REPEAT_PASSWORD');\n return Promise.resolve();\n });\n });\n // wait for all comparisons to complete\n return Promise.all(promises)\n .then(() => {\n return Promise.resolve();\n })\n .catch(err => {\n if (err === 'REPEAT_PASSWORD')\n // a match was found\n return Promise.reject(\n new Parse.Error(\n Parse.Error.VALIDATION_ERROR,\n `New password should not be the same as last ${this.config.passwordPolicy.maxPasswordHistory} passwords.`\n )\n );\n throw err;\n });\n });\n }\n return Promise.resolve();\n};", "RestWrite.prototype.createSessionTokenIfNeeded = function () {\n if (this.className !== '_User') {\n return;\n }\n // Don't generate session for updating user (this.query is set) unless authData exists\n if (this.query && !this.data.authData) {\n return;\n }\n // Don't generate new sessionToken if linking via sessionToken\n if (this.auth.user && this.data.authData) {\n return;\n }\n if (\n !this.storage['authProvider'] && // signup call, with\n this.config.preventLoginWithUnverifiedEmail && // no login without verification\n this.config.verifyUserEmails\n ) {\n // verification is on\n return; // do not create the session token in that case!\n }\n return this.createSessionToken();\n};", "RestWrite.prototype.createSessionToken = async function () {\n // cloud installationId from Cloud Code,\n // never create session tokens from there.\n if (this.auth.installationId && this.auth.installationId === 'cloud') {\n return;", " }", " if (this.storage['authProvider'] == null && this.data.authData) {\n this.storage['authProvider'] = Object.keys(this.data.authData).join(',');", " }", " const { sessionData, createSession } = Auth.createSession(this.config, {\n userId: this.objectId(),\n createdWith: {\n action: this.storage['authProvider'] ? 'login' : 'signup',\n authProvider: this.storage['authProvider'] || 'password',\n },\n installationId: this.auth.installationId,\n });", " if (this.response && this.response.response) {\n this.response.response.sessionToken = sessionData.sessionToken;\n }", " return createSession();\n};", "// Delete email reset tokens if user is changing password or email.\nRestWrite.prototype.deleteEmailResetTokenIfNeeded = function () {\n if (this.className !== '_User' || this.query === null) {\n // null query means create\n return;\n }", " if ('password' in this.data || 'email' in this.data) {\n const addOps = {\n _perishable_token: { __op: 'Delete' },\n _perishable_token_expires_at: { __op: 'Delete' },\n };\n this.data = Object.assign(this.data, addOps);\n }\n};", "RestWrite.prototype.destroyDuplicatedSessions = function () {\n // Only for _Session, and at creation time\n if (this.className != '_Session' || this.query) {\n return;\n }\n // Destroy the sessions in 'Background'\n const { user, installationId, sessionToken } = this.data;\n if (!user || !installationId) {\n return;\n }\n if (!user.objectId) {\n return;\n }\n this.config.database.destroy(\n '_Session',\n {\n user,\n installationId,\n sessionToken: { $ne: sessionToken },\n },\n {},\n this.validSchemaController\n );\n};", "// Handles any followup logic\nRestWrite.prototype.handleFollowup = function () {\n if (this.storage && this.storage['clearSessions'] && this.config.revokeSessionOnPasswordReset) {\n var sessionQuery = {\n user: {\n __type: 'Pointer',\n className: '_User',\n objectId: this.objectId(),\n },\n };\n delete this.storage['clearSessions'];\n return this.config.database\n .destroy('_Session', sessionQuery)\n .then(this.handleFollowup.bind(this));\n }", " if (this.storage && this.storage['generateNewSession']) {\n delete this.storage['generateNewSession'];\n return this.createSessionToken().then(this.handleFollowup.bind(this));\n }", " if (this.storage && this.storage['sendVerificationEmail']) {\n delete this.storage['sendVerificationEmail'];\n // Fire and forget!\n this.config.userController.sendVerificationEmail(this.data);\n return this.handleFollowup.bind(this);\n }\n};", "// Handles the _Session class specialness.\n// Does nothing if this isn't an _Session object.\nRestWrite.prototype.handleSession = function () {\n if (this.response || this.className !== '_Session') {\n return;\n }", " if (!this.auth.user && !this.auth.isMaster) {\n throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token required.');\n }", " // TODO: Verify proper error to throw\n if (this.data.ACL) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'Cannot set ' + 'ACL on a Session.');\n }", " if (this.query) {\n if (this.data.user && !this.auth.isMaster && this.data.user.objectId != this.auth.user.id) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME);\n } else if (this.data.installationId) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME);\n } else if (this.data.sessionToken) {\n throw new Parse.Error(Parse.Error.INVALID_KEY_NAME);\n }\n }", " if (!this.query && !this.auth.isMaster) {\n const additionalSessionData = {};\n for (var key in this.data) {\n if (key === 'objectId' || key === 'user') {\n continue;\n }\n additionalSessionData[key] = this.data[key];\n }", " const { sessionData, createSession } = Auth.createSession(this.config, {\n userId: this.auth.user.id,\n createdWith: {\n action: 'create',\n },\n additionalSessionData,\n });", " return createSession().then(results => {\n if (!results.response) {\n throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'Error creating session.');\n }\n sessionData['objectId'] = results.response['objectId'];\n this.response = {\n status: 201,\n location: results.location,\n response: sessionData,\n };\n });\n }\n};", "// Handles the _Installation class specialness.\n// Does nothing if this isn't an installation object.\n// If an installation is found, this can mutate this.query and turn a create\n// into an update.\n// Returns a promise for when we're done if it can't finish this tick.\nRestWrite.prototype.handleInstallation = function () {\n if (this.response || this.className !== '_Installation') {\n return;\n }", " if (\n !this.query &&\n !this.data.deviceToken &&\n !this.data.installationId &&\n !this.auth.installationId\n ) {\n throw new Parse.Error(\n 135,\n 'at least one ID field (deviceToken, installationId) ' + 'must be specified in this operation'\n );\n }", " // If the device token is 64 characters long, we assume it is for iOS\n // and lowercase it.\n if (this.data.deviceToken && this.data.deviceToken.length == 64) {\n this.data.deviceToken = this.data.deviceToken.toLowerCase();\n }", " // We lowercase the installationId if present\n if (this.data.installationId) {\n this.data.installationId = this.data.installationId.toLowerCase();\n }", " let installationId = this.data.installationId;", " // If data.installationId is not set and we're not master, we can lookup in auth\n if (!installationId && !this.auth.isMaster) {\n installationId = this.auth.installationId;\n }", " if (installationId) {\n installationId = installationId.toLowerCase();\n }", " // Updating _Installation but not updating anything critical\n if (this.query && !this.data.deviceToken && !installationId && !this.data.deviceType) {\n return;\n }", " var promise = Promise.resolve();", " var idMatch; // Will be a match on either objectId or installationId\n var objectIdMatch;\n var installationIdMatch;\n var deviceTokenMatches = [];", " // Instead of issuing 3 reads, let's do it with one OR.\n const orQueries = [];\n if (this.query && this.query.objectId) {\n orQueries.push({\n objectId: this.query.objectId,\n });\n }\n if (installationId) {\n orQueries.push({\n installationId: installationId,\n });\n }\n if (this.data.deviceToken) {\n orQueries.push({ deviceToken: this.data.deviceToken });\n }", " if (orQueries.length == 0) {\n return;\n }", " promise = promise\n .then(() => {\n return this.config.database.find(\n '_Installation',\n {\n $or: orQueries,\n },\n {}\n );\n })\n .then(results => {\n results.forEach(result => {\n if (this.query && this.query.objectId && result.objectId == this.query.objectId) {\n objectIdMatch = result;\n }\n if (result.installationId == installationId) {\n installationIdMatch = result;\n }\n if (result.deviceToken == this.data.deviceToken) {\n deviceTokenMatches.push(result);\n }\n });", " // Sanity checks when running a query\n if (this.query && this.query.objectId) {\n if (!objectIdMatch) {\n throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found for update.');\n }\n if (\n this.data.installationId &&\n objectIdMatch.installationId &&\n this.data.installationId !== objectIdMatch.installationId\n ) {\n throw new Parse.Error(136, 'installationId may not be changed in this ' + 'operation');\n }\n if (\n this.data.deviceToken &&\n objectIdMatch.deviceToken &&\n this.data.deviceToken !== objectIdMatch.deviceToken &&\n !this.data.installationId &&\n !objectIdMatch.installationId\n ) {\n throw new Parse.Error(136, 'deviceToken may not be changed in this ' + 'operation');\n }\n if (\n this.data.deviceType &&\n this.data.deviceType &&\n this.data.deviceType !== objectIdMatch.deviceType\n ) {\n throw new Parse.Error(136, 'deviceType may not be changed in this ' + 'operation');\n }\n }", " if (this.query && this.query.objectId && objectIdMatch) {\n idMatch = objectIdMatch;\n }", " if (installationId && installationIdMatch) {\n idMatch = installationIdMatch;\n }\n // need to specify deviceType only if it's new\n if (!this.query && !this.data.deviceType && !idMatch) {\n throw new Parse.Error(135, 'deviceType must be specified in this operation');\n }\n })\n .then(() => {\n if (!idMatch) {\n if (!deviceTokenMatches.length) {\n return;\n } else if (\n deviceTokenMatches.length == 1 &&\n (!deviceTokenMatches[0]['installationId'] || !installationId)\n ) {\n // Single match on device token but none on installationId, and either\n // the passed object or the match is missing an installationId, so we\n // can just return the match.\n return deviceTokenMatches[0]['objectId'];\n } else if (!this.data.installationId) {\n throw new Parse.Error(\n 132,\n 'Must specify installationId when deviceToken ' +\n 'matches multiple Installation objects'\n );\n } else {\n // Multiple device token matches and we specified an installation ID,\n // or a single match where both the passed and matching objects have\n // an installation ID. Try cleaning out old installations that match\n // the deviceToken, and return nil to signal that a new object should\n // be created.\n var delQuery = {\n deviceToken: this.data.deviceToken,\n installationId: {\n $ne: installationId,\n },\n };\n if (this.data.appIdentifier) {\n delQuery['appIdentifier'] = this.data.appIdentifier;\n }\n this.config.database.destroy('_Installation', delQuery).catch(err => {\n if (err.code == Parse.Error.OBJECT_NOT_FOUND) {\n // no deletions were made. Can be ignored.\n return;\n }\n // rethrow the error\n throw err;\n });\n return;\n }\n } else {\n if (deviceTokenMatches.length == 1 && !deviceTokenMatches[0]['installationId']) {\n // Exactly one device token match and it doesn't have an installation\n // ID. This is the one case where we want to merge with the existing\n // object.\n const delQuery = { objectId: idMatch.objectId };\n return this.config.database\n .destroy('_Installation', delQuery)\n .then(() => {\n return deviceTokenMatches[0]['objectId'];\n })\n .catch(err => {\n if (err.code == Parse.Error.OBJECT_NOT_FOUND) {\n // no deletions were made. Can be ignored\n return;\n }\n // rethrow the error\n throw err;\n });\n } else {\n if (this.data.deviceToken && idMatch.deviceToken != this.data.deviceToken) {\n // We're setting the device token on an existing installation, so\n // we should try cleaning out old installations that match this\n // device token.\n const delQuery = {\n deviceToken: this.data.deviceToken,\n };\n // We have a unique install Id, use that to preserve\n // the interesting installation\n if (this.data.installationId) {\n delQuery['installationId'] = {\n $ne: this.data.installationId,\n };\n } else if (\n idMatch.objectId &&\n this.data.objectId &&\n idMatch.objectId == this.data.objectId\n ) {\n // we passed an objectId, preserve that instalation\n delQuery['objectId'] = {\n $ne: idMatch.objectId,\n };\n } else {\n // What to do here? can't really clean up everything...\n return idMatch.objectId;\n }\n if (this.data.appIdentifier) {\n delQuery['appIdentifier'] = this.data.appIdentifier;\n }\n this.config.database.destroy('_Installation', delQuery).catch(err => {\n if (err.code == Parse.Error.OBJECT_NOT_FOUND) {\n // no deletions were made. Can be ignored.\n return;\n }\n // rethrow the error\n throw err;\n });\n }\n // In non-merge scenarios, just return the installation match id\n return idMatch.objectId;\n }\n }\n })\n .then(objId => {\n if (objId) {\n this.query = { objectId: objId };\n delete this.data.objectId;\n delete this.data.createdAt;\n }\n // TODO: Validate ops (add/remove on channels, $inc on badge, etc.)\n });\n return promise;\n};", "// If we short-circuted the object response - then we need to make sure we expand all the files,\n// since this might not have a query, meaning it won't return the full result back.\n// TODO: (nlutsenko) This should die when we move to per-class based controllers on _Session/_User\nRestWrite.prototype.expandFilesForExistingObjects = function () {\n // Check whether we have a short-circuited response - only then run expansion.\n if (this.response && this.response.response) {\n this.config.filesController.expandFilesInObject(this.config, this.response.response);\n }\n};", "RestWrite.prototype.runDatabaseOperation = function () {\n if (this.response) {\n return;\n }", " if (this.className === '_Role') {\n this.config.cacheController.role.clear();\n }", " if (this.className === '_User' && this.query && this.auth.isUnauthenticated()) {\n throw new Parse.Error(\n Parse.Error.SESSION_MISSING,\n `Cannot modify user ${this.query.objectId}.`\n );\n }", " if (this.className === '_Product' && this.data.download) {\n this.data.downloadName = this.data.download.name;\n }", " // TODO: Add better detection for ACL, ensuring a user can't be locked from\n // their own user record.\n if (this.data.ACL && this.data.ACL['*unresolved']) {\n throw new Parse.Error(Parse.Error.INVALID_ACL, 'Invalid ACL.');\n }", " if (this.query) {\n // Force the user to not lockout\n // Matched with parse.com\n if (this.className === '_User' && this.data.ACL && this.auth.isMaster !== true) {\n this.data.ACL[this.query.objectId] = { read: true, write: true };\n }\n // update password timestamp if user password is being changed\n if (\n this.className === '_User' &&\n this.data._hashed_password &&\n this.config.passwordPolicy &&\n this.config.passwordPolicy.maxPasswordAge\n ) {\n this.data._password_changed_at = Parse._encode(new Date());\n }\n // Ignore createdAt when update\n delete this.data.createdAt;", " let defer = Promise.resolve();\n // if password history is enabled then save the current password to history\n if (\n this.className === '_User' &&\n this.data._hashed_password &&\n this.config.passwordPolicy &&\n this.config.passwordPolicy.maxPasswordHistory\n ) {\n defer = this.config.database\n .find(\n '_User',\n { objectId: this.objectId() },\n { keys: ['_password_history', '_hashed_password'] }\n )\n .then(results => {\n if (results.length != 1) {\n throw undefined;\n }\n const user = results[0];\n let oldPasswords = [];\n if (user._password_history) {\n oldPasswords = _.take(\n user._password_history,\n this.config.passwordPolicy.maxPasswordHistory\n );\n }\n //n-1 passwords go into history including last password\n while (\n oldPasswords.length > Math.max(0, this.config.passwordPolicy.maxPasswordHistory - 2)\n ) {\n oldPasswords.shift();\n }\n oldPasswords.push(user.password);\n this.data._password_history = oldPasswords;\n });\n }", " return defer.then(() => {\n // Run an update\n return this.config.database\n .update(\n this.className,\n this.query,\n this.data,\n this.runOptions,\n false,\n false,\n this.validSchemaController\n )\n .then(response => {\n response.updatedAt = this.updatedAt;\n this._updateResponseWithData(response, this.data);\n this.response = { response };\n });\n });\n } else {\n // Set the default ACL and password timestamp for the new _User\n if (this.className === '_User') {\n var ACL = this.data.ACL;\n // default public r/w ACL\n if (!ACL) {\n ACL = {};\n ACL['*'] = { read: true, write: false };\n }\n // make sure the user is not locked down\n ACL[this.data.objectId] = { read: true, write: true };\n this.data.ACL = ACL;\n // password timestamp to be used when password expiry policy is enforced\n if (this.config.passwordPolicy && this.config.passwordPolicy.maxPasswordAge) {\n this.data._password_changed_at = Parse._encode(new Date());\n }\n }", " // Run a create\n return this.config.database\n .create(this.className, this.data, this.runOptions, false, this.validSchemaController)\n .catch(error => {\n if (this.className !== '_User' || error.code !== Parse.Error.DUPLICATE_VALUE) {\n throw error;\n }", " // Quick check, if we were able to infer the duplicated field name\n if (error && error.userInfo && error.userInfo.duplicated_field === 'username') {\n throw new Parse.Error(\n Parse.Error.USERNAME_TAKEN,\n 'Account already exists for this username.'\n );\n }", " if (error && error.userInfo && error.userInfo.duplicated_field === 'email') {\n throw new Parse.Error(\n Parse.Error.EMAIL_TAKEN,\n 'Account already exists for this email address.'\n );\n }", " // If this was a failed user creation due to username or email already taken, we need to\n // check whether it was username or email and return the appropriate error.\n // Fallback to the original method\n // TODO: See if we can later do this without additional queries by using named indexes.\n return this.config.database\n .find(\n this.className,\n {\n username: this.data.username,\n objectId: { $ne: this.objectId() },\n },\n { limit: 1 }\n )\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.USERNAME_TAKEN,\n 'Account already exists for this username.'\n );\n }\n return this.config.database.find(\n this.className,\n { email: this.data.email, objectId: { $ne: this.objectId() } },\n { limit: 1 }\n );\n })\n .then(results => {\n if (results.length > 0) {\n throw new Parse.Error(\n Parse.Error.EMAIL_TAKEN,\n 'Account already exists for this email address.'\n );\n }\n throw new Parse.Error(\n Parse.Error.DUPLICATE_VALUE,\n 'A duplicate value for a field with unique values was provided'\n );\n });\n })\n .then(response => {\n response.objectId = this.data.objectId;\n response.createdAt = this.data.createdAt;", " if (this.responseShouldHaveUsername) {\n response.username = this.data.username;\n }\n this._updateResponseWithData(response, this.data);\n this.response = {\n status: 201,\n response,\n location: this.location(),\n };\n });\n }\n};", "// Returns nothing - doesn't wait for the trigger.\nRestWrite.prototype.runAfterSaveTrigger = function () {\n if (!this.response || !this.response.response) {\n return;\n }", " // Avoid doing any setup for triggers if there is no 'afterSave' trigger for this class.\n const hasAfterSaveHook = triggers.triggerExists(\n this.className,\n triggers.Types.afterSave,\n this.config.applicationId\n );\n const hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className);\n if (!hasAfterSaveHook && !hasLiveQuery) {\n return Promise.resolve();\n }", " var extraData = { className: this.className };\n if (this.query && this.query.objectId) {\n extraData.objectId = this.query.objectId;\n }", " // Build the original object, we only do this for a update write.\n let originalObject;\n if (this.query && this.query.objectId) {\n originalObject = triggers.inflate(extraData, this.originalData);\n }", " // Build the inflated object, different from beforeSave, originalData is not empty\n // since developers can change data in the beforeSave.\n const updatedObject = this.buildUpdatedObject(extraData);\n updatedObject._handleSaveResponse(this.response.response, this.response.status || 200);", " this.config.database.loadSchema().then(schemaController => {\n // Notifiy LiveQueryServer if possible\n const perms = schemaController.getClassLevelPermissions(updatedObject.className);\n this.config.liveQueryController.onAfterSave(\n updatedObject.className,\n updatedObject,\n originalObject,\n perms\n );\n });", " // Run afterSave trigger\n return triggers\n .maybeRunTrigger(\n triggers.Types.afterSave,\n this.auth,\n updatedObject,\n originalObject,\n this.config,\n this.context\n )\n .then(result => {\n if (result && typeof result === 'object') {\n this.response.response = result;\n }\n })\n .catch(function (err) {\n logger.warn('afterSave caught an error', err);\n });\n};", "// A helper to figure out what location this operation happens at.\nRestWrite.prototype.location = function () {\n var middle = this.className === '_User' ? '/users/' : '/classes/' + this.className + '/';\n const mount = this.config.mount || this.config.serverURL;\n return mount + middle + this.data.objectId;\n};", "// A helper to get the object id for this operation.\n// Because it could be either on the query or on the data\nRestWrite.prototype.objectId = function () {\n return this.data.objectId || this.query.objectId;\n};", "// Returns a copy of the data and delete bad keys (_auth_data, _hashed_password...)\nRestWrite.prototype.sanitizedData = function () {\n const data = Object.keys(this.data).reduce((data, key) => {\n // Regexp comes from Parse.Object.prototype.validate\n if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {\n delete data[key];\n }\n return data;\n }, deepcopy(this.data));\n return Parse._decode(undefined, data);\n};", "// Returns an updated copy of the object\nRestWrite.prototype.buildUpdatedObject = function (extraData) {\n const updatedObject = triggers.inflate(extraData, this.originalData);\n Object.keys(this.data).reduce(function (data, key) {\n if (key.indexOf('.') > 0) {\n if (typeof data[key].__op === 'string') {\n updatedObject.set(key, data[key]);\n } else {\n // subdocument key with dot notation { 'x.y': v } => { 'x': { 'y' : v } })\n const splittedKey = key.split('.');\n const parentProp = splittedKey[0];\n let parentVal = updatedObject.get(parentProp);\n if (typeof parentVal !== 'object') {\n parentVal = {};\n }\n parentVal[splittedKey[1]] = data[key];\n updatedObject.set(parentProp, parentVal);\n }\n delete data[key];\n }\n return data;\n }, deepcopy(this.data));", " updatedObject.set(this.sanitizedData());\n return updatedObject;\n};", "RestWrite.prototype.cleanUserAuthData = function () {\n if (this.response && this.response.response && this.className === '_User') {\n const user = this.response.response;\n if (user.authData) {\n Object.keys(user.authData).forEach(provider => {\n if (user.authData[provider] === null) {\n delete user.authData[provider];\n }\n });\n if (Object.keys(user.authData).length == 0) {\n delete user.authData;\n }\n }\n }\n};", "RestWrite.prototype._updateResponseWithData = function (response, data) {\n if (_.isEmpty(this.storage.fieldsChangedByTrigger)) {\n return response;\n }\n const clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK);\n this.storage.fieldsChangedByTrigger.forEach(fieldName => {\n const dataValue = data[fieldName];", " if (!Object.prototype.hasOwnProperty.call(response, fieldName)) {\n response[fieldName] = dataValue;\n }", " // Strips operations from responses\n if (response[fieldName] && response[fieldName].__op) {\n delete response[fieldName];\n if (clientSupportsDelete && dataValue.__op == 'Delete') {\n response[fieldName] = dataValue;\n }\n }\n });\n return response;\n};", "export default RestWrite;\nmodule.exports = RestWrite;" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 2430, 857], "buggy_code_start_loc": [4, 2377, 857], "filenames": ["CHANGELOG.md", "spec/ParseUser.spec.js", "src/RestWrite.js"], "fixing_code_end_loc": [10, 2434, 862], "fixing_code_start_loc": [4, 2377, 858], "message": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:parseplatform:parse-server:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "9DE0F06D-5868-45AD-B21E-C5268BCC7F52", "versionEndExcluding": "4.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Developers can use the REST API to signup users and also allow users to login anonymously. Prior to version 4.5.1, when an anonymous user is first signed up using REST, the server creates session incorrectly. Particularly, the `authProvider` field in `_Session` class under `createdWith` shows the user logged in creating a password. If a developer later depends on the `createdWith` field to provide a different level of access between a password user and anonymous user, the server incorrectly classified the session type as being created with a `password`. The server does not currently use `createdWith` to make decisions about internal functions, so if a developer is not using `createdWith` directly, they are not affected. The vulnerability only affects users who depend on `createdWith` by using it directly. The issue is patched in Parse Server version 4.5.1. As a workaround, do not use the `createdWith` Session field to make decisions if one allows anonymous login."}, {"lang": "es", "value": "Parse Server es un backend de c\u00f3digo abierto que puede desplegarse en cualquier infraestructura que pueda ejecutar Node.js. Los desarrolladores pueden usar la API REST para registrar usuarios y tambi\u00e9n permitir a usuarios registrarse an\u00f3nimamente. Versiones anteriores a 4.5.1, cuando un usuario an\u00f3nimo es registrado por primera vez usando REST, el servidor creaba la sesi\u00f3n incorrectamente. En particular, el campo \"authProvider\" de la clase \"_Session\" en \"createdWith\" muestra que el usuario se ha registrado creando una contrase\u00f1a. Si un desarrollador depende posteriormente del campo \"createdWith\" para proporcionar un nivel de acceso diferente entre un usuario con contrase\u00f1a y un usuario an\u00f3nimo, el servidor clasifica incorrectamente el tipo de sesi\u00f3n como creada con un \"password\". El servidor no usa actualmente \"createdWith\" para tomar decisiones sobre las funciones internas, por lo que si un desarrollador no est\u00e1 usando \"createdWith\" directamente, no est\u00e1 afectado. La vulnerabilidad s\u00f3lo afecta a usuarios que dependen de \"createdWith\" al usarlo directamente. El problema est\u00e1 parcheado en Parse Server versi\u00f3n 4.5.1. Como soluci\u00f3n, no use el campo de sesi\u00f3n \"createdWith\" para tomar decisiones si se permite el acceso an\u00f3nimo."}], "evaluatorComment": null, "id": "CVE-2021-39138", "lastModified": "2022-08-12T18:01:28.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 6.4, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.5, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-19T16:15:12.483", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/releases/tag/4.5.1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/parse-community/parse-server/security/advisories/GHSA-23r4-5mxp-c7g5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-863"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/parse-community/parse-server/commit/147bd9a3dc43391e92c36e05d5db860b04ca27db"}, "type": "CWE-863"}
299
Determine whether the {function_name} code is vulnerable or not.
[ "/* hivex - Windows Registry \"hive\" extraction library.\n * Copyright (C) 2009-2011 Red Hat Inc.\n * Derived from code by Petter Nordahl-Hagen under a compatible license:\n * Copyright (c) 1997-2007 Petter Nordahl-Hagen.\n * Derived from code by Markus Stephany under a compatible license:\n * Copyright (c) 2000-2004, Markus Stephany.\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * See file LICENSE for the full license.\n */", "#include <config.h>", "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <inttypes.h>\n#include <string.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n#include <errno.h>\n#include <assert.h>", "#ifdef HAVE_MMAP\n#include <sys/mman.h>\n#else\n/* On systems without mmap (and munmap), use a replacement function. */\n#include \"mmap.h\"\n#endif", "#include \"full-read.h\"\n#include \"full-write.h\"\n#include \"c-ctype.h\"", "#include \"hivex.h\"\n#include \"hivex-internal.h\"", "static uint32_t\nheader_checksum (const hive_h *h)\n{\n uint32_t *daddr = (uint32_t *) h->addr;\n size_t i;\n uint32_t sum = 0;", " for (i = 0; i < 0x1fc / 4; ++i) {\n sum ^= le32toh (*daddr);\n daddr++;\n }", " return sum;\n}", "#define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)", "hive_h *\nhivex_open (const char *filename, int flags)\n{\n hive_h *h = NULL;", " assert (sizeof (struct ntreg_header) == 0x1000);\n assert (offsetof (struct ntreg_header, csum) == 0x1fc);", " h = calloc (1, sizeof *h);\n if (h == NULL)\n goto error;", " h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;", " const char *debug = getenv (\"HIVEX_DEBUG\");\n if (debug && STREQ (debug, \"1\"))\n h->msglvl = 2;", " DEBUG (2, \"created handle %p\", h);", " h->writable = !!(flags & HIVEX_OPEN_WRITE);\n h->filename = strdup (filename);\n if (h->filename == NULL)\n goto error;", "#ifdef O_CLOEXEC\n h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);\n#else\n h->fd = open (filename, O_RDONLY | O_BINARY);\n#endif\n if (h->fd == -1)\n goto error;\n#ifndef O_CLOEXEC\n fcntl (h->fd, F_SETFD, FD_CLOEXEC);\n#endif", " struct stat statbuf;\n if (fstat (h->fd, &statbuf) == -1)\n goto error;", " h->size = statbuf.st_size;", "", "\n if (!h->writable) {\n h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);\n if (h->addr == MAP_FAILED)\n goto error;", " DEBUG (2, \"mapped file at %p\", h->addr);\n } else {\n h->addr = malloc (h->size);\n if (h->addr == NULL)\n goto error;", " if (full_read (h->fd, h->addr, h->size) < h->size)\n goto error;", " /* We don't need the file descriptor along this path, since we\n * have read all the data.\n */\n if (close (h->fd) == -1)\n goto error;\n h->fd = -1;\n }", " /* Check header. */\n if (h->hdr->magic[0] != 'r' ||\n h->hdr->magic[1] != 'e' ||\n h->hdr->magic[2] != 'g' ||\n h->hdr->magic[3] != 'f') {\n SET_ERRNO (ENOTSUP,\n \"%s: not a Windows NT Registry hive file\", filename);\n goto error;\n }", " /* Check major version. */\n uint32_t major_ver = le32toh (h->hdr->major_ver);\n if (major_ver != 1) {\n SET_ERRNO (ENOTSUP,\n \"%s: hive file major version %\" PRIu32 \" (expected 1)\",\n filename, major_ver);\n goto error;\n }", " h->bitmap = calloc (1 + h->size / 32, 1);\n if (h->bitmap == NULL)\n goto error;", " /* Header checksum. */\n uint32_t sum = header_checksum (h);\n if (sum != le32toh (h->hdr->csum)) {\n SET_ERRNO (EINVAL, \"%s: bad checksum in hive header\", filename);\n goto error;\n }", " /* Last modified time. */\n h->last_modified = le64toh ((int64_t) h->hdr->last_modified);", " if (h->msglvl >= 2) {\n char *name = _hivex_windows_utf16_to_utf8 (h->hdr->name, 64);", " fprintf (stderr,\n \"hivex_open: header fields:\\n\"\n \" file version %\" PRIu32 \".%\" PRIu32 \"\\n\"\n \" sequence nos %\" PRIu32 \" %\" PRIu32 \"\\n\"\n \" (sequences nos should match if hive was synched at shutdown)\\n\"\n \" last modified %\" PRIu64 \"\\n\"\n \" (Windows filetime, x 100 ns since 1601-01-01)\\n\"\n \" original file name %s\\n\"\n \" (only 32 chars are stored, name is probably truncated)\\n\"\n \" root offset 0x%x + 0x1000\\n\"\n \" end of last page 0x%x + 0x1000 (total file size 0x%zx)\\n\"\n \" checksum 0x%x (calculated 0x%x)\\n\",\n major_ver, le32toh (h->hdr->minor_ver),\n le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),\n h->last_modified,\n name ? name : \"(conversion failed)\",\n le32toh (h->hdr->offset),\n le32toh (h->hdr->blocks), h->size,\n le32toh (h->hdr->csum), sum);\n free (name);\n }", " h->rootoffs = le32toh (h->hdr->offset) + 0x1000;\n h->endpages = le32toh (h->hdr->blocks) + 0x1000;", " DEBUG (2, \"root offset = 0x%zx\", h->rootoffs);", " /* We'll set this flag when we see a block with the root offset (ie.\n * the root block).\n */\n int seen_root_block = 0, bad_root_block = 0;", " /* Collect some stats. */\n size_t pages = 0; /* Number of hbin pages read. */\n size_t smallest_page = SIZE_MAX, largest_page = 0;\n size_t blocks = 0; /* Total number of blocks found. */\n size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;\n size_t used_blocks = 0; /* Total number of used blocks found. */\n size_t used_size = 0; /* Total size (bytes) of used blocks. */", " /* Read the pages and blocks. The aim here is to be robust against\n * corrupt or malicious registries. So we make sure the loops\n * always make forward progress. We add the address of each block\n * we read to a hash table so pointers will only reference the start\n * of valid blocks.\n */\n size_t off;\n struct ntreg_hbin_page *page;\n for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {\n if (off >= h->endpages)\n break;", " page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] != 'h' ||\n page->magic[1] != 'b' ||\n page->magic[2] != 'i' ||\n page->magic[3] != 'n') {\n SET_ERRNO (ENOTSUP,\n \"%s: trailing garbage at end of file \"\n \"(at 0x%zx, after %zu pages)\",\n filename, off, pages);\n goto error;\n }", " size_t page_size = le32toh (page->page_size);\n DEBUG (2, \"page at 0x%zx, size %zu\", off, page_size);\n pages++;\n if (page_size < smallest_page) smallest_page = page_size;\n if (page_size > largest_page) largest_page = page_size;", " if (page_size <= sizeof (struct ntreg_hbin_page) ||\n (page_size & 0x0fff) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx, bad registry\",\n filename, page_size, off);\n goto error;\n }", " /* Read the blocks in this page. */\n size_t blkoff;\n struct ntreg_hbin_block *block;\n size_t seg_len;\n for (blkoff = off + 0x20;\n blkoff < off + page_size;\n blkoff += seg_len) {\n blocks++;", " int is_root = blkoff == h->rootoffs;\n if (is_root)\n seen_root_block = 1;", " block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);\n int used;\n seg_len = block_len (h, blkoff, &used);\n if (seg_len <= 4 || (seg_len & 3) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: block size %\" PRIu32 \" at 0x%zx, bad registry\",\n filename, le32toh (block->seg_len), blkoff);\n goto error;\n }", " if (h->msglvl >= 2) {\n unsigned char *id = (unsigned char *) block->id;\n int id0 = id[0], id1 = id[1];", " fprintf (stderr, \"%s: %s: \"\n \"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\\n\",\n \"hivex\", __func__,\n used ? \"used\" : \"free\",\n id0, id1,\n c_isprint (id0) ? id0 : '.',\n c_isprint (id1) ? id1 : '.',\n blkoff,\n seg_len, is_root ? \" (root)\" : \"\");\n }", " blocks_bytes += seg_len;\n if (seg_len < smallest_block) smallest_block = seg_len;\n if (seg_len > largest_block) largest_block = seg_len;", " if (is_root && !used)\n bad_root_block = 1;", " if (used) {\n used_blocks++;\n used_size += seg_len;", " /* Root block must be an nk-block. */\n if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))\n bad_root_block = 1;", " /* Note this blkoff is a valid address. */\n BITMAP_SET (h->bitmap, blkoff);\n }\n }\n }", " if (!seen_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: no root block found\", filename);\n goto error;\n }", " if (bad_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: bad root block (free or not nk)\", filename);\n goto error;\n }", " DEBUG (1, \"successfully read Windows Registry hive file:\\n\"\n \" pages: %zu [sml: %zu, lge: %zu]\\n\"\n \" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\\n\"\n \" blocks used: %zu\\n\"\n \" bytes used: %zu\",\n pages, smallest_page, largest_page,\n blocks, smallest_block, blocks_bytes / blocks, largest_block,\n used_blocks, used_size);", " return h;", " error:;\n int err = errno;\n if (h) {\n free (h->bitmap);\n if (h->addr && h->size && h->addr != MAP_FAILED) {\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n }\n if (h->fd >= 0)\n close (h->fd);\n free (h->filename);\n free (h);\n }\n errno = err;\n return NULL;\n}", "int\nhivex_close (hive_h *h)\n{\n int r;", " DEBUG (1, \"hivex_close\");", " free (h->bitmap);\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n if (h->fd >= 0)\n r = close (h->fd);\n else\n r = 0;\n free (h->filename);\n free (h);", " return r;\n}", "int\nhivex_commit (hive_h *h, const char *filename, int flags)\n{\n int fd;", " if (flags != 0) {\n SET_ERRNO (EINVAL, \"flags != 0\");\n return -1;\n }", " CHECK_WRITABLE (-1);", " filename = filename ? : h->filename;\n#ifdef O_CLOEXEC\n fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_CLOEXEC|O_BINARY,\n 0666);\n#else\n fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_BINARY, 0666);\n#endif\n if (fd == -1)\n return -1;\n#ifndef O_CLOEXEC\n fcntl (fd, F_SETFD, FD_CLOEXEC);\n#endif", " /* Update the header fields. */\n uint32_t sequence = le32toh (h->hdr->sequence1);\n sequence++;\n h->hdr->sequence1 = htole32 (sequence);\n h->hdr->sequence2 = htole32 (sequence);\n /* XXX Ought to update h->hdr->last_modified. */\n h->hdr->blocks = htole32 (h->endpages - 0x1000);", " /* Recompute header checksum. */\n uint32_t sum = header_checksum (h);\n h->hdr->csum = htole32 (sum);", " DEBUG (2, \"hivex_commit: new header checksum: 0x%x\", sum);", " if (full_write (fd, h->addr, h->size) != h->size) {\n int err = errno;\n close (fd);\n errno = err;\n return -1;\n }", " if (close (fd) == -1)\n return -1;", " return 0;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [105], "buggy_code_start_loc": [105], "filenames": ["lib/handle.c"], "fixing_code_end_loc": [113], "fixing_code_start_loc": [106], "message": "lib/handle.c in Hivex before 1.3.11 allows local users to execute arbitrary code and gain privileges via a small hive files, which triggers an out-of-bounds read or write.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:opensuse:13.1:*:*:*:*:*:*:*", "matchCriteriaId": "A10BC294-9196-425F-9FB0-B1625465B47F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:13.2:*:*:*:*:*:*:*", "matchCriteriaId": "03117DF1-3BEC-4B8D-AD63-DBBDB2126081", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux_desktop:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "EE249E1B-A1FD-4E08-AA71-A0E1F10FFE97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_desktop:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "33C068A4-3780-4EAB-A937-6082DF847564", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_hpc_node:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2FAC325-6EEB-466D-9EBA-8ED4DBC9CFBF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "9BBCD86A-E6C7-4444-9D74-F861084090F0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "51EF4996-72F4-4FA4-814F-F5991E7A8318", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_workstation:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "E5ED5807-55B7-47C5-97A6-03233F4FBC3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_workstation:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "825ECE2D-E232-46E0-A047-074B34DB1E97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:debian:hivex:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C345E9F-F4FB-46BE-B55C-DBD7E7DD605F", "versionEndExcluding": null, "versionEndIncluding": "1.3.10-2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "lib/handle.c in Hivex before 1.3.11 allows local users to execute arbitrary code and gain privileges via a small hive files, which triggers an out-of-bounds read or write."}, {"lang": "es", "value": "lib/handle.c en Hivex anterior a 1.3.11 permite a usuarios locales ejecutar c\u00f3digo arbitrario y ganar privilegios a trav\u00e9s de un fichero de hive peque\u00f1o, lo que provoca una lectura o escritura fuera de rango."}], "evaluatorComment": null, "id": "CVE-2014-9273", "lastModified": "2018-10-30T16:27:35.843", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": true, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-08T16:59:11.947", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2015-02/msg00005.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2015-0301.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2015-1378.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/25/6"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/12/04/14"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.securityfocus.com/bid/71279"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1167756"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch", "Issue Tracking"], "url": "https://github.com/libguestfs/hivex/commit/357f26fa64fd1d9ccac2331fe174a8ee9c607adb"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch", "Issue Tracking"], "url": "https://github.com/libguestfs/hivex/commit/4bbdf555f88baeae0fa804a369a81a83908bd705"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://security.gentoo.org/glsa/201503-07"}, {"source": "secalert@redhat.com", "tags": ["Vendor Advisory"], "url": "https://www.redhat.com/archives/libguestfs/2014-October/msg00235.html"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/libguestfs/hivex/commit/357f26fa64fd1d9ccac2331fe174a8ee9c607adb"}, "type": "CWE-119"}
300
Determine whether the {function_name} code is vulnerable or not.
[ "/* hivex - Windows Registry \"hive\" extraction library.\n * Copyright (C) 2009-2011 Red Hat Inc.\n * Derived from code by Petter Nordahl-Hagen under a compatible license:\n * Copyright (c) 1997-2007 Petter Nordahl-Hagen.\n * Derived from code by Markus Stephany under a compatible license:\n * Copyright (c) 2000-2004, Markus Stephany.\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * See file LICENSE for the full license.\n */", "#include <config.h>", "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <inttypes.h>\n#include <string.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n#include <errno.h>\n#include <assert.h>", "#ifdef HAVE_MMAP\n#include <sys/mman.h>\n#else\n/* On systems without mmap (and munmap), use a replacement function. */\n#include \"mmap.h\"\n#endif", "#include \"full-read.h\"\n#include \"full-write.h\"\n#include \"c-ctype.h\"", "#include \"hivex.h\"\n#include \"hivex-internal.h\"", "static uint32_t\nheader_checksum (const hive_h *h)\n{\n uint32_t *daddr = (uint32_t *) h->addr;\n size_t i;\n uint32_t sum = 0;", " for (i = 0; i < 0x1fc / 4; ++i) {\n sum ^= le32toh (*daddr);\n daddr++;\n }", " return sum;\n}", "#define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)", "hive_h *\nhivex_open (const char *filename, int flags)\n{\n hive_h *h = NULL;", " assert (sizeof (struct ntreg_header) == 0x1000);\n assert (offsetof (struct ntreg_header, csum) == 0x1fc);", " h = calloc (1, sizeof *h);\n if (h == NULL)\n goto error;", " h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;", " const char *debug = getenv (\"HIVEX_DEBUG\");\n if (debug && STREQ (debug, \"1\"))\n h->msglvl = 2;", " DEBUG (2, \"created handle %p\", h);", " h->writable = !!(flags & HIVEX_OPEN_WRITE);\n h->filename = strdup (filename);\n if (h->filename == NULL)\n goto error;", "#ifdef O_CLOEXEC\n h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);\n#else\n h->fd = open (filename, O_RDONLY | O_BINARY);\n#endif\n if (h->fd == -1)\n goto error;\n#ifndef O_CLOEXEC\n fcntl (h->fd, F_SETFD, FD_CLOEXEC);\n#endif", " struct stat statbuf;\n if (fstat (h->fd, &statbuf) == -1)\n goto error;", " h->size = statbuf.st_size;", "\n if (h->size < 0x2000) {\n SET_ERRNO (EINVAL,\n \"%s: file is too small to be a Windows NT Registry hive file\",\n filename);\n goto error;\n }", "\n if (!h->writable) {\n h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);\n if (h->addr == MAP_FAILED)\n goto error;", " DEBUG (2, \"mapped file at %p\", h->addr);\n } else {\n h->addr = malloc (h->size);\n if (h->addr == NULL)\n goto error;", " if (full_read (h->fd, h->addr, h->size) < h->size)\n goto error;", " /* We don't need the file descriptor along this path, since we\n * have read all the data.\n */\n if (close (h->fd) == -1)\n goto error;\n h->fd = -1;\n }", " /* Check header. */\n if (h->hdr->magic[0] != 'r' ||\n h->hdr->magic[1] != 'e' ||\n h->hdr->magic[2] != 'g' ||\n h->hdr->magic[3] != 'f') {\n SET_ERRNO (ENOTSUP,\n \"%s: not a Windows NT Registry hive file\", filename);\n goto error;\n }", " /* Check major version. */\n uint32_t major_ver = le32toh (h->hdr->major_ver);\n if (major_ver != 1) {\n SET_ERRNO (ENOTSUP,\n \"%s: hive file major version %\" PRIu32 \" (expected 1)\",\n filename, major_ver);\n goto error;\n }", " h->bitmap = calloc (1 + h->size / 32, 1);\n if (h->bitmap == NULL)\n goto error;", " /* Header checksum. */\n uint32_t sum = header_checksum (h);\n if (sum != le32toh (h->hdr->csum)) {\n SET_ERRNO (EINVAL, \"%s: bad checksum in hive header\", filename);\n goto error;\n }", " /* Last modified time. */\n h->last_modified = le64toh ((int64_t) h->hdr->last_modified);", " if (h->msglvl >= 2) {\n char *name = _hivex_windows_utf16_to_utf8 (h->hdr->name, 64);", " fprintf (stderr,\n \"hivex_open: header fields:\\n\"\n \" file version %\" PRIu32 \".%\" PRIu32 \"\\n\"\n \" sequence nos %\" PRIu32 \" %\" PRIu32 \"\\n\"\n \" (sequences nos should match if hive was synched at shutdown)\\n\"\n \" last modified %\" PRIu64 \"\\n\"\n \" (Windows filetime, x 100 ns since 1601-01-01)\\n\"\n \" original file name %s\\n\"\n \" (only 32 chars are stored, name is probably truncated)\\n\"\n \" root offset 0x%x + 0x1000\\n\"\n \" end of last page 0x%x + 0x1000 (total file size 0x%zx)\\n\"\n \" checksum 0x%x (calculated 0x%x)\\n\",\n major_ver, le32toh (h->hdr->minor_ver),\n le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),\n h->last_modified,\n name ? name : \"(conversion failed)\",\n le32toh (h->hdr->offset),\n le32toh (h->hdr->blocks), h->size,\n le32toh (h->hdr->csum), sum);\n free (name);\n }", " h->rootoffs = le32toh (h->hdr->offset) + 0x1000;\n h->endpages = le32toh (h->hdr->blocks) + 0x1000;", " DEBUG (2, \"root offset = 0x%zx\", h->rootoffs);", " /* We'll set this flag when we see a block with the root offset (ie.\n * the root block).\n */\n int seen_root_block = 0, bad_root_block = 0;", " /* Collect some stats. */\n size_t pages = 0; /* Number of hbin pages read. */\n size_t smallest_page = SIZE_MAX, largest_page = 0;\n size_t blocks = 0; /* Total number of blocks found. */\n size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;\n size_t used_blocks = 0; /* Total number of used blocks found. */\n size_t used_size = 0; /* Total size (bytes) of used blocks. */", " /* Read the pages and blocks. The aim here is to be robust against\n * corrupt or malicious registries. So we make sure the loops\n * always make forward progress. We add the address of each block\n * we read to a hash table so pointers will only reference the start\n * of valid blocks.\n */\n size_t off;\n struct ntreg_hbin_page *page;\n for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {\n if (off >= h->endpages)\n break;", " page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] != 'h' ||\n page->magic[1] != 'b' ||\n page->magic[2] != 'i' ||\n page->magic[3] != 'n') {\n SET_ERRNO (ENOTSUP,\n \"%s: trailing garbage at end of file \"\n \"(at 0x%zx, after %zu pages)\",\n filename, off, pages);\n goto error;\n }", " size_t page_size = le32toh (page->page_size);\n DEBUG (2, \"page at 0x%zx, size %zu\", off, page_size);\n pages++;\n if (page_size < smallest_page) smallest_page = page_size;\n if (page_size > largest_page) largest_page = page_size;", " if (page_size <= sizeof (struct ntreg_hbin_page) ||\n (page_size & 0x0fff) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx, bad registry\",\n filename, page_size, off);\n goto error;\n }", " /* Read the blocks in this page. */\n size_t blkoff;\n struct ntreg_hbin_block *block;\n size_t seg_len;\n for (blkoff = off + 0x20;\n blkoff < off + page_size;\n blkoff += seg_len) {\n blocks++;", " int is_root = blkoff == h->rootoffs;\n if (is_root)\n seen_root_block = 1;", " block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);\n int used;\n seg_len = block_len (h, blkoff, &used);\n if (seg_len <= 4 || (seg_len & 3) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: block size %\" PRIu32 \" at 0x%zx, bad registry\",\n filename, le32toh (block->seg_len), blkoff);\n goto error;\n }", " if (h->msglvl >= 2) {\n unsigned char *id = (unsigned char *) block->id;\n int id0 = id[0], id1 = id[1];", " fprintf (stderr, \"%s: %s: \"\n \"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\\n\",\n \"hivex\", __func__,\n used ? \"used\" : \"free\",\n id0, id1,\n c_isprint (id0) ? id0 : '.',\n c_isprint (id1) ? id1 : '.',\n blkoff,\n seg_len, is_root ? \" (root)\" : \"\");\n }", " blocks_bytes += seg_len;\n if (seg_len < smallest_block) smallest_block = seg_len;\n if (seg_len > largest_block) largest_block = seg_len;", " if (is_root && !used)\n bad_root_block = 1;", " if (used) {\n used_blocks++;\n used_size += seg_len;", " /* Root block must be an nk-block. */\n if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))\n bad_root_block = 1;", " /* Note this blkoff is a valid address. */\n BITMAP_SET (h->bitmap, blkoff);\n }\n }\n }", " if (!seen_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: no root block found\", filename);\n goto error;\n }", " if (bad_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: bad root block (free or not nk)\", filename);\n goto error;\n }", " DEBUG (1, \"successfully read Windows Registry hive file:\\n\"\n \" pages: %zu [sml: %zu, lge: %zu]\\n\"\n \" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\\n\"\n \" blocks used: %zu\\n\"\n \" bytes used: %zu\",\n pages, smallest_page, largest_page,\n blocks, smallest_block, blocks_bytes / blocks, largest_block,\n used_blocks, used_size);", " return h;", " error:;\n int err = errno;\n if (h) {\n free (h->bitmap);\n if (h->addr && h->size && h->addr != MAP_FAILED) {\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n }\n if (h->fd >= 0)\n close (h->fd);\n free (h->filename);\n free (h);\n }\n errno = err;\n return NULL;\n}", "int\nhivex_close (hive_h *h)\n{\n int r;", " DEBUG (1, \"hivex_close\");", " free (h->bitmap);\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n if (h->fd >= 0)\n r = close (h->fd);\n else\n r = 0;\n free (h->filename);\n free (h);", " return r;\n}", "int\nhivex_commit (hive_h *h, const char *filename, int flags)\n{\n int fd;", " if (flags != 0) {\n SET_ERRNO (EINVAL, \"flags != 0\");\n return -1;\n }", " CHECK_WRITABLE (-1);", " filename = filename ? : h->filename;\n#ifdef O_CLOEXEC\n fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_CLOEXEC|O_BINARY,\n 0666);\n#else\n fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_BINARY, 0666);\n#endif\n if (fd == -1)\n return -1;\n#ifndef O_CLOEXEC\n fcntl (fd, F_SETFD, FD_CLOEXEC);\n#endif", " /* Update the header fields. */\n uint32_t sequence = le32toh (h->hdr->sequence1);\n sequence++;\n h->hdr->sequence1 = htole32 (sequence);\n h->hdr->sequence2 = htole32 (sequence);\n /* XXX Ought to update h->hdr->last_modified. */\n h->hdr->blocks = htole32 (h->endpages - 0x1000);", " /* Recompute header checksum. */\n uint32_t sum = header_checksum (h);\n h->hdr->csum = htole32 (sum);", " DEBUG (2, \"hivex_commit: new header checksum: 0x%x\", sum);", " if (full_write (fd, h->addr, h->size) != h->size) {\n int err = errno;\n close (fd);\n errno = err;\n return -1;\n }", " if (close (fd) == -1)\n return -1;", " return 0;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [105], "buggy_code_start_loc": [105], "filenames": ["lib/handle.c"], "fixing_code_end_loc": [113], "fixing_code_start_loc": [106], "message": "lib/handle.c in Hivex before 1.3.11 allows local users to execute arbitrary code and gain privileges via a small hive files, which triggers an out-of-bounds read or write.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:opensuse:13.1:*:*:*:*:*:*:*", "matchCriteriaId": "A10BC294-9196-425F-9FB0-B1625465B47F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:opensuse:13.2:*:*:*:*:*:*:*", "matchCriteriaId": "03117DF1-3BEC-4B8D-AD63-DBBDB2126081", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux_desktop:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "EE249E1B-A1FD-4E08-AA71-A0E1F10FFE97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_desktop:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "33C068A4-3780-4EAB-A937-6082DF847564", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_hpc_node:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2FAC325-6EEB-466D-9EBA-8ED4DBC9CFBF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "9BBCD86A-E6C7-4444-9D74-F861084090F0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_server:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "51EF4996-72F4-4FA4-814F-F5991E7A8318", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_workstation:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "E5ED5807-55B7-47C5-97A6-03233F4FBC3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_workstation:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "825ECE2D-E232-46E0-A047-074B34DB1E97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:debian:hivex:*:*:*:*:*:*:*:*", "matchCriteriaId": "9C345E9F-F4FB-46BE-B55C-DBD7E7DD605F", "versionEndExcluding": null, "versionEndIncluding": "1.3.10-2", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "lib/handle.c in Hivex before 1.3.11 allows local users to execute arbitrary code and gain privileges via a small hive files, which triggers an out-of-bounds read or write."}, {"lang": "es", "value": "lib/handle.c en Hivex anterior a 1.3.11 permite a usuarios locales ejecutar c\u00f3digo arbitrario y ganar privilegios a trav\u00e9s de un fichero de hive peque\u00f1o, lo que provoca una lectura o escritura fuera de rango."}], "evaluatorComment": null, "id": "CVE-2014-9273", "lastModified": "2018-10-30T16:27:35.843", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": true, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-12-08T16:59:11.947", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-updates/2015-02/msg00005.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2015-0301.html"}, {"source": "secalert@redhat.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2015-1378.html"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/11/25/6"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/12/04/14"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.securityfocus.com/bid/71279"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1167756"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch", "Issue Tracking"], "url": "https://github.com/libguestfs/hivex/commit/357f26fa64fd1d9ccac2331fe174a8ee9c607adb"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch", "Issue Tracking"], "url": "https://github.com/libguestfs/hivex/commit/4bbdf555f88baeae0fa804a369a81a83908bd705"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://security.gentoo.org/glsa/201503-07"}, {"source": "secalert@redhat.com", "tags": ["Vendor Advisory"], "url": "https://www.redhat.com/archives/libguestfs/2014-October/msg00235.html"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/libguestfs/hivex/commit/357f26fa64fd1d9ccac2331fe174a8ee9c607adb"}, "type": "CWE-119"}
300
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#include <utility>\n#include <vector>", "#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/variant.h\"\n#include \"tensorflow/core/framework/variant_encode_decode.h\"\n#include \"tensorflow/core/framework/variant_op_registry.h\"\n#include \"tensorflow/core/kernels/concat_lib.h\"\n#include \"tensorflow/core/kernels/ragged_tensor_variant.h\"\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/core/status.h\"\n#include \"tensorflow/core/util/tensor_ops_util.h\"", "namespace tensorflow {\nnamespace {", "template <typename VALUE_TYPE, typename SPLIT_TYPE>\nStatus UnbatchRaggedZerothDim(\n const RaggedTensorVariant& batched_ragged,\n std::vector<RaggedTensorVariant>* ragged_components) {\n // Set up the component Ragged Tensors.\n int ragged_rank = batched_ragged.ragged_rank();\n auto batched_splits_top_vec = batched_ragged.splits(0).vec<SPLIT_TYPE>();\n int num_components = batched_splits_top_vec.size() - 1;\n int num_splits = ragged_rank - 1;\n ragged_components->resize(num_components);\n for (RaggedTensorVariant& ragged_component : *ragged_components) {\n ragged_component.mutable_nested_splits()->reserve(num_splits);\n }\n const auto& batched_flat = batched_ragged.values().flat<VALUE_TYPE>();\n int num_inner_elems = batched_ragged.values().NumElements();\n if (batched_ragged.values().dim_size(0) > 1) {\n num_inner_elems /= batched_ragged.values().dim_size(0);\n }\n TensorShape values_shape = batched_ragged.values().shape();", " // Corner case: ragged_rank == 1, e.g. [[1, 2, 3], [4, 5]]\n if (num_splits == 0) {\n for (int i = 0; i < num_components; i++) {\n int start = batched_splits_top_vec(i);\n int limit = batched_splits_top_vec(i + 1);\n int num_values = limit - start;\n values_shape.set_dim(0, num_values);\n (*ragged_components)[i].set_values(\n Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));\n auto ragged_component_values_flat =\n (*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();\n for (int j = 0; j < num_values * num_inner_elems; j++) {\n ragged_component_values_flat(j) =\n batched_flat(j + start * num_inner_elems);\n }\n }\n return Status::OK();\n }", " // Unbatch nested splits.\n std::vector<typename TTypes<SPLIT_TYPE>::ConstVec> batched_splits_vec;\n batched_splits_vec.reserve(ragged_rank);\n for (int i = 0; i < ragged_rank; i++) {\n batched_splits_vec.push_back(batched_ragged.splits(i).vec<SPLIT_TYPE>());\n }\n std::vector<int> index(num_splits, 1);\n std::vector<int> ragged_component_values_size(num_components, 0);\n for (int i = 0; i < num_components; i++) {\n std::vector<typename TTypes<SPLIT_TYPE>::Vec> ragged_component_splits_vec;\n ragged_component_splits_vec.reserve(num_splits);\n int split_size = -1;\n for (int j = 0; j < num_splits; j++) {\n if (j == 0) {\n split_size =\n batched_splits_top_vec(i + 1) - batched_splits_top_vec(i) + 1;\n } else {\n // Update split size based on previous split.\n int last_index = ragged_component_splits_vec[j - 1].size() - 1;\n split_size = ragged_component_splits_vec[j - 1](last_index) + 1;\n }\n (*ragged_components)[i].append_splits(\n Tensor(DataTypeToEnum<SPLIT_TYPE>::value, TensorShape({split_size})));\n ragged_component_splits_vec.push_back(\n (*ragged_components)[i].mutable_splits(j)->vec<SPLIT_TYPE>());\n SPLIT_TYPE last_split_value = batched_splits_vec[j + 1](index[j] - 1);\n ragged_component_splits_vec[j](0) = 0;\n for (int k = 1; k < split_size; k++, index[j]++) {\n ragged_component_splits_vec[j](k) =\n batched_splits_vec[j + 1](index[j]) - last_split_value;\n }\n }\n int last_split_size = ragged_component_splits_vec[num_splits - 1].size();\n ragged_component_values_size[i] =\n ragged_component_splits_vec[num_splits - 1](last_split_size - 1);\n }", " // Unbatch values.\n int value_index = 0;\n for (int i = 0; i < num_components; i++) {\n int num_values = ragged_component_values_size[i];\n values_shape.set_dim(0, num_values);\n (*ragged_components)[i].set_values(\n Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));\n auto ragged_component_values_flat =\n (*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();\n for (int j = 0; j < num_values * num_inner_elems; j++, value_index++) {\n ragged_component_values_flat(j) = batched_flat(value_index);\n }\n }", " return Status::OK();\n}\n} // namespace", "template <typename VALUE_TYPE, typename SPLIT_TYPE>\nclass RaggedTensorToVariantOp : public OpKernel {\n public:\n explicit RaggedTensorToVariantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batched_input\", &batched_input_));\n }", " void Compute(OpKernelContext* context) override {\n // Read ragged_splits inputs.\n OpInputList ragged_nested_splits_in;\n OP_REQUIRES_OK(context, context->input_list(\"rt_nested_splits\",\n &ragged_nested_splits_in));\n const int ragged_nested_splits_len = ragged_nested_splits_in.size();\n RaggedTensorVariant batched_ragged_input;\n // Read ragged_values input.\n batched_ragged_input.set_values(context->input(ragged_nested_splits_len));\n batched_ragged_input.mutable_nested_splits()->reserve(\n ragged_nested_splits_len);\n for (int i = 0; i < ragged_nested_splits_len; i++) {\n batched_ragged_input.append_splits(ragged_nested_splits_in[i]);\n }", " if (!batched_input_) {\n // Encode as a Scalar Variant Tensor.\n Tensor* encoded_scalar;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),\n &encoded_scalar));\n encoded_scalar->scalar<Variant>()() = std::move(batched_ragged_input);\n return;\n }", "", "\n // Unbatch the Ragged Tensor and encode the components.\n std::vector<RaggedTensorVariant> unbatched_ragged_input;\n auto batched_splits_top_vec =\n batched_ragged_input.splits(0).vec<SPLIT_TYPE>();\n int num_components = batched_splits_top_vec.size() - 1;\n OP_REQUIRES(context, num_components >= 0,\n errors::Internal(\"Invalid split argument.\"));\n OP_REQUIRES_OK(context, UnbatchRaggedZerothDim<VALUE_TYPE, SPLIT_TYPE>(\n batched_ragged_input, &unbatched_ragged_input));", " // Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.\n Tensor* encoded_vector;\n int output_size = unbatched_ragged_input.size();\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({output_size}),\n &encoded_vector));\n auto encoded_vector_t = encoded_vector->vec<Variant>();\n for (int i = 0; i < output_size; i++) {\n encoded_vector_t(i) = unbatched_ragged_input[i];\n }\n }", " private:\n bool batched_input_;\n};", "template <typename VALUE_TYPE, typename SPLIT_TYPE>\nclass RaggedTensorToVariantGradientOp : public OpKernel {\n public:\n using OpKernel::OpKernel;", " void Compute(OpKernelContext* context) override {\n // Read inputs.\n Tensor encoded_variant = context->input(0);\n Tensor row_splits = context->input(1);\n auto flat_row_splits = row_splits.flat<SPLIT_TYPE>();\n TensorShape dense_values_shape;\n OP_REQUIRES_OK(context,\n TensorShapeUtils::MakeShape(context->input(2).vec<int32>(),\n &dense_values_shape));", " const auto& flat_variants = encoded_variant.flat<Variant>();", " // Get a Tensor containing the flat_values for each variant.\n std::vector<Tensor> values;\n for (int i = 0; i < flat_variants.size(); ++i) {\n if (const auto* encoded = flat_variants(i).get<RaggedTensorVariant>()) {\n values.push_back(encoded->values());\n } else {\n // Missing value: this happens if only some of the variant values\n // generated by ragged_tensor_to_variant impacted the value that we're\n // calculating the gradient for. In this case, we will see a\n // default-constructed variant; so treat it as a zero tensor with the\n // appropriate shape.\n const auto value_dtype = DataTypeToEnum<VALUE_TYPE>::v();\n int piece_size = flat_row_splits(i + 1) - flat_row_splits(i);\n TensorShape zeros_shape = dense_values_shape;\n zeros_shape.set_dim(0, piece_size);\n Tensor zero(value_dtype, zeros_shape);\n zero.flat<VALUE_TYPE>() =\n zero.flat<VALUE_TYPE>().constant(VALUE_TYPE());\n values.push_back(zero);\n }\n }", " if (values.size() == 1) {\n // Just one flat_value tensor: return as-is.\n context->set_output(0, values[0]);\n } else {\n // Multiple flat_values tensors: concatenate them together.\n using Piece = typename TTypes<VALUE_TYPE, 2>::Matrix;\n using ConstPiece = typename TTypes<VALUE_TYPE, 2>::ConstMatrix;\n std::vector<std::unique_ptr<ConstPiece>> pieces;\n pieces.reserve(values.size());\n for (const Tensor& t : values) {\n pieces.emplace_back(\n new ConstPiece(t.shaped<VALUE_TYPE, 2>({1, t.NumElements()})));\n }\n Tensor* out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, dense_values_shape, &out));\n Piece out_flat =\n out->shaped<VALUE_TYPE, 2>({1, dense_values_shape.num_elements()});\n ConcatCPU<VALUE_TYPE>(context->device(), pieces, &out_flat);\n }\n }\n};", "#define REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, split_type) \\\n REGISTER_KERNEL_BUILDER(Name(\"RaggedTensorToVariant\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<value_type>(\"Tvalues\") \\\n .TypeConstraint<split_type>(\"Tsplits\"), \\\n RaggedTensorToVariantOp<value_type, split_type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"RaggedTensorToVariantGradient\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<value_type>(\"Tvalues\") \\\n .TypeConstraint<split_type>(\"Tsplits\"), \\\n RaggedTensorToVariantGradientOp<value_type, split_type>);", "#define REGISTER_KERNELS(value_type) \\\n REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int32) \\\n REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int64)\nTF_CALL_POD_TYPES(REGISTER_KERNELS);\nTF_CALL_tstring(REGISTER_KERNELS);\nTF_CALL_QUANTIZED_TYPES(REGISTER_KERNELS);\nTF_CALL_quint16(REGISTER_KERNELS);\nTF_CALL_qint16(REGISTER_KERNELS);\n#undef REGISTER_KERNELS\n#undef REGISTER_KERNELS_WITH_SPLIT_TYPE\n} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [158], "buggy_code_start_loc": [158], "filenames": ["tensorflow/core/kernels/ragged_tensor_to_variant_op.cc"], "fixing_code_end_loc": [165], "fixing_code_start_loc": [159], "message": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.RaggedTensorToVariant`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) has an incomplete validation of the splits values, missing the case when the argument would be empty. We have patched the issue in GitHub commit be7a4de6adfbd303ce08be4332554dff70362612. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F83C081-51CC-415F-A8C0-0A44C75E2CD6", "versionEndExcluding": "2.3.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "BD3F2BF8-EBA9-42BF-8F9B-D918B880B15A", "versionEndExcluding": "2.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "D03E99A7-4E3D-427D-A156-C0713E9FB02A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc0:*:*:*:*:*:*", "matchCriteriaId": "70FA6E48-6C57-40CA-809F-4E3D07CBF348", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "42187561-E491-434D-828C-F36701446634", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C66B61C8-450A-4C5E-9174-F970D6DEE778", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.RaggedTensorToVariant`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) has an incomplete validation of the splits values, missing the case when the argument would be empty. We have patched the issue in GitHub commit be7a4de6adfbd303ce08be4332554dff70362612. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto de extremo a extremo para el aprendizaje autom\u00e1tico. En las versiones afectadas un atacante puede causar un comportamiento indefinido por medio de la vinculaci\u00f3n de una referencia a un puntero null en \"tf.raw_ops.RaggedTensorToVariant\". La [implementaci\u00f3n](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) presenta una comprobaci\u00f3n incompleta de los valores de divisi\u00f3n, omitiendo el caso cuando el argumento estar\u00eda vac\u00edo. Hemos parcheado el problema en el commit be7a4de6adfbd303ce08be4332554dff70362612 de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.6.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow versi\u00f3n 2.5.1, TensorFlow versi\u00f3n 2.4.3, y TensorFlow versi\u00f3n 2.3.4, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango de soporte."}], "evaluatorComment": null, "id": "CVE-2021-37666", "lastModified": "2021-08-18T20:48:48.633", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-12T22:15:08.243", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/be7a4de6adfbd303ce08be4332554dff70362612"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-w4xf-2pqw-5mq7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-824"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/be7a4de6adfbd303ce08be4332554dff70362612"}, "type": "CWE-824"}
301
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#include <utility>\n#include <vector>", "#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/variant.h\"\n#include \"tensorflow/core/framework/variant_encode_decode.h\"\n#include \"tensorflow/core/framework/variant_op_registry.h\"\n#include \"tensorflow/core/kernels/concat_lib.h\"\n#include \"tensorflow/core/kernels/ragged_tensor_variant.h\"\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/core/status.h\"\n#include \"tensorflow/core/util/tensor_ops_util.h\"", "namespace tensorflow {\nnamespace {", "template <typename VALUE_TYPE, typename SPLIT_TYPE>\nStatus UnbatchRaggedZerothDim(\n const RaggedTensorVariant& batched_ragged,\n std::vector<RaggedTensorVariant>* ragged_components) {\n // Set up the component Ragged Tensors.\n int ragged_rank = batched_ragged.ragged_rank();\n auto batched_splits_top_vec = batched_ragged.splits(0).vec<SPLIT_TYPE>();\n int num_components = batched_splits_top_vec.size() - 1;\n int num_splits = ragged_rank - 1;\n ragged_components->resize(num_components);\n for (RaggedTensorVariant& ragged_component : *ragged_components) {\n ragged_component.mutable_nested_splits()->reserve(num_splits);\n }\n const auto& batched_flat = batched_ragged.values().flat<VALUE_TYPE>();\n int num_inner_elems = batched_ragged.values().NumElements();\n if (batched_ragged.values().dim_size(0) > 1) {\n num_inner_elems /= batched_ragged.values().dim_size(0);\n }\n TensorShape values_shape = batched_ragged.values().shape();", " // Corner case: ragged_rank == 1, e.g. [[1, 2, 3], [4, 5]]\n if (num_splits == 0) {\n for (int i = 0; i < num_components; i++) {\n int start = batched_splits_top_vec(i);\n int limit = batched_splits_top_vec(i + 1);\n int num_values = limit - start;\n values_shape.set_dim(0, num_values);\n (*ragged_components)[i].set_values(\n Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));\n auto ragged_component_values_flat =\n (*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();\n for (int j = 0; j < num_values * num_inner_elems; j++) {\n ragged_component_values_flat(j) =\n batched_flat(j + start * num_inner_elems);\n }\n }\n return Status::OK();\n }", " // Unbatch nested splits.\n std::vector<typename TTypes<SPLIT_TYPE>::ConstVec> batched_splits_vec;\n batched_splits_vec.reserve(ragged_rank);\n for (int i = 0; i < ragged_rank; i++) {\n batched_splits_vec.push_back(batched_ragged.splits(i).vec<SPLIT_TYPE>());\n }\n std::vector<int> index(num_splits, 1);\n std::vector<int> ragged_component_values_size(num_components, 0);\n for (int i = 0; i < num_components; i++) {\n std::vector<typename TTypes<SPLIT_TYPE>::Vec> ragged_component_splits_vec;\n ragged_component_splits_vec.reserve(num_splits);\n int split_size = -1;\n for (int j = 0; j < num_splits; j++) {\n if (j == 0) {\n split_size =\n batched_splits_top_vec(i + 1) - batched_splits_top_vec(i) + 1;\n } else {\n // Update split size based on previous split.\n int last_index = ragged_component_splits_vec[j - 1].size() - 1;\n split_size = ragged_component_splits_vec[j - 1](last_index) + 1;\n }\n (*ragged_components)[i].append_splits(\n Tensor(DataTypeToEnum<SPLIT_TYPE>::value, TensorShape({split_size})));\n ragged_component_splits_vec.push_back(\n (*ragged_components)[i].mutable_splits(j)->vec<SPLIT_TYPE>());\n SPLIT_TYPE last_split_value = batched_splits_vec[j + 1](index[j] - 1);\n ragged_component_splits_vec[j](0) = 0;\n for (int k = 1; k < split_size; k++, index[j]++) {\n ragged_component_splits_vec[j](k) =\n batched_splits_vec[j + 1](index[j]) - last_split_value;\n }\n }\n int last_split_size = ragged_component_splits_vec[num_splits - 1].size();\n ragged_component_values_size[i] =\n ragged_component_splits_vec[num_splits - 1](last_split_size - 1);\n }", " // Unbatch values.\n int value_index = 0;\n for (int i = 0; i < num_components; i++) {\n int num_values = ragged_component_values_size[i];\n values_shape.set_dim(0, num_values);\n (*ragged_components)[i].set_values(\n Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));\n auto ragged_component_values_flat =\n (*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();\n for (int j = 0; j < num_values * num_inner_elems; j++, value_index++) {\n ragged_component_values_flat(j) = batched_flat(value_index);\n }\n }", " return Status::OK();\n}\n} // namespace", "template <typename VALUE_TYPE, typename SPLIT_TYPE>\nclass RaggedTensorToVariantOp : public OpKernel {\n public:\n explicit RaggedTensorToVariantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batched_input\", &batched_input_));\n }", " void Compute(OpKernelContext* context) override {\n // Read ragged_splits inputs.\n OpInputList ragged_nested_splits_in;\n OP_REQUIRES_OK(context, context->input_list(\"rt_nested_splits\",\n &ragged_nested_splits_in));\n const int ragged_nested_splits_len = ragged_nested_splits_in.size();\n RaggedTensorVariant batched_ragged_input;\n // Read ragged_values input.\n batched_ragged_input.set_values(context->input(ragged_nested_splits_len));\n batched_ragged_input.mutable_nested_splits()->reserve(\n ragged_nested_splits_len);\n for (int i = 0; i < ragged_nested_splits_len; i++) {\n batched_ragged_input.append_splits(ragged_nested_splits_in[i]);\n }", " if (!batched_input_) {\n // Encode as a Scalar Variant Tensor.\n Tensor* encoded_scalar;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),\n &encoded_scalar));\n encoded_scalar->scalar<Variant>()() = std::move(batched_ragged_input);\n return;\n }", "\n // Checked here instead of at input in case batched_input_ is false\n OP_REQUIRES(context, ragged_nested_splits_len > 0,\n errors::InvalidArgument(\n \"rt_nested_splits must be a list of one or more, but \"\n \"received rt_nested_splits of length 0.\"));", "\n // Unbatch the Ragged Tensor and encode the components.\n std::vector<RaggedTensorVariant> unbatched_ragged_input;\n auto batched_splits_top_vec =\n batched_ragged_input.splits(0).vec<SPLIT_TYPE>();\n int num_components = batched_splits_top_vec.size() - 1;\n OP_REQUIRES(context, num_components >= 0,\n errors::Internal(\"Invalid split argument.\"));\n OP_REQUIRES_OK(context, UnbatchRaggedZerothDim<VALUE_TYPE, SPLIT_TYPE>(\n batched_ragged_input, &unbatched_ragged_input));", " // Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.\n Tensor* encoded_vector;\n int output_size = unbatched_ragged_input.size();\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({output_size}),\n &encoded_vector));\n auto encoded_vector_t = encoded_vector->vec<Variant>();\n for (int i = 0; i < output_size; i++) {\n encoded_vector_t(i) = unbatched_ragged_input[i];\n }\n }", " private:\n bool batched_input_;\n};", "template <typename VALUE_TYPE, typename SPLIT_TYPE>\nclass RaggedTensorToVariantGradientOp : public OpKernel {\n public:\n using OpKernel::OpKernel;", " void Compute(OpKernelContext* context) override {\n // Read inputs.\n Tensor encoded_variant = context->input(0);\n Tensor row_splits = context->input(1);\n auto flat_row_splits = row_splits.flat<SPLIT_TYPE>();\n TensorShape dense_values_shape;\n OP_REQUIRES_OK(context,\n TensorShapeUtils::MakeShape(context->input(2).vec<int32>(),\n &dense_values_shape));", " const auto& flat_variants = encoded_variant.flat<Variant>();", " // Get a Tensor containing the flat_values for each variant.\n std::vector<Tensor> values;\n for (int i = 0; i < flat_variants.size(); ++i) {\n if (const auto* encoded = flat_variants(i).get<RaggedTensorVariant>()) {\n values.push_back(encoded->values());\n } else {\n // Missing value: this happens if only some of the variant values\n // generated by ragged_tensor_to_variant impacted the value that we're\n // calculating the gradient for. In this case, we will see a\n // default-constructed variant; so treat it as a zero tensor with the\n // appropriate shape.\n const auto value_dtype = DataTypeToEnum<VALUE_TYPE>::v();\n int piece_size = flat_row_splits(i + 1) - flat_row_splits(i);\n TensorShape zeros_shape = dense_values_shape;\n zeros_shape.set_dim(0, piece_size);\n Tensor zero(value_dtype, zeros_shape);\n zero.flat<VALUE_TYPE>() =\n zero.flat<VALUE_TYPE>().constant(VALUE_TYPE());\n values.push_back(zero);\n }\n }", " if (values.size() == 1) {\n // Just one flat_value tensor: return as-is.\n context->set_output(0, values[0]);\n } else {\n // Multiple flat_values tensors: concatenate them together.\n using Piece = typename TTypes<VALUE_TYPE, 2>::Matrix;\n using ConstPiece = typename TTypes<VALUE_TYPE, 2>::ConstMatrix;\n std::vector<std::unique_ptr<ConstPiece>> pieces;\n pieces.reserve(values.size());\n for (const Tensor& t : values) {\n pieces.emplace_back(\n new ConstPiece(t.shaped<VALUE_TYPE, 2>({1, t.NumElements()})));\n }\n Tensor* out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, dense_values_shape, &out));\n Piece out_flat =\n out->shaped<VALUE_TYPE, 2>({1, dense_values_shape.num_elements()});\n ConcatCPU<VALUE_TYPE>(context->device(), pieces, &out_flat);\n }\n }\n};", "#define REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, split_type) \\\n REGISTER_KERNEL_BUILDER(Name(\"RaggedTensorToVariant\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<value_type>(\"Tvalues\") \\\n .TypeConstraint<split_type>(\"Tsplits\"), \\\n RaggedTensorToVariantOp<value_type, split_type>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"RaggedTensorToVariantGradient\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<value_type>(\"Tvalues\") \\\n .TypeConstraint<split_type>(\"Tsplits\"), \\\n RaggedTensorToVariantGradientOp<value_type, split_type>);", "#define REGISTER_KERNELS(value_type) \\\n REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int32) \\\n REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int64)\nTF_CALL_POD_TYPES(REGISTER_KERNELS);\nTF_CALL_tstring(REGISTER_KERNELS);\nTF_CALL_QUANTIZED_TYPES(REGISTER_KERNELS);\nTF_CALL_quint16(REGISTER_KERNELS);\nTF_CALL_qint16(REGISTER_KERNELS);\n#undef REGISTER_KERNELS\n#undef REGISTER_KERNELS_WITH_SPLIT_TYPE\n} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [158], "buggy_code_start_loc": [158], "filenames": ["tensorflow/core/kernels/ragged_tensor_to_variant_op.cc"], "fixing_code_end_loc": [165], "fixing_code_start_loc": [159], "message": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.RaggedTensorToVariant`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) has an incomplete validation of the splits values, missing the case when the argument would be empty. We have patched the issue in GitHub commit be7a4de6adfbd303ce08be4332554dff70362612. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F83C081-51CC-415F-A8C0-0A44C75E2CD6", "versionEndExcluding": "2.3.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "BD3F2BF8-EBA9-42BF-8F9B-D918B880B15A", "versionEndExcluding": "2.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "D03E99A7-4E3D-427D-A156-C0713E9FB02A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc0:*:*:*:*:*:*", "matchCriteriaId": "70FA6E48-6C57-40CA-809F-4E3D07CBF348", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "42187561-E491-434D-828C-F36701446634", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C66B61C8-450A-4C5E-9174-F970D6DEE778", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions an attacker can cause undefined behavior via binding a reference to null pointer in `tf.raw_ops.RaggedTensorToVariant`. The [implementation](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) has an incomplete validation of the splits values, missing the case when the argument would be empty. We have patched the issue in GitHub commit be7a4de6adfbd303ce08be4332554dff70362612. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto de extremo a extremo para el aprendizaje autom\u00e1tico. En las versiones afectadas un atacante puede causar un comportamiento indefinido por medio de la vinculaci\u00f3n de una referencia a un puntero null en \"tf.raw_ops.RaggedTensorToVariant\". La [implementaci\u00f3n](https://github.com/tensorflow/tensorflow/blob/460e000de3a83278fb00b61a16d161b1964f15f4/tensorflow/core/kernels/ragged_tensor_to_variant_op.cc#L129) presenta una comprobaci\u00f3n incompleta de los valores de divisi\u00f3n, omitiendo el caso cuando el argumento estar\u00eda vac\u00edo. Hemos parcheado el problema en el commit be7a4de6adfbd303ce08be4332554dff70362612 de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.6.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow versi\u00f3n 2.5.1, TensorFlow versi\u00f3n 2.4.3, y TensorFlow versi\u00f3n 2.3.4, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango de soporte."}], "evaluatorComment": null, "id": "CVE-2021-37666", "lastModified": "2021-08-18T20:48:48.633", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:L/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-12T22:15:08.243", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/be7a4de6adfbd303ce08be4332554dff70362612"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-w4xf-2pqw-5mq7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-824"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/be7a4de6adfbd303ce08be4332554dff70362612"}, "type": "CWE-824"}
301
Determine whether the {function_name} code is vulnerable or not.
[ "/****************************************************************************\n *\n * Copyright (C) 2006,2007 A.Kleine\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n ****************************************************************************/", "#define _GNU_SOURCE 1", "//#define DEBUGSTACK\n#define DECOMP_SWITCH\n// #define DEBUGSWITCH", "//#define STATEMENT_CLASS \n// I have uncommented some buggy class recognition stuff in decompileIF()\n// to make work simple code lines like: \"if(!a) trace(a);\" - ak, November 2006", "// To do: add some free()-calls for allocated blocks", "#include <assert.h>", "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>", "#include \"read.h\"\n#include \"action.h\"\n#include \"swftypes.h\"\n#include \"../src/blocks/error.h\"\n#include \"vasprintf.h\"", "\nstatic char **pool;\nstatic unsigned short poolcounter;\nstruct SWF_ACTIONPUSHPARAM *regs[256];", "static char *getName(struct SWF_ACTIONPUSHPARAM *act);", "static int offseoloop;\t// offset wherever a break can jump to (loops and switch)", "static void\ndumpRegs()\n{\nint i;\nfor(i=0;i<6;i++)\n\tif( regs[i] )\n\t\tprintf(\"reg[%d] %s\\n\", i, getName(regs[i]));\n}", "/*\n * Start Package \n *\n * A package to build up a string that can be returned to the caller\n * ak/2006: Extended for temporary swichting to a 2nd buffer\n */\n#define USE_LIB 1", "static int strsize=0;\nstatic int strmaxsize=0;\nstatic char *dcstr=NULL;\nstatic char *dcptr=NULL;", "#define DCSTRSIZE 40960\n#define PARAM_STRSIZE 512\nvoid\ndcinit()\n{\n\tstrsize = 1; // We start with empty string, i.e. \\0\n\tstrmaxsize=DCSTRSIZE;\n\tdcstr=calloc(DCSTRSIZE,1);\n\tdcptr=dcstr;\n}", "void\ndcchkstr(int size)\n{\n\twhile( (strsize+size) > strmaxsize ) {\n\t\tdcstr=realloc(dcstr,strmaxsize+DCSTRSIZE);\n\t\tstrmaxsize+=DCSTRSIZE;\n\t\tdcptr=dcstr+strsize;\n\t}", "}", "void\ndcputs(const char *s)\n{\n\tint len=strlen(s);\n\tdcchkstr(len);\n\tstrcat(dcptr,s);\n\tdcptr+=len;\n\tstrsize+=len;\n}", "void\ndcputchar(char c)\n{\n\tdcchkstr(1);", "\t*dcptr++=c;\n\t*dcptr='\\000';\n\tstrsize++;\n}", "int\ndcprintf(char *format, ...)\n{\n\tchar *s;\n\tsize_t size;\n\tint ret;", "\tva_list args;\n\tva_start(args,format);\n\tret = vasprintf(&s,format,args);\n\tdcputs(s);\n\tsize=strlen(s);\n\tfree(s);\n\treturn size;\n}", "char *\ndcgetstr()\n{\n\tchar *ret;\n\tret = dcstr;\n\tdcstr=NULL;\n\tstrmaxsize=0;\n\treturn ret;\n}", "struct strbufinfo\n{\n\tint size;\n\tint maxsize;\n\tchar *str;\n\tchar *ptr;\n};", "\nstatic struct strbufinfo setTempString(void)\n{\n\tstruct strbufinfo current;\n\tcurrent.size=strsize;\n\tcurrent.maxsize=strmaxsize;\n\tcurrent.str=dcstr;\n\tcurrent.ptr=dcptr;\n\tdcinit();\n\treturn current;\n}", "static void setOrigString(struct strbufinfo old)\n{\n\tfree(dcstr);\t\t\t\t/* not needed anymore */\n\tstrsize=old.size;\n\tstrmaxsize=old.maxsize;\n\tdcstr=old.str;\n\tdcptr=old.ptr;\n}", "// a variant of setOrigString()\n// but for further usage of 2nd buffer\n//\nstatic char *\nswitchToOrigString(struct strbufinfo old)\n{\n\tchar *tmp=dcstr;\n\tstrsize=old.size;\n\tstrmaxsize=old.maxsize;\n\tdcstr=old.str;\n\tdcptr=old.ptr;\n\treturn tmp;\n}", "#if USE_LIB\n#define puts(s) dcputs(s)\n#define putchar(c) dcputchar(c)\n#define printf dcprintf\n#endif", "#define INDENT { int ii=gIndent; while(--ii>=0) { putchar(' '); putchar(' '); } }", "/* String used for terminating lines (see println) */\nstatic const char* newlinestring = \"\\\\\\n\";", "/* Set the newline character. By default it is an escaped NL. */\nvoid\nsetNewLineString(const char* ch)\n{\n\tnewlinestring = ch;\n}", "/* Print a line with a terminating newline, which can be set by\n * setNewLineString()\n */\nstatic void\nprintln(const char* fmt, ...)\n{\n\tchar *tmp;\n\tint written;", "\tva_list ap;\n\tva_start (ap, fmt);\n\twritten = vasprintf (&tmp, fmt, ap);", "\tdcprintf(\"%s%s\", tmp, newlinestring);", "\tfree(tmp);\n}", "\n/* End Package */", "/*\n * Start Package \n *\n * A package to maintain escaped characters strings\n * [ BSC == BackSlashCounter ]\n */\n#define BSC 2\nstatic int strlenext(char *str)\n{\n\tint i=0;\n\twhile (*str)\n\t{\n\t\ti++;\n\t\tif (*str=='\\'') i+=BSC;\n\t\t\tstr++;\t\n\t}\n\treturn i;\n}", "static char* strcpyext(char *dest,char *src)\n{\n\tchar *r=dest;\n\twhile (*src)\n\t{\n\t\tif (*src=='\\'')\n\t\t{\n\t\t\t*dest++='\\\\';\n#if BSC == 2\n\t\t\t*dest++='\\\\';\n#endif\n\t\t}\n\t\t*dest++=*src++;\n\t}\n\t*dest='\\0';\n\treturn r;\n}", "static char* strcatext(char *dest,char *src)\n{\n\tchar *r=dest;\n\twhile (*dest)\n\t\tdest++;\n\tstrcpyext(dest,src);\n\treturn r;\n}\n/* End Package */", "/*\n * Start Package \n *\n * A package to maintain a representation of the Flash VM stack\n */", "struct _stack {\n\tchar type;\n\tstruct SWF_ACTIONPUSHPARAM *val;\n\tstruct _stack *next;\n};", "struct _stack *Stack;", "enum\n{\n\tPUSH_STRING = 0,\n\tPUSH_FLOAT = 1,\n\tPUSH_NULL = 2,\n\tPUSH_UNDEF = 3,\n\tPUSH_REGISTER = 4,\n\tPUSH_BOOLEAN = 5,\n\tPUSH_DOUBLE = 6,\n\tPUSH_INT = 7,\n\tPUSH_CONSTANT = 8,\n\tPUSH_CONSTANT16 = 9,\n\tPUSH_VARIABLE = 10,\n};", "static char *\ngetString(struct SWF_ACTIONPUSHPARAM *act)\n{\n\tchar *t;\n#ifdef DEBUG\n\tprintf(\"*getString* type=%d\\n\",act->Type);\n#endif\n\tswitch( act->Type ) \n\t{\n\tcase PUSH_STRING: \n\t\tif (!act->p.String) /* Not a NULL string */\n\t\t{\n\t\t SWF_warn(\"WARNING: Call to getString with NULL string.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlen(act->p.String)+3); /* 2 \"'\"s and a NULL */\n\t\tstrcpy(t,\"'\");\n\t\tstrcat(t,act->p.String);\n\t\tstrcat(t,\"'\");\n\t\treturn t;\n\tcase PUSH_NULL: /* NULL */\n\t\treturn \"null\";\n\tcase PUSH_UNDEF: /* Undefined */\n\t\treturn \"undefined\";\n\tcase PUSH_REGISTER: /* REGISTER */\n\t\tif( regs[act->p.RegisterNumber] &&\n\t\t regs[act->p.RegisterNumber]->Type != 4 &&\n\t\t regs[act->p.RegisterNumber]->Type != 7 )\n\t\t{\n\t\t\treturn getName(regs[act->p.RegisterNumber]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tt=malloc(5); /* Rddd */\n\t\t\tsprintf(t,\"R%d\", act->p.RegisterNumber );\n\t\t\treturn t;\n\t\t}\n\tcase PUSH_BOOLEAN: /* BOOLEAN */\n\t\tif( act->p.Boolean )\n\t\t\treturn \"true\";\n\t\telse\n\t\t\treturn \"false\";\n\tcase PUSH_DOUBLE: /* DOUBLE */\n\t{\n\t\tchar length_finder[1];\n\t\tint needed_length = snprintf(length_finder, 1, \"%g\", act->p.Double) + 1;\n\t\tif (needed_length <= 0)\n\t\t{\n\t\t SWF_warn(\"WARNING: could not evaluate size of buffer (memory issue ?).\\n\");\n\t\t break;\n\t\t}", "\t\tt = malloc(needed_length);\n\t\tsprintf(t, \"%g\", act->p.Double );\n\t\treturn t;\n\t}\n\tcase PUSH_INT: /* INTEGER */\n\t\tt=malloc(10); /* 32-bit decimal */\n\t\tsprintf(t,\"%ld\", act->p.Integer );\n\t\treturn t;\n\tcase PUSH_CONSTANT: /* CONSTANT8 */\n\t\tif (act->p.Constant8 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant8])+3); /* 2 \"'\"s and a NULL */\n\t\tstrcpy(t,\"'\");\n\t\tstrcatext(t,pool[act->p.Constant8]);\n\t\tstrcat(t,\"'\");\n\t\treturn t;\n\tcase PUSH_CONSTANT16: /* CONSTANT16 */\n\t\tif (act->p.Constant16 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant16])+3); /* 2 '\\\"'s and a NULL */\n\t\tstrcpy(t,\"'\");\n\t\tstrcatext(t,pool[act->p.Constant16]);\n\t\tstrcat(t,\"'\");\n\t\treturn t;", "\tcase 12:\n\tcase 11: /* INCREMENTED or DECREMENTED VARIABLE */\n\tcase PUSH_VARIABLE: /* VARIABLE */\n\t\treturn act->p.String;\n\tdefault: \n\t\tfprintf (stderr,\" Can't get string for type: %d\\n\", act->Type);\n\t\tbreak;\n\t}", "\tt = malloc(sizeof(char));\n\tstrcpyext(t,\"\");", "\treturn t;\n}", "static char *\ngetName(struct SWF_ACTIONPUSHPARAM *act)\n{\n\tchar *t;", "\tswitch( act->Type ) \t\n\t{\n\tcase PUSH_STRING: /* STRING */\n\t\tif (!act->p.String) /* Not a NULL string */\n\t\t{\n\t\t SWF_warn(\"WARNING: Call to getName with NULL string.\\n\");\n\t\t break;\n\t\t}\n\t\telse if (strlen(act->p.String)) /* Not a zero length string */\n\t\t{\n\t\t t=malloc(strlen(act->p.String)+3);\n\t\t strcpyext(t,act->p.String);\n\t\t return t;\n\t\t}\n\t\telse\n\t\t{\n\t\t char *return_string = \"this\";\n\t t=malloc(strlen(return_string)+1); /* string length + \\0 */\n\t strcpyext(t,return_string);\n\t\t\treturn t;\n\t\t}\n#if 0\n\t case 4: /* REGISTER */\n\t\tt=malloc(5); /* Rddd */\n \t\tsprintf(t,\"R%d\", act->p.RegisterNumber );\n \t\treturn t;\n#endif\n\tcase PUSH_CONSTANT: /* CONSTANT8 */\n\t\tif (act->p.Constant8 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant8])+1);\n\t\tstrcpyext(t,pool[act->p.Constant8]);\n\t\tif(strlen(t)) /* Not a zero length string */\n\t\t\treturn t;\n\t\telse\n\t\t{\n\t\t\tt=realloc(t,6);\n\t\t\treturn strcpy(t,\"this\");\n\t\t}\n\tcase PUSH_CONSTANT16: /* CONSTANT16 */\n\t\tif (act->p.Constant16 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant16])+1);\n\t\tstrcpyext(t,pool[act->p.Constant16]);\n\t\tif(strlen(t)) /* Not a zero length string */\n\t\t\treturn t;\n\t\telse\n\t\t{\n\t\t\tt=realloc(t,6);\n\t\t\treturn strcpy(t,\"this\");\n\t\t}\n\tdefault: \n\t\treturn getString(act);\n\t}", "\tt = malloc(sizeof(char));\n\tstrcpyext(t,\"\");", "\treturn t;\n}", "static int\ngetInt(struct SWF_ACTIONPUSHPARAM *act)\n{\n\tswitch( act->Type ) \n\t{\n\tcase PUSH_FLOAT: /* FLOAT -- also used for PROPERTY storing */\n\t\treturn ((int)act->p.Float);\n\tcase PUSH_NULL: /* NULL */\n\t\treturn 0;\n\tcase PUSH_REGISTER: /* REGISTER */\n\t\treturn getInt(regs[act->p.RegisterNumber]);\n\tcase PUSH_DOUBLE: /* DOUBLE */\n\t\treturn (int)act->p.Double;\n\tcase PUSH_INT: /* INTEGER */\n\t\treturn act->p.Integer;\n\tdefault: \n\t\tfprintf (stderr,\" Can't get int for type: %d\\n\", act->Type);\n\t}\n\treturn 0;\n}", "static char *\ngetProperty(Property prop)\n{\n\tswitch(prop)\n\t{\n\tcase SWF_SETPROPERTY_X: \treturn(\"_x\"); break;\n\tcase SWF_SETPROPERTY_Y:\n\tcase PROPERTY_Y:\t\treturn(\"_y\"); break;\n\tcase PROPERTY_XMOUSE:\t\treturn(\"_xMouse\"); break;\n\tcase PROPERTY_YMOUSE:\t\treturn(\"_yMouse\"); break;\n\tcase SWF_SETPROPERTY_XSCALE:\n\tcase PROPERTY_XSCALE:\t \treturn(\"_xScale\"); break;\n\tcase SWF_SETPROPERTY_YSCALE:\n\tcase PROPERTY_YSCALE:\t \treturn(\"_yScale\"); break;\n\tcase PROPERTY_CURRENTFRAME:\treturn(\"_currentFrame\"); break;\n\tcase PROPERTY_TOTALFRAMES:\treturn(\"_totalFrames\"); break;\n\tcase SWF_SETPROPERTY_ALPHA:\n\tcase PROPERTY_ALPHA:\t\treturn(\"_alpha\"); break;\n\tcase SWF_SETPROPERTY_VISIBILITY:\n\tcase PROPERTY_VISIBLE:\t\treturn(\"_visible\"); break;\n\tcase PROPERTY_WIDTH:\t\treturn(\"_width\"); break;\n\tcase PROPERTY_HEIGHT:\t\treturn(\"_height\"); break;\n\tcase SWF_SETPROPERTY_ROTATION:\n\tcase PROPERTY_ROTATION:\t\treturn(\"_rotation\"); break;\n\tcase PROPERTY_TARGET:\t\treturn(\"_target\"); break;\n\tcase PROPERTY_FRAMESLOADED:\treturn(\"_framesLoaded\"); break;\n\tcase SWF_SETPROPERTY_NAME:\n\tcase PROPERTY_NAME:\t\treturn(\"_name\"); break;\n\tcase PROPERTY_DROPTARGET:\treturn(\"_dropTarget\"); break;\n\tcase PROPERTY_URL:\t\treturn(\"_url\"); break;\n\tcase SWF_SETPROPERTY_HIGHQUALITY:\n\tcase PROPERTY_HIGHQUALITY:\treturn(\"_quality\"); break;\n\tcase SWF_SETPROPERTY_SHOWFOCUSRECT:\n\tcase PROPERTY_FOCUSRECT:\treturn(\"_focusRect\"); break;\n\tcase SWF_SETPROPERTY_SOUNDBUFFERTIME:\n\tcase PROPERTY_SOUNDBUFTIME:\treturn(\"_soundBufTime\"); break;\n\tcase SWF_SETPROPERTY_WTHIT:\n\tcase PROPERTY_WTHIT:\t\treturn(\"_WTHIT!?\"); break;\n\tdefault:\t\t\treturn(\"unknown property!\"); break;\n\t}\n}", "struct SWF_ACTIONPUSHPARAM *\nnewVar(char *var)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE; \n\tv->p.String = var;\n\treturn v;\n}", "struct SWF_ACTIONPUSHPARAM *\nnewVar2(char *var,char *var2)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE;\n\tv->p.String = malloc(strlen(var)+strlen(var2)+1);\n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\treturn v;\n}", "\nstruct SWF_ACTIONPUSHPARAM *\nnewVar3(char *var,char *var2, char *var3)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE; /* VARIABLE */\n\tv->p.String = malloc(strlen(var)+strlen(var2)+strlen(var3)+1);\n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\treturn v;\n}", "struct SWF_ACTIONPUSHPARAM *\nnewVar5(char *var,char *var2, char *var3,char *var4,char *var5)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE; /* VARIABLE */\n\tv->p.String = malloc(strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(var5)+1);\n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\tstrcat(v->p.String,var4);\n\tstrcat(v->p.String,var5);\n\treturn v;\n}", "void\npush(struct SWF_ACTIONPUSHPARAM *val)\n{\n\tstruct _stack *t;\n#ifdef DEBUG\n\tprintf(\"*push* type=%d\\n\",val->Type);\n#endif\n\tt = calloc(1,sizeof(*Stack));\n\tt->type = val->Type;\n\tt->val = val;\n\tt->next = Stack;\n\tStack = t;\n}", "\nvoid\npushdup()\n{\n\tstruct _stack *t;\n#ifdef DEBUG\n\tprintf(\"*pushdup*\\n\");\n#endif\n\tif(Stack == NULL)\n\t{\n\t\tSWF_warn(\"WARNING: pushdup on empty stack. This might be wrong!\\n\");\n\t\treturn;\n\t}\n\tt = calloc(1,sizeof(*Stack));\n\tt->type = Stack->type;", "\t// If element is a string, perform deep copy of Stack->val->p\n\tif (Stack->val->Type == PUSH_STRING) {\n\t\tt->val = calloc(1, sizeof(struct SWF_ACTIONPUSHPARAM));\n\t\t*t->val = *Stack->val;", "\t\tint len = strlen(Stack->val->p.String) + 1; // NULL terminated\n\t\tt->val->p.String = calloc(len, sizeof(char));\n\t\tstrcpy(t->val->p.String, Stack->val->p.String);\n\t} else {\n\t\tt->val = Stack->val;\n\t}", "\tt->next = Stack;\n\tStack = t;\n}", "\nvoid\npushvar(struct SWF_ACTIONPUSHPARAM *val)\n{\n\tstruct _stack *t;\n#ifdef DEBUG\n\tprintf(\"*pushvar*\\n\");\n#endif\n\tt = calloc(1,sizeof(*Stack));\n\tt->type = 'v'; // ???\n\tt->val = val;\n\tt->next = Stack;\n\tStack = t;\n}", "struct SWF_ACTIONPUSHPARAM * pop()\n{\n\tstruct _stack *t;\n\tstruct SWF_ACTIONPUSHPARAM * ret;", "#ifdef DEBUG\n\tprintf(\"*pop*\\n\");\n#endif\n#ifdef DEBUGSTACK\t\t/* continue w stack dummy */\n\tif( Stack == NULL ) push(newVar(\"// *** pop(): INTERNAL STACK ERROR FOUND ***\"));\n#else\n\tif( Stack == NULL ) SWF_error(\"Stack blown!! - pop\");\n#endif\n\tt=Stack;\n\tStack=t->next;\n\tret=t->val;\n\treturn ret;\n}", "struct SWF_ACTIONPUSHPARAM * peek()\n{\n#ifdef DEBUG\n\tprintf(\"*peek*\\n\");\n#endif\n#ifdef DEBUGSTACK\t\t/* continue w stack dummy */\n\tif( Stack == NULL ) push(newVar(\"// *** peek(): INTERNAL STACK ERROR FOUND ***\"));\n#else\n\tif( Stack == NULL ) SWF_error(\"Stack blown!! - peek\");\n#endif\n\treturn Stack->val;\n}", "void\nstackswap()\n{\n#ifdef DEBUG\n\tprintf(\"*stackswap*\\n\");\n#endif\n\tstruct SWF_ACTIONPUSHPARAM *p = peek();\t\t/* peek() includes error handling */\n\tchar type = Stack->type;", " if (Stack->next == NULL) {\n#if DEBUG\n\t\tSWF_warn(\"stackswap: can't swap (stack contains only one element)\\n\");\n#endif\n return;\n }", "\tStack->type = Stack->next->type;\n\tStack->val = Stack->next->val;\n\tStack->next->type = type;\n\tStack->next->val = p;\n}", "\nstatic struct SWF_ACTIONPUSHPARAM *\nnewVar_N(char *var,char *var2, char *var3,char *var4,int pop_counter,char *final)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;\n\tint psize=PARAM_STRSIZE;\n\tint i;\n\tint slen=strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(final);\n\t\n\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->p.String = malloc(psize + slen);\n\tv->Type = PUSH_VARIABLE; \n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\tstrcat(v->p.String,var4);\n\tfor(i=0;i<pop_counter;i++) \n\t{\n\t\tchar *pops=getString(pop());\n\t\twhile ( strlen(v->p.String)+ 2 + strlen(pops) +slen >= psize)\n\t\t{\n\t\t\tpsize += PARAM_STRSIZE;\n\t\t\tv->p.String = realloc( v->p.String, psize);\n\t\t}\n\t\tstrcat(v->p.String,pops);\n\t\tif( i < pop_counter-1 ) \n\t\t\tstrcat(v->p.String,\",\");\n\t}\n\tstrcat(v->p.String,final);\n\treturn v;\n}", "// similar to newVar_N(), \n// but pops 2 items from stack per counter,\n// and second of them we are interested in getName() instead of getString()\nstatic struct SWF_ACTIONPUSHPARAM *\nnewVar_N2(char *var,char *var2, char *var3,char *var4,int pop_counter,char *final)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;\n\tint psize=PARAM_STRSIZE;\n\tint i;\n\tint slen=strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(final);\n\t\n\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->p.String = malloc(psize + slen);\n\tv->Type = PUSH_VARIABLE; \n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\tstrcat(v->p.String,var4);\n\tfor(i=0;i<pop_counter;i++) \n\t{\n\t\tchar *pops1=getString(pop());\n\t\tchar *pops2=getName (pop());", "\t\twhile ( strlen(v->p.String)+ 3 + strlen(pops1)+ strlen(pops2) +slen >= psize)\n\t\t{\n\t\t\tpsize += PARAM_STRSIZE;\n\t\t\tv->p.String = realloc( v->p.String, psize);\n\t\t}\n\t\tstrcat(v->p.String,pops2);\n\t\tstrcat(v->p.String,\":\");\n\t\tstrcat(v->p.String,pops1);\n\t\tif( i < pop_counter-1 ) \n\t\t\tstrcat(v->p.String,\",\");\n\t}\n\tstrcat(v->p.String,final);\n\treturn v;\n}", "/* End Package */", "static int gIndent;\nstatic void decompileActions(int n, SWF_ACTION *actions,int indent);\nchar * decompile5Action(int n, SWF_ACTION *actions,int indent);", "/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/", "\n#define SanityCheck(curact,test,msg ) \\\n if(!(test) ) SWF_error( \"SanityCheck failed in %s\\n %s\\n\", #curact, msg );", "#define OUT_BEGIN(block) \\\n\t struct block *sact = (struct block *)act;\n#define OUT_BEGIN2(block) \\\n\t struct block *sact = (struct block *)&(actions[n]);", "static void\ndecompileCONSTANTPOOL (SWF_ACTION *act)\n{\n\tOUT_BEGIN(SWF_ACTIONCONSTANTPOOL);\n\tpool=sact->ConstantPool;\n\tpoolcounter = sact->Count;\n}", "static void\ndecompileWAITFORFRAME (SWF_ACTION *act)\n{\n\tOUT_BEGIN(SWF_ACTIONWAITFORFRAME);", "\tINDENT\n\tprintln(\"WaitForFrame(%d,%d);\", sact->Frame,sact->SkipCount);\n}", "static void\ndecompilePUSHPARAM (struct SWF_ACTIONPUSHPARAM *act, int wantstring)\n{\n\tchar *t;\n\tswitch( act->Type ) \n\t{\n\tcase PUSH_STRING: /* STRING */\n\t\tif( wantstring ) printf (\"'%s'\", act->p.String);\n\t\telse printf (\"%s\", act->p.String);\n\t\tbreak;\n\tcase PUSH_FLOAT: /* FLOAT */\n\t\tprintf (\"%f\", act->p.Float);\n\t\tbreak;\n\tcase PUSH_NULL: /* NULL */\n\t\tprintf (\"NULL\" );\n\t\tbreak;\n\tcase PUSH_UNDEF: /* Undefined */\n\t\tprintf (\"undefined\" );\n\t\tbreak;\n\tcase PUSH_REGISTER: /* Register */\n\t\tif( regs[act->p.RegisterNumber] ) {\n\t\t\tprintf (\"%s\", getName(act));\n\t\t} else {\n\t\t\tprintf (\"R%d\", (int)act->p.RegisterNumber);\n\t\t}\n\t\tbreak;\n\tcase PUSH_BOOLEAN: /* BOOLEAN */\n\t\tprintf (\"%s\", act->p.Boolean?\"true\":\"false\");\n\t\tbreak;\n\tcase PUSH_DOUBLE: /* DOUBLE */\n\t\tprintf (\"%g\", act->p.Double);\n\t\tbreak;\n\tcase PUSH_INT: /* INTEGER */\n\t\tprintf (\"%ld\", act->p.Integer);\n\t\tbreak;", "\tcase PUSH_CONSTANT: /* CONSTANT8 */\n\tcase PUSH_CONSTANT16: /* CONSTANT16 */\n\t\tif( wantstring ) t=getString(act);\n\t \telse t=getName(act);\n\t \tputs(t); \n\t \tfree(t); \n\t \tbreak;", "#if 0\n\t case 8: /* CONSTANT8 */\n\t\tif (act->p.Constant8 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tif( wantstring )\n \t\t printf (\"'%s'\", pool[act->p.Constant8]);\n\t\telse\n \t\t printf (\"%s\", pool[act->p.Constant8]);\n\t\tbreak;\n\t case 9: /* CONSTANT16 */\n\t\tif (act->p.Constant16 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tif( wantstring )\n \t\t printf (\"'%s'\", pool[act->p.Constant16]);\n\t\telse\n \t\t printf (\"%s\", pool[act->p.Constant16]);\n\t\tbreak;\n#endif\n\tcase 12:\n\tcase 11: /* INCREMENTED or DECREMENTED VARIABLE */\n\tcase PUSH_VARIABLE: /* VARIABLE */\n\t\tprintf (\"%s\", act->p.String);\n\t\tbreak;\n\tdefault: \n\t\tprintf (\" Unknown type: %d\\n\", act->Type);\n\t}\n}", "static void\ndecompileGETURL (SWF_ACTION *act)\n{\n\tOUT_BEGIN(SWF_ACTIONGETURL);", "\tINDENT\n\tprintln(\"getUrl('%s',%s);\", sact->UrlString, sact->TargetString);\n}", "static int\ndecompileGETURL2 (SWF_ACTION *act)\n{\n\tstruct SWF_ACTIONPUSHPARAM *a,*b;\n\tOUT_BEGIN(SWF_ACTIONGETURL2);\n\tINDENT", "\ta = pop();\n\tb = pop();", "\tif (sact->f.FlagBits.SendVarsMethod==3)\n\t\tputs(\"loadVariables(\");\n\telse \n\t{\n\t\tif (sact->f.FlagBits.SendVarsMethod==2)\n\t\t\tputs(\"loadVariablesNum(\");\n\t\telse\n\t\t{\n\t\t\tif (sact->f.FlagBits.SendVarsMethod==1) \n\t\t\t\tputs(\"loadMovie(\");\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (*getName(a)=='_')\t// found a _level\n\t\t\t\t\tputs(\"loadMovieNum(\");\t\n\t\t\t\telse\n\t\t\t\t\tputs(\"getURL(\");\n\t\t\t}\n\t\t}\n\t}\n\tdecompilePUSHPARAM (b, 1);\n\tputs(\",\");\n\tdecompilePUSHPARAM (a, 1);\n\tif (sact->f.FlagBits.LoadVariableFlag)\n\t\tputs(\",'GET'\");\n\tif (sact->f.FlagBits.LoadTargetFlag)\n\t\tputs(\",'POST'\");\n\tprintln(\");\");\n\treturn 0;\n}", "static inline int OpCode(SWF_ACTION *actions, int n, int maxn)\n{\n\tif(!n || n >= maxn)\n\t{\n#if DEBUG\n\t\tSWF_warn(\"OpCode: want %i, max %i\\n\", n, maxn);\n#endif\n\t\treturn -999;\n\t} else if (n < 1) {", "#if DEBUG\n\t\tSWF_warn(\"OpCode: want %i < 1\\n\", n);\n#endif\n\t\treturn -998;\n }\n\treturn actions[n].SWF_ACTIONRECORD.ActionCode;\n}", "static int\nisStoreOp(int n, SWF_ACTION *actions,int maxn)\n{\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\tcase SWFACTION_STOREREGISTER:\n\tcase SWFACTION_SETVARIABLE:\n\tcase SWFACTION_SETMEMBER:\n\tcase SWFACTION_CASTOP:\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}", "static int \ndecompileGOTOFRAME(int n, SWF_ACTION *actions,int maxn,int islabel)\n{\n\tint i=0;\n\tstruct SWF_ACTIONGOTOLABEL *sactv2;\n\tOUT_BEGIN2(SWF_ACTIONGOTOFRAME);\n\tsactv2 = (struct SWF_ACTIONGOTOLABEL*)sact;\n\tINDENT\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_PLAY)\n\t{\n\t\ti=1;\n\t\tputs(\"gotoAndPlay(\");\n\t}\n\telse\n\t{\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_STOP)\n\t\t\ti=1;\n\t\tputs(\"gotoAndStop(\");\n\t}\n\t\n\tif (islabel)\n\t\tprintln(\"'%s');\", sactv2->FrameLabel);\n\telse\n\t\tprintln(\"%d);\", sact->Frame+1); /* GOTOFRAME arg is 0-based */\n\treturn i;\n}", "static int \ndecompileGOTOFRAME2(int n, SWF_ACTION *actions, int maxn)\n{\n\tint i=0;\n\tOUT_BEGIN2(SWF_ACTIONGOTOFRAME2);\n\tINDENT\n\tif (n+1 < maxn)\n\t{\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_PLAY ||\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_STOP)\n\t\t\ti=1;\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_PLAY)\n\t\t\tputs(\"gotoAndPlay(\");\n\t\telse\n\t\t{\n\t\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_STOP)\n\t\t\t\tputs(\"gotoAndStop(\");\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (sact->f.FlagBits.PlayFlag)\n\t\t\t\t\tputs(\"gotoAndPlay(\");\n\t\t\t\telse\n\t\t\t\t\tputs(\"gotoAndStop(\");\n\t\t\t}\n\t\t}\n\t}\n\telse \n\t{\n\t\tif (sact->f.FlagBits.PlayFlag)\n\t\t\tputs(\"gotoAndPlay(\");\n\t\telse\n\t\t\tputs(\"gotoAndStop(\");\n\t}\n\tdecompilePUSHPARAM(pop(),0);\n\tprintln(\");\");\n\treturn i;\n}", "\nstatic int precedence(int op1,int op2)\n{\n\tstatic unsigned char ops[]= { \t\t// array of opcodes w rising precedence\n//\tSWFACTION_SETVARIABLE,\t\t// TAKE CARE: array is incomplete\n//\tSWFACTION_TRACE,\n\t// missing ops are considered with low precedence\n\t\tSWFACTION_LOGICALOR,\n\t\tSWFACTION_LOGICALAND,\n\t\tSWFACTION_BITWISEOR,\n\t\tSWFACTION_BITWISEXOR,\n\t\tSWFACTION_BITWISEAND,\n\t\tSWFACTION_STRICTEQUALS,\n\t\tSWFACTION_EQUALS2,\n\t\tSWFACTION_EQUAL,\n\t\tSWFACTION_GREATER,\n\t\tSWFACTION_LESSTHAN,\n\t\tSWFACTION_LESS2,\t\n\t\tSWFACTION_SHIFTRIGHT,\n\t\tSWFACTION_SHIFTRIGHT2,\n\t\tSWFACTION_SHIFTLEFT,\n\t\tSWFACTION_ADD,\n\t\tSWFACTION_ADD2,\n\t\tSWFACTION_SUBTRACT,\n\t\tSWFACTION_MODULO,\n\t\tSWFACTION_MULTIPLY,\n\t\tSWFACTION_DIVIDE,\n\t\tSWFACTION_LOGICALNOT,\n\t\tSWFACTION_PUSH\t\t\t// FIXME: need more analysis on code after PUSH\n\t};\n\tunsigned char* f=memchr(ops,op1,sizeof(ops));\n\tunsigned char* s=memchr(ops,op2,sizeof(ops));\n#ifdef DEBUG\n\tprintf(\"1op=%d 2op=%d result=%d\\n\",op1,op2,f>s);\n\tif (!f) printf(\"opcode=%d NOT in precedence list\\n\",op1);\n\tif (!s) printf(\"opcode=%d NOT in precedence list\\n\",op2);\n#endif\n\treturn f>s;\n}", "#ifdef DECOMP_SWITCH\nstatic int\ncheck_switch(int firstcode)\n{\n\treturn (firstcode == SWFACTION_PUSH || firstcode == SWFACTION_JUMP);\n}\n#endif", "\nstatic int\ndecompileArithmeticOp(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *left, *right;\n\tint op_l = OpCode(actions, n, maxn);\n\tint op_r = OpCode(actions, n+1, maxn);\n\tright=pop();\n\tleft=pop();\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\t/*\n\tcase SWFACTION_GETMEMBER:\n\t\tdecompilePUSHPARAM(peek(),0);\n\t\tbreak;\n\t*/\n\tcase SWFACTION_INSTANCEOF:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\" instanceof \",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\" instanceof \",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_ADD:\n\tcase SWFACTION_ADD2:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"+\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"+\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SUBTRACT:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"-\",getString(right)));\t \n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"-\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_MULTIPLY:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"*\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"*\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_DIVIDE:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"/\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"/\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_MODULO:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"%\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"%\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SHIFTLEFT:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"<<\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"<<\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SHIFTRIGHT:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\">>\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\">>\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SHIFTRIGHT2:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\">>>\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\">>>\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LOGICALAND:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"&&\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"&&\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LOGICALOR:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"||\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"||\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_BITWISEAND:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"&\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"&\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_BITWISEOR:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"|\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"|\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_BITWISEXOR:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"^\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"^\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_EQUALS2:\t/* including negation */\n\tcase SWFACTION_EQUAL:\n\t\tif( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t\t OpCode(actions, n+2, maxn) != SWFACTION_IF)\n\t\t{\n\t\t\top_r = OpCode(actions, n+1, maxn);\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\"!=\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\"!=\",getString(right),0,\")\"));\n\t\t\treturn 1; /* due negation op */\n\t\t}\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"==\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"==\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LESS2:\n\t\tif( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t\t OpCode(actions, n+2, maxn) != SWFACTION_IF ) \n\t\t{\n\t\t\top_r = OpCode(actions, n+2, maxn);\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\">=\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\">=\",getString(right),0,\")\"));\n\t\t\treturn 1; /* due negation op */\n\t\t}\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"<\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"<\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_GREATER:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\">\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\">\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LESSTHAN:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"<\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"<\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_STRINGEQ:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"==\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"==\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_STRINGCOMPARE:\n\t\tputs(\"STRINGCOMPARE\");\n\t\tbreak;\n\tcase SWFACTION_STRICTEQUALS:\n#ifdef DECOMP_SWITCH\n\t\tif (OpCode(actions, n, maxn) == SWFACTION_IF)\n\t\t{\n\t\t\tint code = actions[n+1].SWF_ACTIONIF.Actions[0].SWF_ACTIONRECORD.ActionCode;\n\t\t\tif(check_switch(code))\n\t\t\t{\n\t\t\t\tpush(right);\t// keep left and right side separated\n\t\t\t\tpush(left);\t// because it seems we have found a switch(){} and\n\t\t\t\tbreak;\t// let decompileIF() once more do all the dirty work\n\t\t\t}\n\t\t}\n#endif\n\t\tif( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t\t OpCode(actions, n+2, maxn) != SWFACTION_IF ) \n\t\t{\n\t\t\top_r = OpCode(actions, n+2, maxn);\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\"!==\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\"!==\",getString(right),0,\")\"));\n\t\t\treturn 1; /* due negation op */\n\t\t} else {\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\"===\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\"===\",getString(right),0,\")\"));\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\tprintf(\"Unhandled Arithmetic/Logic OP %x\\n\",\n\t\t\tOpCode(actions, n, maxn));\n\t}\n\treturn 0;\n}", "static int\nisLogicalOp(int n, SWF_ACTION *actions, int maxn)\n{\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\tcase SWFACTION_LESSTHAN:\n\tcase SWFACTION_LOGICALAND:\n\tcase SWFACTION_LOGICALOR:\n\tcase SWFACTION_LOGICALNOT:\n\tcase SWFACTION_STRINGEQ:\n\tcase SWFACTION_STRINGCOMPARE:\n\tcase SWFACTION_LESS2:\n\tcase SWFACTION_EQUALS2:\n\tcase SWFACTION_EQUAL:\n\tcase SWFACTION_BITWISEAND:\n\tcase SWFACTION_BITWISEOR:\n\tcase SWFACTION_BITWISEXOR:\n\tcase SWFACTION_STRICTEQUALS:\n\tcase SWFACTION_GREATER:\n\t/*\n\tcase SWFACTION_GETMEMBER:\n\t*/\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}", "static int \nisLogicalOp2(int n, SWF_ACTION *actions,int maxn)\n{\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\tcase SWFACTION_LOGICALNOT:\n\tcase SWFACTION_PUSHDUP:\n\tcase SWFACTION_IF:\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}", "static int\nstackVal(int n, SWF_ACTION *actions)\n{\n\tif (!n) \n\t\treturn 0;", "\tswitch((actions[n-1]).SWF_ACTIONRECORD.ActionCode)\n\t{\n\tcase SWFACTION_LOGICALNOT:\n\tcase SWFACTION_DECREMENT:\n\tcase SWFACTION_INCREMENT:\n\tcase SWFACTION_RANDOMNUMBER:\n\tcase SWFACTION_TOSTRING:\n\tcase SWFACTION_TONUMBER:\n\tcase SWFACTION_ORD:\n\tcase SWFACTION_CHR:\n\tcase SWFACTION_MBORD:\n\tcase SWFACTION_MBCHR:\n\tcase SWFACTION_INT:\n\tcase SWFACTION_GETVARIABLE:\n\tcase SWFACTION_SUBSTRING:\n\tcase SWFACTION_MBSUBSTRING:\n\tcase SWFACTION_GETMEMBER:\n\tcase SWFACTION_ADD:\n\tcase SWFACTION_ADD2:\n\tcase SWFACTION_SUBTRACT:\n\tcase SWFACTION_MULTIPLY:\n\tcase SWFACTION_DIVIDE:\n\tcase SWFACTION_MODULO:\n\tcase SWFACTION_BITWISEAND:\n\tcase SWFACTION_BITWISEOR:\n\tcase SWFACTION_BITWISEXOR:\n\tcase SWFACTION_LESSTHAN:\n\tcase SWFACTION_LOGICALAND:\n\tcase SWFACTION_LOGICALOR:\n\tcase SWFACTION_STRINGEQ:\n\tcase SWFACTION_STRINGCOMPARE:\n\tcase SWFACTION_LESS2:\n\tcase SWFACTION_EQUALS2:\n\tcase SWFACTION_EQUAL:\n\tcase SWFACTION_STRICTEQUALS:\n\tcase SWFACTION_GREATER:\n\tcase SWFACTION_STRINGGREATER:\n\tcase SWFACTION_STRINGCONCAT:\n\tcase SWFACTION_SHIFTLEFT:\n\tcase SWFACTION_SHIFTRIGHT:\n\tcase SWFACTION_SHIFTRIGHT2:\n\tcase SWFACTION_INSTANCEOF:\n\tcase SWFACTION_CALLMETHOD:\n\tcase SWFACTION_CALLFUNCTION:\n\tcase SWFACTION_GETTIME:\n\tcase SWFACTION_GETPROPERTY:\n\tcase SWFACTION_PUSH:\n\tcase SWFACTION_DELETE:\n\tcase SWFACTION_DELETE2:\n\tcase SWFACTION_MBLENGTH:\n\tcase SWFACTION_STRINGLENGTH:\n\tcase SWFACTION_CASTOP:\n\tcase SWFACTION_TYPEOF:\n\tcase SWFACTION_PUSHDUP:\n\t\treturn 1;\n\tdefault:\n\treturn 0;\n\t}\n}", "static int\ndecompileLogicalNot(int n, SWF_ACTION *actions, int maxn)\n{\n#ifdef STATEMENT_CLASS\n\tif(OpCode(actions, n-1, maxn) == SWFACTION_GETVARIABLE &&\n\t OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t OpCode(actions, n+2, maxn) == SWFACTION_IF ) \n\t{\n\t\t/* It's a class statement -- skip over both NOTs */\n\t\treturn 1;\n\t}\n#endif\n\tif(OpCode(actions, n+1, maxn) != SWFACTION_IF )\n\t\tpush(newVar2(\"!\",getString(pop())));\n\treturn 0;\n}", "static void\ndecompilePUSH (SWF_ACTION *act)\n{\n\tint i;\n\tOUT_BEGIN(SWF_ACTIONPUSH);", "\tSanityCheck(SWF_PUSH,\n\t\tact->SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSH,\n\t\t\"not a PUSH\")", "\tfor(i=0;i<sact->NumParam;i++)\n\t\tpush(&(sact->Params[i]));\n}", "static void\ndecompilePUSHDUP (SWF_ACTION *act)\n{\n\tSanityCheck(SWF_PUSHDUP,\n\t\tact->SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSHDUP,\n\t\t\"not a PUSHDUP\")\n\tpushdup();\n}", "static void\ndecompileSTACKSWAP (SWF_ACTION *act)\n{\n\tSanityCheck(SWF_STACKSWAP,\n\t\tact->SWF_ACTIONRECORD.ActionCode == SWFACTION_STACKSWAP,\n\t\t\"not a STACKSWAP\")\n\tstackswap();\n}", "static int\ndecompileSETPROPERTY(int n, SWF_ACTION *actions,int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *val, *idx, *obj;", "\tINDENT\n\tval = pop();\n\tidx = pop();\n\tobj = pop();\n#ifdef DEBUG\n\tprintf(\"*setProp* objName %s (type=%d) Prop (type=%d) =%x\\n\",\n\t getName(obj), obj->Type, idx->Type,getInt(idx));\n#endif\n\tif (obj->Type == PUSH_VARIABLE)\n\t\tputs(\"eval(\");\n\t\n\tdecompilePUSHPARAM(obj,0);\n\tif (obj->Type == PUSH_VARIABLE)\n\t\tputs(\")\");\n\t\n\tputs(\".\");\n\tputs(getProperty(getInt(idx)));\n\tprintf(\" = \" );\n\tdecompilePUSHPARAM(val,0);\n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileGETPROPERTY(int n, SWF_ACTION *actions,int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *idx, *obj;", "\tINDENT\n\tidx = pop();\n\tobj = pop();\n#ifdef DEBUG\n\tprintf(\"*GETProp* objName %s (type=%d) Prop (type=%d) =%x\\n\",\n\t getName(obj), obj->Type, idx->Type,getInt(idx));\n#endif\n\tif (obj->Type == PUSH_VARIABLE)\n\t\tpush( newVar5(\"eval(\",getName(obj),\".\",getProperty(getInt(idx)),\")\"));\n\telse\n\t\tpush( newVar3( getName(obj),\".\",getProperty(getInt(idx))));\n\treturn 0;\n}", "static int\ndecompileTRACE(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"trace(\");\n\tdecompilePUSHPARAM(pop(),1);\n\tprintln(\");\");\n\treturn 0;\n}", "static int\ndecompileCALLFRAME(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"callFrame(\");\n\tdecompilePUSHPARAM(pop(),1);\n\tprintln(\");\");\n\treturn 0;\n}", "static int\ndecompileGETTIME(int n, SWF_ACTION *actions, int maxn)\n{\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\tINDENT\n\t\tprintln(\"getTimer();\");\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tpush(newVar(\"getTimer()\"));\n\t\treturn 0;\n\t}\n}", "static int\ndecompileINCR_DECR(int n, SWF_ACTION *actions, int maxn, int is_incr)\n{\n\tint is_postop;\n\tstruct SWF_ACTIONPUSHPARAM *var=pop();\n\tchar *dblop=is_incr ? \"++\":\"--\";", "\tif((OpCode(actions, n, maxn) == SWFACTION_PUSHDUP\n\t || OpCode(actions, n+1, maxn) == SWFACTION_PUSHDUP \n\t || OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE)\n\t || ( OpCode(actions, n-1, maxn) == SWFACTION_GETVARIABLE\n\t && OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER\n\t && OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE))\n\t{\n\t\tis_postop=(OpCode(actions, n-1, maxn) == SWFACTION_PUSHDUP)?1:0;\n\t\tif (is_postop)\n\t\t\tvar = newVar2(getString(var),dblop);\n\t\telse\n\t\t\tvar = newVar2(dblop,getString(var));\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE)\n\t\t{\n\t\t\tvar->Type=11;\t/* later trigger printing variable inc/dec */\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar->Type=12;\t/* later be quiet, see decompileSETVARIABLE() */\n\t\t\tif (is_postop)\n\t\t\t{\n\t\t\t\tpop();\n\t\t\t\tpush(var);\t/* will duplicate stacktop */\n\t\t\t}\n\t\t}\n\t\tpush(var);\n\t}\n\telse\n\t{\n\t\tif((OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER &&\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER &&\n\t\t OpCode(actions, n+2, maxn) == SWFACTION_SETMEMBER ) ||\n\t\t (OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER &&\n\t \t OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER &&\n\t\t OpCode(actions, n+2, maxn) == SWFACTION_PUSH ) ||\n\t\t (OpCode(actions, n-1, maxn) == SWFACTION_PUSH &&\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER) ||\n\t\t (OpCode(actions, n-3, maxn) == SWFACTION_GETMEMBER &&\n\t\t OpCode(actions, n-2, maxn) == SWFACTION_PUSH &&\n\t\t OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER &&\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER &&\n\t \t((struct SWF_ACTIONPUSH *)&actions[n-2].SWF_ACTIONRECORD)->NumParam >= 4 \n\t \t\t/* 4: a pair of get/set - FIXME: add more analysis about stack here */))\n\t\t{\t\t// incr/decr object variables with side effects\n\t\t\tis_postop= (OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER)?1:0;\n\t\t\tif (is_postop)\n\t\t\t\tvar = newVar2(getString(var),dblop);\n\t\t\telse\n\t\t\t\tvar = newVar2(dblop,getString(var));\n\t\t\tif (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_PUSH) \n\t\t\t\tpop();\n\t\t\tif(OpCode(actions, n+1, maxn) == SWFACTION_GETMEMBER) \n\t\t\t\tpop();\n\t\t\t\n\t\t\tpop();\n\t\t\tpop();\n\t\t\tvar->Type=12;\t// to be quiet later in ...SETMEMBER()\n\t\t\tregs[0]=var;\t// FIXME: r0 perhaps a ming special\n\t\t\tpush(var);\n\t\t\tpush(var);\n\t\t\tpush(var);\n\t\t\n\t\t\tif (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_PUSH ) \n\t\t\t\tpush(var);\n\t\t\tif (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER ) \n\t\t\t\tpush(var);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(OpCode(actions, n-1, maxn) == SWFACTION_PUSH &&\n\t\t\t OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER &&\n\t\t\t regs[actions[n+1].SWF_ACTIONSTOREREGISTER.Register]->Type == PUSH_VARIABLE)\n\t\t\t{\n\t\t\t\tvar = newVar2(dblop,getString(var));\n\t\t\t\tif ((OpCode(actions, n+2, maxn) == SWFACTION_POP \n\t\t\t\t && actions[n-1].SWF_ACTIONPUSH.NumParam==1) \n\t\t\t\t || OpCode(actions, n+3, maxn) == SWFACTION_POP)\n\t\t\t\t{\n\t\t\t\t\tvar->Type=11;\t// later print inc/dec\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar->Type=12;\t// later be quiet in ..STOREREGISTER()\n\t\t\t\t\tif (actions[n-1].SWF_ACTIONPUSH.NumParam>1) \n\t\t\t\t\t{\n\t\t\t\t\t\tpop();\n\t\t\t\t\t\tpush(var);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpush(var);\n\t\t\t}\n\t\t\telse\t\t// fallback to old incr/decr code\n\t\t\t{\t\t// FIXME: this is bad designed for handling side effect code\n\t\t\t\tINDENT\t// like post-incrementing a function argument etc.\n\t\t\t\tdecompilePUSHPARAM(var,0);\n\t\t\t\tputs(dblop);\n\t\t\t\tprintln(\";\");\n\t\t\t\tpush(var);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "static int\ndecompileSTOREREGISTER(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *data;\n\tOUT_BEGIN2(SWF_ACTIONSTOREREGISTER);\n\tdata=peek();", "\tif (!regs[sact->Register] || sact->Register==0 )\t// ===internal===\n\t{\n\t\tregs[sact->Register] = data;\n\t}\n\telse\t\t\t\t\t\t// ===user visible level===\n\t{\n\t\tif ( regs[sact->Register]->Type == PUSH_VARIABLE) // V7: a named function parameter in register\n\t\t{\t\t\t\t\t\t// V7: a local var in register\n\t\t\tif (data->Type==12)\n\t\t\t\tdata->Type = PUSH_VARIABLE;\t\t\t// do nothing, but only once\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar *l=getName(regs[sact->Register]);\n\t\t\t\tchar *r=getName(data);\n\t\t\t\tif (strcmp(l,r))\n\t\t\t\t{\n\t\t\t\t\tINDENT\n\t\t\t\t\tif (data->Type==11)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintln(\"%s;\", r);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"%s = \",l);\n\t\t\t\t\t\tdecompilePUSHPARAM(data,1);\n\t\t\t\t\t\tprintln(\";\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "static int\ndecompileNEWOBJECT(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *obj, *nparam;\n\tobj = pop();\n\tnparam=pop();\n\tpush(newVar_N(\"new \",\"\",getName(obj),\"(\", nparam->p.Integer,\")\"));\n\treturn 0;\n}", "static int\ndecompileNEWMETHOD(int n, SWF_ACTION *actions, int maxn)\n{\n\tchar *t;\n\tstruct SWF_ACTIONPUSHPARAM *meth, *nparam, *obj;\n\tmeth = pop();\n\tobj = pop();\n\tnparam=pop();", "\tt=malloc(strlen( getName(obj) ) +2);\n\tstrcpy(t,getName(obj));\n\tstrcat(t,\".\");", "\tpush(newVar_N(\"new \",t,getName(meth),\"(\", nparam->p.Integer,\")\"));\n\tfree (t);\n\treturn 0;\n}", "\nstatic int\ndecompileGETMEMBER(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *obj, *mem, *var;\n\tchar *vname, *varname,*memname;\n\tint len;", "\tmem=pop();\n\tvar=pop();\n\tvarname=getName(var);\n\tmemname=getName(mem);\n#ifdef DEBUG\n\tprintf(\"*getMember* varName %s (type=%d) memName=%s (type=%d)\\n\",\n\t varname,var->Type, memname,mem->Type);\n#endif\n\tlen = strlen(varname)+strlen(memname);\n\tif (mem->Type == PUSH_INT || mem->Type == PUSH_DOUBLE || mem->Type == PUSH_VARIABLE\n\t || mem->Type == PUSH_REGISTER || mem->Type == 12 )\n\t{\n\t\tvname = malloc(len+3);\n\t\tstrcpy(vname,varname);\n\t\tstrcat(vname,\"[\");\n\t\tstrcat(vname,memname);\n\t\tstrcat(vname,\"]\");\n\t}\n\telse\n\t{\n\t\tvname = malloc(len+2);\n\t\tstrcpy(vname,varname);\n\t\tstrcat(vname,\".\");\n\t\tstrcat(vname,memname);\n\t} \n\tobj = newVar(vname);\n\tpushvar(obj);", "\treturn 0;\n}", "\nstatic int\ndecompileSETMEMBER(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *val, *var, *obj;\n\tval = pop();\n\tvar = pop();\n\tobj = pop();", "#ifdef DEBUG\n\tprintf(\"*SETMember* varName %s (type=%d) objName=%s (type=%d)\\n\",getName(var),var->Type, getName(obj),obj->Type);\n#endif\n\tif (obj->Type == 12)\t\t\t\t/* do nothing: inline inc/dec using side effect */\n\t{\n\t\tobj->Type = PUSH_VARIABLE;\t\t/* ...but only once */\n\t\treturn 0;\n\t}\n\tINDENT\n\tif (obj->Type == 11)\t\t\t\t/* simply output variable and inc/dec op */\n\t{\n\t\tdecompilePUSHPARAM(obj,0);\n\t\tprintln(\";\");\n\t\treturn 0;\n\t}", "\tdecompilePUSHPARAM(obj,0);\n\tif (var->Type == PUSH_INT || var->Type == PUSH_DOUBLE || var->Type == PUSH_VARIABLE\n\t || var->Type == PUSH_REGISTER || var->Type == 12 )\n\t{\n\t\tputs(\"[\");\n\t}\n\telse\n\t{\n\t\tputs(\".\");\n\t\tif (OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER)\n\t\t{\n\t\t\tstruct SWF_ACTIONSTOREREGISTER *sactv2 = (struct SWF_ACTIONSTOREREGISTER*)&actions[n-1];\n\t\t\tif (sactv2->Register==0)\n\t\t\t\tregs[0]=newVar3(getName(obj),\".\",getName(var));\t\t// easter 07: some sugar for mtc et al.\n\t\t}\n\t}\n\tdecompilePUSHPARAM(var,0);\n\tif (var->Type == PUSH_INT || var->Type == PUSH_DOUBLE || var->Type == PUSH_VARIABLE\n\t\t|| var->Type == PUSH_REGISTER || var->Type == 12 )\n\t{\n\t\tputs(\"]\");\n\t}\n\tprintf(\" = \" );", "\n\tif ( OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER ) {\n\t\tstruct SWF_ACTIONSTOREREGISTER *sr =\n\t\t\t(struct SWF_ACTIONSTOREREGISTER*)&actions[n-1];\n\t\tprintf(\"R%d\", sr->Register);\n\t}\n\telse if (val->Type != PUSH_VARIABLE) {\n\t\t/* later it will be a switch{} */\n\t\tdecompilePUSHPARAM(val,1);\n\t}\n\telse {\n\t\tdecompilePUSHPARAM(val,0);\n\t}\n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileGETVARIABLE(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *var;", "\tvar = pop();\n#ifdef DEBUG\n\tprintf(\"*GETVariable* varName %s (type=%d)\\n\",getName(var),var->Type);\n#endif\n\tif (var->Type == PUSH_VARIABLE)\n\t\tpushvar(newVar3(\"eval(\",getName(var),\")\"));\n\telse\n\t\tpushvar(newVar(getName(var)));", "\treturn 0;\n}", "static int\ndecompileSETVARIABLE(int n, SWF_ACTION *actions,int maxn,int islocalvar)\n{\n\tstruct SWF_ACTIONPUSHPARAM *val, *var;", "\tval = pop();\n\tvar = pop();\n\tif (val->Type!=12)\n\t{\n\t\tINDENT\n\t}\n#ifdef DEBUG\n\tprintf(\"*SETVariable* varName %s (type=%d) valName=%s (type=%d)\\n\",\n\t getName(var),var->Type, getName(val),val->Type);\n#endif\n\tif (val->Type!=12 && islocalvar)\n\t{\n\t\tputs(\"var \");\n\t}\n\tif (gIndent<0)\t/* the ENUM workaround: */\n\t{\t\t\t/* in \"for (xx in yy) { }\" we need xx, but nothing else */\n\t\tputs(getName(var));\n\t\treturn 0;\n\t}", "\n\tswitch (val->Type)\n\t{\n\tcase 10:\t\n\t\tputs(getName(var));\t\t// Variable (NEVER as string)\n\t\tprintf(\" = \" );\n\t\tdecompilePUSHPARAM(val,0);\n\t\tprintln(\";\");\n\t\tbreak;\t\t\n\tcase 11:\t\t\t\t/* simply output variable and inc/dec op */\n\t\tputs(getName(val));\n\t\tprintln(\";\");\n\t\tbreak;\n\tcase 12:\t\t\t\t/* do nothing: inline increment/decrement (using side effect only) */\n\t\tval->Type = PUSH_VARIABLE; \t\t// but print next time e.g. in y=++x;\n\t\tbreak;\n\tdefault:\t\n\t\tputs(getName(var));\n\t\tprintf(\" = \" );\n\t\tdecompilePUSHPARAM(val,1);\t// for certain types parameter 1 does not care\n\t\tprintln(\";\");\n\t}\n\treturn 0;\n}", "static int\ndecompileRETURN(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *var=pop();\n\tINDENT\n\tprintf(\"return \");\n\tif (var->Type== PUSH_REGISTER && var->p.RegisterNumber==0)\t/* REGISTER 0 used as helper variable */\n\t\tputs(getName(regs[0]));\n\telse\n\t\tdecompilePUSHPARAM(var,1); \n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileJUMP(int n, SWF_ACTION *actions, int maxn)\n{\n\tint i=0,j=0;\n\tint offSave;\n\tstruct SWF_ACTIONIF *sactif;\n\tOUT_BEGIN2(SWF_ACTIONJUMP);\n\tsactif=NULL;", "\tif(isLogicalOp(n+1, actions, maxn) ||\n\t (OpCode(actions, n+1, maxn) == SWFACTION_PUSH && isLogicalOp(n+2, actions, maxn)))\n\t{\n\t\t/* Probably the start of a do {} while(), so skip it */\n\t\treturn 0;\n\t}", "\t/* Probably the end of a switch{}, so skip it */\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t\treturn 1;", "\tif (OpCode(actions, n+1, maxn) == SWFACTION_JUMP) \n\t{\n\t\tif (actions[n+1].SWF_ACTIONJUMP.BranchOffset==0)\n\t\t\treturn 1;\n\t}", "\tfor(i=0; n + 1 + i < maxn && (actions[(n+1)+i].SWF_ACTIONRECORD.Offset < (actions[n+1].SWF_ACTIONRECORD.Offset+actions[n ].SWF_ACTIONJUMP.BranchOffset)); i++)\n\t{\n#if 0\n\t\tprintf(\"/* for PART3 OP 0x%x */\\n\",actions[n+1+i].SWF_ACTIONRECORD.ActionCode);\n#endif\n\t\t; // NOOP\n\t}", "\tif (i)\n\t{\n\t\tfor (j=0; n+j+i<maxn; j++)\n\t\t{\n#if 0\n\t\t\t printf(\"/* FOR part2 OP 0x%x */\\n\",actions[n+i+j].SWF_ACTIONRECORD.ActionCode)\n\t\t\t// at least one should push on stack\n#endif\n\t \n\t\t\tif (OpCode(actions, n+i+j, maxn) == SWFACTION_IF)\n\t\t\t{\n\t\t\t\tsactif = (struct SWF_ACTIONIF *)&(actions[n+i+j]);\n\t\t\t\t/* chk whether last jump does lead us back to start of loop */\n\t\t\t\tif (sactif->Actions[sactif->numActions-1].SWF_ACTIONRECORD.ActionCode==SWFACTION_JUMP\n\t\t\t\t && sactif->Actions[sactif->numActions-1].SWF_ACTIONJUMP.BranchOffset+\n\t\t\t\t sactif->Actions[sactif->numActions-1].SWF_ACTIONJUMP.Offset==\n\t\t\t\t actions[n].SWF_ACTIONRECORD.Offset )\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tsactif=NULL;\n\t\t\t}\n\t\t}\n\t}", "\tif (sactif)\n\t{\n\t\tINDENT\n\t\tputs(\"while(\");\n\t\tdecompileActions(j-1, &actions[n+1+i], gIndent);\n\t\tputs(getName(pop()));\n\t\tprintln(\"){ /* original FOR loop rewritten to WHILE */\");\n\t\toffSave=offseoloop;\n\t\tif (n+i+j+1<maxn)\t\t\t\t\t\t// see part2 above\n\t\t\toffseoloop=actions[n+i+j+1].SWF_ACTIONRECORD.Offset;\n\t\telse\n\t\t\toffseoloop=actions[n+i+j].SWF_ACTIONRECORD.Offset+5;\n\t\tdecompileActions(sactif->numActions-1, sactif->Actions,gIndent+1);\n\t\tdecompileActions(i, &actions[n+1], gIndent+1);\n\t\toffseoloop=offSave;\n\t\tINDENT\n\t\tprintln(\"};\");\n\t\treturn i+j; \n\t}\n\t\n\tif (sact->BranchOffset>0)\n\t{\n\t\tif ( stackVal(n,actions) == 1 && n+1==maxn)\n\t\t{\t// leaving block @last op with value on stack: a return x;\n\t\t\treturn decompileRETURN(n, actions,maxn);\n\t\t}\n\t\tif (n+2 < maxn && OpCode(actions, n+1, maxn) == SWFACTION_PUSH && \n\t\t\tactions[n+2].SWF_ACTIONRECORD.Offset == actions[n+1].SWF_ACTIONRECORD.Offset+sact->BranchOffset)\n\t\t{\n\t\t\treturn 1; \t// jump to short to be a 'break': but an internal jump over a push\n\t\t}\t\t\t// to do: add some control flow analysis\n\t\t\n\t\tINDENT\n\t\t\n\t\tif (offseoloop==actions[n].SWF_ACTIONRECORD.Offset+sact->BranchOffset+5)\n\t\t\tputs(\"break;\" );\n\t\telse\n\t\t\tputs(\"return;\" );\n\t\t\n\t\tprintln(\"\\t\\t\\t// offs_end_of_loop=%d offs_jmp_dest=%d\",\n\t\t offseoloop, actions[n].SWF_ACTIONRECORD.Offset+sact->BranchOffset+5);\n\t}\n\telse\n\t{\n\t\tif (sact->BranchOffset<0)\n\t\t{\n\t\t\tINDENT\n\t\t\tprintln(\"continue; /*------*/\");\n\t\t}\n\t}\n\t/* error(\"Unhandled JUMP\"); */\n\treturn 0;\n}", "static int\ndecompileDEFINELOCAL2(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *var;", "\tINDENT\n\tvar = pop();\n\tputs(\"var \");\n\tputs(getName(var));\n\tprintln(\";\");", "\treturn 0;\n}", "static int \ndecompileENUMERATE(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tint i=0;\n\twhile (i < maxn && i < 5 && OpCode(actions, n+i, maxn))\n\t\ti++;\n\t\n\tINDENT \n\tprintln(\"/* a for-var-in loop should follow below: */\" );\n\treturn i-1;\t\t// preserve some code for decompileIF()... \n} \t\t\t\t// ... and let decompileIF() do all the dirty work ;-)", "\n#ifdef DECOMP_SWITCH", "// [recursive] estimate size of buffer needed for decompiling 'switch' \n// [ only call by decompileIF() ]\n//\nstatic int\ncountAllSwitchActions (union SWF_ACTION *actions, union SWF_ACTION *pre)\n{\n\tint i,j=1;\n\tif (actions->SWF_ACTIONRECORD.ActionCode==SWFACTION_IF && pre->SWF_ACTIONRECORD.ActionCode==SWFACTION_STRICTEQUALS )\n\t{\n\t\tfor(i=0; i < ((struct SWF_ACTIONIF*)actions)->numActions; i++)\n\t\t{\n\t\t\tj+=countAllSwitchActions(&((struct SWF_ACTIONIF*)actions)->Actions[i],pre);\n\t\t\tpre=&((struct SWF_ACTIONIF*)actions)->Actions[i];\n\t\t}\n\t} \n\treturn j;\n}", "\n// [recursive] copy all actions in a 'flat' buffer by \n// unpackung all if-actions that are part of the switch operation\n// [ only call by decompileIF() ]\n//\nstatic union SWF_ACTION *\ngetAllSwitchActions(union SWF_ACTION *dest, union SWF_ACTION *actions, union SWF_ACTION *pre)\n{\n#ifdef DEBUGSWITCH\n\tprintln(\"SWCODE: %p %d %s %s\",\n\t dest, actions->SWF_ACTIONRECORD.Offset, \n\t actionName(actions->SWF_ACTIONRECORD.ActionCode),\n\t actionName(pre->SWF_ACTIONRECORD.ActionCode));\n#endif", "\t*dest++=*actions;\n\tif (actions->SWF_ACTIONRECORD.ActionCode==SWFACTION_IF \n\t && pre->SWF_ACTIONRECORD.ActionCode==SWFACTION_STRICTEQUALS )\n\t{\n\t\tint i;\n\t\tstruct SWF_ACTIONIF *sactv2 = (struct SWF_ACTIONIF*)actions;\n\t\tfor(i=0; i< sactv2->numActions; i++)\n\t\t{\n\t\t\tdest=getAllSwitchActions(dest,&sactv2->Actions[i],pre);\n\t\t\tpre=&((struct SWF_ACTIONIF*)actions)->Actions[i];\n\t\t}\n\t}\n\treturn dest;\n}", "// looks similar other decompileXXXX() but \n// can't called by decompileAction()\n// [ do only call by decompileIF() ]\n//\nstatic int\ndecompile_SWITCH(int n, SWF_ACTION *actions, int maxn, int off1end)\n{\n\tint i,j;\n\tint start;\t\t// base action index for case value and code\n\tint ccsize=0;\t\t// size of code for case value\n\tint cvsize=0;\t\t// size of case value\n\tint maxoff=0;\t\t// action offset AFTER switch\n\tint n_maxoff=0;\t\t// array index of maxoff\n\tint pend=0;\t\t// control pending output\n\tint xsize=0;\t\t// ret val\n\tint jmpsize=0;\t\t// debug helper\n\tint lastoff=0;\t\t// debug helper\n\tint n_firstactions=maxn;// array index of 1st case actions code\n\tint lastcasestart=0;\t// offs where last \"case x:\" begins\n\tchar *defa=\"[last]\";\t// debug helper for early \"default:\" \n\tchar *tmp=NULL;\t\t// helper for pending output\n\tstruct strbufinfo origbuf;\t// pending output buffer\n\tstruct _stack *StackSave;\n\tstruct SWF_ACTIONPUSHPARAM *swcopy,*sw=pop();\n\tstruct SWF_ACTIONPUSHPARAM *compare=pop();\n\tint offSave;\n\tfor (i=0; i<n_firstactions; i++) // seek last op in 1st if\n\t{\n\t\tif (actions[i+1].SWF_ACTIONRECORD.Offset==off1end)\n\t\t{\n\t\t\t// println(\"found #off end first= %d\",i+1);\n\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP)\n\t\t\t{\n\t\t\t\tmaxoff=actions[i].SWF_ACTIONJUMP.BranchOffset+actions[i].SWF_ACTIONJUMP.Offset+5;\n\t\t\t\tj=1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// SanityCheck(decompile_SWITCH,0,\"no jump found where expected\");\n\t\t\t}\n\t\t\tbreak;\n\t\t} \n\t}\n\t\n\tif (!maxoff)\n\t{\n\t\tfor (i=maxn-1;i>=0;i--)\t\t\t// seek from end of block last op of switch{}\n\t\t{\n\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP && !actions[i].SWF_ACTIONJUMP.BranchOffset)\n\t\t\t{\n\t\t\t\tmaxoff=actions[i].SWF_ACTIONRECORD.Offset+5;\n\t\t\t\tj=2;\n\t\t\t\tbreak;\n\t\t\t} \n\t\t}\n\t}", "\tfor (i=0;i<maxn;i++)\t\n\t{\n\t\tif (actions[i].SWF_ACTIONRECORD.Offset>=maxoff)\n\t\t{\n\t\t\tn_maxoff=i;\t\t// part of block is switch\n\t\t\tbreak;\n\t\t}\n\t}\n\t\t\n\tif (!n_maxoff) \n\t\tn_maxoff=maxn;\t\t\t// whole block is switch", "\tINDENT\n\tprintln(\"switch( %s ) {\t\t\t// end switch at %d (index %d) / found via meth %d)\",\n\t getString(sw), maxoff,n_maxoff,j);\n\t\t\n\tpush(sw);\n\tpush(compare);", "\ti=1;\n\tdo \t\t\t\t\t// here we go into main loop\n\t{\n\t\tif((OpCode(actions, i, maxn) == SWFACTION_IF\n\t\t && OpCode(actions, i-1, maxn) == SWFACTION_STRICTEQUALS )\n\t\t ||(OpCode(actions, i, maxn) == SWFACTION_JUMP\n\t\t && OpCode(actions, i-1, maxn) == SWFACTION_IF) )\n\t\t{\n\t\t\tstart=i;\n\t\t\twhile (start<maxn \n\t\t\t && actions[start].SWF_ACTIONRECORD.Offset < actions[i].SWF_ACTIONRECORD.Offset+5+actions[i].SWF_ACTIONJUMP.BranchOffset\n)\t\t\t{\n\t\t\t\tstart++;\t\t// count actions until start of \"case x:\"\n\t\t\t}\n\t\t\tif (n_firstactions==maxn) // if not done store earliest \"case x: \"actions\n\t\t\t{\n\t\t\t\tn_firstactions=start;\t// same as array index\n\t\t\t}", "\t\t\tfor (ccsize=0; ccsize+start<n_maxoff; ccsize++)\t// count actions belonging to \"case x:\"\n\t\t\t{\n#ifdef DEBUGSWITCH\n\t\t\t\tprintln(\"in ccsize: ccsize=%d off=%d %s\",\n\t\t\t\t ccsize,actions[ccsize+start].SWF_ACTIONRECORD.Offset,\n\t\t\t\t actionName(OpCode(actions, ccsize+start, maxn)));\n#endif\n\t\t\t\tif (OpCode(actions, ccsize+start, maxn) == SWFACTION_JUMP)\n\t\t\t\t{\n\t\t\t\t\tif (maxoff == actions[ccsize+start].SWF_ACTIONJUMP.Offset+5 + actions[ccsize+start].SWF_ACTIONJUMP.BranchOffset)\n\t\t\t\t\t{\n\t\t\t\t\t\tjmpsize= actions[ccsize+start].SWF_ACTIONJUMP.BranchOffset;\n\t\t\t\t\t\tlastoff= actions[ccsize+start].SWF_ACTIONJUMP.Offset;\n\t\t\t\t\t\tccsize++; // the jmp itself\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "#if USE_LIB\n\t\t\tif (tmp && (start!=pend)) // output pending buffer if neccessary\n\t\t\t{\n\t\t\t\tputs(tmp);\n\t\t\t}\n\t\t\t\n\t\t\tif (tmp)\n\t\t\t{\n\t\t\t\tfree(tmp);\n\t\t\t\ttmp=NULL;\n\t\t\t}\n\t\t\tpend=start;\n#endif\n\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP)\n\t\t\t{\n\t\t\t\tif (ccsize<=1)\n\t\t\t\t\tbreak;\t// ready\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tINDENT\n\t\t\t\t\tif (actions[start].SWF_ACTIONRECORD.Offset>lastcasestart)\n\t\t\t\t\t\txsize+=ccsize; \n\t\t\t\t\telse\n\t\t\t\t\t\tdefa=\"[early]\";\n\t\t\t\t\t\tprintln(\"default:\t\t\t// at %d %s start=%d ccsize=%d\",\n\t\t\t\t\t\t actions[start].SWF_ACTIONRECORD.Offset,defa, start, ccsize);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tINDENT\n\t\t\t\txsize=ccsize;\n\t\t\t\tlastcasestart=actions[start].SWF_ACTIONRECORD.Offset;\n\t\t\t\tprintln(\"case %s:\t\t\t// at %d start=%d ccsize=%d jmp=%d+%d+5\",\n\t\t\t getString(pop()), lastcasestart, start, ccsize, lastoff,jmpsize);\n\t\t\t\tswcopy=pop();\n\t\t\t\t// SanityCheck(decompile_SWITCH,!strcmp(getName(swcopy),getName(sw)),\"sw0 != sw\");\n\t\t\t}", "#if USE_LIB\n\t\t\torigbuf=setTempString(); // switch to temp buffer\n#endif\n\t\t\tStackSave=Stack;\n\t\t\toffSave=offseoloop;\n\t\t\toffseoloop=maxoff;\n\t\t\tdecompileActions( ccsize, &actions[start],gIndent+1);\n\t\t\toffseoloop=offSave;\n\t\t\tStack=StackSave;\n#if USE_LIB\n\t\t\ttmp=switchToOrigString(origbuf);\n#endif", "\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP)\t\t// after \"default:\"\n\t\t\t{\n\t\t\t\tbreak; \t\t\t\t\t\t\t// ready\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (OpCode(actions, i+1, maxn) != SWFACTION_JUMP) \t// not before \"default:\" or end\n\t\t\t\t{\n\t\t\t\t\ti++; // the 'if' itself\n\t\t\t\t\tcvsize=0;\n\t\t\t\t\twhile (i+cvsize < n_firstactions \n\t\t\t\t\t && OpCode(actions, i+cvsize, maxn) != SWFACTION_STRICTEQUALS)\n\t\t\t\t\t{\n#ifdef DEBUGSWITCH\n\t\t\t\t\t\tprintln(\"in cvsize=%d %d %s\",\n\t\t\t\t\t\t cvsize, actions[i+cvsize].SWF_ACTIONRECORD.Offset,\n\t\t\t\t\t\t actionName(OpCode(actions, i+cvsize, maxn)));\n#endif\n\t\t\t\t\t\t\tcvsize++;\t// count \"case X:\" code size\n\t\t\t\t\t}\n\t\t\t\t\tdecompileActions( cvsize, &actions[i],gIndent+1); // at least one push on stack expected\n\t\t\t\t\ti+=cvsize;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} while (++i < n_firstactions);", "#if USE_LIB\n\tif (tmp)\n\t{\n\t\tputs(tmp);\t\t// print last pending output\n\t\tfree(tmp);\n\t}\n#endif\t\n\tINDENT\n\tprintln(\"}\t\t\t\t\t// switch ret value =%d\",xsize);\n\treturn xsize;\n}\n#endif", "static int\ndecompileIF(int n, SWF_ACTION *actions, int maxn)\n{\n\tint offSave;\n\tint j,i=0;\n\tstruct strbufinfo origbuf;\n\tOUT_BEGIN2(SWF_ACTIONIF);", " if (sact->numActions < 1) {\n return 0;\n }", "\t/*\n\t* IF is used in various way to implement different types\n\t* of loops. We try to detect these different types of loops\n\t* here.\n\t*/", "#ifdef STATEMENT_CLASS\n\tif((OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-2, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-3, maxn) == SWFACTION_GETVARIABLE) &&\n\t (OpCode(actions, n-4, maxn) == SWFACTION_PUSH) ) \n\t{\n\t /* It's really a class definition */\n\t\tINDENT\n\t\tputs(\"class \");\n\t\tdecompilePUSHPARAM(newVar(getName(pop())),0);\n\t\tprintln(\" {\" );\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}", "\tif( \n\t (OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-2, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-3, maxn) == SWFACTION_GETMEMBER) &&\n\t (OpCode(actions, n-4, maxn) == SWFACTION_PUSH) ) \n\t{\n\t /* It's really a class definition */\n\t\tINDENT\n\t\tprintln(\" {\");\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}\n#endif\n\t/*\n\t * do {} while() loops have a JUMP at the end of the if clause\n\t * that points to a JUMP above the IF statement.\n\t */\n\tif(n && isLogicalOp(n-1, actions, maxn) &&\n\t (sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&\n\t ( (sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.Offset +\n\t sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset) < actions[n].SWF_ACTIONRECORD.Offset) &&\n\t isLogicalOp(sact->numActions-2, sact->Actions, maxn) ) \n\t{\n\t\tINDENT\n\t\tprintln(\"do {\");\n\t\toffSave=offseoloop;\n\t\toffseoloop=actions[n].SWF_ACTIONRECORD.Offset+5;\n\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\toffseoloop=offSave;\n\t\tINDENT\n\t\tputs(\"while( \");\n\t\tputs(getName(pop()));\n\t\tputs(\");\");\n\t\treturn 0;\n\t}", "\t/* ak,2006\n\t * lots of \"do {} while()\" have simply a CONDITIONED JUMP back at the end of the loop\n\t */\n\tif( actions[n].SWF_ACTIONJUMP.BranchOffset < 0 ) \n\t{\n\t\tINDENT\n\t\tprintln(\"do { /* 2nd type */ \");\n\t\toffSave=offseoloop;\n\t\toffseoloop=actions[n ].SWF_ACTIONRECORD.Offset+5;\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\toffseoloop=offSave;\n\t\tINDENT\n\t\tputs(\"} while( \");\n\t\tputs(getName(pop()));\n\t\tprintln(\");\");\n\t\treturn 0;\n\t}", "\tj=0;\n\twhile (OpCode(actions, n-j, maxn) != SWFACTION_ENUMERATE && \n\t OpCode(actions, n-j, maxn) != SWFACTION_ENUMERATE2 && j<n && j<5) \n\t{\n\t\tj++;\t\t// check for a pending ENUMERATE\n\t}\n\t\n\tif ((OpCode(actions, n-j, maxn) == SWFACTION_ENUMERATE ||\n\t OpCode(actions, n-j, maxn) == SWFACTION_ENUMERATE2 ) && \n\t OpCode(actions, n-j+1, maxn) == SWFACTION_STOREREGISTER )\n\t{\n\t\tstruct SWF_ACTIONPUSHPARAM *var;\n\t\tint x;\n\t\tvar = pop();\n\t\tINDENT\n\t\tputs(\"for ( \");\n\t\t// check for an usual special case w register Rx\n\t\tif (sact->Actions[1].SWF_ACTIONRECORD.ActionCode == SWFACTION_STOREREGISTER)\n\t\t{\n\t\t\tstruct SWF_ACTIONSTOREREGISTER *sactv2 = (struct SWF_ACTIONSTOREREGISTER*)&sact->Actions[1];\n\t\t\tputs(\"var \");\n\t\t\tputs(getName(regs[sactv2->Register]));\n\t\t\tx=3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdecompileActions( 2 , sact->Actions,-1); /* -1 == the ENUM workaround */\n\t\t\tx=2;\n\t\t}\n\t\tputs(\" in \");\n\t\tputs(getName(var));\n\t\tprintln(\" ) {\");\n\t\tif(n+1 >= maxn)\n\t\t{\n\t\t\tSWF_warn(\"Warning: %s:%i: something is wrong here\\n\", __FILE__, __LINE__);\n\t\t}\n\t\telse \n\t\t{\n\t\t\toffSave=offseoloop;\n\t\t\toffseoloop=actions[n+1].SWF_ACTIONRECORD.Offset;\n\t\t\tdecompileActions(sact->numActions-1-x, &sact->Actions[x],gIndent+1);\n\t\t\toffseoloop=offSave;\n\t\t}\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}", "\t/*\n\t * while() loops have a JUMP at the end of the if clause that jumps backwards\n\t * But also \"continue\" statements could jump backwards.\n\t */\n\t\n\tif( isLogicalOp(n-1, actions, maxn) &&\n\t ( (sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&\n\t sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset < 0) ) \n\t{\n\t\tif(0)\t dumpRegs();\n\t\tINDENT\n\t\t/* if on a level >0 we can check for any outer loop \n\t\t To do: get the level on a better way than using gIndent */\n\t\tif (gIndent\t\n\t\t && OpCode(actions, maxn-1, maxn) == SWFACTION_JUMP\n\t \t && actions[maxn-1].SWF_ACTIONJUMP.Offset+actions[maxn].SWF_ACTIONJUMP.BranchOffset==\n\t sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.Offset+sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset)\n\t\t{ \n\t\t /* this jump leads from a block to start of a loop on outer block:\n\t\t it is an 'if' later followed by last action 'continue' */\n\t\t SWF_warn(\"WARNING: this might be wrong (%s:%i)\\n\", __FILE__, __LINE__);\n\t\t puts(\"if ( \");\n\t\t puts(getName(pop()));\n\t\t println(\" ) {\");\n\t\t decompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t}\n\t\telse\t/* while(){} as usual */\n\t\t{\n\t\t\tputs(\"while( \");\n\t\t\tputs(getName(pop()));\n\t\t\tprintln(\" ) {\");\n\t\t\toffSave=offseoloop;\n\t\t\toffseoloop=actions[n+1].SWF_ACTIONRECORD.Offset;\n\t\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\t\toffseoloop=offSave;\n\t\t}\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}\n\t{ // WTF ???\n#define SOME_IF_DEBUG 0\t/* coders only */\n\t\tint has_else_or_break= ((sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&\n\t\t\t(sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset > 0 )) ? 1:0;\n\t\tint has_lognot=(OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) ? 1:0;\n\t\tint else_action_cnt=0,is_logor=0,is_logand=0,sbi,sbe;", "\t\t/* before emitting any \"if\"/\"else\" characters let's check \n\t\t\tfor a ternary operation cond?a:b \n\t\t*/\n\t\tif (has_else_or_break)\n\t\t{\n\t\t\tint limit=actions[n+1].SWF_ACTIONRECORD.Offset + sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset;\n\t\t\t/* Count the number of action records that are part of\n\t\t\t * the else clause, and then decompile only that many.\n\t\t\t */\n\t\t\tfor(else_action_cnt=0;\n\t\t\t else_action_cnt+n+1<maxn && actions[n+1+else_action_cnt].SWF_ACTIONRECORD.Offset < limit;\n\t\t\t else_action_cnt++)\n\t\t\t{\n#if SOME_IF_DEBUG\n\t\t\t\tprintln(\"/* ELSE OP 0x%x at %d*/\", OpCode(actions, n+1+else_action_cnt, maxn),\n\t\t\t\tactions[n+1+else_action_cnt].SWF_ACTIONRECORD.Offset)\n#endif\n\t\t\t\t;\n\t\t\t} \n\t\t}\n\t\ti=else_action_cnt; \t\t// =return value\n\t\tsbi=stackVal (sact->numActions-1,sact->Actions);\n\t\tsbe=stackVal (else_action_cnt,&actions[n+1]);", "\t\t// check against opcodes we do not expect in a ternary operation\n\t\tif (sbi==1 && sbe==1)\n\t \t{\n\t\t\tfor (j=0;j<sact->numActions-1;j++)\n\t\t\t{\n\t\t\t\tif (sact->Actions[j].SWF_ACTIONRECORD.ActionCode==SWFACTION_JUMP) // perhaps more ops\n\t\t\t\t{\n\t\t\t\t\tsbi=i=has_else_or_break=0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (j=0;j<else_action_cnt;j++)\n\t\t\t{\n\t\t\t\tif (OpCode(actions, n+j, maxn) == SWFACTION_JUMP) // perhaps more ops\n\t\t\t\t{\n\t\t\t\t\tsbe=i=has_else_or_break=0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#if SOME_IF_DEBUG\n\t\tprintf(\"sbi=%d sbe=%d\\n\", sbi,sbe);\n#endif\n\t\tif (sbi==1 && sbe==1)\n\t\t{\n#if SOME_IF_DEBUG\n\t\t\tprintln(\"/* ****Found ternary ternary operation \\\"cond ? a : b\\\" **** */\");\n\t\t\tprintf(\"If Actions=%d\\n\",sact->numActions-1);\n\t\t\tprintf(\"Else Actions=%d\\n\",else_action_cnt);\n#endif\n\t\t\tstruct strbufinfo origbuf;\n#if USE_LIB\n\t\t\torigbuf=setTempString();\t/* switch to a temporary string buffer */\n#endif\n\t\t\tputs(\"(\");\n\t\t\tputs(getName(pop()));\n\t\t\tputs(\" ? \");\n\t\t\tdecompileActions(else_action_cnt , &actions[n+1],0);\n\t\t\tputs(getName(pop()));\n\t\t\tputs(\" : \");\n\t\t\tdecompileActions(sact->numActions-1, sact->Actions,0);\n\t\t\tputs(getName(pop()));\n\t\t\tputs(\")\");\n#if USE_LIB\n\t\t\tpush (newVar(dcgetstr()));\t/* push for later assignment */\n\t\t\tsetOrigString(origbuf);\t\t/* switch back to orig buffer */\n#else\n\t\t\tpush (newVar(\"/* ternary op: see code above */\"));\n#endif\n\t\t} \n\t\telse\n\t\t{\n\t\t/* at this point let's check for conditioned jumps that are NOT 'if':\n\t \tcurrently that is code for the locical operations && and ||\n\t \t*/\n\t\t\tif (OpCode(actions, n-1, maxn) == SWFACTION_PUSHDUP)\n\t\t\t\tis_logor=1;\n\t\t\t\n\t\t\tif (OpCode(actions, n-2, maxn)== SWFACTION_PUSHDUP\n\t\t\t && OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT)\n\t\t\t{\n\t\t\t\tis_logand=1;\n\t\t\t}", "\t\tif (is_logor || is_logand) \n\t\t{\n#if SOME_IF_DEBUG\n\t\t\tprintln(\"\");\n\t\t\tprintln(\"/* detected LOGICAL %s: %d actions*/\", is_logor ? \"OR\":\"AND\",sact->numActions);\n#endif\n#if USE_LIB\n\t\t\torigbuf=setTempString();\t/* switch to a temporary string buffer */\n#endif", "\t\t\tputs(getName(pop()));\t/* get left side of logical or */\n\t\t\tputs(is_logor ? \" || \":\" && \");\n\t\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t\tputs(getName(pop()));\t/* get right side of logical or */\n#if USE_LIB\n\t\t\tpush(newVar(dcgetstr()));\n\t\t\tsetOrigString(origbuf);\t/* switch back to orig buffer */\n#else\n\t\t\tpush (newVar(\"/* see logical term lines above */\")); \n#endif\n\t\t\treturn 0;\n\t\t}\n#ifdef DECOMP_SWITCH\n\t\tif ( OpCode(actions, n-1, maxn) == SWFACTION_STRICTEQUALS\n\t\t && check_switch(sact->Actions[0].SWF_ACTIONRECORD.ActionCode) )\n\t\t{\n\t\t\tunion SWF_ACTION *xact,*xact0;\n\t\t\tfor(i=n-1,j=0; i< maxn ;i++)\t// n-1 due adding 1st SWFACTION_STRICTEQUALS in buffer\t\n\t\t\t{\n\t\t\t\tj+=countAllSwitchActions(&actions[i],&actions[i-1]); \t\t// FIRST count size of code\n\t\t\t}\n\t\t\txact0=xact = (union SWF_ACTION *) calloc (j,sizeof (SWF_ACTION));\n\t\t\tINDENT\n\t\t\tprintln(\"// checking %d actions for switch(){}\",j);\n\t\t\tfor(i=n-1; i< maxn ;i++)\n\t\t\t{\n\t\t\t\txact=getAllSwitchActions(xact,&actions[i],&actions[i-1]);\t// SECOND copy into xtra buffer\n\t\t\t}\n\t\t\tj=decompile_SWITCH(0,xact0,j,actions[n+1].SWF_ACTIONRECORD.Offset);\t// THIRD decompile xtra buffer\n\t\t\tfree(xact0);\n\t\t\treturn j;\n\t\t}\n#endif\n\t\t/* it seems we have a found the REAL 'if' statement,\n\t\tso it's right time to print the \"if\" just NOW!\n\t\t*/\n\t\tINDENT\n\t\tputs(\"if( \");\n\t\tputs(getName(pop()));\t/* the condition itself */\n\t\tprintln(\" ) {\");\n\t\tif ( has_else_or_break )\n\t\t{\n\t\t\tint limit=actions[n+1].SWF_ACTIONRECORD.Offset + sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset;\n\t\t\t// limit == dest of jmp == offset next op after 'if' + jumpdist at end of 'if'\n\t\t\tint lastopsize=actions[maxn-1].SWF_ACTIONRECORD.Length;\n\t\t\tif (OpCode(actions, maxn-1, maxn) == SWFACTION_IF)\n\t\t\t\tlastopsize+=actions[maxn-1].SWF_ACTIONIF.BranchOffset + 3; /* +3 see parser.c: \"Action + Length bytes not included in the length\" */\n\t\t\t\n\t\t\tif (offseoloop \n\t\t\t && ! (has_lognot\n\t\t\t && OpCode(actions, n-2, maxn) == SWFACTION_EQUALS2 \n\t\t\t && OpCode(actions, n-3, maxn) == SWFACTION_PUSH\n\t\t\t && OpCode(actions, n-4, maxn) == SWFACTION_PUSHDUP)\n\t\t\t && limit > actions[maxn-1].SWF_ACTIONRECORD.Offset+lastopsize)\n\t\t\t{\n\t\t\t\t/* the jump leads outside this limit, so it is a simple 'if'\n\t\t\t\twith a 'break' or 'return' at the end, and there is NO else clause.\n\t\t\t\t*/ \n\t\t\t\tINDENT\n\t\t\t\tprintln(\"// offs_endjump_dest=%d offs_after_blk %d\",\n\t\t\t\t limit, actions[maxn-1].SWF_ACTIONRECORD.Offset+lastopsize);\n\t\t\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t\t\ti=0;\t\t\t/* found break/return but no else and thus return 0 */\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* There is an else clause also! \n\t\t\t\t(action counter is set above)\n\t\t\t\t*/\n\t\t\t\tstruct _stack *StackSave=Stack;\t/* decompile if and else blocks at same stack base */\n\t\t\t\tif (has_lognot)\n\t\t\t\t{\n\t\t\t\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\t\t\t\tINDENT\n\t\t\t\t\tprintln(\"} else {\");\n\t\t\t\t}\t \n\t\t\t\tStack=StackSave;\n\t\t\t\tdecompileActions(else_action_cnt , &actions[n+1],gIndent+1);\n\t\t\t\tif (!has_lognot)\t\t/* the missing if-part just NOW */\n\t\t\t\t{\n\t\t\t\t\tStack=StackSave;\n\t\t\t\t\tINDENT\n\t\t\t\t\tprintln (\"} else {\" );\n\t\t\t\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t\telse \n\t\t{\n\t\t\t/* It's a simple if() {} */\n\t\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t}\n\t\tINDENT\n\t\tprintln(\"}\");\n\t} // WTF ???\n\treturn i;\n\t}\n\treturn 0;\n}", "static int\ndecompileINITOBJECT(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *nparam;\n\tnparam=pop();\n\tpush(newVar_N2(\"\",\"\",\"\",\"{\", nparam->p.Integer,\"}\"));\n\treturn 0;\n}", "static int\ndecompileWITH(int n, SWF_ACTION *actions, int maxn)\n{\n\tOUT_BEGIN2(SWF_ACTIONWITH);", "\tINDENT\n\tputs(\"with(\");\n\tdecompilePUSHPARAM(pop(),0);\n\tputs(\")\");\n\tprintln(\" {\" );\n\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\tINDENT\n\tprintln(\"}\" );", "\treturn 1;\n}", "static int\ndecompileTRY(int n, SWF_ACTION *actions, int maxn)\n{\n#ifdef DEBUG\n\tstruct _stack *StackSave=Stack;\n#endif \n\tOUT_BEGIN2(SWF_ACTIONTRY);\n\tINDENT\n\tprintln(\"try {\");\n\tdecompileActions(sact->numTryActs, sact->TryActs,gIndent+1);\n\tINDENT\n\tprintln(\"}\");\n#ifdef DEBUG\n\tif (Stack!=StackSave)\n\t{\n\t\tprintln(\"/* Stack problem in try{} code above */\");\n\t\tStack=StackSave;\n\t}\n#endif\n\tif (sact->numCatchActs) \n\t{\n\t\tstruct SWF_ACTIONPUSHPARAM *rsave=NULL;\n\t\tINDENT\n\t\tif( ! sact->CatchInRegisterFlag)\n\t\t\tprintln(\"catch (%s) {\",sact->CatchName);\n\t\telse\n\t\t{\n\t\t\tchar *t=malloc(5); /* Rddd */\n\t\t\tsprintf(t,\"R%d\", sact->CatchRegister );\n\t\t\trsave=regs[sact->CatchRegister];\n\t\t\tregs[sact->CatchRegister] = newVar(t);\n\t\t\tprintln(\"catch (%s) {\",t);\n\t\t}\n\t\tdecompileActions(sact->numCatchActs, sact->CatchActs,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\tif (rsave)\n\t\t\tregs[sact->CatchRegister]=rsave;\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in catch{} code above */\");\n\t\t\tStack=StackSave;\n\t\t}\n#endif\n\t} \n\tif (sact->numFinallyActs)\n\t{\n\t\tINDENT\n\t\tprintln(\"finally () {\");\n\t\tdecompileActions(sact->numFinallyActs, sact->FinallyActs,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in finally{} code above */\");\n\t\t\tStack=StackSave;\n\t\t}\n#endif\n\t}\n\treturn 0;\n}", "\nstatic int\ndecompileDEFINEFUNCTION(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tint i,j,k,m,r;\n\tstruct SWF_ACTIONPUSHPARAM *myregs[ 256 ];\n\tstruct _stack *StackSave; \n\tstruct SWF_ACTIONDEFINEFUNCTION2 *sactv2;\n\tstruct strbufinfo origbuf;\n\tOUT_BEGIN2(SWF_ACTIONDEFINEFUNCTION);\n\tsactv2 = (struct SWF_ACTIONDEFINEFUNCTION2*)sact;", "#ifdef DEBUG\n\tif(n+1 < maxn)\n\t{\n\t\tprintln(\"/* function followed by OP %x */\", \n\t\t OpCode(actions, n+1, maxn));\n\t}\n#endif\n#if USE_LIB\n\tif (isStoreOp(n+1, actions,maxn) \n\t || ( *sact->FunctionName==0 && !is_type2 )\n\t || (*sactv2->FunctionName==0 && is_type2 ))\n\t{\n\t\torigbuf=setTempString();\t/* switch to a temporary string buffer */\n\t}\n#endif\n\tputs(\"function \");\n\tif (is_type2)\n\t{\n\t\tfor(j=1;j<sactv2->RegisterCount;j++) \n\t\t{\n\t\t\tmyregs[j]=regs[j];\n\t\t\tregs[j]=NULL;\n\t\t}\n\t\tr=1;\n\t\tif (sactv2->PreloadThisFlag)\tregs[r++]=newVar(\"this\");\n\t\tif (sactv2->PreloadArgumentsFlag)\tregs[r++]=newVar(\"arguments\");\n\t\tif (sactv2->PreloadSuperFlag)\tregs[r++]=newVar(\"super\");\n\t\tif (sactv2->PreloadRootFlag)\tregs[r++]=newVar(\"root\");\n\t\tif (sactv2->PreloadParentFlag)\tregs[r++]=newVar(\"parent\");\n\t\tif (sactv2->PreloadGlobalFlag)\tregs[r++]=newVar(\"global\");", "\t\tputs(sactv2->FunctionName);\n\t\tputs(\"(\");", "\t\tfor(i=0,m=0;i<sactv2->NumParams;i++) \n\t\t{\n\t\t\tputs(sactv2->Params[i].ParamName);\n\t\t\tif ( sactv2->Params[i].Register)\n\t\t\t{\n\t\t\t\t printf(\" /*=R%d*/ \",sactv2->Params[i].Register);\n\t\t\t\t regs[sactv2->Params[i].Register] = newVar(sactv2->Params[i].ParamName);\n\t\t\t\t m++;\t\t\t\t\t// do not count 'void' etc\n\t\t\t}\n\t\t\tif( sactv2->NumParams > i+1 ) puts(\",\");\n\t\t}\n\t\tprintln(\") {\" );\n\t\tif (r+m < sactv2->RegisterCount)\n\t\t{\n\t\t\tINDENT\n\t\t\tputs(\" var \");\n\t\t}\n\t\tfor(k=r;r<sactv2->RegisterCount;r++)\n\t\t{\n\t\t\tif (!regs[r])\n\t\t\t{\n\t\t\t\tchar *t=malloc(5); /* Rddd */\n\t\t\t\tsprintf(t,\"R%d\", r );\n\t\t\t\tputs (t);\n\t\t\t\tif (k++ < sactv2->RegisterCount- m -1)\n\t\t\t\t\tputs(\", \");\n\t\t\t\telse\n\t\t\t\t\tprintln(\";\" );\n\t\t\t\tregs[r]=newVar(t);\n\t\t\t}\n\t\t}\n\t\tStackSave=Stack;\n\t\tdecompileActions(sactv2->numActions, sactv2->Actions,gIndent+1);\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in function code above */\");\n\t\t}\n#endif\n\t\tStack=StackSave;\n\t\tfor(j=1;j<sactv2->RegisterCount;j++) \n\t\t\tregs[j]=myregs[j];\n\t}\n\telse\n\t{\n\t\tputs(sact->FunctionName);\n\t\tputs(\"(\");\n\t\tfor(i=0;i<sact->NumParams;i++) {\n\t\t\tputs(sact->Params[i]);\n\t\t\tif( sact->NumParams > i+1 ) puts(\",\");\n\t\t}\n\t\tprintln(\") {\" );\n\t\tk=0;\n\t\tif (sact->Actions[0].SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSH)\n\t\t{\n\t\t\tstruct SWF_ACTIONPUSH *sactPush=(struct SWF_ACTIONPUSH *)sact->Actions;\n\t\t\tfor(i=0;i<sactPush->NumParam;i++)\n\t\t\t{\n\t\t\t\tif ((&(sactPush->Params[i]))->Type == PUSH_REGISTER) \n\t\t\t\t\tk++;\t/* REGISTER */\n\t\t\t}\n\t\t\tif (k)\n\t\t\t{\n\t\t\t\tINDENT\n\t\t\t\tputs(\" var \");\n\t\t\t\tfor(i=1;i<=k;i++)\n\t\t\t\t{\n\t\t\t\t\tchar *t=malloc(5); /* Rddd */\n\t\t\t\t\tsprintf(t,\"R%d\", i );\n\t\t\t\t\tputs (t);\n\t\t\t\t\tif (i < k)\n\t\t\t\t\t\tputs(\", \");\n\t\t\t\t\telse\n\t\t\t\t\t\tprintln(\";\" );\n\t\t\t\t\tregs[i]=newVar(t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(j=1;j<=k;j++) \n\t\t\tmyregs[j]=regs[j];\n\t\tStackSave=Stack;\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in function code above */\");\n\t\t}\n#endif\n\t\tStack=StackSave;\n\t\tfor(j=1;j<=k;j++) \n\t\t\tregs[j]=myregs[j];\n\t}\n\tINDENT\n\tif (isStoreOp(n+1, actions,maxn) \n\t || ( *sact->FunctionName==0 && !is_type2 )\n\t || (*sactv2->FunctionName==0 && is_type2 ))\n\t{\n\t\tputs(\"}\");\n#if USE_LIB\n\t\tpush (newVar(dcgetstr()));\t/* push func body for later assignment */\n\t\tsetOrigString(origbuf);\t\t/* switch back to orig buffer */\n#else\n\t\tpush (newVar(\"/* see function code above */\"));\t/* workaround only if LIB is not in use */\n#endif\n\t}\n\telse\n\t\tprintln(\"}\" );\n\treturn 0;\n}", "static int\ndecompileCALLMETHOD(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *meth, *obj, *nparam;\n\tmeth=pop();\n\tobj=pop();\n\tnparam=pop();\n\tif (nparam->p.Integer>25)\n\t{\n\t\tINDENT\n\t\tprintln(\"// Problem getting method arguments (%d ignored) below:\",\n\t\t nparam->p.Integer);\n\t\tnparam->p.Integer=0;\n\t}\n#ifdef DEBUG\n\tprintf(\"*CALLMethod* objName=%s (type=%d) methName=%s (type=%d)\\n\",\n\t\tgetName(obj), obj->Type, getName(meth), meth->Type);\n#endif\n\tif (meth->Type == PUSH_UNDEF) \t/* just undefined, like in \"super();\" */\n\t\tpush(newVar_N(getName(obj),\"\",\"\",\"(\", nparam->p.Integer,\")\"));\n\telse\n\t{\n\t\tif (meth->Type == PUSH_INT || meth->Type == PUSH_DOUBLE || meth->Type == PUSH_VARIABLE\n\t\t || meth->Type == PUSH_REGISTER || meth->Type == 12 )\n\t\t{\n\t\t\tpush(newVar_N(getName(obj),\"[\",getName(meth),\"](\", nparam->p.Integer,\")\"));\n\t\t}\n\t\telse\n\t\t\tpush(newVar_N(getName(obj),\".\",getName(meth),\"(\", nparam->p.Integer,\")\"));\n\t}\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call method and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileCALLFUNCTION(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *meth, *nparam;", "\tSanityCheck(SWF_CALLMETHOD, OpCode(actions, n-1, maxn) == SWFACTION_PUSH,\n\t\t\"CALLMETHOD not preceeded by PUSH\")", "\tmeth=pop();\n\tnparam=pop();\n\tif (nparam->p.Integer>25)\n\t{\n\t\tINDENT\n\t\tprintln(\"// Problem getting function arguments (%d ignored) below:\",\n\t\t\tnparam->p.Integer);\n\t\tnparam->p.Integer=0;\n\t}\n\tpush(newVar_N(\"\",\"\",getName(meth),\"(\", nparam->p.Integer,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompile_Null_ArgBuiltInFunctionCall(int n, SWF_ACTION *actions, int maxn, char *functionname)\n{\n\tINDENT\n\tputs(functionname);\t\t// only used for cases w/o return value\n\tprintln(\"();\" );\n\treturn 0;\n}", "static int\ndecompileSingleArgBuiltInFunctionCall(int n, SWF_ACTION *actions, int maxn, char *functionname)\n{\n\tpush(newVar_N(\"\",\"\",functionname,\"(\", 1,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileSTARTDRAG(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"startDrag(\");\n\tdecompilePUSHPARAM(pop(),1);\n\tputs(\",\");\n\tdecompilePUSHPARAM(pop(),0);\n\tputs(\",\");\n\tdecompilePUSHPARAM(pop(),0);\t//\n\tprintln(\");\" );\n\treturn 0;\n}", "static int\ndecompileSUBSTRING(int n, SWF_ACTION *actions,int maxn)\n{\n\tpush(newVar_N(\"\",\"\",\"substr\",\"(\", 3,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileSTRINGCONCAT(int n, SWF_ACTION *actions, int maxn)\n{\n\tpush(newVar_N(\"\",\"\",\"concat\",\"(\", 2,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileTHROW(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"throw \");\n\tputs(getName(pop()));\n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileREMOVECLIP(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"removeMovieClip(\");\n\tputs(getName(pop()));\n\tprintln(\");\" );\n\treturn 0;\n}", "static int \ndecompileDUPLICATECLIP(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *a, *b;", "\tINDENT\n\ta = pop();\n\tb = pop();", "\tputs(\"duplicateMovieClip(\");\n\tputs(getString(pop()));\n\tputs(\",\");\n\tputs(getString(b));\n\tputs(\",\");\n\tputs(getString(a));\n\tprintln(\");\" );\n\treturn 0;\n}", "static int\ndecompileINITARRAY(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *nparam;\n\tnparam=pop();\n\tpush(newVar_N(\"\",\"\",\"\",\"[\", nparam->p.Integer,\"]\"));\n\treturn 0;\n}", "static int\ndecompileEXTENDS(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *baseclass;", "\tbaseclass=pop();\n#if 0\n\t/* It's useless to open a class body when there's no\n\t * other code supporting it. */\n\tprintf(\"class \");\n\tputs(getName(pop()));\n\tprintf(\" extends \");\n\tputs(getName(baseclass));\n\tprintln(\" {\" );\n#else\n\t/* We'll do it with asm{} */\n\tprintln(\"asm {\");\n\tprintln(\" push '%s'\", getName(pop()));\n\tprintln(\" getvariable\");\n\tprintln(\" push '%s'\", getName(baseclass));\n\tprintln(\" getvariable\");\n\tprintln(\" extends\");\n\tprintln(\"};\");\n#endif", "\treturn 0;\n}", "static int\ndecompileDELETE(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tif (is_type2)\n\t\tpush(newVar3(\"delete(\",getName(pop()),\")\"));\n\telse\n\t\tpush(newVar_N(\"delete(\",getName(pop()),\".\",getName(pop()), 0,\")\"));", "\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call delete() with its args and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileSETTARGET(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tint action_cnt=0;\n\tchar *name;\n\tOUT_BEGIN2(SWF_ACTIONSETTARGET);\n\tname = is_type2 ? getString(pop()) : sact->TargetName;\n\tif (*name)\n\t{\n\t\tINDENT\n\t\tprintln(\"tellTarget('%s') {\" ,name);\n\t\twhile(action_cnt+n<maxn)\n\t\t{\n\t\t\tif (OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_SETTARGET\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_SETTARGET2\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_DEFINEFUNCTION\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_DEFINEFUNCTION2\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_END) \n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\taction_cnt++;\n\t\t}\n\t\tdecompileActions(action_cnt,&actions[n+1],gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\" );\n\t}\n\treturn action_cnt;\n}", "static int\ndecompileIMPLEMENTS(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *nparam;\n\tint i;\n\tINDENT;\n\tputs(getName(pop()));\n\tprintf(\" implements \");\n\tnparam=pop();\n\tfor(i=0;i<nparam->p.Integer;i++) \n\t{\n\t\tputs(getName(pop()));\n\t}\n\tprintln(\" ;\");\n\treturn 0;\n}", "static int\ndecompileCAST(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *iparam=pop();\n\tstruct SWF_ACTIONPUSHPARAM *tparam=pop();\n\tpush(newVar_N( getName(tparam),\"(\",getName(iparam),\"\", 0,\")\")); \n\treturn 0;\n}", "int\ndecompileAction(int n, SWF_ACTION *actions, int maxn)\n{", "\tif( n > maxn ) SWF_error(\"Action overflow!!\");", "\n#ifdef DEBUG\n\tfprintf(stderr,\"%d:\\tACTION[%3.3d]: %s\\n\",\n\t actions[n].SWF_ACTIONRECORD.Offset, n, \n\t actionName(actions[n].SWF_ACTIONRECORD.ActionCode));\n#endif\n", "\tswitch(actions[n].SWF_ACTIONRECORD.ActionCode)", "\t{\n\tcase SWFACTION_END:\n\t\treturn 0;", "\tcase SWFACTION_CONSTANTPOOL:\n\t\tdecompileCONSTANTPOOL(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_GOTOLABEL:\n\t\treturn decompileGOTOFRAME(n, actions, maxn,1);", "\tcase SWFACTION_GOTOFRAME:\n\t\treturn decompileGOTOFRAME(n, actions, maxn,0);", "\tcase SWFACTION_GOTOFRAME2:\n\t\treturn decompileGOTOFRAME2(n, actions, maxn);", "\tcase SWFACTION_WAITFORFRAME:\n\t\tdecompileWAITFORFRAME(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_GETURL2:\n\t\tdecompileGETURL2(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_GETURL:\n\t\tdecompileGETURL(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_PUSH:\n\t\tdecompilePUSH(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_PUSHDUP:\n\t\tdecompilePUSHDUP(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_STACKSWAP:\n\t\tdecompileSTACKSWAP(&actions[n]);\t\n\t\treturn 0;", "\tcase SWFACTION_SETPROPERTY:\n\t\tdecompileSETPROPERTY(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETPROPERTY:\n\t\tdecompileGETPROPERTY(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETTIME:\n\t\treturn decompileGETTIME(n, actions, maxn);", "\tcase SWFACTION_TRACE:\n\t\tdecompileTRACE(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_CALLFRAME:\n\t\tdecompileCALLFRAME(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_EXTENDS:\n\t\tdecompileEXTENDS(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_INITOBJECT:\n\t\tdecompileINITOBJECT(n, actions, maxn);\n\t\treturn 0;\t ", "\tcase SWFACTION_NEWOBJECT:\n\t\tdecompileNEWOBJECT(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_NEWMETHOD:\n\t\tdecompileNEWMETHOD(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETMEMBER:\n\t\tdecompileGETMEMBER(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_SETMEMBER:\n\t\tdecompileSETMEMBER(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETVARIABLE:\n\t\tdecompileGETVARIABLE(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_SETVARIABLE:\n\t\tdecompileSETVARIABLE(n, actions, maxn, 0);\n\t\treturn 0;", "\tcase SWFACTION_DEFINELOCAL:\n\t\tdecompileSETVARIABLE(n, actions, maxn, 1);\n\t\treturn 0;", "\tcase SWFACTION_DEFINELOCAL2:\n\t\tdecompileDEFINELOCAL2(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_DECREMENT:\n\t\treturn decompileINCR_DECR(n, actions, maxn, 0);", "\tcase SWFACTION_INCREMENT:\n\t\treturn decompileINCR_DECR(n, actions, maxn,1);", "\tcase SWFACTION_STOREREGISTER:\n\t\tdecompileSTOREREGISTER(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_JUMP:\n\t\treturn decompileJUMP(n, actions, maxn);", "\tcase SWFACTION_RETURN:\n\t\tdecompileRETURN(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_LOGICALNOT:\n\t\treturn decompileLogicalNot(n, actions, maxn);", "\tcase SWFACTION_IF:\n\t\treturn decompileIF(n, actions, maxn);", "\tcase SWFACTION_WITH:\n\t\tdecompileWITH(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_ENUMERATE:\n\t\treturn decompileENUMERATE(n, actions, maxn, 0);", "\tcase SWFACTION_ENUMERATE2 :\n\t\treturn decompileENUMERATE(n, actions, maxn,1);", "\tcase SWFACTION_INITARRAY:\n\t\treturn decompileINITARRAY(n, actions, maxn);", "\tcase SWFACTION_DEFINEFUNCTION:\t\n\t\treturn decompileDEFINEFUNCTION(n, actions, maxn,0);", "\tcase SWFACTION_DEFINEFUNCTION2:\n\t\treturn decompileDEFINEFUNCTION(n, actions, maxn,1);", "\tcase SWFACTION_CALLFUNCTION:\n\t\treturn decompileCALLFUNCTION(n, actions, maxn);", "\tcase SWFACTION_CALLMETHOD:\n\t\treturn decompileCALLMETHOD(n, actions, maxn);", "\tcase SWFACTION_INSTANCEOF:\n\tcase SWFACTION_SHIFTLEFT:\n\tcase SWFACTION_SHIFTRIGHT:\n\tcase SWFACTION_SHIFTRIGHT2: \n\tcase SWFACTION_ADD:\n\tcase SWFACTION_ADD2:\n\tcase SWFACTION_SUBTRACT:\n\tcase SWFACTION_MULTIPLY:\n\tcase SWFACTION_DIVIDE:\n\tcase SWFACTION_MODULO:\n\tcase SWFACTION_BITWISEAND:\n\tcase SWFACTION_BITWISEOR:\n\tcase SWFACTION_BITWISEXOR:\n\tcase SWFACTION_EQUAL:\n\tcase SWFACTION_EQUALS2:\n\tcase SWFACTION_LESS2:\n\tcase SWFACTION_LOGICALAND:\n\tcase SWFACTION_LOGICALOR:\n\tcase SWFACTION_GREATER:\n\tcase SWFACTION_LESSTHAN:\n\tcase SWFACTION_STRINGEQ:\n\tcase SWFACTION_STRINGCOMPARE:\n\tcase SWFACTION_STRICTEQUALS:\n\t\treturn decompileArithmeticOp(n, actions, maxn);", "\tcase SWFACTION_POP:\n\t\tpop();\n\t\treturn 0;", "\tcase SWFACTION_STARTDRAG:\n\t\treturn decompileSTARTDRAG(n, actions, maxn);", "\tcase SWFACTION_DELETE:\n\t\treturn decompileDELETE(n, actions, maxn,0);", "\tcase SWFACTION_DELETE2:\n\t\treturn decompileDELETE(n, actions, maxn,1);", "\tcase SWFACTION_TARGETPATH:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"targetPath\");", "\tcase SWFACTION_TYPEOF:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"typeof\");", "\tcase SWFACTION_ORD:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"ord\");", "\tcase SWFACTION_CHR:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"chr\");", "\tcase SWFACTION_INT:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"int\");", "\tcase SWFACTION_TOSTRING:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"String\"); ", "\tcase SWFACTION_TONUMBER:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"Number\");", "\tcase SWFACTION_RANDOMNUMBER:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"random\");", "\tcase SWFACTION_STRINGLENGTH:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"length\");", "\tcase SWFACTION_PLAY:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"play\");", "\tcase SWFACTION_STOP:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"stop\");", "\tcase SWFACTION_NEXTFRAME:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"nextFrame\");", "\tcase SWFACTION_PREVFRAME:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"prevFrame\");", "\tcase SWFACTION_ENDDRAG:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"stopDrag\");", "\tcase SWFACTION_STOPSOUNDS:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"stopAllSounds\"); ", "\tcase SWFACTION_TOGGLEQUALITY:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"toggleHighQuality\"); ", "\tcase SWFACTION_MBSUBSTRING:\n\tcase SWFACTION_SUBSTRING:\n\t\treturn decompileSUBSTRING(n, actions, maxn);", "\tcase SWFACTION_STRINGCONCAT:\n\t\treturn decompileSTRINGCONCAT(n, actions, maxn);", "\tcase SWFACTION_REMOVECLIP:\n\t\treturn decompileREMOVECLIP(n, actions, maxn);", "\tcase SWFACTION_DUPLICATECLIP:\n\t\treturn decompileDUPLICATECLIP(n, actions, maxn);", "\tcase SWFACTION_SETTARGET:\n\t\treturn decompileSETTARGET(n, actions, maxn,0);", "\tcase SWFACTION_SETTARGET2:\n\t\treturn decompileSETTARGET(n, actions, maxn,1);", "\tcase SWFACTION_IMPLEMENTSOP:\n\t\treturn decompileIMPLEMENTS(n, actions, maxn);", "\tcase SWFACTION_CASTOP:\n\t\treturn decompileCAST(n, actions, maxn);", "\tcase SWFACTION_THROW:\n\t\treturn decompileTHROW(n, actions, maxn);", "\tcase SWFACTION_TRY:\n\t\treturn decompileTRY(n, actions, maxn);", "\tdefault:\n\t\toutputSWF_ACTION(n,&actions[n]);\n\t\treturn 0;\n\t}\n}", "static void\ndecompileActions(int n, SWF_ACTION *actions, int indent)\n{\n\tint i, svindent;", "\tsvindent = gIndent;\n\tgIndent = indent;\n\t\n\tfor(i=0;i<n;i++) {\n\t\ti+=decompileAction(i, actions, n);\n\t}\n\tgIndent = svindent;\n}", "char *\ndecompile5Action(int n, SWF_ACTION *actions,int indent)\n{\n\tint j;\n\tif( !n )\n\t\treturn NULL;", "\tpool = NULL;\n\tpoolcounter = 0;", "\tdcinit();", "\tfor(j=0;j<256;j++) regs[j]=0;\n\tregs[1] = newVar(\"R1\");\n\tregs[2] = newVar(\"R2\");\n\tregs[3] = newVar(\"R3\");\n\tregs[4] = newVar(\"R4\");", "\tdecompileActions(n, actions, indent);\n#ifdef DEBUGSTACK\n\tif( Stack != NULL && *dcstr) \n\t{ \n\t\tint i=0;\n\t\tprintln(\"/* -----------------------------------------------------------------\");\n\t\tprintln(\"NOTE: some stuff left on the stack at the end of a block of actions:\");\n\t\twhile (Stack)\n\t\t{\n\t\t\ti++;\n\t\t\tprintf(\"%d.:\\t%s\",i, getString(pop()));\n\t\t\tprintln(\"\");\n\t\t}\n\t\tprintln(\"*/\");\n\t}\n#else\n\tif( Stack != NULL ) \n\t\tfprintf(stderr,\n\t\t\"Stuff left on the stack at the end of a block of actions!?!?!?\\n\");\n\twhile (Stack)\n\t{\n\t\tpop();\n\t}\n#endif\n\treturn dcgetstr();\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [3214], "buggy_code_start_loc": [3205], "filenames": ["util/decompile.c"], "fixing_code_end_loc": [3213], "fixing_code_start_loc": [3204], "message": "Ming (aka libming) 0.4.8 has a heap buffer overflow and underflow in the decompileCAST function in util/decompile.c in libutil.a. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted SWF file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:libming:libming:0.4.8:*:*:*:*:*:*:*", "matchCriteriaId": "DD92BC79-2548-4C6F-9BDD-26C12BDF68AC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ming (aka libming) 0.4.8 has a heap buffer overflow and underflow in the decompileCAST function in util/decompile.c in libutil.a. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted SWF file."}, {"lang": "es", "value": "Ming (aka libming) versi\u00f3n 0.4.8 tiene un desbordamiento y subdesbordamiento de b\u00fafer de mont\u00f3n en la funci\u00f3n decompileCAST en util/decompile.c en libutil.a. Los atacantes remotos podr\u00edan aprovechar esta vulnerabilidad para provocar una denegaci\u00f3n de servicio a trav\u00e9s de un archivo SWF dise\u00f1ado."}], "evaluatorComment": null, "id": "CVE-2019-12982", "lastModified": "2020-10-14T17:27:46.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-06-26T18:15:10.587", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/libming/libming/commit/da9d86eab55cbf608d5c916b8b690f5b76bca462"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/libming/libming/commit/da9d86eab55cbf608d5c916b8b690f5b76bca462"}, "type": "CWE-119"}
302
Determine whether the {function_name} code is vulnerable or not.
[ "/****************************************************************************\n *\n * Copyright (C) 2006,2007 A.Kleine\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n ****************************************************************************/", "#define _GNU_SOURCE 1", "//#define DEBUGSTACK\n#define DECOMP_SWITCH\n// #define DEBUGSWITCH", "//#define STATEMENT_CLASS \n// I have uncommented some buggy class recognition stuff in decompileIF()\n// to make work simple code lines like: \"if(!a) trace(a);\" - ak, November 2006", "// To do: add some free()-calls for allocated blocks", "#include <assert.h>", "#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>", "#include \"read.h\"\n#include \"action.h\"\n#include \"swftypes.h\"\n#include \"../src/blocks/error.h\"\n#include \"vasprintf.h\"", "\nstatic char **pool;\nstatic unsigned short poolcounter;\nstruct SWF_ACTIONPUSHPARAM *regs[256];", "static char *getName(struct SWF_ACTIONPUSHPARAM *act);", "static int offseoloop;\t// offset wherever a break can jump to (loops and switch)", "static void\ndumpRegs()\n{\nint i;\nfor(i=0;i<6;i++)\n\tif( regs[i] )\n\t\tprintf(\"reg[%d] %s\\n\", i, getName(regs[i]));\n}", "/*\n * Start Package \n *\n * A package to build up a string that can be returned to the caller\n * ak/2006: Extended for temporary swichting to a 2nd buffer\n */\n#define USE_LIB 1", "static int strsize=0;\nstatic int strmaxsize=0;\nstatic char *dcstr=NULL;\nstatic char *dcptr=NULL;", "#define DCSTRSIZE 40960\n#define PARAM_STRSIZE 512\nvoid\ndcinit()\n{\n\tstrsize = 1; // We start with empty string, i.e. \\0\n\tstrmaxsize=DCSTRSIZE;\n\tdcstr=calloc(DCSTRSIZE,1);\n\tdcptr=dcstr;\n}", "void\ndcchkstr(int size)\n{\n\twhile( (strsize+size) > strmaxsize ) {\n\t\tdcstr=realloc(dcstr,strmaxsize+DCSTRSIZE);\n\t\tstrmaxsize+=DCSTRSIZE;\n\t\tdcptr=dcstr+strsize;\n\t}", "}", "void\ndcputs(const char *s)\n{\n\tint len=strlen(s);\n\tdcchkstr(len);\n\tstrcat(dcptr,s);\n\tdcptr+=len;\n\tstrsize+=len;\n}", "void\ndcputchar(char c)\n{\n\tdcchkstr(1);", "\t*dcptr++=c;\n\t*dcptr='\\000';\n\tstrsize++;\n}", "int\ndcprintf(char *format, ...)\n{\n\tchar *s;\n\tsize_t size;\n\tint ret;", "\tva_list args;\n\tva_start(args,format);\n\tret = vasprintf(&s,format,args);\n\tdcputs(s);\n\tsize=strlen(s);\n\tfree(s);\n\treturn size;\n}", "char *\ndcgetstr()\n{\n\tchar *ret;\n\tret = dcstr;\n\tdcstr=NULL;\n\tstrmaxsize=0;\n\treturn ret;\n}", "struct strbufinfo\n{\n\tint size;\n\tint maxsize;\n\tchar *str;\n\tchar *ptr;\n};", "\nstatic struct strbufinfo setTempString(void)\n{\n\tstruct strbufinfo current;\n\tcurrent.size=strsize;\n\tcurrent.maxsize=strmaxsize;\n\tcurrent.str=dcstr;\n\tcurrent.ptr=dcptr;\n\tdcinit();\n\treturn current;\n}", "static void setOrigString(struct strbufinfo old)\n{\n\tfree(dcstr);\t\t\t\t/* not needed anymore */\n\tstrsize=old.size;\n\tstrmaxsize=old.maxsize;\n\tdcstr=old.str;\n\tdcptr=old.ptr;\n}", "// a variant of setOrigString()\n// but for further usage of 2nd buffer\n//\nstatic char *\nswitchToOrigString(struct strbufinfo old)\n{\n\tchar *tmp=dcstr;\n\tstrsize=old.size;\n\tstrmaxsize=old.maxsize;\n\tdcstr=old.str;\n\tdcptr=old.ptr;\n\treturn tmp;\n}", "#if USE_LIB\n#define puts(s) dcputs(s)\n#define putchar(c) dcputchar(c)\n#define printf dcprintf\n#endif", "#define INDENT { int ii=gIndent; while(--ii>=0) { putchar(' '); putchar(' '); } }", "/* String used for terminating lines (see println) */\nstatic const char* newlinestring = \"\\\\\\n\";", "/* Set the newline character. By default it is an escaped NL. */\nvoid\nsetNewLineString(const char* ch)\n{\n\tnewlinestring = ch;\n}", "/* Print a line with a terminating newline, which can be set by\n * setNewLineString()\n */\nstatic void\nprintln(const char* fmt, ...)\n{\n\tchar *tmp;\n\tint written;", "\tva_list ap;\n\tva_start (ap, fmt);\n\twritten = vasprintf (&tmp, fmt, ap);", "\tdcprintf(\"%s%s\", tmp, newlinestring);", "\tfree(tmp);\n}", "\n/* End Package */", "/*\n * Start Package \n *\n * A package to maintain escaped characters strings\n * [ BSC == BackSlashCounter ]\n */\n#define BSC 2\nstatic int strlenext(char *str)\n{\n\tint i=0;\n\twhile (*str)\n\t{\n\t\ti++;\n\t\tif (*str=='\\'') i+=BSC;\n\t\t\tstr++;\t\n\t}\n\treturn i;\n}", "static char* strcpyext(char *dest,char *src)\n{\n\tchar *r=dest;\n\twhile (*src)\n\t{\n\t\tif (*src=='\\'')\n\t\t{\n\t\t\t*dest++='\\\\';\n#if BSC == 2\n\t\t\t*dest++='\\\\';\n#endif\n\t\t}\n\t\t*dest++=*src++;\n\t}\n\t*dest='\\0';\n\treturn r;\n}", "static char* strcatext(char *dest,char *src)\n{\n\tchar *r=dest;\n\twhile (*dest)\n\t\tdest++;\n\tstrcpyext(dest,src);\n\treturn r;\n}\n/* End Package */", "/*\n * Start Package \n *\n * A package to maintain a representation of the Flash VM stack\n */", "struct _stack {\n\tchar type;\n\tstruct SWF_ACTIONPUSHPARAM *val;\n\tstruct _stack *next;\n};", "struct _stack *Stack;", "enum\n{\n\tPUSH_STRING = 0,\n\tPUSH_FLOAT = 1,\n\tPUSH_NULL = 2,\n\tPUSH_UNDEF = 3,\n\tPUSH_REGISTER = 4,\n\tPUSH_BOOLEAN = 5,\n\tPUSH_DOUBLE = 6,\n\tPUSH_INT = 7,\n\tPUSH_CONSTANT = 8,\n\tPUSH_CONSTANT16 = 9,\n\tPUSH_VARIABLE = 10,\n};", "static char *\ngetString(struct SWF_ACTIONPUSHPARAM *act)\n{\n\tchar *t;\n#ifdef DEBUG\n\tprintf(\"*getString* type=%d\\n\",act->Type);\n#endif\n\tswitch( act->Type ) \n\t{\n\tcase PUSH_STRING: \n\t\tif (!act->p.String) /* Not a NULL string */\n\t\t{\n\t\t SWF_warn(\"WARNING: Call to getString with NULL string.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlen(act->p.String)+3); /* 2 \"'\"s and a NULL */\n\t\tstrcpy(t,\"'\");\n\t\tstrcat(t,act->p.String);\n\t\tstrcat(t,\"'\");\n\t\treturn t;\n\tcase PUSH_NULL: /* NULL */\n\t\treturn \"null\";\n\tcase PUSH_UNDEF: /* Undefined */\n\t\treturn \"undefined\";\n\tcase PUSH_REGISTER: /* REGISTER */\n\t\tif( regs[act->p.RegisterNumber] &&\n\t\t regs[act->p.RegisterNumber]->Type != 4 &&\n\t\t regs[act->p.RegisterNumber]->Type != 7 )\n\t\t{\n\t\t\treturn getName(regs[act->p.RegisterNumber]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tt=malloc(5); /* Rddd */\n\t\t\tsprintf(t,\"R%d\", act->p.RegisterNumber );\n\t\t\treturn t;\n\t\t}\n\tcase PUSH_BOOLEAN: /* BOOLEAN */\n\t\tif( act->p.Boolean )\n\t\t\treturn \"true\";\n\t\telse\n\t\t\treturn \"false\";\n\tcase PUSH_DOUBLE: /* DOUBLE */\n\t{\n\t\tchar length_finder[1];\n\t\tint needed_length = snprintf(length_finder, 1, \"%g\", act->p.Double) + 1;\n\t\tif (needed_length <= 0)\n\t\t{\n\t\t SWF_warn(\"WARNING: could not evaluate size of buffer (memory issue ?).\\n\");\n\t\t break;\n\t\t}", "\t\tt = malloc(needed_length);\n\t\tsprintf(t, \"%g\", act->p.Double );\n\t\treturn t;\n\t}\n\tcase PUSH_INT: /* INTEGER */\n\t\tt=malloc(10); /* 32-bit decimal */\n\t\tsprintf(t,\"%ld\", act->p.Integer );\n\t\treturn t;\n\tcase PUSH_CONSTANT: /* CONSTANT8 */\n\t\tif (act->p.Constant8 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant8])+3); /* 2 \"'\"s and a NULL */\n\t\tstrcpy(t,\"'\");\n\t\tstrcatext(t,pool[act->p.Constant8]);\n\t\tstrcat(t,\"'\");\n\t\treturn t;\n\tcase PUSH_CONSTANT16: /* CONSTANT16 */\n\t\tif (act->p.Constant16 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant16])+3); /* 2 '\\\"'s and a NULL */\n\t\tstrcpy(t,\"'\");\n\t\tstrcatext(t,pool[act->p.Constant16]);\n\t\tstrcat(t,\"'\");\n\t\treturn t;", "\tcase 12:\n\tcase 11: /* INCREMENTED or DECREMENTED VARIABLE */\n\tcase PUSH_VARIABLE: /* VARIABLE */\n\t\treturn act->p.String;\n\tdefault: \n\t\tfprintf (stderr,\" Can't get string for type: %d\\n\", act->Type);\n\t\tbreak;\n\t}", "\tt = malloc(sizeof(char));\n\tstrcpyext(t,\"\");", "\treturn t;\n}", "static char *\ngetName(struct SWF_ACTIONPUSHPARAM *act)\n{\n\tchar *t;", "\tswitch( act->Type ) \t\n\t{\n\tcase PUSH_STRING: /* STRING */\n\t\tif (!act->p.String) /* Not a NULL string */\n\t\t{\n\t\t SWF_warn(\"WARNING: Call to getName with NULL string.\\n\");\n\t\t break;\n\t\t}\n\t\telse if (strlen(act->p.String)) /* Not a zero length string */\n\t\t{\n\t\t t=malloc(strlen(act->p.String)+3);\n\t\t strcpyext(t,act->p.String);\n\t\t return t;\n\t\t}\n\t\telse\n\t\t{\n\t\t char *return_string = \"this\";\n\t t=malloc(strlen(return_string)+1); /* string length + \\0 */\n\t strcpyext(t,return_string);\n\t\t\treturn t;\n\t\t}\n#if 0\n\t case 4: /* REGISTER */\n\t\tt=malloc(5); /* Rddd */\n \t\tsprintf(t,\"R%d\", act->p.RegisterNumber );\n \t\treturn t;\n#endif\n\tcase PUSH_CONSTANT: /* CONSTANT8 */\n\t\tif (act->p.Constant8 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant8])+1);\n\t\tstrcpyext(t,pool[act->p.Constant8]);\n\t\tif(strlen(t)) /* Not a zero length string */\n\t\t\treturn t;\n\t\telse\n\t\t{\n\t\t\tt=realloc(t,6);\n\t\t\treturn strcpy(t,\"this\");\n\t\t}\n\tcase PUSH_CONSTANT16: /* CONSTANT16 */\n\t\tif (act->p.Constant16 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tt=malloc(strlenext(pool[act->p.Constant16])+1);\n\t\tstrcpyext(t,pool[act->p.Constant16]);\n\t\tif(strlen(t)) /* Not a zero length string */\n\t\t\treturn t;\n\t\telse\n\t\t{\n\t\t\tt=realloc(t,6);\n\t\t\treturn strcpy(t,\"this\");\n\t\t}\n\tdefault: \n\t\treturn getString(act);\n\t}", "\tt = malloc(sizeof(char));\n\tstrcpyext(t,\"\");", "\treturn t;\n}", "static int\ngetInt(struct SWF_ACTIONPUSHPARAM *act)\n{\n\tswitch( act->Type ) \n\t{\n\tcase PUSH_FLOAT: /* FLOAT -- also used for PROPERTY storing */\n\t\treturn ((int)act->p.Float);\n\tcase PUSH_NULL: /* NULL */\n\t\treturn 0;\n\tcase PUSH_REGISTER: /* REGISTER */\n\t\treturn getInt(regs[act->p.RegisterNumber]);\n\tcase PUSH_DOUBLE: /* DOUBLE */\n\t\treturn (int)act->p.Double;\n\tcase PUSH_INT: /* INTEGER */\n\t\treturn act->p.Integer;\n\tdefault: \n\t\tfprintf (stderr,\" Can't get int for type: %d\\n\", act->Type);\n\t}\n\treturn 0;\n}", "static char *\ngetProperty(Property prop)\n{\n\tswitch(prop)\n\t{\n\tcase SWF_SETPROPERTY_X: \treturn(\"_x\"); break;\n\tcase SWF_SETPROPERTY_Y:\n\tcase PROPERTY_Y:\t\treturn(\"_y\"); break;\n\tcase PROPERTY_XMOUSE:\t\treturn(\"_xMouse\"); break;\n\tcase PROPERTY_YMOUSE:\t\treturn(\"_yMouse\"); break;\n\tcase SWF_SETPROPERTY_XSCALE:\n\tcase PROPERTY_XSCALE:\t \treturn(\"_xScale\"); break;\n\tcase SWF_SETPROPERTY_YSCALE:\n\tcase PROPERTY_YSCALE:\t \treturn(\"_yScale\"); break;\n\tcase PROPERTY_CURRENTFRAME:\treturn(\"_currentFrame\"); break;\n\tcase PROPERTY_TOTALFRAMES:\treturn(\"_totalFrames\"); break;\n\tcase SWF_SETPROPERTY_ALPHA:\n\tcase PROPERTY_ALPHA:\t\treturn(\"_alpha\"); break;\n\tcase SWF_SETPROPERTY_VISIBILITY:\n\tcase PROPERTY_VISIBLE:\t\treturn(\"_visible\"); break;\n\tcase PROPERTY_WIDTH:\t\treturn(\"_width\"); break;\n\tcase PROPERTY_HEIGHT:\t\treturn(\"_height\"); break;\n\tcase SWF_SETPROPERTY_ROTATION:\n\tcase PROPERTY_ROTATION:\t\treturn(\"_rotation\"); break;\n\tcase PROPERTY_TARGET:\t\treturn(\"_target\"); break;\n\tcase PROPERTY_FRAMESLOADED:\treturn(\"_framesLoaded\"); break;\n\tcase SWF_SETPROPERTY_NAME:\n\tcase PROPERTY_NAME:\t\treturn(\"_name\"); break;\n\tcase PROPERTY_DROPTARGET:\treturn(\"_dropTarget\"); break;\n\tcase PROPERTY_URL:\t\treturn(\"_url\"); break;\n\tcase SWF_SETPROPERTY_HIGHQUALITY:\n\tcase PROPERTY_HIGHQUALITY:\treturn(\"_quality\"); break;\n\tcase SWF_SETPROPERTY_SHOWFOCUSRECT:\n\tcase PROPERTY_FOCUSRECT:\treturn(\"_focusRect\"); break;\n\tcase SWF_SETPROPERTY_SOUNDBUFFERTIME:\n\tcase PROPERTY_SOUNDBUFTIME:\treturn(\"_soundBufTime\"); break;\n\tcase SWF_SETPROPERTY_WTHIT:\n\tcase PROPERTY_WTHIT:\t\treturn(\"_WTHIT!?\"); break;\n\tdefault:\t\t\treturn(\"unknown property!\"); break;\n\t}\n}", "struct SWF_ACTIONPUSHPARAM *\nnewVar(char *var)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE; \n\tv->p.String = var;\n\treturn v;\n}", "struct SWF_ACTIONPUSHPARAM *\nnewVar2(char *var,char *var2)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE;\n\tv->p.String = malloc(strlen(var)+strlen(var2)+1);\n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\treturn v;\n}", "\nstruct SWF_ACTIONPUSHPARAM *\nnewVar3(char *var,char *var2, char *var3)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE; /* VARIABLE */\n\tv->p.String = malloc(strlen(var)+strlen(var2)+strlen(var3)+1);\n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\treturn v;\n}", "struct SWF_ACTIONPUSHPARAM *\nnewVar5(char *var,char *var2, char *var3,char *var4,char *var5)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;", "\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->Type = PUSH_VARIABLE; /* VARIABLE */\n\tv->p.String = malloc(strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(var5)+1);\n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\tstrcat(v->p.String,var4);\n\tstrcat(v->p.String,var5);\n\treturn v;\n}", "void\npush(struct SWF_ACTIONPUSHPARAM *val)\n{\n\tstruct _stack *t;\n#ifdef DEBUG\n\tprintf(\"*push* type=%d\\n\",val->Type);\n#endif\n\tt = calloc(1,sizeof(*Stack));\n\tt->type = val->Type;\n\tt->val = val;\n\tt->next = Stack;\n\tStack = t;\n}", "\nvoid\npushdup()\n{\n\tstruct _stack *t;\n#ifdef DEBUG\n\tprintf(\"*pushdup*\\n\");\n#endif\n\tif(Stack == NULL)\n\t{\n\t\tSWF_warn(\"WARNING: pushdup on empty stack. This might be wrong!\\n\");\n\t\treturn;\n\t}\n\tt = calloc(1,sizeof(*Stack));\n\tt->type = Stack->type;", "\t// If element is a string, perform deep copy of Stack->val->p\n\tif (Stack->val->Type == PUSH_STRING) {\n\t\tt->val = calloc(1, sizeof(struct SWF_ACTIONPUSHPARAM));\n\t\t*t->val = *Stack->val;", "\t\tint len = strlen(Stack->val->p.String) + 1; // NULL terminated\n\t\tt->val->p.String = calloc(len, sizeof(char));\n\t\tstrcpy(t->val->p.String, Stack->val->p.String);\n\t} else {\n\t\tt->val = Stack->val;\n\t}", "\tt->next = Stack;\n\tStack = t;\n}", "\nvoid\npushvar(struct SWF_ACTIONPUSHPARAM *val)\n{\n\tstruct _stack *t;\n#ifdef DEBUG\n\tprintf(\"*pushvar*\\n\");\n#endif\n\tt = calloc(1,sizeof(*Stack));\n\tt->type = 'v'; // ???\n\tt->val = val;\n\tt->next = Stack;\n\tStack = t;\n}", "struct SWF_ACTIONPUSHPARAM * pop()\n{\n\tstruct _stack *t;\n\tstruct SWF_ACTIONPUSHPARAM * ret;", "#ifdef DEBUG\n\tprintf(\"*pop*\\n\");\n#endif\n#ifdef DEBUGSTACK\t\t/* continue w stack dummy */\n\tif( Stack == NULL ) push(newVar(\"// *** pop(): INTERNAL STACK ERROR FOUND ***\"));\n#else\n\tif( Stack == NULL ) SWF_error(\"Stack blown!! - pop\");\n#endif\n\tt=Stack;\n\tStack=t->next;\n\tret=t->val;\n\treturn ret;\n}", "struct SWF_ACTIONPUSHPARAM * peek()\n{\n#ifdef DEBUG\n\tprintf(\"*peek*\\n\");\n#endif\n#ifdef DEBUGSTACK\t\t/* continue w stack dummy */\n\tif( Stack == NULL ) push(newVar(\"// *** peek(): INTERNAL STACK ERROR FOUND ***\"));\n#else\n\tif( Stack == NULL ) SWF_error(\"Stack blown!! - peek\");\n#endif\n\treturn Stack->val;\n}", "void\nstackswap()\n{\n#ifdef DEBUG\n\tprintf(\"*stackswap*\\n\");\n#endif\n\tstruct SWF_ACTIONPUSHPARAM *p = peek();\t\t/* peek() includes error handling */\n\tchar type = Stack->type;", " if (Stack->next == NULL) {\n#if DEBUG\n\t\tSWF_warn(\"stackswap: can't swap (stack contains only one element)\\n\");\n#endif\n return;\n }", "\tStack->type = Stack->next->type;\n\tStack->val = Stack->next->val;\n\tStack->next->type = type;\n\tStack->next->val = p;\n}", "\nstatic struct SWF_ACTIONPUSHPARAM *\nnewVar_N(char *var,char *var2, char *var3,char *var4,int pop_counter,char *final)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;\n\tint psize=PARAM_STRSIZE;\n\tint i;\n\tint slen=strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(final);\n\t\n\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->p.String = malloc(psize + slen);\n\tv->Type = PUSH_VARIABLE; \n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\tstrcat(v->p.String,var4);\n\tfor(i=0;i<pop_counter;i++) \n\t{\n\t\tchar *pops=getString(pop());\n\t\twhile ( strlen(v->p.String)+ 2 + strlen(pops) +slen >= psize)\n\t\t{\n\t\t\tpsize += PARAM_STRSIZE;\n\t\t\tv->p.String = realloc( v->p.String, psize);\n\t\t}\n\t\tstrcat(v->p.String,pops);\n\t\tif( i < pop_counter-1 ) \n\t\t\tstrcat(v->p.String,\",\");\n\t}\n\tstrcat(v->p.String,final);\n\treturn v;\n}", "// similar to newVar_N(), \n// but pops 2 items from stack per counter,\n// and second of them we are interested in getName() instead of getString()\nstatic struct SWF_ACTIONPUSHPARAM *\nnewVar_N2(char *var,char *var2, char *var3,char *var4,int pop_counter,char *final)\n{\n\tstruct SWF_ACTIONPUSHPARAM *v;\n\tint psize=PARAM_STRSIZE;\n\tint i;\n\tint slen=strlen(var)+strlen(var2)+strlen(var3)+strlen(var4)+strlen(final);\n\t\n\tv=malloc(sizeof(struct SWF_ACTIONPUSHPARAM));\n\tv->p.String = malloc(psize + slen);\n\tv->Type = PUSH_VARIABLE; \n\tstrcpy(v->p.String,var);\n\tstrcat(v->p.String,var2);\n\tstrcat(v->p.String,var3);\n\tstrcat(v->p.String,var4);\n\tfor(i=0;i<pop_counter;i++) \n\t{\n\t\tchar *pops1=getString(pop());\n\t\tchar *pops2=getName (pop());", "\t\twhile ( strlen(v->p.String)+ 3 + strlen(pops1)+ strlen(pops2) +slen >= psize)\n\t\t{\n\t\t\tpsize += PARAM_STRSIZE;\n\t\t\tv->p.String = realloc( v->p.String, psize);\n\t\t}\n\t\tstrcat(v->p.String,pops2);\n\t\tstrcat(v->p.String,\":\");\n\t\tstrcat(v->p.String,pops1);\n\t\tif( i < pop_counter-1 ) \n\t\t\tstrcat(v->p.String,\",\");\n\t}\n\tstrcat(v->p.String,final);\n\treturn v;\n}", "/* End Package */", "static int gIndent;\nstatic void decompileActions(int n, SWF_ACTION *actions,int indent);\nchar * decompile5Action(int n, SWF_ACTION *actions,int indent);", "/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/", "\n#define SanityCheck(curact,test,msg ) \\\n if(!(test) ) SWF_error( \"SanityCheck failed in %s\\n %s\\n\", #curact, msg );", "#define OUT_BEGIN(block) \\\n\t struct block *sact = (struct block *)act;\n#define OUT_BEGIN2(block) \\\n\t struct block *sact = (struct block *)&(actions[n]);", "static void\ndecompileCONSTANTPOOL (SWF_ACTION *act)\n{\n\tOUT_BEGIN(SWF_ACTIONCONSTANTPOOL);\n\tpool=sact->ConstantPool;\n\tpoolcounter = sact->Count;\n}", "static void\ndecompileWAITFORFRAME (SWF_ACTION *act)\n{\n\tOUT_BEGIN(SWF_ACTIONWAITFORFRAME);", "\tINDENT\n\tprintln(\"WaitForFrame(%d,%d);\", sact->Frame,sact->SkipCount);\n}", "static void\ndecompilePUSHPARAM (struct SWF_ACTIONPUSHPARAM *act, int wantstring)\n{\n\tchar *t;\n\tswitch( act->Type ) \n\t{\n\tcase PUSH_STRING: /* STRING */\n\t\tif( wantstring ) printf (\"'%s'\", act->p.String);\n\t\telse printf (\"%s\", act->p.String);\n\t\tbreak;\n\tcase PUSH_FLOAT: /* FLOAT */\n\t\tprintf (\"%f\", act->p.Float);\n\t\tbreak;\n\tcase PUSH_NULL: /* NULL */\n\t\tprintf (\"NULL\" );\n\t\tbreak;\n\tcase PUSH_UNDEF: /* Undefined */\n\t\tprintf (\"undefined\" );\n\t\tbreak;\n\tcase PUSH_REGISTER: /* Register */\n\t\tif( regs[act->p.RegisterNumber] ) {\n\t\t\tprintf (\"%s\", getName(act));\n\t\t} else {\n\t\t\tprintf (\"R%d\", (int)act->p.RegisterNumber);\n\t\t}\n\t\tbreak;\n\tcase PUSH_BOOLEAN: /* BOOLEAN */\n\t\tprintf (\"%s\", act->p.Boolean?\"true\":\"false\");\n\t\tbreak;\n\tcase PUSH_DOUBLE: /* DOUBLE */\n\t\tprintf (\"%g\", act->p.Double);\n\t\tbreak;\n\tcase PUSH_INT: /* INTEGER */\n\t\tprintf (\"%ld\", act->p.Integer);\n\t\tbreak;", "\tcase PUSH_CONSTANT: /* CONSTANT8 */\n\tcase PUSH_CONSTANT16: /* CONSTANT16 */\n\t\tif( wantstring ) t=getString(act);\n\t \telse t=getName(act);\n\t \tputs(t); \n\t \tfree(t); \n\t \tbreak;", "#if 0\n\t case 8: /* CONSTANT8 */\n\t\tif (act->p.Constant8 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tif( wantstring )\n \t\t printf (\"'%s'\", pool[act->p.Constant8]);\n\t\telse\n \t\t printf (\"%s\", pool[act->p.Constant8]);\n\t\tbreak;\n\t case 9: /* CONSTANT16 */\n\t\tif (act->p.Constant16 > poolcounter)\n\t\t{\n\t\t SWF_warn(\"WARNING: retrieving constants not present in the pool.\\n\");\n\t\t break;\n\t\t}\n\t\tif( wantstring )\n \t\t printf (\"'%s'\", pool[act->p.Constant16]);\n\t\telse\n \t\t printf (\"%s\", pool[act->p.Constant16]);\n\t\tbreak;\n#endif\n\tcase 12:\n\tcase 11: /* INCREMENTED or DECREMENTED VARIABLE */\n\tcase PUSH_VARIABLE: /* VARIABLE */\n\t\tprintf (\"%s\", act->p.String);\n\t\tbreak;\n\tdefault: \n\t\tprintf (\" Unknown type: %d\\n\", act->Type);\n\t}\n}", "static void\ndecompileGETURL (SWF_ACTION *act)\n{\n\tOUT_BEGIN(SWF_ACTIONGETURL);", "\tINDENT\n\tprintln(\"getUrl('%s',%s);\", sact->UrlString, sact->TargetString);\n}", "static int\ndecompileGETURL2 (SWF_ACTION *act)\n{\n\tstruct SWF_ACTIONPUSHPARAM *a,*b;\n\tOUT_BEGIN(SWF_ACTIONGETURL2);\n\tINDENT", "\ta = pop();\n\tb = pop();", "\tif (sact->f.FlagBits.SendVarsMethod==3)\n\t\tputs(\"loadVariables(\");\n\telse \n\t{\n\t\tif (sact->f.FlagBits.SendVarsMethod==2)\n\t\t\tputs(\"loadVariablesNum(\");\n\t\telse\n\t\t{\n\t\t\tif (sact->f.FlagBits.SendVarsMethod==1) \n\t\t\t\tputs(\"loadMovie(\");\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (*getName(a)=='_')\t// found a _level\n\t\t\t\t\tputs(\"loadMovieNum(\");\t\n\t\t\t\telse\n\t\t\t\t\tputs(\"getURL(\");\n\t\t\t}\n\t\t}\n\t}\n\tdecompilePUSHPARAM (b, 1);\n\tputs(\",\");\n\tdecompilePUSHPARAM (a, 1);\n\tif (sact->f.FlagBits.LoadVariableFlag)\n\t\tputs(\",'GET'\");\n\tif (sact->f.FlagBits.LoadTargetFlag)\n\t\tputs(\",'POST'\");\n\tprintln(\");\");\n\treturn 0;\n}", "static inline int OpCode(SWF_ACTION *actions, int n, int maxn)\n{\n\tif(!n || n >= maxn)\n\t{\n#if DEBUG\n\t\tSWF_warn(\"OpCode: want %i, max %i\\n\", n, maxn);\n#endif\n\t\treturn -999;\n\t} else if (n < 1) {", "#if DEBUG\n\t\tSWF_warn(\"OpCode: want %i < 1\\n\", n);\n#endif\n\t\treturn -998;\n }\n\treturn actions[n].SWF_ACTIONRECORD.ActionCode;\n}", "static int\nisStoreOp(int n, SWF_ACTION *actions,int maxn)\n{\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\tcase SWFACTION_STOREREGISTER:\n\tcase SWFACTION_SETVARIABLE:\n\tcase SWFACTION_SETMEMBER:\n\tcase SWFACTION_CASTOP:\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}", "static int \ndecompileGOTOFRAME(int n, SWF_ACTION *actions,int maxn,int islabel)\n{\n\tint i=0;\n\tstruct SWF_ACTIONGOTOLABEL *sactv2;\n\tOUT_BEGIN2(SWF_ACTIONGOTOFRAME);\n\tsactv2 = (struct SWF_ACTIONGOTOLABEL*)sact;\n\tINDENT\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_PLAY)\n\t{\n\t\ti=1;\n\t\tputs(\"gotoAndPlay(\");\n\t}\n\telse\n\t{\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_STOP)\n\t\t\ti=1;\n\t\tputs(\"gotoAndStop(\");\n\t}\n\t\n\tif (islabel)\n\t\tprintln(\"'%s');\", sactv2->FrameLabel);\n\telse\n\t\tprintln(\"%d);\", sact->Frame+1); /* GOTOFRAME arg is 0-based */\n\treturn i;\n}", "static int \ndecompileGOTOFRAME2(int n, SWF_ACTION *actions, int maxn)\n{\n\tint i=0;\n\tOUT_BEGIN2(SWF_ACTIONGOTOFRAME2);\n\tINDENT\n\tif (n+1 < maxn)\n\t{\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_PLAY ||\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_STOP)\n\t\t\ti=1;\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_PLAY)\n\t\t\tputs(\"gotoAndPlay(\");\n\t\telse\n\t\t{\n\t\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_STOP)\n\t\t\t\tputs(\"gotoAndStop(\");\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (sact->f.FlagBits.PlayFlag)\n\t\t\t\t\tputs(\"gotoAndPlay(\");\n\t\t\t\telse\n\t\t\t\t\tputs(\"gotoAndStop(\");\n\t\t\t}\n\t\t}\n\t}\n\telse \n\t{\n\t\tif (sact->f.FlagBits.PlayFlag)\n\t\t\tputs(\"gotoAndPlay(\");\n\t\telse\n\t\t\tputs(\"gotoAndStop(\");\n\t}\n\tdecompilePUSHPARAM(pop(),0);\n\tprintln(\");\");\n\treturn i;\n}", "\nstatic int precedence(int op1,int op2)\n{\n\tstatic unsigned char ops[]= { \t\t// array of opcodes w rising precedence\n//\tSWFACTION_SETVARIABLE,\t\t// TAKE CARE: array is incomplete\n//\tSWFACTION_TRACE,\n\t// missing ops are considered with low precedence\n\t\tSWFACTION_LOGICALOR,\n\t\tSWFACTION_LOGICALAND,\n\t\tSWFACTION_BITWISEOR,\n\t\tSWFACTION_BITWISEXOR,\n\t\tSWFACTION_BITWISEAND,\n\t\tSWFACTION_STRICTEQUALS,\n\t\tSWFACTION_EQUALS2,\n\t\tSWFACTION_EQUAL,\n\t\tSWFACTION_GREATER,\n\t\tSWFACTION_LESSTHAN,\n\t\tSWFACTION_LESS2,\t\n\t\tSWFACTION_SHIFTRIGHT,\n\t\tSWFACTION_SHIFTRIGHT2,\n\t\tSWFACTION_SHIFTLEFT,\n\t\tSWFACTION_ADD,\n\t\tSWFACTION_ADD2,\n\t\tSWFACTION_SUBTRACT,\n\t\tSWFACTION_MODULO,\n\t\tSWFACTION_MULTIPLY,\n\t\tSWFACTION_DIVIDE,\n\t\tSWFACTION_LOGICALNOT,\n\t\tSWFACTION_PUSH\t\t\t// FIXME: need more analysis on code after PUSH\n\t};\n\tunsigned char* f=memchr(ops,op1,sizeof(ops));\n\tunsigned char* s=memchr(ops,op2,sizeof(ops));\n#ifdef DEBUG\n\tprintf(\"1op=%d 2op=%d result=%d\\n\",op1,op2,f>s);\n\tif (!f) printf(\"opcode=%d NOT in precedence list\\n\",op1);\n\tif (!s) printf(\"opcode=%d NOT in precedence list\\n\",op2);\n#endif\n\treturn f>s;\n}", "#ifdef DECOMP_SWITCH\nstatic int\ncheck_switch(int firstcode)\n{\n\treturn (firstcode == SWFACTION_PUSH || firstcode == SWFACTION_JUMP);\n}\n#endif", "\nstatic int\ndecompileArithmeticOp(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *left, *right;\n\tint op_l = OpCode(actions, n, maxn);\n\tint op_r = OpCode(actions, n+1, maxn);\n\tright=pop();\n\tleft=pop();\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\t/*\n\tcase SWFACTION_GETMEMBER:\n\t\tdecompilePUSHPARAM(peek(),0);\n\t\tbreak;\n\t*/\n\tcase SWFACTION_INSTANCEOF:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\" instanceof \",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\" instanceof \",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_ADD:\n\tcase SWFACTION_ADD2:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"+\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"+\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SUBTRACT:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"-\",getString(right)));\t \n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"-\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_MULTIPLY:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"*\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"*\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_DIVIDE:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"/\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"/\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_MODULO:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"%\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"%\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SHIFTLEFT:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"<<\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"<<\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SHIFTRIGHT:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\">>\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\">>\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_SHIFTRIGHT2:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\">>>\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\">>>\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LOGICALAND:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"&&\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"&&\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LOGICALOR:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"||\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"||\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_BITWISEAND:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"&\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"&\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_BITWISEOR:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"|\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"|\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_BITWISEXOR:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"^\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"^\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_EQUALS2:\t/* including negation */\n\tcase SWFACTION_EQUAL:\n\t\tif( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t\t OpCode(actions, n+2, maxn) != SWFACTION_IF)\n\t\t{\n\t\t\top_r = OpCode(actions, n+1, maxn);\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\"!=\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\"!=\",getString(right),0,\")\"));\n\t\t\treturn 1; /* due negation op */\n\t\t}\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"==\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"==\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LESS2:\n\t\tif( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t\t OpCode(actions, n+2, maxn) != SWFACTION_IF ) \n\t\t{\n\t\t\top_r = OpCode(actions, n+2, maxn);\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\">=\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\">=\",getString(right),0,\")\"));\n\t\t\treturn 1; /* due negation op */\n\t\t}\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"<\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"<\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_GREATER:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\">\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\">\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_LESSTHAN:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"<\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"<\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_STRINGEQ:\n\t\tif (precedence(op_l, op_r))\n\t\t\tpush(newVar3(getString(left),\"==\",getString(right)));\n\t\telse\n\t\t\tpush(newVar_N(\"(\",getString(left),\"==\",getString(right),0,\")\"));\n\t\tbreak;\n\tcase SWFACTION_STRINGCOMPARE:\n\t\tputs(\"STRINGCOMPARE\");\n\t\tbreak;\n\tcase SWFACTION_STRICTEQUALS:\n#ifdef DECOMP_SWITCH\n\t\tif (OpCode(actions, n, maxn) == SWFACTION_IF)\n\t\t{\n\t\t\tint code = actions[n+1].SWF_ACTIONIF.Actions[0].SWF_ACTIONRECORD.ActionCode;\n\t\t\tif(check_switch(code))\n\t\t\t{\n\t\t\t\tpush(right);\t// keep left and right side separated\n\t\t\t\tpush(left);\t// because it seems we have found a switch(){} and\n\t\t\t\tbreak;\t// let decompileIF() once more do all the dirty work\n\t\t\t}\n\t\t}\n#endif\n\t\tif( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t\t OpCode(actions, n+2, maxn) != SWFACTION_IF ) \n\t\t{\n\t\t\top_r = OpCode(actions, n+2, maxn);\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\"!==\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\"!==\",getString(right),0,\")\"));\n\t\t\treturn 1; /* due negation op */\n\t\t} else {\n\t\t\tif (precedence(op_l, op_r))\n\t\t\t\tpush(newVar3(getString(left),\"===\",getString(right)));\n\t\t\telse\n\t\t\t\tpush(newVar_N(\"(\",getString(left),\"===\",getString(right),0,\")\"));\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\tprintf(\"Unhandled Arithmetic/Logic OP %x\\n\",\n\t\t\tOpCode(actions, n, maxn));\n\t}\n\treturn 0;\n}", "static int\nisLogicalOp(int n, SWF_ACTION *actions, int maxn)\n{\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\tcase SWFACTION_LESSTHAN:\n\tcase SWFACTION_LOGICALAND:\n\tcase SWFACTION_LOGICALOR:\n\tcase SWFACTION_LOGICALNOT:\n\tcase SWFACTION_STRINGEQ:\n\tcase SWFACTION_STRINGCOMPARE:\n\tcase SWFACTION_LESS2:\n\tcase SWFACTION_EQUALS2:\n\tcase SWFACTION_EQUAL:\n\tcase SWFACTION_BITWISEAND:\n\tcase SWFACTION_BITWISEOR:\n\tcase SWFACTION_BITWISEXOR:\n\tcase SWFACTION_STRICTEQUALS:\n\tcase SWFACTION_GREATER:\n\t/*\n\tcase SWFACTION_GETMEMBER:\n\t*/\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}", "static int \nisLogicalOp2(int n, SWF_ACTION *actions,int maxn)\n{\n\tswitch(OpCode(actions, n, maxn))\n\t{\n\tcase SWFACTION_LOGICALNOT:\n\tcase SWFACTION_PUSHDUP:\n\tcase SWFACTION_IF:\n\t\treturn 1;\n\tdefault:\n\t\treturn 0;\n\t}\n}", "static int\nstackVal(int n, SWF_ACTION *actions)\n{\n\tif (!n) \n\t\treturn 0;", "\tswitch((actions[n-1]).SWF_ACTIONRECORD.ActionCode)\n\t{\n\tcase SWFACTION_LOGICALNOT:\n\tcase SWFACTION_DECREMENT:\n\tcase SWFACTION_INCREMENT:\n\tcase SWFACTION_RANDOMNUMBER:\n\tcase SWFACTION_TOSTRING:\n\tcase SWFACTION_TONUMBER:\n\tcase SWFACTION_ORD:\n\tcase SWFACTION_CHR:\n\tcase SWFACTION_MBORD:\n\tcase SWFACTION_MBCHR:\n\tcase SWFACTION_INT:\n\tcase SWFACTION_GETVARIABLE:\n\tcase SWFACTION_SUBSTRING:\n\tcase SWFACTION_MBSUBSTRING:\n\tcase SWFACTION_GETMEMBER:\n\tcase SWFACTION_ADD:\n\tcase SWFACTION_ADD2:\n\tcase SWFACTION_SUBTRACT:\n\tcase SWFACTION_MULTIPLY:\n\tcase SWFACTION_DIVIDE:\n\tcase SWFACTION_MODULO:\n\tcase SWFACTION_BITWISEAND:\n\tcase SWFACTION_BITWISEOR:\n\tcase SWFACTION_BITWISEXOR:\n\tcase SWFACTION_LESSTHAN:\n\tcase SWFACTION_LOGICALAND:\n\tcase SWFACTION_LOGICALOR:\n\tcase SWFACTION_STRINGEQ:\n\tcase SWFACTION_STRINGCOMPARE:\n\tcase SWFACTION_LESS2:\n\tcase SWFACTION_EQUALS2:\n\tcase SWFACTION_EQUAL:\n\tcase SWFACTION_STRICTEQUALS:\n\tcase SWFACTION_GREATER:\n\tcase SWFACTION_STRINGGREATER:\n\tcase SWFACTION_STRINGCONCAT:\n\tcase SWFACTION_SHIFTLEFT:\n\tcase SWFACTION_SHIFTRIGHT:\n\tcase SWFACTION_SHIFTRIGHT2:\n\tcase SWFACTION_INSTANCEOF:\n\tcase SWFACTION_CALLMETHOD:\n\tcase SWFACTION_CALLFUNCTION:\n\tcase SWFACTION_GETTIME:\n\tcase SWFACTION_GETPROPERTY:\n\tcase SWFACTION_PUSH:\n\tcase SWFACTION_DELETE:\n\tcase SWFACTION_DELETE2:\n\tcase SWFACTION_MBLENGTH:\n\tcase SWFACTION_STRINGLENGTH:\n\tcase SWFACTION_CASTOP:\n\tcase SWFACTION_TYPEOF:\n\tcase SWFACTION_PUSHDUP:\n\t\treturn 1;\n\tdefault:\n\treturn 0;\n\t}\n}", "static int\ndecompileLogicalNot(int n, SWF_ACTION *actions, int maxn)\n{\n#ifdef STATEMENT_CLASS\n\tif(OpCode(actions, n-1, maxn) == SWFACTION_GETVARIABLE &&\n\t OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT &&\n\t OpCode(actions, n+2, maxn) == SWFACTION_IF ) \n\t{\n\t\t/* It's a class statement -- skip over both NOTs */\n\t\treturn 1;\n\t}\n#endif\n\tif(OpCode(actions, n+1, maxn) != SWFACTION_IF )\n\t\tpush(newVar2(\"!\",getString(pop())));\n\treturn 0;\n}", "static void\ndecompilePUSH (SWF_ACTION *act)\n{\n\tint i;\n\tOUT_BEGIN(SWF_ACTIONPUSH);", "\tSanityCheck(SWF_PUSH,\n\t\tact->SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSH,\n\t\t\"not a PUSH\")", "\tfor(i=0;i<sact->NumParam;i++)\n\t\tpush(&(sact->Params[i]));\n}", "static void\ndecompilePUSHDUP (SWF_ACTION *act)\n{\n\tSanityCheck(SWF_PUSHDUP,\n\t\tact->SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSHDUP,\n\t\t\"not a PUSHDUP\")\n\tpushdup();\n}", "static void\ndecompileSTACKSWAP (SWF_ACTION *act)\n{\n\tSanityCheck(SWF_STACKSWAP,\n\t\tact->SWF_ACTIONRECORD.ActionCode == SWFACTION_STACKSWAP,\n\t\t\"not a STACKSWAP\")\n\tstackswap();\n}", "static int\ndecompileSETPROPERTY(int n, SWF_ACTION *actions,int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *val, *idx, *obj;", "\tINDENT\n\tval = pop();\n\tidx = pop();\n\tobj = pop();\n#ifdef DEBUG\n\tprintf(\"*setProp* objName %s (type=%d) Prop (type=%d) =%x\\n\",\n\t getName(obj), obj->Type, idx->Type,getInt(idx));\n#endif\n\tif (obj->Type == PUSH_VARIABLE)\n\t\tputs(\"eval(\");\n\t\n\tdecompilePUSHPARAM(obj,0);\n\tif (obj->Type == PUSH_VARIABLE)\n\t\tputs(\")\");\n\t\n\tputs(\".\");\n\tputs(getProperty(getInt(idx)));\n\tprintf(\" = \" );\n\tdecompilePUSHPARAM(val,0);\n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileGETPROPERTY(int n, SWF_ACTION *actions,int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *idx, *obj;", "\tINDENT\n\tidx = pop();\n\tobj = pop();\n#ifdef DEBUG\n\tprintf(\"*GETProp* objName %s (type=%d) Prop (type=%d) =%x\\n\",\n\t getName(obj), obj->Type, idx->Type,getInt(idx));\n#endif\n\tif (obj->Type == PUSH_VARIABLE)\n\t\tpush( newVar5(\"eval(\",getName(obj),\".\",getProperty(getInt(idx)),\")\"));\n\telse\n\t\tpush( newVar3( getName(obj),\".\",getProperty(getInt(idx))));\n\treturn 0;\n}", "static int\ndecompileTRACE(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"trace(\");\n\tdecompilePUSHPARAM(pop(),1);\n\tprintln(\");\");\n\treturn 0;\n}", "static int\ndecompileCALLFRAME(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"callFrame(\");\n\tdecompilePUSHPARAM(pop(),1);\n\tprintln(\");\");\n\treturn 0;\n}", "static int\ndecompileGETTIME(int n, SWF_ACTION *actions, int maxn)\n{\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\tINDENT\n\t\tprintln(\"getTimer();\");\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tpush(newVar(\"getTimer()\"));\n\t\treturn 0;\n\t}\n}", "static int\ndecompileINCR_DECR(int n, SWF_ACTION *actions, int maxn, int is_incr)\n{\n\tint is_postop;\n\tstruct SWF_ACTIONPUSHPARAM *var=pop();\n\tchar *dblop=is_incr ? \"++\":\"--\";", "\tif((OpCode(actions, n, maxn) == SWFACTION_PUSHDUP\n\t || OpCode(actions, n+1, maxn) == SWFACTION_PUSHDUP \n\t || OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE)\n\t || ( OpCode(actions, n-1, maxn) == SWFACTION_GETVARIABLE\n\t && OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER\n\t && OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE))\n\t{\n\t\tis_postop=(OpCode(actions, n-1, maxn) == SWFACTION_PUSHDUP)?1:0;\n\t\tif (is_postop)\n\t\t\tvar = newVar2(getString(var),dblop);\n\t\telse\n\t\t\tvar = newVar2(dblop,getString(var));\n\t\tif (OpCode(actions, n+1, maxn) == SWFACTION_SETVARIABLE)\n\t\t{\n\t\t\tvar->Type=11;\t/* later trigger printing variable inc/dec */\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar->Type=12;\t/* later be quiet, see decompileSETVARIABLE() */\n\t\t\tif (is_postop)\n\t\t\t{\n\t\t\t\tpop();\n\t\t\t\tpush(var);\t/* will duplicate stacktop */\n\t\t\t}\n\t\t}\n\t\tpush(var);\n\t}\n\telse\n\t{\n\t\tif((OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER &&\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER &&\n\t\t OpCode(actions, n+2, maxn) == SWFACTION_SETMEMBER ) ||\n\t\t (OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER &&\n\t \t OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER &&\n\t\t OpCode(actions, n+2, maxn) == SWFACTION_PUSH ) ||\n\t\t (OpCode(actions, n-1, maxn) == SWFACTION_PUSH &&\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER) ||\n\t\t (OpCode(actions, n-3, maxn) == SWFACTION_GETMEMBER &&\n\t\t OpCode(actions, n-2, maxn) == SWFACTION_PUSH &&\n\t\t OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER &&\n\t\t OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER &&\n\t \t((struct SWF_ACTIONPUSH *)&actions[n-2].SWF_ACTIONRECORD)->NumParam >= 4 \n\t \t\t/* 4: a pair of get/set - FIXME: add more analysis about stack here */))\n\t\t{\t\t// incr/decr object variables with side effects\n\t\t\tis_postop= (OpCode(actions, n+1, maxn) == SWFACTION_SETMEMBER)?1:0;\n\t\t\tif (is_postop)\n\t\t\t\tvar = newVar2(getString(var),dblop);\n\t\t\telse\n\t\t\t\tvar = newVar2(dblop,getString(var));\n\t\t\tif (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_PUSH) \n\t\t\t\tpop();\n\t\t\tif(OpCode(actions, n+1, maxn) == SWFACTION_GETMEMBER) \n\t\t\t\tpop();\n\t\t\t\n\t\t\tpop();\n\t\t\tpop();\n\t\t\tvar->Type=12;\t// to be quiet later in ...SETMEMBER()\n\t\t\tregs[0]=var;\t// FIXME: r0 perhaps a ming special\n\t\t\tpush(var);\n\t\t\tpush(var);\n\t\t\tpush(var);\n\t\t\n\t\t\tif (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_PUSH ) \n\t\t\t\tpush(var);\n\t\t\tif (is_postop && OpCode(actions, n-1, maxn) == SWFACTION_GETMEMBER ) \n\t\t\t\tpush(var);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(OpCode(actions, n-1, maxn) == SWFACTION_PUSH &&\n\t\t\t OpCode(actions, n+1, maxn) == SWFACTION_STOREREGISTER &&\n\t\t\t regs[actions[n+1].SWF_ACTIONSTOREREGISTER.Register]->Type == PUSH_VARIABLE)\n\t\t\t{\n\t\t\t\tvar = newVar2(dblop,getString(var));\n\t\t\t\tif ((OpCode(actions, n+2, maxn) == SWFACTION_POP \n\t\t\t\t && actions[n-1].SWF_ACTIONPUSH.NumParam==1) \n\t\t\t\t || OpCode(actions, n+3, maxn) == SWFACTION_POP)\n\t\t\t\t{\n\t\t\t\t\tvar->Type=11;\t// later print inc/dec\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar->Type=12;\t// later be quiet in ..STOREREGISTER()\n\t\t\t\t\tif (actions[n-1].SWF_ACTIONPUSH.NumParam>1) \n\t\t\t\t\t{\n\t\t\t\t\t\tpop();\n\t\t\t\t\t\tpush(var);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpush(var);\n\t\t\t}\n\t\t\telse\t\t// fallback to old incr/decr code\n\t\t\t{\t\t// FIXME: this is bad designed for handling side effect code\n\t\t\t\tINDENT\t// like post-incrementing a function argument etc.\n\t\t\t\tdecompilePUSHPARAM(var,0);\n\t\t\t\tputs(dblop);\n\t\t\t\tprintln(\";\");\n\t\t\t\tpush(var);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "static int\ndecompileSTOREREGISTER(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *data;\n\tOUT_BEGIN2(SWF_ACTIONSTOREREGISTER);\n\tdata=peek();", "\tif (!regs[sact->Register] || sact->Register==0 )\t// ===internal===\n\t{\n\t\tregs[sact->Register] = data;\n\t}\n\telse\t\t\t\t\t\t// ===user visible level===\n\t{\n\t\tif ( regs[sact->Register]->Type == PUSH_VARIABLE) // V7: a named function parameter in register\n\t\t{\t\t\t\t\t\t// V7: a local var in register\n\t\t\tif (data->Type==12)\n\t\t\t\tdata->Type = PUSH_VARIABLE;\t\t\t// do nothing, but only once\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar *l=getName(regs[sact->Register]);\n\t\t\t\tchar *r=getName(data);\n\t\t\t\tif (strcmp(l,r))\n\t\t\t\t{\n\t\t\t\t\tINDENT\n\t\t\t\t\tif (data->Type==11)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintln(\"%s;\", r);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"%s = \",l);\n\t\t\t\t\t\tdecompilePUSHPARAM(data,1);\n\t\t\t\t\t\tprintln(\";\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "static int\ndecompileNEWOBJECT(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *obj, *nparam;\n\tobj = pop();\n\tnparam=pop();\n\tpush(newVar_N(\"new \",\"\",getName(obj),\"(\", nparam->p.Integer,\")\"));\n\treturn 0;\n}", "static int\ndecompileNEWMETHOD(int n, SWF_ACTION *actions, int maxn)\n{\n\tchar *t;\n\tstruct SWF_ACTIONPUSHPARAM *meth, *nparam, *obj;\n\tmeth = pop();\n\tobj = pop();\n\tnparam=pop();", "\tt=malloc(strlen( getName(obj) ) +2);\n\tstrcpy(t,getName(obj));\n\tstrcat(t,\".\");", "\tpush(newVar_N(\"new \",t,getName(meth),\"(\", nparam->p.Integer,\")\"));\n\tfree (t);\n\treturn 0;\n}", "\nstatic int\ndecompileGETMEMBER(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *obj, *mem, *var;\n\tchar *vname, *varname,*memname;\n\tint len;", "\tmem=pop();\n\tvar=pop();\n\tvarname=getName(var);\n\tmemname=getName(mem);\n#ifdef DEBUG\n\tprintf(\"*getMember* varName %s (type=%d) memName=%s (type=%d)\\n\",\n\t varname,var->Type, memname,mem->Type);\n#endif\n\tlen = strlen(varname)+strlen(memname);\n\tif (mem->Type == PUSH_INT || mem->Type == PUSH_DOUBLE || mem->Type == PUSH_VARIABLE\n\t || mem->Type == PUSH_REGISTER || mem->Type == 12 )\n\t{\n\t\tvname = malloc(len+3);\n\t\tstrcpy(vname,varname);\n\t\tstrcat(vname,\"[\");\n\t\tstrcat(vname,memname);\n\t\tstrcat(vname,\"]\");\n\t}\n\telse\n\t{\n\t\tvname = malloc(len+2);\n\t\tstrcpy(vname,varname);\n\t\tstrcat(vname,\".\");\n\t\tstrcat(vname,memname);\n\t} \n\tobj = newVar(vname);\n\tpushvar(obj);", "\treturn 0;\n}", "\nstatic int\ndecompileSETMEMBER(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *val, *var, *obj;\n\tval = pop();\n\tvar = pop();\n\tobj = pop();", "#ifdef DEBUG\n\tprintf(\"*SETMember* varName %s (type=%d) objName=%s (type=%d)\\n\",getName(var),var->Type, getName(obj),obj->Type);\n#endif\n\tif (obj->Type == 12)\t\t\t\t/* do nothing: inline inc/dec using side effect */\n\t{\n\t\tobj->Type = PUSH_VARIABLE;\t\t/* ...but only once */\n\t\treturn 0;\n\t}\n\tINDENT\n\tif (obj->Type == 11)\t\t\t\t/* simply output variable and inc/dec op */\n\t{\n\t\tdecompilePUSHPARAM(obj,0);\n\t\tprintln(\";\");\n\t\treturn 0;\n\t}", "\tdecompilePUSHPARAM(obj,0);\n\tif (var->Type == PUSH_INT || var->Type == PUSH_DOUBLE || var->Type == PUSH_VARIABLE\n\t || var->Type == PUSH_REGISTER || var->Type == 12 )\n\t{\n\t\tputs(\"[\");\n\t}\n\telse\n\t{\n\t\tputs(\".\");\n\t\tif (OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER)\n\t\t{\n\t\t\tstruct SWF_ACTIONSTOREREGISTER *sactv2 = (struct SWF_ACTIONSTOREREGISTER*)&actions[n-1];\n\t\t\tif (sactv2->Register==0)\n\t\t\t\tregs[0]=newVar3(getName(obj),\".\",getName(var));\t\t// easter 07: some sugar for mtc et al.\n\t\t}\n\t}\n\tdecompilePUSHPARAM(var,0);\n\tif (var->Type == PUSH_INT || var->Type == PUSH_DOUBLE || var->Type == PUSH_VARIABLE\n\t\t|| var->Type == PUSH_REGISTER || var->Type == 12 )\n\t{\n\t\tputs(\"]\");\n\t}\n\tprintf(\" = \" );", "\n\tif ( OpCode(actions, n-1, maxn) == SWFACTION_STOREREGISTER ) {\n\t\tstruct SWF_ACTIONSTOREREGISTER *sr =\n\t\t\t(struct SWF_ACTIONSTOREREGISTER*)&actions[n-1];\n\t\tprintf(\"R%d\", sr->Register);\n\t}\n\telse if (val->Type != PUSH_VARIABLE) {\n\t\t/* later it will be a switch{} */\n\t\tdecompilePUSHPARAM(val,1);\n\t}\n\telse {\n\t\tdecompilePUSHPARAM(val,0);\n\t}\n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileGETVARIABLE(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *var;", "\tvar = pop();\n#ifdef DEBUG\n\tprintf(\"*GETVariable* varName %s (type=%d)\\n\",getName(var),var->Type);\n#endif\n\tif (var->Type == PUSH_VARIABLE)\n\t\tpushvar(newVar3(\"eval(\",getName(var),\")\"));\n\telse\n\t\tpushvar(newVar(getName(var)));", "\treturn 0;\n}", "static int\ndecompileSETVARIABLE(int n, SWF_ACTION *actions,int maxn,int islocalvar)\n{\n\tstruct SWF_ACTIONPUSHPARAM *val, *var;", "\tval = pop();\n\tvar = pop();\n\tif (val->Type!=12)\n\t{\n\t\tINDENT\n\t}\n#ifdef DEBUG\n\tprintf(\"*SETVariable* varName %s (type=%d) valName=%s (type=%d)\\n\",\n\t getName(var),var->Type, getName(val),val->Type);\n#endif\n\tif (val->Type!=12 && islocalvar)\n\t{\n\t\tputs(\"var \");\n\t}\n\tif (gIndent<0)\t/* the ENUM workaround: */\n\t{\t\t\t/* in \"for (xx in yy) { }\" we need xx, but nothing else */\n\t\tputs(getName(var));\n\t\treturn 0;\n\t}", "\n\tswitch (val->Type)\n\t{\n\tcase 10:\t\n\t\tputs(getName(var));\t\t// Variable (NEVER as string)\n\t\tprintf(\" = \" );\n\t\tdecompilePUSHPARAM(val,0);\n\t\tprintln(\";\");\n\t\tbreak;\t\t\n\tcase 11:\t\t\t\t/* simply output variable and inc/dec op */\n\t\tputs(getName(val));\n\t\tprintln(\";\");\n\t\tbreak;\n\tcase 12:\t\t\t\t/* do nothing: inline increment/decrement (using side effect only) */\n\t\tval->Type = PUSH_VARIABLE; \t\t// but print next time e.g. in y=++x;\n\t\tbreak;\n\tdefault:\t\n\t\tputs(getName(var));\n\t\tprintf(\" = \" );\n\t\tdecompilePUSHPARAM(val,1);\t// for certain types parameter 1 does not care\n\t\tprintln(\";\");\n\t}\n\treturn 0;\n}", "static int\ndecompileRETURN(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *var=pop();\n\tINDENT\n\tprintf(\"return \");\n\tif (var->Type== PUSH_REGISTER && var->p.RegisterNumber==0)\t/* REGISTER 0 used as helper variable */\n\t\tputs(getName(regs[0]));\n\telse\n\t\tdecompilePUSHPARAM(var,1); \n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileJUMP(int n, SWF_ACTION *actions, int maxn)\n{\n\tint i=0,j=0;\n\tint offSave;\n\tstruct SWF_ACTIONIF *sactif;\n\tOUT_BEGIN2(SWF_ACTIONJUMP);\n\tsactif=NULL;", "\tif(isLogicalOp(n+1, actions, maxn) ||\n\t (OpCode(actions, n+1, maxn) == SWFACTION_PUSH && isLogicalOp(n+2, actions, maxn)))\n\t{\n\t\t/* Probably the start of a do {} while(), so skip it */\n\t\treturn 0;\n\t}", "\t/* Probably the end of a switch{}, so skip it */\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t\treturn 1;", "\tif (OpCode(actions, n+1, maxn) == SWFACTION_JUMP) \n\t{\n\t\tif (actions[n+1].SWF_ACTIONJUMP.BranchOffset==0)\n\t\t\treturn 1;\n\t}", "\tfor(i=0; n + 1 + i < maxn && (actions[(n+1)+i].SWF_ACTIONRECORD.Offset < (actions[n+1].SWF_ACTIONRECORD.Offset+actions[n ].SWF_ACTIONJUMP.BranchOffset)); i++)\n\t{\n#if 0\n\t\tprintf(\"/* for PART3 OP 0x%x */\\n\",actions[n+1+i].SWF_ACTIONRECORD.ActionCode);\n#endif\n\t\t; // NOOP\n\t}", "\tif (i)\n\t{\n\t\tfor (j=0; n+j+i<maxn; j++)\n\t\t{\n#if 0\n\t\t\t printf(\"/* FOR part2 OP 0x%x */\\n\",actions[n+i+j].SWF_ACTIONRECORD.ActionCode)\n\t\t\t// at least one should push on stack\n#endif\n\t \n\t\t\tif (OpCode(actions, n+i+j, maxn) == SWFACTION_IF)\n\t\t\t{\n\t\t\t\tsactif = (struct SWF_ACTIONIF *)&(actions[n+i+j]);\n\t\t\t\t/* chk whether last jump does lead us back to start of loop */\n\t\t\t\tif (sactif->Actions[sactif->numActions-1].SWF_ACTIONRECORD.ActionCode==SWFACTION_JUMP\n\t\t\t\t && sactif->Actions[sactif->numActions-1].SWF_ACTIONJUMP.BranchOffset+\n\t\t\t\t sactif->Actions[sactif->numActions-1].SWF_ACTIONJUMP.Offset==\n\t\t\t\t actions[n].SWF_ACTIONRECORD.Offset )\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tsactif=NULL;\n\t\t\t}\n\t\t}\n\t}", "\tif (sactif)\n\t{\n\t\tINDENT\n\t\tputs(\"while(\");\n\t\tdecompileActions(j-1, &actions[n+1+i], gIndent);\n\t\tputs(getName(pop()));\n\t\tprintln(\"){ /* original FOR loop rewritten to WHILE */\");\n\t\toffSave=offseoloop;\n\t\tif (n+i+j+1<maxn)\t\t\t\t\t\t// see part2 above\n\t\t\toffseoloop=actions[n+i+j+1].SWF_ACTIONRECORD.Offset;\n\t\telse\n\t\t\toffseoloop=actions[n+i+j].SWF_ACTIONRECORD.Offset+5;\n\t\tdecompileActions(sactif->numActions-1, sactif->Actions,gIndent+1);\n\t\tdecompileActions(i, &actions[n+1], gIndent+1);\n\t\toffseoloop=offSave;\n\t\tINDENT\n\t\tprintln(\"};\");\n\t\treturn i+j; \n\t}\n\t\n\tif (sact->BranchOffset>0)\n\t{\n\t\tif ( stackVal(n,actions) == 1 && n+1==maxn)\n\t\t{\t// leaving block @last op with value on stack: a return x;\n\t\t\treturn decompileRETURN(n, actions,maxn);\n\t\t}\n\t\tif (n+2 < maxn && OpCode(actions, n+1, maxn) == SWFACTION_PUSH && \n\t\t\tactions[n+2].SWF_ACTIONRECORD.Offset == actions[n+1].SWF_ACTIONRECORD.Offset+sact->BranchOffset)\n\t\t{\n\t\t\treturn 1; \t// jump to short to be a 'break': but an internal jump over a push\n\t\t}\t\t\t// to do: add some control flow analysis\n\t\t\n\t\tINDENT\n\t\t\n\t\tif (offseoloop==actions[n].SWF_ACTIONRECORD.Offset+sact->BranchOffset+5)\n\t\t\tputs(\"break;\" );\n\t\telse\n\t\t\tputs(\"return;\" );\n\t\t\n\t\tprintln(\"\\t\\t\\t// offs_end_of_loop=%d offs_jmp_dest=%d\",\n\t\t offseoloop, actions[n].SWF_ACTIONRECORD.Offset+sact->BranchOffset+5);\n\t}\n\telse\n\t{\n\t\tif (sact->BranchOffset<0)\n\t\t{\n\t\t\tINDENT\n\t\t\tprintln(\"continue; /*------*/\");\n\t\t}\n\t}\n\t/* error(\"Unhandled JUMP\"); */\n\treturn 0;\n}", "static int\ndecompileDEFINELOCAL2(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *var;", "\tINDENT\n\tvar = pop();\n\tputs(\"var \");\n\tputs(getName(var));\n\tprintln(\";\");", "\treturn 0;\n}", "static int \ndecompileENUMERATE(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tint i=0;\n\twhile (i < maxn && i < 5 && OpCode(actions, n+i, maxn))\n\t\ti++;\n\t\n\tINDENT \n\tprintln(\"/* a for-var-in loop should follow below: */\" );\n\treturn i-1;\t\t// preserve some code for decompileIF()... \n} \t\t\t\t// ... and let decompileIF() do all the dirty work ;-)", "\n#ifdef DECOMP_SWITCH", "// [recursive] estimate size of buffer needed for decompiling 'switch' \n// [ only call by decompileIF() ]\n//\nstatic int\ncountAllSwitchActions (union SWF_ACTION *actions, union SWF_ACTION *pre)\n{\n\tint i,j=1;\n\tif (actions->SWF_ACTIONRECORD.ActionCode==SWFACTION_IF && pre->SWF_ACTIONRECORD.ActionCode==SWFACTION_STRICTEQUALS )\n\t{\n\t\tfor(i=0; i < ((struct SWF_ACTIONIF*)actions)->numActions; i++)\n\t\t{\n\t\t\tj+=countAllSwitchActions(&((struct SWF_ACTIONIF*)actions)->Actions[i],pre);\n\t\t\tpre=&((struct SWF_ACTIONIF*)actions)->Actions[i];\n\t\t}\n\t} \n\treturn j;\n}", "\n// [recursive] copy all actions in a 'flat' buffer by \n// unpackung all if-actions that are part of the switch operation\n// [ only call by decompileIF() ]\n//\nstatic union SWF_ACTION *\ngetAllSwitchActions(union SWF_ACTION *dest, union SWF_ACTION *actions, union SWF_ACTION *pre)\n{\n#ifdef DEBUGSWITCH\n\tprintln(\"SWCODE: %p %d %s %s\",\n\t dest, actions->SWF_ACTIONRECORD.Offset, \n\t actionName(actions->SWF_ACTIONRECORD.ActionCode),\n\t actionName(pre->SWF_ACTIONRECORD.ActionCode));\n#endif", "\t*dest++=*actions;\n\tif (actions->SWF_ACTIONRECORD.ActionCode==SWFACTION_IF \n\t && pre->SWF_ACTIONRECORD.ActionCode==SWFACTION_STRICTEQUALS )\n\t{\n\t\tint i;\n\t\tstruct SWF_ACTIONIF *sactv2 = (struct SWF_ACTIONIF*)actions;\n\t\tfor(i=0; i< sactv2->numActions; i++)\n\t\t{\n\t\t\tdest=getAllSwitchActions(dest,&sactv2->Actions[i],pre);\n\t\t\tpre=&((struct SWF_ACTIONIF*)actions)->Actions[i];\n\t\t}\n\t}\n\treturn dest;\n}", "// looks similar other decompileXXXX() but \n// can't called by decompileAction()\n// [ do only call by decompileIF() ]\n//\nstatic int\ndecompile_SWITCH(int n, SWF_ACTION *actions, int maxn, int off1end)\n{\n\tint i,j;\n\tint start;\t\t// base action index for case value and code\n\tint ccsize=0;\t\t// size of code for case value\n\tint cvsize=0;\t\t// size of case value\n\tint maxoff=0;\t\t// action offset AFTER switch\n\tint n_maxoff=0;\t\t// array index of maxoff\n\tint pend=0;\t\t// control pending output\n\tint xsize=0;\t\t// ret val\n\tint jmpsize=0;\t\t// debug helper\n\tint lastoff=0;\t\t// debug helper\n\tint n_firstactions=maxn;// array index of 1st case actions code\n\tint lastcasestart=0;\t// offs where last \"case x:\" begins\n\tchar *defa=\"[last]\";\t// debug helper for early \"default:\" \n\tchar *tmp=NULL;\t\t// helper for pending output\n\tstruct strbufinfo origbuf;\t// pending output buffer\n\tstruct _stack *StackSave;\n\tstruct SWF_ACTIONPUSHPARAM *swcopy,*sw=pop();\n\tstruct SWF_ACTIONPUSHPARAM *compare=pop();\n\tint offSave;\n\tfor (i=0; i<n_firstactions; i++) // seek last op in 1st if\n\t{\n\t\tif (actions[i+1].SWF_ACTIONRECORD.Offset==off1end)\n\t\t{\n\t\t\t// println(\"found #off end first= %d\",i+1);\n\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP)\n\t\t\t{\n\t\t\t\tmaxoff=actions[i].SWF_ACTIONJUMP.BranchOffset+actions[i].SWF_ACTIONJUMP.Offset+5;\n\t\t\t\tj=1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// SanityCheck(decompile_SWITCH,0,\"no jump found where expected\");\n\t\t\t}\n\t\t\tbreak;\n\t\t} \n\t}\n\t\n\tif (!maxoff)\n\t{\n\t\tfor (i=maxn-1;i>=0;i--)\t\t\t// seek from end of block last op of switch{}\n\t\t{\n\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP && !actions[i].SWF_ACTIONJUMP.BranchOffset)\n\t\t\t{\n\t\t\t\tmaxoff=actions[i].SWF_ACTIONRECORD.Offset+5;\n\t\t\t\tj=2;\n\t\t\t\tbreak;\n\t\t\t} \n\t\t}\n\t}", "\tfor (i=0;i<maxn;i++)\t\n\t{\n\t\tif (actions[i].SWF_ACTIONRECORD.Offset>=maxoff)\n\t\t{\n\t\t\tn_maxoff=i;\t\t// part of block is switch\n\t\t\tbreak;\n\t\t}\n\t}\n\t\t\n\tif (!n_maxoff) \n\t\tn_maxoff=maxn;\t\t\t// whole block is switch", "\tINDENT\n\tprintln(\"switch( %s ) {\t\t\t// end switch at %d (index %d) / found via meth %d)\",\n\t getString(sw), maxoff,n_maxoff,j);\n\t\t\n\tpush(sw);\n\tpush(compare);", "\ti=1;\n\tdo \t\t\t\t\t// here we go into main loop\n\t{\n\t\tif((OpCode(actions, i, maxn) == SWFACTION_IF\n\t\t && OpCode(actions, i-1, maxn) == SWFACTION_STRICTEQUALS )\n\t\t ||(OpCode(actions, i, maxn) == SWFACTION_JUMP\n\t\t && OpCode(actions, i-1, maxn) == SWFACTION_IF) )\n\t\t{\n\t\t\tstart=i;\n\t\t\twhile (start<maxn \n\t\t\t && actions[start].SWF_ACTIONRECORD.Offset < actions[i].SWF_ACTIONRECORD.Offset+5+actions[i].SWF_ACTIONJUMP.BranchOffset\n)\t\t\t{\n\t\t\t\tstart++;\t\t// count actions until start of \"case x:\"\n\t\t\t}\n\t\t\tif (n_firstactions==maxn) // if not done store earliest \"case x: \"actions\n\t\t\t{\n\t\t\t\tn_firstactions=start;\t// same as array index\n\t\t\t}", "\t\t\tfor (ccsize=0; ccsize+start<n_maxoff; ccsize++)\t// count actions belonging to \"case x:\"\n\t\t\t{\n#ifdef DEBUGSWITCH\n\t\t\t\tprintln(\"in ccsize: ccsize=%d off=%d %s\",\n\t\t\t\t ccsize,actions[ccsize+start].SWF_ACTIONRECORD.Offset,\n\t\t\t\t actionName(OpCode(actions, ccsize+start, maxn)));\n#endif\n\t\t\t\tif (OpCode(actions, ccsize+start, maxn) == SWFACTION_JUMP)\n\t\t\t\t{\n\t\t\t\t\tif (maxoff == actions[ccsize+start].SWF_ACTIONJUMP.Offset+5 + actions[ccsize+start].SWF_ACTIONJUMP.BranchOffset)\n\t\t\t\t\t{\n\t\t\t\t\t\tjmpsize= actions[ccsize+start].SWF_ACTIONJUMP.BranchOffset;\n\t\t\t\t\t\tlastoff= actions[ccsize+start].SWF_ACTIONJUMP.Offset;\n\t\t\t\t\t\tccsize++; // the jmp itself\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "#if USE_LIB\n\t\t\tif (tmp && (start!=pend)) // output pending buffer if neccessary\n\t\t\t{\n\t\t\t\tputs(tmp);\n\t\t\t}\n\t\t\t\n\t\t\tif (tmp)\n\t\t\t{\n\t\t\t\tfree(tmp);\n\t\t\t\ttmp=NULL;\n\t\t\t}\n\t\t\tpend=start;\n#endif\n\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP)\n\t\t\t{\n\t\t\t\tif (ccsize<=1)\n\t\t\t\t\tbreak;\t// ready\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tINDENT\n\t\t\t\t\tif (actions[start].SWF_ACTIONRECORD.Offset>lastcasestart)\n\t\t\t\t\t\txsize+=ccsize; \n\t\t\t\t\telse\n\t\t\t\t\t\tdefa=\"[early]\";\n\t\t\t\t\t\tprintln(\"default:\t\t\t// at %d %s start=%d ccsize=%d\",\n\t\t\t\t\t\t actions[start].SWF_ACTIONRECORD.Offset,defa, start, ccsize);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tINDENT\n\t\t\t\txsize=ccsize;\n\t\t\t\tlastcasestart=actions[start].SWF_ACTIONRECORD.Offset;\n\t\t\t\tprintln(\"case %s:\t\t\t// at %d start=%d ccsize=%d jmp=%d+%d+5\",\n\t\t\t getString(pop()), lastcasestart, start, ccsize, lastoff,jmpsize);\n\t\t\t\tswcopy=pop();\n\t\t\t\t// SanityCheck(decompile_SWITCH,!strcmp(getName(swcopy),getName(sw)),\"sw0 != sw\");\n\t\t\t}", "#if USE_LIB\n\t\t\torigbuf=setTempString(); // switch to temp buffer\n#endif\n\t\t\tStackSave=Stack;\n\t\t\toffSave=offseoloop;\n\t\t\toffseoloop=maxoff;\n\t\t\tdecompileActions( ccsize, &actions[start],gIndent+1);\n\t\t\toffseoloop=offSave;\n\t\t\tStack=StackSave;\n#if USE_LIB\n\t\t\ttmp=switchToOrigString(origbuf);\n#endif", "\t\t\tif (OpCode(actions, i, maxn) == SWFACTION_JUMP)\t\t// after \"default:\"\n\t\t\t{\n\t\t\t\tbreak; \t\t\t\t\t\t\t// ready\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (OpCode(actions, i+1, maxn) != SWFACTION_JUMP) \t// not before \"default:\" or end\n\t\t\t\t{\n\t\t\t\t\ti++; // the 'if' itself\n\t\t\t\t\tcvsize=0;\n\t\t\t\t\twhile (i+cvsize < n_firstactions \n\t\t\t\t\t && OpCode(actions, i+cvsize, maxn) != SWFACTION_STRICTEQUALS)\n\t\t\t\t\t{\n#ifdef DEBUGSWITCH\n\t\t\t\t\t\tprintln(\"in cvsize=%d %d %s\",\n\t\t\t\t\t\t cvsize, actions[i+cvsize].SWF_ACTIONRECORD.Offset,\n\t\t\t\t\t\t actionName(OpCode(actions, i+cvsize, maxn)));\n#endif\n\t\t\t\t\t\t\tcvsize++;\t// count \"case X:\" code size\n\t\t\t\t\t}\n\t\t\t\t\tdecompileActions( cvsize, &actions[i],gIndent+1); // at least one push on stack expected\n\t\t\t\t\ti+=cvsize;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} while (++i < n_firstactions);", "#if USE_LIB\n\tif (tmp)\n\t{\n\t\tputs(tmp);\t\t// print last pending output\n\t\tfree(tmp);\n\t}\n#endif\t\n\tINDENT\n\tprintln(\"}\t\t\t\t\t// switch ret value =%d\",xsize);\n\treturn xsize;\n}\n#endif", "static int\ndecompileIF(int n, SWF_ACTION *actions, int maxn)\n{\n\tint offSave;\n\tint j,i=0;\n\tstruct strbufinfo origbuf;\n\tOUT_BEGIN2(SWF_ACTIONIF);", " if (sact->numActions < 1) {\n return 0;\n }", "\t/*\n\t* IF is used in various way to implement different types\n\t* of loops. We try to detect these different types of loops\n\t* here.\n\t*/", "#ifdef STATEMENT_CLASS\n\tif((OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-2, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-3, maxn) == SWFACTION_GETVARIABLE) &&\n\t (OpCode(actions, n-4, maxn) == SWFACTION_PUSH) ) \n\t{\n\t /* It's really a class definition */\n\t\tINDENT\n\t\tputs(\"class \");\n\t\tdecompilePUSHPARAM(newVar(getName(pop())),0);\n\t\tprintln(\" {\" );\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}", "\tif( \n\t (OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-2, maxn) == SWFACTION_LOGICALNOT) &&\n\t (OpCode(actions, n-3, maxn) == SWFACTION_GETMEMBER) &&\n\t (OpCode(actions, n-4, maxn) == SWFACTION_PUSH) ) \n\t{\n\t /* It's really a class definition */\n\t\tINDENT\n\t\tprintln(\" {\");\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}\n#endif\n\t/*\n\t * do {} while() loops have a JUMP at the end of the if clause\n\t * that points to a JUMP above the IF statement.\n\t */\n\tif(n && isLogicalOp(n-1, actions, maxn) &&\n\t (sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&\n\t ( (sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.Offset +\n\t sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset) < actions[n].SWF_ACTIONRECORD.Offset) &&\n\t isLogicalOp(sact->numActions-2, sact->Actions, maxn) ) \n\t{\n\t\tINDENT\n\t\tprintln(\"do {\");\n\t\toffSave=offseoloop;\n\t\toffseoloop=actions[n].SWF_ACTIONRECORD.Offset+5;\n\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\toffseoloop=offSave;\n\t\tINDENT\n\t\tputs(\"while( \");\n\t\tputs(getName(pop()));\n\t\tputs(\");\");\n\t\treturn 0;\n\t}", "\t/* ak,2006\n\t * lots of \"do {} while()\" have simply a CONDITIONED JUMP back at the end of the loop\n\t */\n\tif( actions[n].SWF_ACTIONJUMP.BranchOffset < 0 ) \n\t{\n\t\tINDENT\n\t\tprintln(\"do { /* 2nd type */ \");\n\t\toffSave=offseoloop;\n\t\toffseoloop=actions[n ].SWF_ACTIONRECORD.Offset+5;\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\toffseoloop=offSave;\n\t\tINDENT\n\t\tputs(\"} while( \");\n\t\tputs(getName(pop()));\n\t\tprintln(\");\");\n\t\treturn 0;\n\t}", "\tj=0;\n\twhile (OpCode(actions, n-j, maxn) != SWFACTION_ENUMERATE && \n\t OpCode(actions, n-j, maxn) != SWFACTION_ENUMERATE2 && j<n && j<5) \n\t{\n\t\tj++;\t\t// check for a pending ENUMERATE\n\t}\n\t\n\tif ((OpCode(actions, n-j, maxn) == SWFACTION_ENUMERATE ||\n\t OpCode(actions, n-j, maxn) == SWFACTION_ENUMERATE2 ) && \n\t OpCode(actions, n-j+1, maxn) == SWFACTION_STOREREGISTER )\n\t{\n\t\tstruct SWF_ACTIONPUSHPARAM *var;\n\t\tint x;\n\t\tvar = pop();\n\t\tINDENT\n\t\tputs(\"for ( \");\n\t\t// check for an usual special case w register Rx\n\t\tif (sact->Actions[1].SWF_ACTIONRECORD.ActionCode == SWFACTION_STOREREGISTER)\n\t\t{\n\t\t\tstruct SWF_ACTIONSTOREREGISTER *sactv2 = (struct SWF_ACTIONSTOREREGISTER*)&sact->Actions[1];\n\t\t\tputs(\"var \");\n\t\t\tputs(getName(regs[sactv2->Register]));\n\t\t\tx=3;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdecompileActions( 2 , sact->Actions,-1); /* -1 == the ENUM workaround */\n\t\t\tx=2;\n\t\t}\n\t\tputs(\" in \");\n\t\tputs(getName(var));\n\t\tprintln(\" ) {\");\n\t\tif(n+1 >= maxn)\n\t\t{\n\t\t\tSWF_warn(\"Warning: %s:%i: something is wrong here\\n\", __FILE__, __LINE__);\n\t\t}\n\t\telse \n\t\t{\n\t\t\toffSave=offseoloop;\n\t\t\toffseoloop=actions[n+1].SWF_ACTIONRECORD.Offset;\n\t\t\tdecompileActions(sact->numActions-1-x, &sact->Actions[x],gIndent+1);\n\t\t\toffseoloop=offSave;\n\t\t}\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}", "\t/*\n\t * while() loops have a JUMP at the end of the if clause that jumps backwards\n\t * But also \"continue\" statements could jump backwards.\n\t */\n\t\n\tif( isLogicalOp(n-1, actions, maxn) &&\n\t ( (sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&\n\t sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset < 0) ) \n\t{\n\t\tif(0)\t dumpRegs();\n\t\tINDENT\n\t\t/* if on a level >0 we can check for any outer loop \n\t\t To do: get the level on a better way than using gIndent */\n\t\tif (gIndent\t\n\t\t && OpCode(actions, maxn-1, maxn) == SWFACTION_JUMP\n\t \t && actions[maxn-1].SWF_ACTIONJUMP.Offset+actions[maxn].SWF_ACTIONJUMP.BranchOffset==\n\t sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.Offset+sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset)\n\t\t{ \n\t\t /* this jump leads from a block to start of a loop on outer block:\n\t\t it is an 'if' later followed by last action 'continue' */\n\t\t SWF_warn(\"WARNING: this might be wrong (%s:%i)\\n\", __FILE__, __LINE__);\n\t\t puts(\"if ( \");\n\t\t puts(getName(pop()));\n\t\t println(\" ) {\");\n\t\t decompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t}\n\t\telse\t/* while(){} as usual */\n\t\t{\n\t\t\tputs(\"while( \");\n\t\t\tputs(getName(pop()));\n\t\t\tprintln(\" ) {\");\n\t\t\toffSave=offseoloop;\n\t\t\toffseoloop=actions[n+1].SWF_ACTIONRECORD.Offset;\n\t\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\t\toffseoloop=offSave;\n\t\t}\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\treturn 0;\n\t}\n\t{ // WTF ???\n#define SOME_IF_DEBUG 0\t/* coders only */\n\t\tint has_else_or_break= ((sact->Actions[sact->numActions-1].SWF_ACTIONRECORD.ActionCode == SWFACTION_JUMP) &&\n\t\t\t(sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset > 0 )) ? 1:0;\n\t\tint has_lognot=(OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT) ? 1:0;\n\t\tint else_action_cnt=0,is_logor=0,is_logand=0,sbi,sbe;", "\t\t/* before emitting any \"if\"/\"else\" characters let's check \n\t\t\tfor a ternary operation cond?a:b \n\t\t*/\n\t\tif (has_else_or_break)\n\t\t{\n\t\t\tint limit=actions[n+1].SWF_ACTIONRECORD.Offset + sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset;\n\t\t\t/* Count the number of action records that are part of\n\t\t\t * the else clause, and then decompile only that many.\n\t\t\t */\n\t\t\tfor(else_action_cnt=0;\n\t\t\t else_action_cnt+n+1<maxn && actions[n+1+else_action_cnt].SWF_ACTIONRECORD.Offset < limit;\n\t\t\t else_action_cnt++)\n\t\t\t{\n#if SOME_IF_DEBUG\n\t\t\t\tprintln(\"/* ELSE OP 0x%x at %d*/\", OpCode(actions, n+1+else_action_cnt, maxn),\n\t\t\t\tactions[n+1+else_action_cnt].SWF_ACTIONRECORD.Offset)\n#endif\n\t\t\t\t;\n\t\t\t} \n\t\t}\n\t\ti=else_action_cnt; \t\t// =return value\n\t\tsbi=stackVal (sact->numActions-1,sact->Actions);\n\t\tsbe=stackVal (else_action_cnt,&actions[n+1]);", "\t\t// check against opcodes we do not expect in a ternary operation\n\t\tif (sbi==1 && sbe==1)\n\t \t{\n\t\t\tfor (j=0;j<sact->numActions-1;j++)\n\t\t\t{\n\t\t\t\tif (sact->Actions[j].SWF_ACTIONRECORD.ActionCode==SWFACTION_JUMP) // perhaps more ops\n\t\t\t\t{\n\t\t\t\t\tsbi=i=has_else_or_break=0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (j=0;j<else_action_cnt;j++)\n\t\t\t{\n\t\t\t\tif (OpCode(actions, n+j, maxn) == SWFACTION_JUMP) // perhaps more ops\n\t\t\t\t{\n\t\t\t\t\tsbe=i=has_else_or_break=0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#if SOME_IF_DEBUG\n\t\tprintf(\"sbi=%d sbe=%d\\n\", sbi,sbe);\n#endif\n\t\tif (sbi==1 && sbe==1)\n\t\t{\n#if SOME_IF_DEBUG\n\t\t\tprintln(\"/* ****Found ternary ternary operation \\\"cond ? a : b\\\" **** */\");\n\t\t\tprintf(\"If Actions=%d\\n\",sact->numActions-1);\n\t\t\tprintf(\"Else Actions=%d\\n\",else_action_cnt);\n#endif\n\t\t\tstruct strbufinfo origbuf;\n#if USE_LIB\n\t\t\torigbuf=setTempString();\t/* switch to a temporary string buffer */\n#endif\n\t\t\tputs(\"(\");\n\t\t\tputs(getName(pop()));\n\t\t\tputs(\" ? \");\n\t\t\tdecompileActions(else_action_cnt , &actions[n+1],0);\n\t\t\tputs(getName(pop()));\n\t\t\tputs(\" : \");\n\t\t\tdecompileActions(sact->numActions-1, sact->Actions,0);\n\t\t\tputs(getName(pop()));\n\t\t\tputs(\")\");\n#if USE_LIB\n\t\t\tpush (newVar(dcgetstr()));\t/* push for later assignment */\n\t\t\tsetOrigString(origbuf);\t\t/* switch back to orig buffer */\n#else\n\t\t\tpush (newVar(\"/* ternary op: see code above */\"));\n#endif\n\t\t} \n\t\telse\n\t\t{\n\t\t/* at this point let's check for conditioned jumps that are NOT 'if':\n\t \tcurrently that is code for the locical operations && and ||\n\t \t*/\n\t\t\tif (OpCode(actions, n-1, maxn) == SWFACTION_PUSHDUP)\n\t\t\t\tis_logor=1;\n\t\t\t\n\t\t\tif (OpCode(actions, n-2, maxn)== SWFACTION_PUSHDUP\n\t\t\t && OpCode(actions, n-1, maxn) == SWFACTION_LOGICALNOT)\n\t\t\t{\n\t\t\t\tis_logand=1;\n\t\t\t}", "\t\tif (is_logor || is_logand) \n\t\t{\n#if SOME_IF_DEBUG\n\t\t\tprintln(\"\");\n\t\t\tprintln(\"/* detected LOGICAL %s: %d actions*/\", is_logor ? \"OR\":\"AND\",sact->numActions);\n#endif\n#if USE_LIB\n\t\t\torigbuf=setTempString();\t/* switch to a temporary string buffer */\n#endif", "\t\t\tputs(getName(pop()));\t/* get left side of logical or */\n\t\t\tputs(is_logor ? \" || \":\" && \");\n\t\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t\tputs(getName(pop()));\t/* get right side of logical or */\n#if USE_LIB\n\t\t\tpush(newVar(dcgetstr()));\n\t\t\tsetOrigString(origbuf);\t/* switch back to orig buffer */\n#else\n\t\t\tpush (newVar(\"/* see logical term lines above */\")); \n#endif\n\t\t\treturn 0;\n\t\t}\n#ifdef DECOMP_SWITCH\n\t\tif ( OpCode(actions, n-1, maxn) == SWFACTION_STRICTEQUALS\n\t\t && check_switch(sact->Actions[0].SWF_ACTIONRECORD.ActionCode) )\n\t\t{\n\t\t\tunion SWF_ACTION *xact,*xact0;\n\t\t\tfor(i=n-1,j=0; i< maxn ;i++)\t// n-1 due adding 1st SWFACTION_STRICTEQUALS in buffer\t\n\t\t\t{\n\t\t\t\tj+=countAllSwitchActions(&actions[i],&actions[i-1]); \t\t// FIRST count size of code\n\t\t\t}\n\t\t\txact0=xact = (union SWF_ACTION *) calloc (j,sizeof (SWF_ACTION));\n\t\t\tINDENT\n\t\t\tprintln(\"// checking %d actions for switch(){}\",j);\n\t\t\tfor(i=n-1; i< maxn ;i++)\n\t\t\t{\n\t\t\t\txact=getAllSwitchActions(xact,&actions[i],&actions[i-1]);\t// SECOND copy into xtra buffer\n\t\t\t}\n\t\t\tj=decompile_SWITCH(0,xact0,j,actions[n+1].SWF_ACTIONRECORD.Offset);\t// THIRD decompile xtra buffer\n\t\t\tfree(xact0);\n\t\t\treturn j;\n\t\t}\n#endif\n\t\t/* it seems we have a found the REAL 'if' statement,\n\t\tso it's right time to print the \"if\" just NOW!\n\t\t*/\n\t\tINDENT\n\t\tputs(\"if( \");\n\t\tputs(getName(pop()));\t/* the condition itself */\n\t\tprintln(\" ) {\");\n\t\tif ( has_else_or_break )\n\t\t{\n\t\t\tint limit=actions[n+1].SWF_ACTIONRECORD.Offset + sact->Actions[sact->numActions-1].SWF_ACTIONJUMP.BranchOffset;\n\t\t\t// limit == dest of jmp == offset next op after 'if' + jumpdist at end of 'if'\n\t\t\tint lastopsize=actions[maxn-1].SWF_ACTIONRECORD.Length;\n\t\t\tif (OpCode(actions, maxn-1, maxn) == SWFACTION_IF)\n\t\t\t\tlastopsize+=actions[maxn-1].SWF_ACTIONIF.BranchOffset + 3; /* +3 see parser.c: \"Action + Length bytes not included in the length\" */\n\t\t\t\n\t\t\tif (offseoloop \n\t\t\t && ! (has_lognot\n\t\t\t && OpCode(actions, n-2, maxn) == SWFACTION_EQUALS2 \n\t\t\t && OpCode(actions, n-3, maxn) == SWFACTION_PUSH\n\t\t\t && OpCode(actions, n-4, maxn) == SWFACTION_PUSHDUP)\n\t\t\t && limit > actions[maxn-1].SWF_ACTIONRECORD.Offset+lastopsize)\n\t\t\t{\n\t\t\t\t/* the jump leads outside this limit, so it is a simple 'if'\n\t\t\t\twith a 'break' or 'return' at the end, and there is NO else clause.\n\t\t\t\t*/ \n\t\t\t\tINDENT\n\t\t\t\tprintln(\"// offs_endjump_dest=%d offs_after_blk %d\",\n\t\t\t\t limit, actions[maxn-1].SWF_ACTIONRECORD.Offset+lastopsize);\n\t\t\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t\t\ti=0;\t\t\t/* found break/return but no else and thus return 0 */\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* There is an else clause also! \n\t\t\t\t(action counter is set above)\n\t\t\t\t*/\n\t\t\t\tstruct _stack *StackSave=Stack;\t/* decompile if and else blocks at same stack base */\n\t\t\t\tif (has_lognot)\n\t\t\t\t{\n\t\t\t\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\t\t\t\tINDENT\n\t\t\t\t\tprintln(\"} else {\");\n\t\t\t\t}\t \n\t\t\t\tStack=StackSave;\n\t\t\t\tdecompileActions(else_action_cnt , &actions[n+1],gIndent+1);\n\t\t\t\tif (!has_lognot)\t\t/* the missing if-part just NOW */\n\t\t\t\t{\n\t\t\t\t\tStack=StackSave;\n\t\t\t\t\tINDENT\n\t\t\t\t\tprintln (\"} else {\" );\n\t\t\t\t\tdecompileActions(sact->numActions-1, sact->Actions,gIndent+1);\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t\telse \n\t\t{\n\t\t\t/* It's a simple if() {} */\n\t\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\t\t}\n\t\tINDENT\n\t\tprintln(\"}\");\n\t} // WTF ???\n\treturn i;\n\t}\n\treturn 0;\n}", "static int\ndecompileINITOBJECT(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *nparam;\n\tnparam=pop();\n\tpush(newVar_N2(\"\",\"\",\"\",\"{\", nparam->p.Integer,\"}\"));\n\treturn 0;\n}", "static int\ndecompileWITH(int n, SWF_ACTION *actions, int maxn)\n{\n\tOUT_BEGIN2(SWF_ACTIONWITH);", "\tINDENT\n\tputs(\"with(\");\n\tdecompilePUSHPARAM(pop(),0);\n\tputs(\")\");\n\tprintln(\" {\" );\n\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n\tINDENT\n\tprintln(\"}\" );", "\treturn 1;\n}", "static int\ndecompileTRY(int n, SWF_ACTION *actions, int maxn)\n{\n#ifdef DEBUG\n\tstruct _stack *StackSave=Stack;\n#endif \n\tOUT_BEGIN2(SWF_ACTIONTRY);\n\tINDENT\n\tprintln(\"try {\");\n\tdecompileActions(sact->numTryActs, sact->TryActs,gIndent+1);\n\tINDENT\n\tprintln(\"}\");\n#ifdef DEBUG\n\tif (Stack!=StackSave)\n\t{\n\t\tprintln(\"/* Stack problem in try{} code above */\");\n\t\tStack=StackSave;\n\t}\n#endif\n\tif (sact->numCatchActs) \n\t{\n\t\tstruct SWF_ACTIONPUSHPARAM *rsave=NULL;\n\t\tINDENT\n\t\tif( ! sact->CatchInRegisterFlag)\n\t\t\tprintln(\"catch (%s) {\",sact->CatchName);\n\t\telse\n\t\t{\n\t\t\tchar *t=malloc(5); /* Rddd */\n\t\t\tsprintf(t,\"R%d\", sact->CatchRegister );\n\t\t\trsave=regs[sact->CatchRegister];\n\t\t\tregs[sact->CatchRegister] = newVar(t);\n\t\t\tprintln(\"catch (%s) {\",t);\n\t\t}\n\t\tdecompileActions(sact->numCatchActs, sact->CatchActs,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n\t\tif (rsave)\n\t\t\tregs[sact->CatchRegister]=rsave;\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in catch{} code above */\");\n\t\t\tStack=StackSave;\n\t\t}\n#endif\n\t} \n\tif (sact->numFinallyActs)\n\t{\n\t\tINDENT\n\t\tprintln(\"finally () {\");\n\t\tdecompileActions(sact->numFinallyActs, sact->FinallyActs,gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\");\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in finally{} code above */\");\n\t\t\tStack=StackSave;\n\t\t}\n#endif\n\t}\n\treturn 0;\n}", "\nstatic int\ndecompileDEFINEFUNCTION(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tint i,j,k,m,r;\n\tstruct SWF_ACTIONPUSHPARAM *myregs[ 256 ];\n\tstruct _stack *StackSave; \n\tstruct SWF_ACTIONDEFINEFUNCTION2 *sactv2;\n\tstruct strbufinfo origbuf;\n\tOUT_BEGIN2(SWF_ACTIONDEFINEFUNCTION);\n\tsactv2 = (struct SWF_ACTIONDEFINEFUNCTION2*)sact;", "#ifdef DEBUG\n\tif(n+1 < maxn)\n\t{\n\t\tprintln(\"/* function followed by OP %x */\", \n\t\t OpCode(actions, n+1, maxn));\n\t}\n#endif\n#if USE_LIB\n\tif (isStoreOp(n+1, actions,maxn) \n\t || ( *sact->FunctionName==0 && !is_type2 )\n\t || (*sactv2->FunctionName==0 && is_type2 ))\n\t{\n\t\torigbuf=setTempString();\t/* switch to a temporary string buffer */\n\t}\n#endif\n\tputs(\"function \");\n\tif (is_type2)\n\t{\n\t\tfor(j=1;j<sactv2->RegisterCount;j++) \n\t\t{\n\t\t\tmyregs[j]=regs[j];\n\t\t\tregs[j]=NULL;\n\t\t}\n\t\tr=1;\n\t\tif (sactv2->PreloadThisFlag)\tregs[r++]=newVar(\"this\");\n\t\tif (sactv2->PreloadArgumentsFlag)\tregs[r++]=newVar(\"arguments\");\n\t\tif (sactv2->PreloadSuperFlag)\tregs[r++]=newVar(\"super\");\n\t\tif (sactv2->PreloadRootFlag)\tregs[r++]=newVar(\"root\");\n\t\tif (sactv2->PreloadParentFlag)\tregs[r++]=newVar(\"parent\");\n\t\tif (sactv2->PreloadGlobalFlag)\tregs[r++]=newVar(\"global\");", "\t\tputs(sactv2->FunctionName);\n\t\tputs(\"(\");", "\t\tfor(i=0,m=0;i<sactv2->NumParams;i++) \n\t\t{\n\t\t\tputs(sactv2->Params[i].ParamName);\n\t\t\tif ( sactv2->Params[i].Register)\n\t\t\t{\n\t\t\t\t printf(\" /*=R%d*/ \",sactv2->Params[i].Register);\n\t\t\t\t regs[sactv2->Params[i].Register] = newVar(sactv2->Params[i].ParamName);\n\t\t\t\t m++;\t\t\t\t\t// do not count 'void' etc\n\t\t\t}\n\t\t\tif( sactv2->NumParams > i+1 ) puts(\",\");\n\t\t}\n\t\tprintln(\") {\" );\n\t\tif (r+m < sactv2->RegisterCount)\n\t\t{\n\t\t\tINDENT\n\t\t\tputs(\" var \");\n\t\t}\n\t\tfor(k=r;r<sactv2->RegisterCount;r++)\n\t\t{\n\t\t\tif (!regs[r])\n\t\t\t{\n\t\t\t\tchar *t=malloc(5); /* Rddd */\n\t\t\t\tsprintf(t,\"R%d\", r );\n\t\t\t\tputs (t);\n\t\t\t\tif (k++ < sactv2->RegisterCount- m -1)\n\t\t\t\t\tputs(\", \");\n\t\t\t\telse\n\t\t\t\t\tprintln(\";\" );\n\t\t\t\tregs[r]=newVar(t);\n\t\t\t}\n\t\t}\n\t\tStackSave=Stack;\n\t\tdecompileActions(sactv2->numActions, sactv2->Actions,gIndent+1);\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in function code above */\");\n\t\t}\n#endif\n\t\tStack=StackSave;\n\t\tfor(j=1;j<sactv2->RegisterCount;j++) \n\t\t\tregs[j]=myregs[j];\n\t}\n\telse\n\t{\n\t\tputs(sact->FunctionName);\n\t\tputs(\"(\");\n\t\tfor(i=0;i<sact->NumParams;i++) {\n\t\t\tputs(sact->Params[i]);\n\t\t\tif( sact->NumParams > i+1 ) puts(\",\");\n\t\t}\n\t\tprintln(\") {\" );\n\t\tk=0;\n\t\tif (sact->Actions[0].SWF_ACTIONRECORD.ActionCode == SWFACTION_PUSH)\n\t\t{\n\t\t\tstruct SWF_ACTIONPUSH *sactPush=(struct SWF_ACTIONPUSH *)sact->Actions;\n\t\t\tfor(i=0;i<sactPush->NumParam;i++)\n\t\t\t{\n\t\t\t\tif ((&(sactPush->Params[i]))->Type == PUSH_REGISTER) \n\t\t\t\t\tk++;\t/* REGISTER */\n\t\t\t}\n\t\t\tif (k)\n\t\t\t{\n\t\t\t\tINDENT\n\t\t\t\tputs(\" var \");\n\t\t\t\tfor(i=1;i<=k;i++)\n\t\t\t\t{\n\t\t\t\t\tchar *t=malloc(5); /* Rddd */\n\t\t\t\t\tsprintf(t,\"R%d\", i );\n\t\t\t\t\tputs (t);\n\t\t\t\t\tif (i < k)\n\t\t\t\t\t\tputs(\", \");\n\t\t\t\t\telse\n\t\t\t\t\t\tprintln(\";\" );\n\t\t\t\t\tregs[i]=newVar(t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(j=1;j<=k;j++) \n\t\t\tmyregs[j]=regs[j];\n\t\tStackSave=Stack;\n\t\tdecompileActions(sact->numActions, sact->Actions,gIndent+1);\n#ifdef DEBUG\n\t\tif (Stack!=StackSave)\n\t\t{\n\t\t\tprintln(\"/* Stack problem in function code above */\");\n\t\t}\n#endif\n\t\tStack=StackSave;\n\t\tfor(j=1;j<=k;j++) \n\t\t\tregs[j]=myregs[j];\n\t}\n\tINDENT\n\tif (isStoreOp(n+1, actions,maxn) \n\t || ( *sact->FunctionName==0 && !is_type2 )\n\t || (*sactv2->FunctionName==0 && is_type2 ))\n\t{\n\t\tputs(\"}\");\n#if USE_LIB\n\t\tpush (newVar(dcgetstr()));\t/* push func body for later assignment */\n\t\tsetOrigString(origbuf);\t\t/* switch back to orig buffer */\n#else\n\t\tpush (newVar(\"/* see function code above */\"));\t/* workaround only if LIB is not in use */\n#endif\n\t}\n\telse\n\t\tprintln(\"}\" );\n\treturn 0;\n}", "static int\ndecompileCALLMETHOD(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *meth, *obj, *nparam;\n\tmeth=pop();\n\tobj=pop();\n\tnparam=pop();\n\tif (nparam->p.Integer>25)\n\t{\n\t\tINDENT\n\t\tprintln(\"// Problem getting method arguments (%d ignored) below:\",\n\t\t nparam->p.Integer);\n\t\tnparam->p.Integer=0;\n\t}\n#ifdef DEBUG\n\tprintf(\"*CALLMethod* objName=%s (type=%d) methName=%s (type=%d)\\n\",\n\t\tgetName(obj), obj->Type, getName(meth), meth->Type);\n#endif\n\tif (meth->Type == PUSH_UNDEF) \t/* just undefined, like in \"super();\" */\n\t\tpush(newVar_N(getName(obj),\"\",\"\",\"(\", nparam->p.Integer,\")\"));\n\telse\n\t{\n\t\tif (meth->Type == PUSH_INT || meth->Type == PUSH_DOUBLE || meth->Type == PUSH_VARIABLE\n\t\t || meth->Type == PUSH_REGISTER || meth->Type == 12 )\n\t\t{\n\t\t\tpush(newVar_N(getName(obj),\"[\",getName(meth),\"](\", nparam->p.Integer,\")\"));\n\t\t}\n\t\telse\n\t\t\tpush(newVar_N(getName(obj),\".\",getName(meth),\"(\", nparam->p.Integer,\")\"));\n\t}\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call method and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileCALLFUNCTION(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *meth, *nparam;", "\tSanityCheck(SWF_CALLMETHOD, OpCode(actions, n-1, maxn) == SWFACTION_PUSH,\n\t\t\"CALLMETHOD not preceeded by PUSH\")", "\tmeth=pop();\n\tnparam=pop();\n\tif (nparam->p.Integer>25)\n\t{\n\t\tINDENT\n\t\tprintln(\"// Problem getting function arguments (%d ignored) below:\",\n\t\t\tnparam->p.Integer);\n\t\tnparam->p.Integer=0;\n\t}\n\tpush(newVar_N(\"\",\"\",getName(meth),\"(\", nparam->p.Integer,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompile_Null_ArgBuiltInFunctionCall(int n, SWF_ACTION *actions, int maxn, char *functionname)\n{\n\tINDENT\n\tputs(functionname);\t\t// only used for cases w/o return value\n\tprintln(\"();\" );\n\treturn 0;\n}", "static int\ndecompileSingleArgBuiltInFunctionCall(int n, SWF_ACTION *actions, int maxn, char *functionname)\n{\n\tpush(newVar_N(\"\",\"\",functionname,\"(\", 1,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileSTARTDRAG(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"startDrag(\");\n\tdecompilePUSHPARAM(pop(),1);\n\tputs(\",\");\n\tdecompilePUSHPARAM(pop(),0);\n\tputs(\",\");\n\tdecompilePUSHPARAM(pop(),0);\t//\n\tprintln(\");\" );\n\treturn 0;\n}", "static int\ndecompileSUBSTRING(int n, SWF_ACTION *actions,int maxn)\n{\n\tpush(newVar_N(\"\",\"\",\"substr\",\"(\", 3,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileSTRINGCONCAT(int n, SWF_ACTION *actions, int maxn)\n{\n\tpush(newVar_N(\"\",\"\",\"concat\",\"(\", 2,\")\"));\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call function and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileTHROW(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"throw \");\n\tputs(getName(pop()));\n\tprintln(\";\");\n\treturn 0;\n}", "static int\ndecompileREMOVECLIP(int n, SWF_ACTION *actions, int maxn)\n{\n\tINDENT\n\tputs(\"removeMovieClip(\");\n\tputs(getName(pop()));\n\tprintln(\");\" );\n\treturn 0;\n}", "static int \ndecompileDUPLICATECLIP(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *a, *b;", "\tINDENT\n\ta = pop();\n\tb = pop();", "\tputs(\"duplicateMovieClip(\");\n\tputs(getString(pop()));\n\tputs(\",\");\n\tputs(getString(b));\n\tputs(\",\");\n\tputs(getString(a));\n\tprintln(\");\" );\n\treturn 0;\n}", "static int\ndecompileINITARRAY(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *nparam;\n\tnparam=pop();\n\tpush(newVar_N(\"\",\"\",\"\",\"[\", nparam->p.Integer,\"]\"));\n\treturn 0;\n}", "static int\ndecompileEXTENDS(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *baseclass;", "\tbaseclass=pop();\n#if 0\n\t/* It's useless to open a class body when there's no\n\t * other code supporting it. */\n\tprintf(\"class \");\n\tputs(getName(pop()));\n\tprintf(\" extends \");\n\tputs(getName(baseclass));\n\tprintln(\" {\" );\n#else\n\t/* We'll do it with asm{} */\n\tprintln(\"asm {\");\n\tprintln(\" push '%s'\", getName(pop()));\n\tprintln(\" getvariable\");\n\tprintln(\" push '%s'\", getName(baseclass));\n\tprintln(\" getvariable\");\n\tprintln(\" extends\");\n\tprintln(\"};\");\n#endif", "\treturn 0;\n}", "static int\ndecompileDELETE(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tif (is_type2)\n\t\tpush(newVar3(\"delete(\",getName(pop()),\")\"));\n\telse\n\t\tpush(newVar_N(\"delete(\",getName(pop()),\".\",getName(pop()), 0,\")\"));", "\n\tif (OpCode(actions, n+1, maxn) == SWFACTION_POP)\n\t{\n\t\t/* call delete() with its args and throw away any result */\n\t\tINDENT\n\t\tputs(getName(pop()));\n\t\tprintln(\";\" );\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static int\ndecompileSETTARGET(int n, SWF_ACTION *actions, int maxn, int is_type2)\n{\n\tint action_cnt=0;\n\tchar *name;\n\tOUT_BEGIN2(SWF_ACTIONSETTARGET);\n\tname = is_type2 ? getString(pop()) : sact->TargetName;\n\tif (*name)\n\t{\n\t\tINDENT\n\t\tprintln(\"tellTarget('%s') {\" ,name);\n\t\twhile(action_cnt+n<maxn)\n\t\t{\n\t\t\tif (OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_SETTARGET\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_SETTARGET2\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_DEFINEFUNCTION\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_DEFINEFUNCTION2\n\t\t\t || OpCode(actions, n+1+action_cnt, maxn)==SWFACTION_END) \n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\taction_cnt++;\n\t\t}\n\t\tdecompileActions(action_cnt,&actions[n+1],gIndent+1);\n\t\tINDENT\n\t\tprintln(\"}\" );\n\t}\n\treturn action_cnt;\n}", "static int\ndecompileIMPLEMENTS(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *nparam;\n\tint i;\n\tINDENT;\n\tputs(getName(pop()));\n\tprintf(\" implements \");\n\tnparam=pop();\n\tfor(i=0;i<nparam->p.Integer;i++) \n\t{\n\t\tputs(getName(pop()));\n\t}\n\tprintln(\" ;\");\n\treturn 0;\n}", "static int\ndecompileCAST(int n, SWF_ACTION *actions, int maxn)\n{\n\tstruct SWF_ACTIONPUSHPARAM *iparam=pop();\n\tstruct SWF_ACTIONPUSHPARAM *tparam=pop();\n\tpush(newVar_N( getName(tparam),\"(\",getName(iparam),\"\", 0,\")\")); \n\treturn 0;\n}", "int\ndecompileAction(int n, SWF_ACTION *actions, int maxn)\n{", "", "\n#ifdef DEBUG\n\tfprintf(stderr,\"%d:\\tACTION[%3.3d]: %s\\n\",\n\t actions[n].SWF_ACTIONRECORD.Offset, n, \n\t actionName(actions[n].SWF_ACTIONRECORD.ActionCode));\n#endif\n", "\tswitch(OpCode(actions, n, maxn))", "\t{\n\tcase SWFACTION_END:\n\t\treturn 0;", "\tcase SWFACTION_CONSTANTPOOL:\n\t\tdecompileCONSTANTPOOL(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_GOTOLABEL:\n\t\treturn decompileGOTOFRAME(n, actions, maxn,1);", "\tcase SWFACTION_GOTOFRAME:\n\t\treturn decompileGOTOFRAME(n, actions, maxn,0);", "\tcase SWFACTION_GOTOFRAME2:\n\t\treturn decompileGOTOFRAME2(n, actions, maxn);", "\tcase SWFACTION_WAITFORFRAME:\n\t\tdecompileWAITFORFRAME(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_GETURL2:\n\t\tdecompileGETURL2(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_GETURL:\n\t\tdecompileGETURL(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_PUSH:\n\t\tdecompilePUSH(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_PUSHDUP:\n\t\tdecompilePUSHDUP(&actions[n]);\n\t\treturn 0;", "\tcase SWFACTION_STACKSWAP:\n\t\tdecompileSTACKSWAP(&actions[n]);\t\n\t\treturn 0;", "\tcase SWFACTION_SETPROPERTY:\n\t\tdecompileSETPROPERTY(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETPROPERTY:\n\t\tdecompileGETPROPERTY(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETTIME:\n\t\treturn decompileGETTIME(n, actions, maxn);", "\tcase SWFACTION_TRACE:\n\t\tdecompileTRACE(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_CALLFRAME:\n\t\tdecompileCALLFRAME(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_EXTENDS:\n\t\tdecompileEXTENDS(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_INITOBJECT:\n\t\tdecompileINITOBJECT(n, actions, maxn);\n\t\treturn 0;\t ", "\tcase SWFACTION_NEWOBJECT:\n\t\tdecompileNEWOBJECT(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_NEWMETHOD:\n\t\tdecompileNEWMETHOD(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETMEMBER:\n\t\tdecompileGETMEMBER(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_SETMEMBER:\n\t\tdecompileSETMEMBER(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_GETVARIABLE:\n\t\tdecompileGETVARIABLE(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_SETVARIABLE:\n\t\tdecompileSETVARIABLE(n, actions, maxn, 0);\n\t\treturn 0;", "\tcase SWFACTION_DEFINELOCAL:\n\t\tdecompileSETVARIABLE(n, actions, maxn, 1);\n\t\treturn 0;", "\tcase SWFACTION_DEFINELOCAL2:\n\t\tdecompileDEFINELOCAL2(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_DECREMENT:\n\t\treturn decompileINCR_DECR(n, actions, maxn, 0);", "\tcase SWFACTION_INCREMENT:\n\t\treturn decompileINCR_DECR(n, actions, maxn,1);", "\tcase SWFACTION_STOREREGISTER:\n\t\tdecompileSTOREREGISTER(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_JUMP:\n\t\treturn decompileJUMP(n, actions, maxn);", "\tcase SWFACTION_RETURN:\n\t\tdecompileRETURN(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_LOGICALNOT:\n\t\treturn decompileLogicalNot(n, actions, maxn);", "\tcase SWFACTION_IF:\n\t\treturn decompileIF(n, actions, maxn);", "\tcase SWFACTION_WITH:\n\t\tdecompileWITH(n, actions, maxn);\n\t\treturn 0;", "\tcase SWFACTION_ENUMERATE:\n\t\treturn decompileENUMERATE(n, actions, maxn, 0);", "\tcase SWFACTION_ENUMERATE2 :\n\t\treturn decompileENUMERATE(n, actions, maxn,1);", "\tcase SWFACTION_INITARRAY:\n\t\treturn decompileINITARRAY(n, actions, maxn);", "\tcase SWFACTION_DEFINEFUNCTION:\t\n\t\treturn decompileDEFINEFUNCTION(n, actions, maxn,0);", "\tcase SWFACTION_DEFINEFUNCTION2:\n\t\treturn decompileDEFINEFUNCTION(n, actions, maxn,1);", "\tcase SWFACTION_CALLFUNCTION:\n\t\treturn decompileCALLFUNCTION(n, actions, maxn);", "\tcase SWFACTION_CALLMETHOD:\n\t\treturn decompileCALLMETHOD(n, actions, maxn);", "\tcase SWFACTION_INSTANCEOF:\n\tcase SWFACTION_SHIFTLEFT:\n\tcase SWFACTION_SHIFTRIGHT:\n\tcase SWFACTION_SHIFTRIGHT2: \n\tcase SWFACTION_ADD:\n\tcase SWFACTION_ADD2:\n\tcase SWFACTION_SUBTRACT:\n\tcase SWFACTION_MULTIPLY:\n\tcase SWFACTION_DIVIDE:\n\tcase SWFACTION_MODULO:\n\tcase SWFACTION_BITWISEAND:\n\tcase SWFACTION_BITWISEOR:\n\tcase SWFACTION_BITWISEXOR:\n\tcase SWFACTION_EQUAL:\n\tcase SWFACTION_EQUALS2:\n\tcase SWFACTION_LESS2:\n\tcase SWFACTION_LOGICALAND:\n\tcase SWFACTION_LOGICALOR:\n\tcase SWFACTION_GREATER:\n\tcase SWFACTION_LESSTHAN:\n\tcase SWFACTION_STRINGEQ:\n\tcase SWFACTION_STRINGCOMPARE:\n\tcase SWFACTION_STRICTEQUALS:\n\t\treturn decompileArithmeticOp(n, actions, maxn);", "\tcase SWFACTION_POP:\n\t\tpop();\n\t\treturn 0;", "\tcase SWFACTION_STARTDRAG:\n\t\treturn decompileSTARTDRAG(n, actions, maxn);", "\tcase SWFACTION_DELETE:\n\t\treturn decompileDELETE(n, actions, maxn,0);", "\tcase SWFACTION_DELETE2:\n\t\treturn decompileDELETE(n, actions, maxn,1);", "\tcase SWFACTION_TARGETPATH:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"targetPath\");", "\tcase SWFACTION_TYPEOF:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"typeof\");", "\tcase SWFACTION_ORD:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"ord\");", "\tcase SWFACTION_CHR:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"chr\");", "\tcase SWFACTION_INT:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"int\");", "\tcase SWFACTION_TOSTRING:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"String\"); ", "\tcase SWFACTION_TONUMBER:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"Number\");", "\tcase SWFACTION_RANDOMNUMBER:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"random\");", "\tcase SWFACTION_STRINGLENGTH:\n\t\treturn decompileSingleArgBuiltInFunctionCall(n, actions, maxn,\"length\");", "\tcase SWFACTION_PLAY:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"play\");", "\tcase SWFACTION_STOP:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"stop\");", "\tcase SWFACTION_NEXTFRAME:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"nextFrame\");", "\tcase SWFACTION_PREVFRAME:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"prevFrame\");", "\tcase SWFACTION_ENDDRAG:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"stopDrag\");", "\tcase SWFACTION_STOPSOUNDS:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"stopAllSounds\"); ", "\tcase SWFACTION_TOGGLEQUALITY:\n\t\treturn decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,\"toggleHighQuality\"); ", "\tcase SWFACTION_MBSUBSTRING:\n\tcase SWFACTION_SUBSTRING:\n\t\treturn decompileSUBSTRING(n, actions, maxn);", "\tcase SWFACTION_STRINGCONCAT:\n\t\treturn decompileSTRINGCONCAT(n, actions, maxn);", "\tcase SWFACTION_REMOVECLIP:\n\t\treturn decompileREMOVECLIP(n, actions, maxn);", "\tcase SWFACTION_DUPLICATECLIP:\n\t\treturn decompileDUPLICATECLIP(n, actions, maxn);", "\tcase SWFACTION_SETTARGET:\n\t\treturn decompileSETTARGET(n, actions, maxn,0);", "\tcase SWFACTION_SETTARGET2:\n\t\treturn decompileSETTARGET(n, actions, maxn,1);", "\tcase SWFACTION_IMPLEMENTSOP:\n\t\treturn decompileIMPLEMENTS(n, actions, maxn);", "\tcase SWFACTION_CASTOP:\n\t\treturn decompileCAST(n, actions, maxn);", "\tcase SWFACTION_THROW:\n\t\treturn decompileTHROW(n, actions, maxn);", "\tcase SWFACTION_TRY:\n\t\treturn decompileTRY(n, actions, maxn);", "\tdefault:\n\t\toutputSWF_ACTION(n,&actions[n]);\n\t\treturn 0;\n\t}\n}", "static void\ndecompileActions(int n, SWF_ACTION *actions, int indent)\n{\n\tint i, svindent;", "\tsvindent = gIndent;\n\tgIndent = indent;\n\t\n\tfor(i=0;i<n;i++) {\n\t\ti+=decompileAction(i, actions, n);\n\t}\n\tgIndent = svindent;\n}", "char *\ndecompile5Action(int n, SWF_ACTION *actions,int indent)\n{\n\tint j;\n\tif( !n )\n\t\treturn NULL;", "\tpool = NULL;\n\tpoolcounter = 0;", "\tdcinit();", "\tfor(j=0;j<256;j++) regs[j]=0;\n\tregs[1] = newVar(\"R1\");\n\tregs[2] = newVar(\"R2\");\n\tregs[3] = newVar(\"R3\");\n\tregs[4] = newVar(\"R4\");", "\tdecompileActions(n, actions, indent);\n#ifdef DEBUGSTACK\n\tif( Stack != NULL && *dcstr) \n\t{ \n\t\tint i=0;\n\t\tprintln(\"/* -----------------------------------------------------------------\");\n\t\tprintln(\"NOTE: some stuff left on the stack at the end of a block of actions:\");\n\t\twhile (Stack)\n\t\t{\n\t\t\ti++;\n\t\t\tprintf(\"%d.:\\t%s\",i, getString(pop()));\n\t\t\tprintln(\"\");\n\t\t}\n\t\tprintln(\"*/\");\n\t}\n#else\n\tif( Stack != NULL ) \n\t\tfprintf(stderr,\n\t\t\"Stuff left on the stack at the end of a block of actions!?!?!?\\n\");\n\twhile (Stack)\n\t{\n\t\tpop();\n\t}\n#endif\n\treturn dcgetstr();\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [3214], "buggy_code_start_loc": [3205], "filenames": ["util/decompile.c"], "fixing_code_end_loc": [3213], "fixing_code_start_loc": [3204], "message": "Ming (aka libming) 0.4.8 has a heap buffer overflow and underflow in the decompileCAST function in util/decompile.c in libutil.a. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted SWF file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:libming:libming:0.4.8:*:*:*:*:*:*:*", "matchCriteriaId": "DD92BC79-2548-4C6F-9BDD-26C12BDF68AC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ming (aka libming) 0.4.8 has a heap buffer overflow and underflow in the decompileCAST function in util/decompile.c in libutil.a. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted SWF file."}, {"lang": "es", "value": "Ming (aka libming) versi\u00f3n 0.4.8 tiene un desbordamiento y subdesbordamiento de b\u00fafer de mont\u00f3n en la funci\u00f3n decompileCAST en util/decompile.c en libutil.a. Los atacantes remotos podr\u00edan aprovechar esta vulnerabilidad para provocar una denegaci\u00f3n de servicio a trav\u00e9s de un archivo SWF dise\u00f1ado."}], "evaluatorComment": null, "id": "CVE-2019-12982", "lastModified": "2020-10-14T17:27:46.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-06-26T18:15:10.587", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/libming/libming/commit/da9d86eab55cbf608d5c916b8b690f5b76bca462"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/libming/libming/commit/da9d86eab55cbf608d5c916b8b690f5b76bca462"}, "type": "CWE-119"}
302
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Quicktime Video (RPZA) Video Decoder\n * Copyright (C) 2003 the ffmpeg project\n *\n * This file is part of FFmpeg.\n *\n * FFmpeg is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * FFmpeg is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n */", "/**\n * @file\n * QT RPZA Video Decoder by Roberto Togni\n * For more information about the RPZA format, visit:\n * http://www.pcisys.net/~melanson/codecs/\n *\n * The RPZA decoder outputs RGB555 colorspace data.\n *\n * Note that this decoder reads big endian RGB555 pixel values from the\n * bytestream, arranges them in the host's endian order, and outputs\n * them to the final rendered map in the same host endian order. This is\n * intended behavior as the libavcodec documentation states that RGB555\n * pixels shall be stored in native CPU endianness.\n */", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>", "#include \"libavutil/internal.h\"\n#include \"libavutil/intreadwrite.h\"\n#include \"avcodec.h\"\n#include \"internal.h\"", "typedef struct RpzaContext {", " AVCodecContext *avctx;\n AVFrame frame;", " const unsigned char *buf;\n int size;", "} RpzaContext;", "#define ADVANCE_BLOCK() \\\n{ \\\n pixel_ptr += 4; \\\n if (pixel_ptr >= width) \\\n { \\\n pixel_ptr = 0; \\\n row_ptr += stride * 4; \\\n } \\\n total_blocks--; \\\n if (total_blocks < 0) \\\n { \\\n av_log(s->avctx, AV_LOG_ERROR, \"warning: block counter just went negative (this should not happen)\\n\"); \\\n return; \\\n } \\\n}", "static void rpza_decode_stream(RpzaContext *s)\n{\n int width = s->avctx->width;\n int stride = s->frame.linesize[0] / 2;\n int row_inc = stride - 4;\n int stream_ptr = 0;\n int chunk_size;\n unsigned char opcode;\n int n_blocks;\n unsigned short colorA = 0, colorB;\n unsigned short color4[4];\n unsigned char index, idx;\n unsigned short ta, tb;\n unsigned short *pixels = (unsigned short *)s->frame.data[0];", " int row_ptr = 0;", " int pixel_ptr = 0;", " int block_ptr;\n int pixel_x, pixel_y;\n int total_blocks;", " /* First byte is always 0xe1. Warn if it's different */\n if (s->buf[stream_ptr] != 0xe1)\n av_log(s->avctx, AV_LOG_ERROR, \"First chunk byte is 0x%02x instead of 0xe1\\n\",\n s->buf[stream_ptr]);", " /* Get chunk size, ingnoring first byte */\n chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;\n stream_ptr += 4;", " /* If length mismatch use size from MOV file and try to decode anyway */\n if (chunk_size != s->size)\n av_log(s->avctx, AV_LOG_ERROR, \"MOV chunk size != encoded chunk size; using MOV chunk size\\n\");", " chunk_size = s->size;", " /* Number of 4x4 blocks in frame. */\n total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);", " /* Process chunk data */\n while (stream_ptr < chunk_size) {\n opcode = s->buf[stream_ptr++]; /* Get opcode */", " n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */", " /* If opcode MSbit is 0, we need more data to decide what to do */\n if ((opcode & 0x80) == 0) {\n colorA = (opcode << 8) | (s->buf[stream_ptr++]);\n opcode = 0;\n if ((s->buf[stream_ptr] & 0x80) != 0) {\n /* Must behave as opcode 110xxxxx, using colorA computed\n * above. Use fake opcode 0x20 to enter switch block at\n * the right place */\n opcode = 0x20;\n n_blocks = 1;\n }\n }", " switch (opcode & 0xe0) {", " /* Skip blocks */\n case 0x80:\n while (n_blocks--) {\n ADVANCE_BLOCK();\n }\n break;", " /* Fill blocks with one color */\n case 0xa0:\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;\n while (n_blocks--) {", "", " block_ptr = row_ptr + pixel_ptr;\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n pixels[block_ptr] = colorA;\n block_ptr++;\n }\n block_ptr += row_inc;\n }", " ADVANCE_BLOCK();", " }\n break;", " /* Fill blocks with 4 colors */\n case 0xc0:\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;\n case 0x20:\n colorB = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;", " /* sort out the colors */\n color4[0] = colorB;\n color4[1] = 0;\n color4[2] = 0;\n color4[3] = colorA;", " /* red components */\n ta = (colorA >> 10) & 0x1F;\n tb = (colorB >> 10) & 0x1F;\n color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;\n color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;", " /* green components */\n ta = (colorA >> 5) & 0x1F;\n tb = (colorB >> 5) & 0x1F;\n color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;\n color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;", " /* blue components */\n ta = colorA & 0x1F;\n tb = colorB & 0x1F;\n color4[1] |= ((11 * ta + 21 * tb) >> 5);\n color4[2] |= ((21 * ta + 11 * tb) >> 5);", " if (s->size - stream_ptr < n_blocks * 4)\n return;\n while (n_blocks--) {", "", " block_ptr = row_ptr + pixel_ptr;\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n index = s->buf[stream_ptr++];\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n idx = (index >> (2 * (3 - pixel_x))) & 0x03;\n pixels[block_ptr] = color4[idx];\n block_ptr++;\n }\n block_ptr += row_inc;\n }", " ADVANCE_BLOCK();", " }\n break;", " /* Fill block with 16 colors */\n case 0x00:\n if (s->size - stream_ptr < 16)\n return;", "", " block_ptr = row_ptr + pixel_ptr;\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n /* We already have color of upper left pixel */\n if ((pixel_y != 0) || (pixel_x !=0)) {\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;\n }\n pixels[block_ptr] = colorA;\n block_ptr++;\n }\n block_ptr += row_inc;\n }", " ADVANCE_BLOCK();", " break;", " /* Unknown opcode */\n default:\n av_log(s->avctx, AV_LOG_ERROR, \"Unknown opcode %d in rpza chunk.\"\n \" Skip remaining %d bytes of chunk data.\\n\", opcode,\n chunk_size - stream_ptr);\n return;\n } /* Opcode switch */\n }\n}", "static av_cold int rpza_decode_init(AVCodecContext *avctx)\n{\n RpzaContext *s = avctx->priv_data;", " s->avctx = avctx;\n avctx->pix_fmt = AV_PIX_FMT_RGB555;", " avcodec_get_frame_defaults(&s->frame);", " return 0;\n}", "static int rpza_decode_frame(AVCodecContext *avctx,\n void *data, int *got_frame,\n AVPacket *avpkt)\n{\n const uint8_t *buf = avpkt->data;\n int buf_size = avpkt->size;\n RpzaContext *s = avctx->priv_data;\n int ret;", " s->buf = buf;\n s->size = buf_size;", " if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0)\n return ret;", " rpza_decode_stream(s);", " if ((ret = av_frame_ref(data, &s->frame)) < 0)\n return ret;", " *got_frame = 1;", " /* always report that the buffer was completely consumed */\n return buf_size;\n}", "static av_cold int rpza_decode_end(AVCodecContext *avctx)\n{\n RpzaContext *s = avctx->priv_data;", " av_frame_unref(&s->frame);", " return 0;\n}", "AVCodec ff_rpza_decoder = {\n .name = \"rpza\",\n .type = AVMEDIA_TYPE_VIDEO,\n .id = AV_CODEC_ID_RPZA,\n .priv_data_size = sizeof(RpzaContext),\n .init = rpza_decode_init,\n .close = rpza_decode_end,\n .decode = rpza_decode_frame,\n .capabilities = CODEC_CAP_DR1,\n .long_name = NULL_IF_CONFIG_SMALL(\"QuickTime video (RPZA)\"),\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [223], "buggy_code_start_loc": [88], "filenames": ["libavcodec/rpza.c"], "fixing_code_end_loc": [222], "fixing_code_start_loc": [88], "message": "The rpza_decode_stream function in libavcodec/rpza.c in FFmpeg before 2.1 does not properly maintain a pointer to pixel data, which allows remote attackers to cause a denial of service (out-of-bounds array access) or possibly have unspecified other impact via crafted Apple RPZA data.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:*:*:*:*:*:*:*:*", "matchCriteriaId": "C41A1983-BA74-4806-A227-EBBF7989112C", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3:*:*:*:*:*:*:*", "matchCriteriaId": "B2649A80-4739-4BBB-AB0B-99AD435BE7CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "D4A2E77D-B826-4B49-ADC8-7F704E149A5A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "18157837-4550-45E3-A12E-AE06E047E253", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "E9F42611-C3E2-416B-9AE7-A5AE83E4DEF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "3A20789F-26E3-4871-B24E-25E922BADDF0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "67C6C243-3ACC-49C3-80CA-D7CA8FEFF0D8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "6AE6D368-0BA6-4499-B7E1-EE16C03012E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "26C0F6EF-0452-4AFE-AF3E-B88F963A0938", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "5B4DD372-4D3B-445C-8C38-E083A3C0D4A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "733C03D7-2780-4D69-A98D-BCFB91D1119A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "0AEE1977-E9E0-4BFF-B33B-B083E49E51F1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E6979C17-0BC6-47D1-9B73-254D84306A96", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.8:*:*:*:*:*:*:*", "matchCriteriaId": "204C7C05-3441-4DB0-8702-D99C8FCB381E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.9:pre1:*:*:*:*:*:*", "matchCriteriaId": "2E1A7011-B992-4E35-B306-45772DACB23C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5:*:*:*:*:*:*:*", "matchCriteriaId": "8D486C17-FC4A-4AEE-A430-1B1FBCC2C27C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.1:*:*:*:*:*:*:*", "matchCriteriaId": "632BC7C2-FE59-47B0-885C-0EB8C74DF041", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.2:*:*:*:*:*:*:*", "matchCriteriaId": "5D1AE0BF-A6FD-4EBA-BF61-07AC81EA560D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "5B8FA106-FE65-4BB0-92A7-E8A5AF978A9B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "514669DA-8D02-44CE-BE18-8783F69AE394", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "8041E6ED-472A-40DF-AA90-F3509D90D47A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "D2C64382-9259-4D61-B352-7F123527289C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.5:*:*:*:*:*:*:*", "matchCriteriaId": "32A152D9-947E-4198-9C2D-2A582F09AB75", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6:*:*:*:*:*:*:*", "matchCriteriaId": "37FBB817-A186-4517-9DA7-B3638576AAE7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "157ABA40-6101-4E9C-A24C-84F8E23D374D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "C7EA46DD-2CC4-426F-8709-821B7572C94A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6.3:*:*:*:*:*:*:*", "matchCriteriaId": "3DE12C59-4409-4F7A-9759-7B26FA9DAC34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7:*:*:*:*:*:*:*", "matchCriteriaId": "30FE6578-F031-4F5B-B955-8F912CFCA1B0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.1:*:*:*:*:*:*:*", "matchCriteriaId": "07669E0E-8C4B-430E-802F-F64EEA2B5A0B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.2:*:*:*:*:*:*:*", "matchCriteriaId": "F3EB7F17-F25D-4E48-8A43-F799619CE71F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.3:*:*:*:*:*:*:*", "matchCriteriaId": "60705A3B-7136-45D1-8068-E2DC9E01EB04", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.4:*:*:*:*:*:*:*", "matchCriteriaId": "C722B143-2648-4EB2-A090-7B788F41F300", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.5:*:*:*:*:*:*:*", "matchCriteriaId": "B31AFDBC-A782-4C18-8EAA-6D927397BEA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.6:*:*:*:*:*:*:*", "matchCriteriaId": "73E9E8F4-A942-4F34-BCE2-82A180F1DD1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.7:*:*:*:*:*:*:*", "matchCriteriaId": "AAA31D75-C3FB-4D89-8B2D-21372AAEB78B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.8:*:*:*:*:*:*:*", "matchCriteriaId": "B20E5358-826C-47A2-B39F-ED4E9213BA95", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.9:*:*:*:*:*:*:*", "matchCriteriaId": "26321888-E140-4F09-AAA0-7392AA7F6307", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.11:*:*:*:*:*:*:*", "matchCriteriaId": "7E46B9F3-A9C0-4B8A-A119-40CA4CBBD0EE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.12:*:*:*:*:*:*:*", "matchCriteriaId": "44800572-71C5-4AA1-9CB6-30AA902B0353", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.0:*:*:*:*:*:*:*", "matchCriteriaId": "87090477-1D36-48B3-88AE-5CD5EE8F89D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.1:*:*:*:*:*:*:*", "matchCriteriaId": "2096FF8B-9B57-4C59-84DB-9CC0DEAB47AC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.2:*:*:*:*:*:*:*", "matchCriteriaId": "34C99254-776C-4AAD-BDA2-3F544256AA67", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.5:*:*:*:*:*:*:*", "matchCriteriaId": "CE9D7B73-9CDA-4BAE-8DD9-8E1E34C20648", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "4FDBF2C0-8E33-4575-8A19-4F1CABA3023F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "72040664-077A-48FB-9E6B-B69EA8D26CB4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.6:*:*:*:*:*:*:*", "matchCriteriaId": "F428A2E4-A54F-4296-A00F-1A4E160253D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.7:*:*:*:*:*:*:*", "matchCriteriaId": "5239E4FA-0359-49F1-93D4-24AB013FAC20", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.8:*:*:*:*:*:*:*", "matchCriteriaId": "F0C8230D-4E89-45F9-B0F7-E317119E0FA0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.10:*:*:*:*:*:*:*", "matchCriteriaId": "585CE7D2-1CE8-44AB-AE67-07D7D3721F68", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.11:*:*:*:*:*:*:*", "matchCriteriaId": "EE81C339-A794-4303-B829-BE743DF0B132", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.9:*:*:*:*:*:*:*", "matchCriteriaId": "5CE0A27B-66D7-4D1B-8E6A-F4722C070BD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.9.1:*:*:*:*:*:*:*", "matchCriteriaId": "864DC4A2-A378-4389-B62E-9E785879A744", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.10:*:*:*:*:*:*:*", "matchCriteriaId": "16304267-C808-4B6B-9903-2DEAB40AD899", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.10.3:*:*:*:*:*:*:*", "matchCriteriaId": "CEEBBA83-1BFC-45A8-B34A-AB3A9B8A9414", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.10.4:*:*:*:*:*:*:*", "matchCriteriaId": "F559B34E-23EE-4E09-A044-E7F54C55B05E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.11:*:*:*:*:*:*:*", "matchCriteriaId": "62BA2708-BE77-42B7-B51A-C1B58632462C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.0:*:*:*:*:*:*:*", "matchCriteriaId": "23E57BB1-DF1E-4173-BE52-72E2B3E6BA23", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "A3E30DB1-0CFC-4EAA-BF07-CE7551ABDCB5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "DBA7D745-DC16-43B9-8A2D-4D6944A6BFD0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "87A511A5-2040-433A-9B32-B89332214FA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "0C01DD9C-98C9-4896-8D66-A8336582298B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.2:*:*:*:*:*:*:*", "matchCriteriaId": "BBE7723A-3D6B-4390-B82E-6A5A6992141A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "1ED8FF93-5AA7-443C-BBDB-845736BB337B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:2.0:*:*:*:*:*:*:*", "matchCriteriaId": "A1337F5B-E9D9-4335-9E05-50018E59E530", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The rpza_decode_stream function in libavcodec/rpza.c in FFmpeg before 2.1 does not properly maintain a pointer to pixel data, which allows remote attackers to cause a denial of service (out-of-bounds array access) or possibly have unspecified other impact via crafted Apple RPZA data."}, {"lang": "es", "value": "La funci\u00f3n rpza_decode_stream en libavcodec/rpza.c en FFmpeg anteriores a 2.1 no mantiene correctamente un puntero a p\u00edxeles, lo cual permite a atacantes remotos causar denegaci\u00f3n de servicio (acceso a array fuera de l\u00edmites) o posiblemente tener otro impacto no especificado a trav\u00e9s de datos Apple RPZA."}], "evaluatorComment": null, "id": "CVE-2013-7009", "lastModified": "2016-12-03T03:00:34.690", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2013-12-09T16:36:47.847", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://ffmpeg.org/security.html"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "http://openwall.com/lists/oss-security/2013/11/26/7"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "http://openwall.com/lists/oss-security/2013/12/08/3"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/FFmpeg/FFmpeg/commit/3819db745da2ac7fb3faacb116788c32f4753f34"}, {"source": "cve@mitre.org", "tags": null, "url": "https://security.gentoo.org/glsa/201603-06"}, {"source": "cve@mitre.org", "tags": ["Exploit"], "url": "https://trac.ffmpeg.org/ticket/2850"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/FFmpeg/FFmpeg/commit/3819db745da2ac7fb3faacb116788c32f4753f34"}, "type": "CWE-119"}
303
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Quicktime Video (RPZA) Video Decoder\n * Copyright (C) 2003 the ffmpeg project\n *\n * This file is part of FFmpeg.\n *\n * FFmpeg is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * FFmpeg is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n */", "/**\n * @file\n * QT RPZA Video Decoder by Roberto Togni\n * For more information about the RPZA format, visit:\n * http://www.pcisys.net/~melanson/codecs/\n *\n * The RPZA decoder outputs RGB555 colorspace data.\n *\n * Note that this decoder reads big endian RGB555 pixel values from the\n * bytestream, arranges them in the host's endian order, and outputs\n * them to the final rendered map in the same host endian order. This is\n * intended behavior as the libavcodec documentation states that RGB555\n * pixels shall be stored in native CPU endianness.\n */", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>", "#include \"libavutil/internal.h\"\n#include \"libavutil/intreadwrite.h\"\n#include \"avcodec.h\"\n#include \"internal.h\"", "typedef struct RpzaContext {", " AVCodecContext *avctx;\n AVFrame frame;", " const unsigned char *buf;\n int size;", "} RpzaContext;", "#define ADVANCE_BLOCK() \\\n{ \\\n pixel_ptr += 4; \\\n if (pixel_ptr >= width) \\\n { \\\n pixel_ptr = 0; \\\n row_ptr += stride * 4; \\\n } \\\n total_blocks--; \\\n if (total_blocks < 0) \\\n { \\\n av_log(s->avctx, AV_LOG_ERROR, \"warning: block counter just went negative (this should not happen)\\n\"); \\\n return; \\\n } \\\n}", "static void rpza_decode_stream(RpzaContext *s)\n{\n int width = s->avctx->width;\n int stride = s->frame.linesize[0] / 2;\n int row_inc = stride - 4;\n int stream_ptr = 0;\n int chunk_size;\n unsigned char opcode;\n int n_blocks;\n unsigned short colorA = 0, colorB;\n unsigned short color4[4];\n unsigned char index, idx;\n unsigned short ta, tb;\n unsigned short *pixels = (unsigned short *)s->frame.data[0];", " int row_ptr = 0;", " int pixel_ptr = -4;", " int block_ptr;\n int pixel_x, pixel_y;\n int total_blocks;", " /* First byte is always 0xe1. Warn if it's different */\n if (s->buf[stream_ptr] != 0xe1)\n av_log(s->avctx, AV_LOG_ERROR, \"First chunk byte is 0x%02x instead of 0xe1\\n\",\n s->buf[stream_ptr]);", " /* Get chunk size, ingnoring first byte */\n chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;\n stream_ptr += 4;", " /* If length mismatch use size from MOV file and try to decode anyway */\n if (chunk_size != s->size)\n av_log(s->avctx, AV_LOG_ERROR, \"MOV chunk size != encoded chunk size; using MOV chunk size\\n\");", " chunk_size = s->size;", " /* Number of 4x4 blocks in frame. */\n total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);", " /* Process chunk data */\n while (stream_ptr < chunk_size) {\n opcode = s->buf[stream_ptr++]; /* Get opcode */", " n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */", " /* If opcode MSbit is 0, we need more data to decide what to do */\n if ((opcode & 0x80) == 0) {\n colorA = (opcode << 8) | (s->buf[stream_ptr++]);\n opcode = 0;\n if ((s->buf[stream_ptr] & 0x80) != 0) {\n /* Must behave as opcode 110xxxxx, using colorA computed\n * above. Use fake opcode 0x20 to enter switch block at\n * the right place */\n opcode = 0x20;\n n_blocks = 1;\n }\n }", " switch (opcode & 0xe0) {", " /* Skip blocks */\n case 0x80:\n while (n_blocks--) {\n ADVANCE_BLOCK();\n }\n break;", " /* Fill blocks with one color */\n case 0xa0:\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;\n while (n_blocks--) {", " ADVANCE_BLOCK()", " block_ptr = row_ptr + pixel_ptr;\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n pixels[block_ptr] = colorA;\n block_ptr++;\n }\n block_ptr += row_inc;\n }", "", " }\n break;", " /* Fill blocks with 4 colors */\n case 0xc0:\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;\n case 0x20:\n colorB = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;", " /* sort out the colors */\n color4[0] = colorB;\n color4[1] = 0;\n color4[2] = 0;\n color4[3] = colorA;", " /* red components */\n ta = (colorA >> 10) & 0x1F;\n tb = (colorB >> 10) & 0x1F;\n color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;\n color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;", " /* green components */\n ta = (colorA >> 5) & 0x1F;\n tb = (colorB >> 5) & 0x1F;\n color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;\n color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;", " /* blue components */\n ta = colorA & 0x1F;\n tb = colorB & 0x1F;\n color4[1] |= ((11 * ta + 21 * tb) >> 5);\n color4[2] |= ((21 * ta + 11 * tb) >> 5);", " if (s->size - stream_ptr < n_blocks * 4)\n return;\n while (n_blocks--) {", " ADVANCE_BLOCK();", " block_ptr = row_ptr + pixel_ptr;\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n index = s->buf[stream_ptr++];\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n idx = (index >> (2 * (3 - pixel_x))) & 0x03;\n pixels[block_ptr] = color4[idx];\n block_ptr++;\n }\n block_ptr += row_inc;\n }", "", " }\n break;", " /* Fill block with 16 colors */\n case 0x00:\n if (s->size - stream_ptr < 16)\n return;", " ADVANCE_BLOCK();", " block_ptr = row_ptr + pixel_ptr;\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n /* We already have color of upper left pixel */\n if ((pixel_y != 0) || (pixel_x !=0)) {\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n stream_ptr += 2;\n }\n pixels[block_ptr] = colorA;\n block_ptr++;\n }\n block_ptr += row_inc;\n }", "", " break;", " /* Unknown opcode */\n default:\n av_log(s->avctx, AV_LOG_ERROR, \"Unknown opcode %d in rpza chunk.\"\n \" Skip remaining %d bytes of chunk data.\\n\", opcode,\n chunk_size - stream_ptr);\n return;\n } /* Opcode switch */\n }\n}", "static av_cold int rpza_decode_init(AVCodecContext *avctx)\n{\n RpzaContext *s = avctx->priv_data;", " s->avctx = avctx;\n avctx->pix_fmt = AV_PIX_FMT_RGB555;", " avcodec_get_frame_defaults(&s->frame);", " return 0;\n}", "static int rpza_decode_frame(AVCodecContext *avctx,\n void *data, int *got_frame,\n AVPacket *avpkt)\n{\n const uint8_t *buf = avpkt->data;\n int buf_size = avpkt->size;\n RpzaContext *s = avctx->priv_data;\n int ret;", " s->buf = buf;\n s->size = buf_size;", " if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0)\n return ret;", " rpza_decode_stream(s);", " if ((ret = av_frame_ref(data, &s->frame)) < 0)\n return ret;", " *got_frame = 1;", " /* always report that the buffer was completely consumed */\n return buf_size;\n}", "static av_cold int rpza_decode_end(AVCodecContext *avctx)\n{\n RpzaContext *s = avctx->priv_data;", " av_frame_unref(&s->frame);", " return 0;\n}", "AVCodec ff_rpza_decoder = {\n .name = \"rpza\",\n .type = AVMEDIA_TYPE_VIDEO,\n .id = AV_CODEC_ID_RPZA,\n .priv_data_size = sizeof(RpzaContext),\n .init = rpza_decode_init,\n .close = rpza_decode_end,\n .decode = rpza_decode_frame,\n .capabilities = CODEC_CAP_DR1,\n .long_name = NULL_IF_CONFIG_SMALL(\"QuickTime video (RPZA)\"),\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [223], "buggy_code_start_loc": [88], "filenames": ["libavcodec/rpza.c"], "fixing_code_end_loc": [222], "fixing_code_start_loc": [88], "message": "The rpza_decode_stream function in libavcodec/rpza.c in FFmpeg before 2.1 does not properly maintain a pointer to pixel data, which allows remote attackers to cause a denial of service (out-of-bounds array access) or possibly have unspecified other impact via crafted Apple RPZA data.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:*:*:*:*:*:*:*:*", "matchCriteriaId": "C41A1983-BA74-4806-A227-EBBF7989112C", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3:*:*:*:*:*:*:*", "matchCriteriaId": "B2649A80-4739-4BBB-AB0B-99AD435BE7CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "D4A2E77D-B826-4B49-ADC8-7F704E149A5A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "18157837-4550-45E3-A12E-AE06E047E253", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "E9F42611-C3E2-416B-9AE7-A5AE83E4DEF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "3A20789F-26E3-4871-B24E-25E922BADDF0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "67C6C243-3ACC-49C3-80CA-D7CA8FEFF0D8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "6AE6D368-0BA6-4499-B7E1-EE16C03012E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "26C0F6EF-0452-4AFE-AF3E-B88F963A0938", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "5B4DD372-4D3B-445C-8C38-E083A3C0D4A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "733C03D7-2780-4D69-A98D-BCFB91D1119A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "0AEE1977-E9E0-4BFF-B33B-B083E49E51F1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.7:*:*:*:*:*:*:*", "matchCriteriaId": "E6979C17-0BC6-47D1-9B73-254D84306A96", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.8:*:*:*:*:*:*:*", "matchCriteriaId": "204C7C05-3441-4DB0-8702-D99C8FCB381E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.4.9:pre1:*:*:*:*:*:*", "matchCriteriaId": "2E1A7011-B992-4E35-B306-45772DACB23C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5:*:*:*:*:*:*:*", "matchCriteriaId": "8D486C17-FC4A-4AEE-A430-1B1FBCC2C27C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.1:*:*:*:*:*:*:*", "matchCriteriaId": "632BC7C2-FE59-47B0-885C-0EB8C74DF041", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.2:*:*:*:*:*:*:*", "matchCriteriaId": "5D1AE0BF-A6FD-4EBA-BF61-07AC81EA560D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "5B8FA106-FE65-4BB0-92A7-E8A5AF978A9B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "514669DA-8D02-44CE-BE18-8783F69AE394", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "8041E6ED-472A-40DF-AA90-F3509D90D47A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.4.6:*:*:*:*:*:*:*", "matchCriteriaId": "D2C64382-9259-4D61-B352-7F123527289C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.5.5:*:*:*:*:*:*:*", "matchCriteriaId": "32A152D9-947E-4198-9C2D-2A582F09AB75", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6:*:*:*:*:*:*:*", "matchCriteriaId": "37FBB817-A186-4517-9DA7-B3638576AAE7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6.1:*:*:*:*:*:*:*", "matchCriteriaId": "157ABA40-6101-4E9C-A24C-84F8E23D374D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6.2:*:*:*:*:*:*:*", "matchCriteriaId": "C7EA46DD-2CC4-426F-8709-821B7572C94A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.6.3:*:*:*:*:*:*:*", "matchCriteriaId": "3DE12C59-4409-4F7A-9759-7B26FA9DAC34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7:*:*:*:*:*:*:*", "matchCriteriaId": "30FE6578-F031-4F5B-B955-8F912CFCA1B0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.1:*:*:*:*:*:*:*", "matchCriteriaId": "07669E0E-8C4B-430E-802F-F64EEA2B5A0B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.2:*:*:*:*:*:*:*", "matchCriteriaId": "F3EB7F17-F25D-4E48-8A43-F799619CE71F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.3:*:*:*:*:*:*:*", "matchCriteriaId": "60705A3B-7136-45D1-8068-E2DC9E01EB04", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.4:*:*:*:*:*:*:*", "matchCriteriaId": "C722B143-2648-4EB2-A090-7B788F41F300", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.5:*:*:*:*:*:*:*", "matchCriteriaId": "B31AFDBC-A782-4C18-8EAA-6D927397BEA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.6:*:*:*:*:*:*:*", "matchCriteriaId": "73E9E8F4-A942-4F34-BCE2-82A180F1DD1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.7:*:*:*:*:*:*:*", "matchCriteriaId": "AAA31D75-C3FB-4D89-8B2D-21372AAEB78B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.8:*:*:*:*:*:*:*", "matchCriteriaId": "B20E5358-826C-47A2-B39F-ED4E9213BA95", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.9:*:*:*:*:*:*:*", "matchCriteriaId": "26321888-E140-4F09-AAA0-7392AA7F6307", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.11:*:*:*:*:*:*:*", "matchCriteriaId": "7E46B9F3-A9C0-4B8A-A119-40CA4CBBD0EE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.7.12:*:*:*:*:*:*:*", "matchCriteriaId": "44800572-71C5-4AA1-9CB6-30AA902B0353", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.0:*:*:*:*:*:*:*", "matchCriteriaId": "87090477-1D36-48B3-88AE-5CD5EE8F89D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.1:*:*:*:*:*:*:*", "matchCriteriaId": "2096FF8B-9B57-4C59-84DB-9CC0DEAB47AC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.2:*:*:*:*:*:*:*", "matchCriteriaId": "34C99254-776C-4AAD-BDA2-3F544256AA67", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.5:*:*:*:*:*:*:*", "matchCriteriaId": "CE9D7B73-9CDA-4BAE-8DD9-8E1E34C20648", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.5.3:*:*:*:*:*:*:*", "matchCriteriaId": "4FDBF2C0-8E33-4575-8A19-4F1CABA3023F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.5.4:*:*:*:*:*:*:*", "matchCriteriaId": "72040664-077A-48FB-9E6B-B69EA8D26CB4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.6:*:*:*:*:*:*:*", "matchCriteriaId": "F428A2E4-A54F-4296-A00F-1A4E160253D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.7:*:*:*:*:*:*:*", "matchCriteriaId": "5239E4FA-0359-49F1-93D4-24AB013FAC20", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.8:*:*:*:*:*:*:*", "matchCriteriaId": "F0C8230D-4E89-45F9-B0F7-E317119E0FA0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.10:*:*:*:*:*:*:*", "matchCriteriaId": "585CE7D2-1CE8-44AB-AE67-07D7D3721F68", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.8.11:*:*:*:*:*:*:*", "matchCriteriaId": "EE81C339-A794-4303-B829-BE743DF0B132", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.9:*:*:*:*:*:*:*", "matchCriteriaId": "5CE0A27B-66D7-4D1B-8E6A-F4722C070BD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.9.1:*:*:*:*:*:*:*", "matchCriteriaId": "864DC4A2-A378-4389-B62E-9E785879A744", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.10:*:*:*:*:*:*:*", "matchCriteriaId": "16304267-C808-4B6B-9903-2DEAB40AD899", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.10.3:*:*:*:*:*:*:*", "matchCriteriaId": "CEEBBA83-1BFC-45A8-B34A-AB3A9B8A9414", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.10.4:*:*:*:*:*:*:*", "matchCriteriaId": "F559B34E-23EE-4E09-A044-E7F54C55B05E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:0.11:*:*:*:*:*:*:*", "matchCriteriaId": "62BA2708-BE77-42B7-B51A-C1B58632462C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.0:*:*:*:*:*:*:*", "matchCriteriaId": "23E57BB1-DF1E-4173-BE52-72E2B3E6BA23", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "A3E30DB1-0CFC-4EAA-BF07-CE7551ABDCB5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "DBA7D745-DC16-43B9-8A2D-4D6944A6BFD0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "87A511A5-2040-433A-9B32-B89332214FA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "0C01DD9C-98C9-4896-8D66-A8336582298B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.2:*:*:*:*:*:*:*", "matchCriteriaId": "BBE7723A-3D6B-4390-B82E-6A5A6992141A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:1.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "1ED8FF93-5AA7-443C-BBDB-845736BB337B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ffmpeg:ffmpeg:2.0:*:*:*:*:*:*:*", "matchCriteriaId": "A1337F5B-E9D9-4335-9E05-50018E59E530", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The rpza_decode_stream function in libavcodec/rpza.c in FFmpeg before 2.1 does not properly maintain a pointer to pixel data, which allows remote attackers to cause a denial of service (out-of-bounds array access) or possibly have unspecified other impact via crafted Apple RPZA data."}, {"lang": "es", "value": "La funci\u00f3n rpza_decode_stream en libavcodec/rpza.c en FFmpeg anteriores a 2.1 no mantiene correctamente un puntero a p\u00edxeles, lo cual permite a atacantes remotos causar denegaci\u00f3n de servicio (acceso a array fuera de l\u00edmites) o posiblemente tener otro impacto no especificado a trav\u00e9s de datos Apple RPZA."}], "evaluatorComment": null, "id": "CVE-2013-7009", "lastModified": "2016-12-03T03:00:34.690", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2013-12-09T16:36:47.847", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://ffmpeg.org/security.html"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "http://openwall.com/lists/oss-security/2013/11/26/7"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "http://openwall.com/lists/oss-security/2013/12/08/3"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/FFmpeg/FFmpeg/commit/3819db745da2ac7fb3faacb116788c32f4753f34"}, {"source": "cve@mitre.org", "tags": null, "url": "https://security.gentoo.org/glsa/201603-06"}, {"source": "cve@mitre.org", "tags": ["Exploit"], "url": "https://trac.ffmpeg.org/ticket/2850"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/FFmpeg/FFmpeg/commit/3819db745da2ac7fb3faacb116788c32f4753f34"}, "type": "CWE-119"}
303
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"", "\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"", "\t\"github.com/gorilla/sessions\"\n\t\"github.com/labstack/echo-contrib/session\"\n\t\"github.com/labstack/echo/v4\"\n)", "var (\n\tuserIDContextKey = \"user-id\"\n)", "func getUserIDContextKey() string {\n\treturn userIDContextKey\n}", "func setUserSession(ctx echo.Context, user *api.User) error {\n\tsess, _ := session.Get(\"memos_session\", ctx)\n\tsess.Options = &sessions.Options{\n\t\tPath: \"/\",\n\t\tMaxAge: 3600 * 24 * 30,\n\t\tHttpOnly: true,", "", "\t}\n\tsess.Values[userIDContextKey] = user.ID\n\terr := sess.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set session, err: %w\", err)\n\t}\n\treturn nil\n}", "func removeUserSession(ctx echo.Context) error {\n\tsess, _ := session.Get(\"memos_session\", ctx)\n\tsess.Options = &sessions.Options{\n\t\tPath: \"/\",\n\t\tMaxAge: 0,\n\t\tHttpOnly: true,\n\t}\n\tsess.Values[userIDContextKey] = nil\n\terr := sess.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set session, err: %w\", err)\n\t}\n\treturn nil\n}", "func aclMiddleware(s *Server, next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tpath := c.Path()", "\t\t// Skip auth.\n\t\tif common.HasPrefixes(path, \"/api/auth\") {\n\t\t\treturn next(c)\n\t\t}", "\t\t{\n\t\t\t// If there is openId in query string and related user is found, then skip auth.\n\t\t\topenID := c.QueryParam(\"openId\")\n\t\t\tif openID != \"\" {\n\t\t\t\tuserFind := &api.UserFind{\n\t\t\t\t\tOpenID: &openID,\n\t\t\t\t}\n\t\t\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\t\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user by open_id\").SetInternal(err)\n\t\t\t\t}\n\t\t\t\tif user != nil {\n\t\t\t\t\t// Stores userID into context.\n\t\t\t\t\tc.Set(getUserIDContextKey(), user.ID)\n\t\t\t\t\treturn next(c)\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t{\n\t\t\tsess, _ := session.Get(\"memos_session\", c)\n\t\t\tuserIDValue := sess.Values[userIDContextKey]\n\t\t\tif userIDValue != nil {\n\t\t\t\tuserID, _ := strconv.Atoi(fmt.Sprintf(\"%v\", userIDValue))\n\t\t\t\tuserFind := &api.UserFind{\n\t\t\t\t\tID: &userID,\n\t\t\t\t}\n\t\t\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\t\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find user by ID: %d\", userID)).SetInternal(err)\n\t\t\t\t}\n\t\t\t\tif user != nil {\n\t\t\t\t\tif user.RowStatus == api.Archived {\n\t\t\t\t\t\treturn echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf(\"User has been archived with username %s\", user.Username))\n\t\t\t\t\t}\n\t\t\t\t\tc.Set(getUserIDContextKey(), userID)\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\tif common.HasPrefixes(path, \"/api/ping\", \"/api/status\", \"/api/user/:id\", \"/api/memo/all\", \"/api/memo/:memoId\", \"/api/memo/amount\") && c.Request().Method == http.MethodGet {\n\t\t\treturn next(c)\n\t\t}", "\t\tif common.HasPrefixes(path, \"/api/memo\", \"/api/tag\", \"/api/shortcut\") && c.Request().Method == http.MethodGet {\n\t\t\tif _, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\t\treturn next(c)\n\t\t\t}\n\t\t}", "\t\tuserID := c.Get(getUserIDContextKey())\n\t\tif userID == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}", "\t\treturn next(c)\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [29, 36], "buggy_code_start_loc": [29, 36], "filenames": ["server/acl.go", "server/server.go"], "fixing_code_end_loc": [31, 41], "fixing_code_start_loc": [30, 37], "message": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4846", "lastModified": "2023-01-05T21:24:28.153", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-29T18:15:10.357", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/38c685fc-7065-472d-a46e-e26bf0b556d3"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, "type": "CWE-352"}
304
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"", "\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"", "\t\"github.com/gorilla/sessions\"\n\t\"github.com/labstack/echo-contrib/session\"\n\t\"github.com/labstack/echo/v4\"\n)", "var (\n\tuserIDContextKey = \"user-id\"\n)", "func getUserIDContextKey() string {\n\treturn userIDContextKey\n}", "func setUserSession(ctx echo.Context, user *api.User) error {\n\tsess, _ := session.Get(\"memos_session\", ctx)\n\tsess.Options = &sessions.Options{\n\t\tPath: \"/\",\n\t\tMaxAge: 3600 * 24 * 30,\n\t\tHttpOnly: true,", "\t\tSameSite: http.SameSiteStrictMode,", "\t}\n\tsess.Values[userIDContextKey] = user.ID\n\terr := sess.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set session, err: %w\", err)\n\t}\n\treturn nil\n}", "func removeUserSession(ctx echo.Context) error {\n\tsess, _ := session.Get(\"memos_session\", ctx)\n\tsess.Options = &sessions.Options{\n\t\tPath: \"/\",\n\t\tMaxAge: 0,\n\t\tHttpOnly: true,\n\t}\n\tsess.Values[userIDContextKey] = nil\n\terr := sess.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set session, err: %w\", err)\n\t}\n\treturn nil\n}", "func aclMiddleware(s *Server, next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tpath := c.Path()", "\t\t// Skip auth.\n\t\tif common.HasPrefixes(path, \"/api/auth\") {\n\t\t\treturn next(c)\n\t\t}", "\t\t{\n\t\t\t// If there is openId in query string and related user is found, then skip auth.\n\t\t\topenID := c.QueryParam(\"openId\")\n\t\t\tif openID != \"\" {\n\t\t\t\tuserFind := &api.UserFind{\n\t\t\t\t\tOpenID: &openID,\n\t\t\t\t}\n\t\t\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\t\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user by open_id\").SetInternal(err)\n\t\t\t\t}\n\t\t\t\tif user != nil {\n\t\t\t\t\t// Stores userID into context.\n\t\t\t\t\tc.Set(getUserIDContextKey(), user.ID)\n\t\t\t\t\treturn next(c)\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t{\n\t\t\tsess, _ := session.Get(\"memos_session\", c)\n\t\t\tuserIDValue := sess.Values[userIDContextKey]\n\t\t\tif userIDValue != nil {\n\t\t\t\tuserID, _ := strconv.Atoi(fmt.Sprintf(\"%v\", userIDValue))\n\t\t\t\tuserFind := &api.UserFind{\n\t\t\t\t\tID: &userID,\n\t\t\t\t}\n\t\t\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\t\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find user by ID: %d\", userID)).SetInternal(err)\n\t\t\t\t}\n\t\t\t\tif user != nil {\n\t\t\t\t\tif user.RowStatus == api.Archived {\n\t\t\t\t\t\treturn echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf(\"User has been archived with username %s\", user.Username))\n\t\t\t\t\t}\n\t\t\t\t\tc.Set(getUserIDContextKey(), userID)\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\tif common.HasPrefixes(path, \"/api/ping\", \"/api/status\", \"/api/user/:id\", \"/api/memo/all\", \"/api/memo/:memoId\", \"/api/memo/amount\") && c.Request().Method == http.MethodGet {\n\t\t\treturn next(c)\n\t\t}", "\t\tif common.HasPrefixes(path, \"/api/memo\", \"/api/tag\", \"/api/shortcut\") && c.Request().Method == http.MethodGet {\n\t\t\tif _, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\t\treturn next(c)\n\t\t\t}\n\t\t}", "\t\tuserID := c.Get(getUserIDContextKey())\n\t\tif userID == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}", "\t\treturn next(c)\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [29, 36], "buggy_code_start_loc": [29, 36], "filenames": ["server/acl.go", "server/server.go"], "fixing_code_end_loc": [31, 41], "fixing_code_start_loc": [30, 37], "message": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4846", "lastModified": "2023-01-05T21:24:28.153", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-29T18:15:10.357", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/38c685fc-7065-472d-a46e-e26bf0b556d3"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, "type": "CWE-352"}
304
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"fmt\"\n\t\"time\"", "\t\"github.com/usememos/memos/server/profile\"\n\t\"github.com/usememos/memos/store\"", "\t\"github.com/gorilla/securecookie\"\n\t\"github.com/gorilla/sessions\"\n\t\"github.com/labstack/echo-contrib/session\"\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/labstack/echo/v4/middleware\"\n)", "type Server struct {\n\te *echo.Echo", "\tCollector *MetricCollector", "\tProfile *profile.Profile", "\tStore *store.Store\n}", "func NewServer(profile *profile.Profile) *Server {\n\te := echo.New()\n\te.Debug = true\n\te.HideBanner = true\n\te.HidePort = true", "\te.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{\n\t\tFormat: `{\"time\":\"${time_rfc3339}\",` +\n\t\t\t`\"method\":\"${method}\",\"uri\":\"${uri}\",` +\n\t\t\t`\"status\":${status},\"error\":\"${error}\"}` + \"\\n\",", "", "\t}))", "\te.Use(middleware.CORS())", "\te.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{\n\t\tSkipper: middleware.DefaultSkipper,\n\t\tErrorMessage: \"Request timeout\",\n\t\tTimeout: 30 * time.Second,\n\t}))", "\tembedFrontend(e)", "\t// In dev mode, set the const secret key to make signin session persistence.\n\tsecret := []byte(\"usememos\")\n\tif profile.Mode == \"prod\" {\n\t\tsecret = securecookie.GenerateRandomKey(16)\n\t}\n\te.Use(session.Middleware(sessions.NewCookieStore(secret)))", "\ts := &Server{\n\t\te: e,\n\t\tProfile: profile,\n\t}", "\trootGroup := e.Group(\"\")\n\ts.registerRSSRoutes(rootGroup)", "\twebhookGroup := e.Group(\"/h\")\n\ts.registerResourcePublicRoutes(webhookGroup)", "\tpublicGroup := e.Group(\"/o\")\n\ts.registerResourcePublicRoutes(publicGroup)\n\ts.registerGetterPublicRoutes(publicGroup)", "\tapiGroup := e.Group(\"/api\")\n\tapiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn aclMiddleware(s, next)\n\t})\n\ts.registerSystemRoutes(apiGroup)\n\ts.registerAuthRoutes(apiGroup)\n\ts.registerUserRoutes(apiGroup)\n\ts.registerMemoRoutes(apiGroup)\n\ts.registerShortcutRoutes(apiGroup)\n\ts.registerResourceRoutes(apiGroup)\n\ts.registerTagRoutes(apiGroup)", "\treturn s\n}", "func (server *Server) Run() error {\n\treturn server.e.Start(fmt.Sprintf(\":%d\", server.Profile.Port))\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [29, 36], "buggy_code_start_loc": [29, 36], "filenames": ["server/acl.go", "server/server.go"], "fixing_code_end_loc": [31, 41], "fixing_code_start_loc": [30, 37], "message": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4846", "lastModified": "2023-01-05T21:24:28.153", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-29T18:15:10.357", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/38c685fc-7065-472d-a46e-e26bf0b556d3"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, "type": "CWE-352"}
304
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"fmt\"\n\t\"time\"", "\t\"github.com/usememos/memos/server/profile\"\n\t\"github.com/usememos/memos/store\"", "\t\"github.com/gorilla/securecookie\"\n\t\"github.com/gorilla/sessions\"\n\t\"github.com/labstack/echo-contrib/session\"\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/labstack/echo/v4/middleware\"\n)", "type Server struct {\n\te *echo.Echo", "\tCollector *MetricCollector", "\tProfile *profile.Profile", "\tStore *store.Store\n}", "func NewServer(profile *profile.Profile) *Server {\n\te := echo.New()\n\te.Debug = true\n\te.HideBanner = true\n\te.HidePort = true", "\te.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{\n\t\tFormat: `{\"time\":\"${time_rfc3339}\",` +\n\t\t\t`\"method\":\"${method}\",\"uri\":\"${uri}\",` +\n\t\t\t`\"status\":${status},\"error\":\"${error}\"}` + \"\\n\",", "\t}))", "\te.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{\n\t\tTokenLookup: \"cookie:_csrf\",", "\t}))", "\te.Use(middleware.CORS())", "\te.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{\n\t\tSkipper: middleware.DefaultSkipper,\n\t\tErrorMessage: \"Request timeout\",\n\t\tTimeout: 30 * time.Second,\n\t}))", "\tembedFrontend(e)", "\t// In dev mode, set the const secret key to make signin session persistence.\n\tsecret := []byte(\"usememos\")\n\tif profile.Mode == \"prod\" {\n\t\tsecret = securecookie.GenerateRandomKey(16)\n\t}\n\te.Use(session.Middleware(sessions.NewCookieStore(secret)))", "\ts := &Server{\n\t\te: e,\n\t\tProfile: profile,\n\t}", "\trootGroup := e.Group(\"\")\n\ts.registerRSSRoutes(rootGroup)", "\twebhookGroup := e.Group(\"/h\")\n\ts.registerResourcePublicRoutes(webhookGroup)", "\tpublicGroup := e.Group(\"/o\")\n\ts.registerResourcePublicRoutes(publicGroup)\n\ts.registerGetterPublicRoutes(publicGroup)", "\tapiGroup := e.Group(\"/api\")\n\tapiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn aclMiddleware(s, next)\n\t})\n\ts.registerSystemRoutes(apiGroup)\n\ts.registerAuthRoutes(apiGroup)\n\ts.registerUserRoutes(apiGroup)\n\ts.registerMemoRoutes(apiGroup)\n\ts.registerShortcutRoutes(apiGroup)\n\ts.registerResourceRoutes(apiGroup)\n\ts.registerTagRoutes(apiGroup)", "\treturn s\n}", "func (server *Server) Run() error {\n\treturn server.e.Start(fmt.Sprintf(\":%d\", server.Profile.Port))\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [29, 36], "buggy_code_start_loc": [29, 36], "filenames": ["server/acl.go", "server/server.go"], "fixing_code_end_loc": [31, 41], "fixing_code_start_loc": [30, 37], "message": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-Site Request Forgery (CSRF) in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4846", "lastModified": "2023-01-05T21:24:28.153", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-29T18:15:10.357", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/38c685fc-7065-472d-a46e-e26bf0b556d3"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/c9bb2b785dc5852655405d5c9ab127a2d5aa3948"}, "type": "CWE-352"}
304
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "// Visibility is the type of a visibility.\ntype Visibility string", "const (\n\t// Public is the PUBLIC visibility.\n\tPublic Visibility = \"PUBLIC\"\n\t// Protected is the PROTECTED visibility.\n\tProtected Visibility = \"PROTECTED\"\n\t// Private is the PRIVATE visibility.\n\tPrivate Visibility = \"PRIVATE\"\n)", "func (e Visibility) String() string {\n\tswitch e {\n\tcase Public:\n\t\treturn \"PUBLIC\"\n\tcase Protected:\n\t\treturn \"PROTECTED\"\n\tcase Private:\n\t\treturn \"PRIVATE\"\n\t}\n\treturn \"PRIVATE\"\n}", "type Memo struct {\n\tID int `json:\"id\"`", "\t// Standard fields\n\tRowStatus RowStatus `json:\"rowStatus\"`\n\tCreatorID int `json:\"creatorId\"`\n\tCreatedTs int64 `json:\"createdTs\"`\n\tUpdatedTs int64 `json:\"updatedTs\"`", "\t// Domain specific fields\n\tContent string `json:\"content\"`\n\tVisibility Visibility `json:\"visibility\"`\n\tPinned bool `json:\"pinned\"`\n\tDisplayTs int64 `json:\"displayTs\"`", "\t// Related fields\n\tCreator *User `json:\"creator\"`\n\tResourceList []*Resource `json:\"resourceList\"`\n}", "type MemoCreate struct {\n\t// Standard fields", "\tCreatorID int", "\n\t// Domain specific fields\n\tVisibility Visibility `json:\"visibility\"`\n\tContent string `json:\"content\"`", "\t// Related fields\n\tResourceIDList []int `json:\"resourceIdList\"`\n}", "type MemoPatch struct {\n\tID int `json:\"-\"`", "\t// Standard fields\n\tCreatedTs *int64 `json:\"createdTs\"`\n\tUpdatedTs *int64\n\tRowStatus *RowStatus `json:\"rowStatus\"`", "\t// Domain specific fields\n\tContent *string `json:\"content\"`\n\tVisibility *Visibility `json:\"visibility\"`", "\t// Related fields\n\tResourceIDList []int `json:\"resourceIdList\"`\n}", "type MemoFind struct {", "\tID *int `json:\"id\"`", "\n\t// Standard fields", "\tRowStatus *RowStatus `json:\"rowStatus\"`\n\tCreatorID *int `json:\"creatorId\"`", "\n\t// Domain specific fields\n\tPinned *bool\n\tContentSearch *string\n\tVisibilityList []Visibility", "\t// Pagination\n\tLimit int\n\tOffset int\n}", "type MemoDelete struct {\n\tID int\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "// Visibility is the type of a visibility.\ntype Visibility string", "const (\n\t// Public is the PUBLIC visibility.\n\tPublic Visibility = \"PUBLIC\"\n\t// Protected is the PROTECTED visibility.\n\tProtected Visibility = \"PROTECTED\"\n\t// Private is the PRIVATE visibility.\n\tPrivate Visibility = \"PRIVATE\"\n)", "func (e Visibility) String() string {\n\tswitch e {\n\tcase Public:\n\t\treturn \"PUBLIC\"\n\tcase Protected:\n\t\treturn \"PROTECTED\"\n\tcase Private:\n\t\treturn \"PRIVATE\"\n\t}\n\treturn \"PRIVATE\"\n}", "type Memo struct {\n\tID int `json:\"id\"`", "\t// Standard fields\n\tRowStatus RowStatus `json:\"rowStatus\"`\n\tCreatorID int `json:\"creatorId\"`\n\tCreatedTs int64 `json:\"createdTs\"`\n\tUpdatedTs int64 `json:\"updatedTs\"`", "\t// Domain specific fields\n\tContent string `json:\"content\"`\n\tVisibility Visibility `json:\"visibility\"`\n\tPinned bool `json:\"pinned\"`\n\tDisplayTs int64 `json:\"displayTs\"`", "\t// Related fields\n\tCreator *User `json:\"creator\"`\n\tResourceList []*Resource `json:\"resourceList\"`\n}", "type MemoCreate struct {\n\t// Standard fields", "\tCreatorID int `json:\"-\"`", "\n\t// Domain specific fields\n\tVisibility Visibility `json:\"visibility\"`\n\tContent string `json:\"content\"`", "\t// Related fields\n\tResourceIDList []int `json:\"resourceIdList\"`\n}", "type MemoPatch struct {\n\tID int `json:\"-\"`", "\t// Standard fields\n\tCreatedTs *int64 `json:\"createdTs\"`\n\tUpdatedTs *int64\n\tRowStatus *RowStatus `json:\"rowStatus\"`", "\t// Domain specific fields\n\tContent *string `json:\"content\"`\n\tVisibility *Visibility `json:\"visibility\"`", "\t// Related fields\n\tResourceIDList []int `json:\"resourceIdList\"`\n}", "type MemoFind struct {", "\tID *int", "\n\t// Standard fields", "\tRowStatus *RowStatus\n\tCreatorID *int", "\n\t// Domain specific fields\n\tPinned *bool\n\tContentSearch *string\n\tVisibilityList []Visibility", "\t// Pagination\n\tLimit int\n\tOffset int\n}", "type MemoDelete struct {\n\tID int\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "type MemoOrganizer struct {\n\tID int", "\t// Domain specific fields\n\tMemoID int\n\tUserID int\n\tPinned bool\n}\n", "", "type MemoOrganizerFind struct {\n\tMemoID int\n\tUserID int", "}", "type MemoOrganizerUpsert struct {\n\tMemoID int\n\tUserID int\n\tPinned bool `json:\"pinned\"`", "}", "type MemoOrganizerDelete struct {\n\tMemoID *int\n\tUserID *int\n}" ]
[ 1, 1, 1, 0, 1, 0, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "type MemoOrganizer struct {\n\tID int", "\t// Domain specific fields\n\tMemoID int\n\tUserID int\n\tPinned bool\n}\n", "type MemoOrganizerUpsert struct {\n\tMemoID int `json:\"-\"`\n\tUserID int `json:\"-\"`\n\tPinned bool `json:\"pinned\"`\n}\n", "type MemoOrganizerFind struct {\n\tMemoID int\n\tUserID int", "", "}", "type MemoOrganizerDelete struct {\n\tMemoID *int\n\tUserID *int\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "type MemoResource struct {\n\tMemoID int\n\tResourceID int\n\tCreatedTs int64\n\tUpdatedTs int64\n}", "type MemoResourceUpsert struct {", "\tMemoID int", "\tResourceID int\n\tUpdatedTs *int64\n}", "type MemoResourceFind struct {\n\tMemoID *int\n\tResourceID *int\n}", "type MemoResourceDelete struct {\n\tMemoID *int\n\tResourceID *int\n}" ]
[ 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "type MemoResource struct {\n\tMemoID int\n\tResourceID int\n\tCreatedTs int64\n\tUpdatedTs int64\n}", "type MemoResourceUpsert struct {", "\tMemoID int `json:\"-\"`", "\tResourceID int\n\tUpdatedTs *int64\n}", "type MemoResourceFind struct {\n\tMemoID *int\n\tResourceID *int\n}", "type MemoResourceDelete struct {\n\tMemoID *int\n\tResourceID *int\n}" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "type Resource struct {\n\tID int `json:\"id\"`", "\t// Standard fields\n\tCreatorID int `json:\"creatorId\"`\n\tCreatedTs int64 `json:\"createdTs\"`\n\tUpdatedTs int64 `json:\"updatedTs\"`", "\t// Domain specific fields\n\tFilename string `json:\"filename\"`\n\tBlob []byte `json:\"-\"`\n\tType string `json:\"type\"`\n\tSize int64 `json:\"size\"`", "\t// Related fields\n\tLinkedMemoAmount int `json:\"linkedMemoAmount\"`\n}", "type ResourceCreate struct {\n\t// Standard fields", "\tCreatorID int", "\n\t// Domain specific fields\n\tFilename string `json:\"filename\"`\n\tBlob []byte `json:\"blob\"`\n\tType string `json:\"type\"`\n\tSize int64 `json:\"size\"`\n}", "type ResourceFind struct {\n\tID *int `json:\"id\"`", "\t// Standard fields\n\tCreatorID *int `json:\"creatorId\"`", "\t// Domain specific fields\n\tFilename *string `json:\"filename\"`\n\tMemoID *int\n}", "type ResourcePatch struct {\n\tID int `json:\"-\"`", "\t// Standard fields\n\tUpdatedTs *int64", "\t// Domain specific fields\n\tFilename *string `json:\"filename\"`\n}", "type ResourceDelete struct {\n\tID int\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305
Determine whether the {function_name} code is vulnerable or not.
[ "package api", "type Resource struct {\n\tID int `json:\"id\"`", "\t// Standard fields\n\tCreatorID int `json:\"creatorId\"`\n\tCreatedTs int64 `json:\"createdTs\"`\n\tUpdatedTs int64 `json:\"updatedTs\"`", "\t// Domain specific fields\n\tFilename string `json:\"filename\"`\n\tBlob []byte `json:\"-\"`\n\tType string `json:\"type\"`\n\tSize int64 `json:\"size\"`", "\t// Related fields\n\tLinkedMemoAmount int `json:\"linkedMemoAmount\"`\n}", "type ResourceCreate struct {\n\t// Standard fields", "\tCreatorID int `json:\"-\"`", "\n\t// Domain specific fields\n\tFilename string `json:\"filename\"`\n\tBlob []byte `json:\"blob\"`\n\tType string `json:\"type\"`\n\tSize int64 `json:\"size\"`\n}", "type ResourceFind struct {\n\tID *int `json:\"id\"`", "\t// Standard fields\n\tCreatorID *int `json:\"creatorId\"`", "\t// Domain specific fields\n\tFilename *string `json:\"filename\"`\n\tMemoID *int\n}", "type ResourcePatch struct {\n\tID int `json:\"-\"`", "\t// Standard fields\n\tUpdatedTs *int64", "\t// Domain specific fields\n\tFilename *string `json:\"filename\"`\n}", "type ResourceDelete struct {\n\tID int\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
305