instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages)
{
unsigned long i;
for (i = 0; i < npages; ++i)
kvm_release_pfn_clean(pfn + i);
}
Commit Message: kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601)
The third parameter of kvm_iommu_put_pages is wrong,
It should be 'gfn - slot->base_gfn'.
By making gfn very large, malicious guest or userspace can cause kvm to
go to this error path, and subsequently to pass a huge value as size.
Alternatively if gfn is small, then pages would be pinned but never
unpinned, causing host memory leak and local DOS.
Passing a reasonable but large value could be the most dangerous case,
because it would unpin a page that should have stayed pinned, and thus
allow the device to DMA into arbitrary memory. However, this cannot
happen because of the condition that can trigger the error:
- out of memory (where you can't allocate even a single page)
should not be possible for the attacker to trigger
- when exceeding the iommu's address space, guest pages after gfn
will also exceed the iommu's address space, and inside
kvm_iommu_put_pages() the iommu_iova_to_phys() will fail. The
page thus would not be unpinned at all.
Reported-by: Jack Morgenstein <[email protected]>
Cc: [email protected]
Signed-off-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189 | static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages)
| 166,352 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119 | void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
| 173,922 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL;
PGconn *pgsql;
smart_str str = {0};
zval **args[5];
int i, connect_type = 0;
PGresult *pg_result;
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5
|| zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) {
WRONG_PARAM_COUNT;
}
smart_str_appends(&str, "pgsql");
for (i = 0; i < ZEND_NUM_ARGS(); i++) {
/* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections
* can re-use this connection. Bug #39979
*/
if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE_PP(args[i]) == IS_LONG) {
if (Z_LVAL_PP(args[1]) == PGSQL_CONNECT_FORCE_NEW) {
continue;
} else if (Z_LVAL_PP(args[1]) & PGSQL_CONNECT_FORCE_NEW) {
smart_str_append_long(&str, Z_LVAL_PP(args[1]) ^ PGSQL_CONNECT_FORCE_NEW);
}
}
convert_to_string_ex(args[i]);
smart_str_appendc(&str, '_');
smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i]));
}
smart_str_0(&str);
if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */
connstring = Z_STRVAL_PP(args[0]);
} else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */
connstring = Z_STRVAL_PP(args[0]);
convert_to_long_ex(args[1]);
connect_type = Z_LVAL_PP(args[1]);
} else {
host = Z_STRVAL_PP(args[0]);
port = Z_STRVAL_PP(args[1]);
dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]);
switch (ZEND_NUM_ARGS()) {
case 5:
tty = Z_STRVAL_PP(args[3]);
/* fall through */
case 4:
options = Z_STRVAL_PP(args[2]);
break;
}
}
if (persistent && PGG(allow_persistent)) {
zend_rsrc_list_entry *le;
/* try to find if we already have this link in our persistent list */
if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) { /* we don't */
zend_rsrc_list_entry new_le;
if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Cannot create new link. Too many open links (%ld)", PGG(num_links));
goto err;
}
if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent));
goto err;
}
/* create the link */
if (connstring) {
pgsql=PQconnectdb(connstring);
} else {
pgsql=PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql)
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* hash it up */
Z_TYPE(new_le) = le_plink;
new_le.ptr = pgsql;
if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
goto err;
}
PGG(num_links)++;
PGG(num_persistent)++;
} else { /* we do */
if (Z_TYPE_P(le) != le_plink) {
RETURN_FALSE;
}
/* ensure that the link did not die */
if (PGG(auto_reset_persistent) & 1) {
/* need to send & get something from backend to
make sure we catch CONNECTION_BAD everytime */
PGresult *pg_result;
pg_result = PQexec(le->ptr, "select 1");
PQclear(pg_result);
}
if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */
if (le->ptr == NULL) {
if (connstring) {
le->ptr=PQconnectdb(connstring);
} else {
le->ptr=PQsetdb(host,port,options,tty,dbname);
}
}
else {
PQreset(le->ptr);
}
if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect");
zend_hash_del(&EG(persistent_list),str.c,str.len+1);
goto err;
}
}
pgsql = (PGconn *) le->ptr;
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) {
#else
if (atof(PG_VERSION) >= 7.2) {
#endif
pg_result = PQexec(pgsql, "RESET ALL;");
PQclear(pg_result);
}
}
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink);
} else { /* Non persistent connection */
zend_rsrc_list_entry *index_ptr,new_index_ptr;
/* first we check the hash for the hashed_details key. if it exists,
* it should point us to the right offset where the actual pgsql link sits.
* if it doesn't, open a new pgsql link, add it to the resource list,
* and add a pointer to it with hashed_details as the key.
*/
if (!(connect_type & PGSQL_CONNECT_FORCE_NEW)
&& zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) {
int type;
ulong link;
void *ptr;
if (Z_TYPE_P(index_ptr) != le_index_ptr) {
RETURN_FALSE;
}
link = (ulong) index_ptr->ptr;
ptr = zend_list_find(link,&type); /* check if the link is still there */
if (ptr && (type==le_link || type==le_plink)) {
Z_LVAL_P(return_value) = link;
zend_list_addref(link);
php_pgsql_set_default_link(link TSRMLS_CC);
Z_TYPE_P(return_value) = IS_RESOURCE;
goto cleanup;
} else {
zend_hash_del(&EG(regular_list),str.c,str.len+1);
}
}
if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links));
goto err;
}
if (connstring) {
pgsql = PQconnectdb(connstring);
} else {
pgsql = PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* add it to the list */
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link);
/* add it to the hash */
new_index_ptr.ptr = (void *) Z_LVAL_P(return_value);
Z_TYPE(new_index_ptr) = le_index_ptr;
if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
goto err;
}
PGG(num_links)++;
}
/* set notice processer */
if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) {
PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RESVAL_P(return_value));
}
php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC);
cleanup:
smart_str_free(&str);
return;
err:
smart_str_free(&str);
RETURN_FALSE;
}
/* }}} */
#if 0
/* {{{ php_pgsql_get_default_link
*/
static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS)
{
if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */
ht = 0;
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
return PGG(default_link);
}
/* }}} */
#endif
/* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)
Open a PostgreSQL connection */
PHP_FUNCTION(pg_connect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
/* }}} */
/* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)
Open a persistent PostgreSQL connection */
PHP_FUNCTION(pg_pconnect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1);
}
/* }}} */
/* {{{ proto bool pg_close([resource connection])
Close a PostgreSQL connection */
PHP_FUNCTION(pg_close)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (id==-1) { /* explicit resource number */
zend_list_delete(Z_RESVAL_P(pgsql_link));
}
if (id!=-1
|| (pgsql_link && Z_RESVAL_P(pgsql_link)==PGG(default_link))) {
zend_list_delete(PGG(default_link));
PGG(default_link) = -1;
}
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DBNAME 1
#define PHP_PG_ERROR_MESSAGE 2
#define PHP_PG_OPTIONS 3
#define PHP_PG_PORT 4
#define PHP_PG_TTY 5
#define PHP_PG_HOST 6
#define PHP_PG_VERSION 7
/* {{{ php_pgsql_get_link_info
*/
static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
char *msgbuf;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
switch(entry_type) {
case PHP_PG_DBNAME:
Z_STRVAL_P(return_value) = PQdb(pgsql);
break;
case PHP_PG_ERROR_MESSAGE:
RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0);
return;
case PHP_PG_OPTIONS:
Z_STRVAL_P(return_value) = PQoptions(pgsql);
break;
case PHP_PG_PORT:
Z_STRVAL_P(return_value) = PQport(pgsql);
break;
case PHP_PG_TTY:
Z_STRVAL_P(return_value) = PQtty(pgsql);
break;
case PHP_PG_HOST:
Z_STRVAL_P(return_value) = PQhost(pgsql);
break;
case PHP_PG_VERSION:
array_init(return_value);
add_assoc_string(return_value, "client", PG_VERSION, 1);
#if HAVE_PQPROTOCOLVERSION
add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql));
#if HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3) {
add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1);
}
#endif
#endif
return;
default:
RETURN_FALSE;
}
if (Z_STRVAL_P(return_value)) {
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
} else {
Z_STRLEN_P(return_value) = 0;
Z_STRVAL_P(return_value) = (char *) estrdup("");
}
Z_TYPE_P(return_value) = IS_STRING;
}
/* }}} */
/* {{{ proto string pg_dbname([resource connection])
Get the database name */
PHP_FUNCTION(pg_dbname)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME);
}
/* }}} */
/* {{{ proto string pg_last_error([resource connection])
Get the error message string */
PHP_FUNCTION(pg_last_error)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE);
}
/* }}} */
/* {{{ proto string pg_options([resource connection])
Get the options associated with the connection */
PHP_FUNCTION(pg_options)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS);
}
/* }}} */
/* {{{ proto int pg_port([resource connection])
Return the port number associated with the connection */
PHP_FUNCTION(pg_port)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT);
}
/* }}} */
/* {{{ proto string pg_tty([resource connection])
Return the tty name associated with the connection */
PHP_FUNCTION(pg_tty)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY);
}
/* }}} */
/* {{{ proto string pg_host([resource connection])
Returns the host name associated with the connection */
PHP_FUNCTION(pg_host)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST);
}
/* }}} */
/* {{{ proto array pg_version([resource connection])
Returns an array with client, protocol and server version (when available) */
PHP_FUNCTION(pg_version)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION);
}
/* }}} */
#if HAVE_PQPARAMETERSTATUS
/* {{{ proto string|false pg_parameter_status([resource connection,] string param_name)
Returns the value of a server parameter */
PHP_FUNCTION(pg_parameter_status)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
char *param;
int len;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, ¶m, &len) == SUCCESS) {
id = -1;
} else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", ¶m, &len) == SUCCESS) {
pgsql_link = NULL;
id = PGG(default_link);
} else {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
param = (char*)PQparameterStatus(pgsql, param);
if (param) {
RETURN_STRING(param, 1);
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
/* {{{ proto bool pg_ping([resource connection])
Ping database. If connection is bad, try to reconnect. */
PHP_FUNCTION(pg_ping)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
PGresult *res;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) {
id = -1;
} else {
pgsql_link = NULL;
id = PGG(default_link);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* ping connection */
res = PQexec(pgsql, "SELECT 1;");
PQclear(res);
/* check status. */
if (PQstatus(pgsql) == CONNECTION_OK)
RETURN_TRUE;
/* reset connection if it's broken */
PQreset(pgsql);
if (PQstatus(pgsql) == CONNECTION_OK) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto resource pg_query([resource connection,] string query)
Execute a query */
PHP_FUNCTION(pg_query)
{
zval *pgsql_link = NULL;
char *query;
int id = -1, query_len, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQexec(pgsql, query);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexec(pgsql, query);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED
/* {{{ _php_pgsql_free_params */
static void _php_pgsql_free_params(char **params, int num_params)
{
if (num_params > 0) {
int i;
for (i = 0; i < num_params; i++) {
if (params[i]) {
efree(params[i]);
}
}
efree(params);
}
}
/* }}} */
#endif
#if HAVE_PQEXECPARAMS
/* {{{ proto resource pg_query_params([resource connection,] string query, array params)
Execute a query */
PHP_FUNCTION(pg_query_params)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, **tmp;
char *query;
int query_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "sa", &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
for(i = 0; i < num_params; i++) {
if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
if (Z_TYPE_PP(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val = **tmp;
zval_copy_ctor(&tmp_val);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
zval_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_dtor(&tmp_val);
}
zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
}
}
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQPREPARE
/* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query)
Prepare a query for future execution */
PHP_FUNCTION(pg_prepare)
{
zval *pgsql_link = NULL;
char *query, *stmtname;
int query_len, stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQEXECPREPARED
/* {{{ proto resource pg_execute([resource connection,] string stmtname, array params)
Execute a prepared query */
PHP_FUNCTION(pg_execute)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, **tmp;
char *stmtname;
int stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
for(i = 0; i < num_params; i++) {
if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
if (Z_TYPE_PP(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val = **tmp;
zval_copy_ctor(&tmp_val);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
zval_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_dtor(&tmp_val);
}
zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
}
}
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#define PHP_PG_NUM_ROWS 1
#define PHP_PG_NUM_FIELDS 2
#define PHP_PG_CMD_TUPLES 3
/* {{{ php_pgsql_get_result_info
*/
static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
switch (entry_type) {
case PHP_PG_NUM_ROWS:
Z_LVAL_P(return_value) = PQntuples(pgsql_result);
break;
case PHP_PG_NUM_FIELDS:
Z_LVAL_P(return_value) = PQnfields(pgsql_result);
break;
case PHP_PG_CMD_TUPLES:
#if HAVE_PQCMDTUPLES
Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result));
#else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build");
Z_LVAL_P(return_value) = 0;
#endif
break;
default:
RETURN_FALSE;
}
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto int pg_num_rows(resource result)
Return the number of rows in the result */
PHP_FUNCTION(pg_num_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS);
}
/* }}} */
/* {{{ proto int pg_num_fields(resource result)
Return the number of fields in the result */
PHP_FUNCTION(pg_num_fields)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
}
/* }}} */
#if HAVE_PQCMDTUPLES
/* {{{ proto int pg_affected_rows(resource result)
Returns the number of affected tuples */
PHP_FUNCTION(pg_affected_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES);
}
/* }}} */
#endif
/* {{{ proto string pg_last_notice(resource connection)
Returns the last notice set by the backend */
PHP_FUNCTION(pg_last_notice)
{
zval *pgsql_link;
PGconn *pg_link;
int id = -1;
php_pgsql_notice **notice;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
return;
}
/* Just to check if user passed valid resoruce */
ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)¬ice) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL((*notice)->message, (*notice)->len, 1);
}
/* }}} */
/* {{{ get_field_name
*/
static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC)
{
PGresult *result;
smart_str str = {0};
zend_rsrc_list_entry *field_type;
char *ret=NULL;
/* try to lookup the type in the resource list */
smart_str_appends(&str, "pgsql_oid_");
smart_str_append_unsigned(&str, oid);
smart_str_0(&str);
if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) {
ret = estrdup((char *)field_type->ptr);
} else { /* hash all oid's */
int i,num_rows;
int oid_offset,name_offset;
char *tmp_oid, *end_ptr, *tmp_name;
zend_rsrc_list_entry new_oid_entry;
if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) {
if (result) {
PQclear(result);
}
smart_str_free(&str);
return STR_EMPTY_ALLOC();
}
num_rows = PQntuples(result);
oid_offset = PQfnumber(result,"oid");
name_offset = PQfnumber(result,"typname");
for (i=0; i<num_rows; i++) {
if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) {
continue;
}
str.len = 0;
smart_str_appends(&str, "pgsql_oid_");
smart_str_appends(&str, tmp_oid);
smart_str_0(&str);
if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) {
continue;
}
Z_TYPE(new_oid_entry) = le_string;
new_oid_entry.ptr = estrdup(tmp_name);
zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(zend_rsrc_list_entry), NULL);
if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) {
ret = estrdup(tmp_name);
}
}
PQclear(result);
}
smart_str_free(&str);
return ret;
}
/* }}} */
#ifdef HAVE_PQFTABLE
/* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only])
Returns the name of the table field belongs to, or table's oid if oid_only is true */
PHP_FUNCTION(pg_field_table)
{
zval *result;
pgsql_result_handle *pg_result;
long fnum = -1;
zend_bool return_oid = 0;
Oid oid;
smart_str hash_key = {0};
char *table_name;
zend_rsrc_list_entry *field_table;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|b", &result, &fnum, &return_oid) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (fnum < 0 || fnum >= PQnfields(pg_result->result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
oid = PQftable(pg_result->result, fnum);
if (InvalidOid == oid) {
RETURN_FALSE;
}
if (return_oid) {
#if UINT_MAX > LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */
if (oid > LONG_MAX) {
smart_str oidstr = {0};
smart_str_append_unsigned(&oidstr, oid);
smart_str_0(&oidstr);
RETURN_STRINGL(oidstr.c, oidstr.len, 0);
} else
#endif
RETURN_LONG((long)oid);
}
/* try to lookup the table name in the resource list */
smart_str_appends(&hash_key, "pgsql_table_oid_");
smart_str_append_unsigned(&hash_key, oid);
smart_str_0(&hash_key);
if (zend_hash_find(&EG(regular_list), hash_key.c, hash_key.len+1, (void **) &field_table) == SUCCESS) {
smart_str_free(&hash_key);
RETURN_STRING((char *)field_table->ptr, 1);
} else { /* Not found, lookup by querying PostgreSQL system tables */
PGresult *tmp_res;
smart_str querystr = {0};
zend_rsrc_list_entry new_field_table;
smart_str_appends(&querystr, "select relname from pg_class where oid=");
smart_str_append_unsigned(&querystr, oid);
smart_str_0(&querystr);
if ((tmp_res = PQexec(pg_result->conn, querystr.c)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
if (tmp_res) {
PQclear(tmp_res);
}
smart_str_free(&querystr);
smart_str_free(&hash_key);
RETURN_FALSE;
}
smart_str_free(&querystr);
if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
PQclear(tmp_res);
smart_str_free(&hash_key);
RETURN_FALSE;
}
Z_TYPE(new_field_table) = le_string;
new_field_table.ptr = estrdup(table_name);
zend_hash_update(&EG(regular_list), hash_key.c, hash_key.len+1, (void *) &new_field_table, sizeof(zend_rsrc_list_entry), NULL);
smart_str_free(&hash_key);
PQclear(tmp_res);
RETURN_STRING(table_name, 1);
}
}
/* }}} */
#endif
#define PHP_PG_FIELD_NAME 1
#define PHP_PG_FIELD_SIZE 2
#define PHP_PG_FIELD_TYPE 3
#define PHP_PG_FIELD_TYPE_OID 4
/* {{{ php_pgsql_get_field_info
*/
static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
long field;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
Oid oid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &field) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (field < 0 || field >= PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_FIELD_NAME:
Z_STRVAL_P(return_value) = PQfname(pgsql_result, field);
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
break;
case PHP_PG_FIELD_SIZE:
Z_LVAL_P(return_value) = PQfsize(pgsql_result, field);
Z_TYPE_P(return_value) = IS_LONG;
break;
case PHP_PG_FIELD_TYPE:
Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, field), &EG(regular_list) TSRMLS_CC);
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
break;
case PHP_PG_FIELD_TYPE_OID:
oid = PQftype(pgsql_result, field);
#if UINT_MAX > LONG_MAX
if (oid > LONG_MAX) {
smart_str s = {0};
smart_str_append_unsigned(&s, oid);
smart_str_0(&s);
Z_STRVAL_P(return_value) = s.c;
Z_STRLEN_P(return_value) = s.len;
Z_TYPE_P(return_value) = IS_STRING;
} else
#endif
{
Z_LVAL_P(return_value) = (long)oid;
Z_TYPE_P(return_value) = IS_LONG;
}
break;
default:
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string pg_field_name(resource result, int field_number)
Returns the name of the field */
PHP_FUNCTION(pg_field_name)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME);
}
/* }}} */
/* {{{ proto int pg_field_size(resource result, int field_number)
Returns the internal size of the field */
PHP_FUNCTION(pg_field_size)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE);
}
/* }}} */
/* {{{ proto string pg_field_type(resource result, int field_number)
Returns the type name for the given field */
PHP_FUNCTION(pg_field_type)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE);
}
/* }}} */
/* {{{ proto string pg_field_type_oid(resource result, int field_number)
Returns the type oid for the given field */
PHP_FUNCTION(pg_field_type_oid)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID);
}
/* }}} */
/* {{{ proto int pg_field_num(resource result, string field_name)
Returns the field number of the named field */
PHP_FUNCTION(pg_field_num)
{
zval *result;
char *field;
int field_len;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result, &field, &field_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
Z_LVAL_P(return_value) = PQfnumber(pgsql_result, field);
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)
Returns values from a result identifier */
PHP_FUNCTION(pg_fetch_result)
{
zval *result, **field=NULL;
long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
pgsql_row = row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
}
switch(Z_TYPE_PP(field)) {
case IS_STRING:
field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
break;
default:
convert_to_long_ex(field);
field_offset = Z_LVAL_PP(field);
break;
}
if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
Z_TYPE_P(return_value) = IS_NULL;
} else {
char *value = PQgetvalue(pgsql_result, pgsql_row, field_offset);
int value_len = PQgetlength(pgsql_result, pgsql_row, field_offset);
ZVAL_STRINGL(return_value, value, value_len, 1);
}
}
/* }}} */
/* {{{ void php_pgsql_fetch_hash */
static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object)
{
zval *result, *zrow = NULL;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int i, num_fields, pgsql_row, use_row;
long row = -1;
char *field_name;
zval *ctor_params = NULL;
zend_class_entry *ce = NULL;
if (into_object) {
char *class_name = NULL;
int class_name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!sz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) {
return;
}
if (!class_name) {
ce = zend_standard_class_def;
} else {
ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
}
if (!ce) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name);
return;
}
result_type = PGSQL_ASSOC;
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!l", &result, &zrow, &result_type) == FAILURE) {
return;
}
}
if (zrow == NULL) {
row = -1;
} else {
convert_to_long(zrow);
row = Z_LVAL_P(zrow);
if (row < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The row parameter must be greater or equal to zero");
RETURN_FALSE;
}
}
use_row = ZEND_NUM_ARGS() > 1 && row != -1;
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (use_row) {
pgsql_row = row;
pg_result->row = pgsql_row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
} else {
/* If 2nd param is NULL, use internal row counter to access next row */
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
pg_result->row++;
}
array_init(return_value);
for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) {
if (PQgetisnull(pgsql_result, pgsql_row, i)) {
if (result_type & PGSQL_NUM) {
add_index_null(return_value, i);
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_null(return_value, field_name);
}
} else {
char *element = PQgetvalue(pgsql_result, pgsql_row, i);
if (element) {
char *data;
int data_len;
int should_copy=0;
const uint element_len = strlen(element);
data = safe_estrndup(element, element_len);
data_len = element_len;
if (result_type & PGSQL_NUM) {
add_index_stringl(return_value, i, data, data_len, should_copy);
should_copy=1;
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_stringl(return_value, field_name, data, data_len, should_copy);
}
}
}
}
if (into_object) {
zval dataset = *return_value;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *retval_ptr;
object_and_properties_init(return_value, ce, NULL);
zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
if (ce->constructor) {
fci.size = sizeof(fci);
fci.function_table = &ce->function_table;
fci.function_name = NULL;
fci.symbol_table = NULL;
fci.object_ptr = return_value;
fci.retval_ptr_ptr = &retval_ptr;
if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
if (Z_TYPE_P(ctor_params) == IS_ARRAY) {
HashTable *ht = Z_ARRVAL_P(ctor_params);
Bucket *p;
fci.param_count = 0;
fci.params = safe_emalloc(sizeof(zval***), ht->nNumOfElements, 0);
p = ht->pListHead;
while (p != NULL) {
fci.params[fci.param_count++] = (zval**)p->pData;
p = p->pListNext;
}
} else {
/* Two problems why we throw exceptions here: PHP is typeless
* and hence passing one argument that's not an array could be
* by mistake and the other way round is possible, too. The
* single value is an array. Also we'd have to make that one
* argument passed by reference.
*/
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC);
return;
}
} else {
fci.param_count = 0;
fci.params = NULL;
}
fci.no_separation = 1;
fcc.initialized = 1;
fcc.function_handler = ce->constructor;
fcc.calling_scope = EG(scope);
fcc.called_scope = Z_OBJCE_P(return_value);
fcc.object_ptr = return_value;
if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name);
} else {
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
}
if (fci.params) {
efree(fci.params);
}
} else if (ctor_params) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name);
}
}
}
/* }}} */
/* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]])
Get a row as an enumerated array */
PHP_FUNCTION(pg_fetch_row)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_assoc(resource result [, int row])
Fetch a row as an assoc array */
PHP_FUNCTION(pg_fetch_assoc)
{
/* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when
there is 3rd parameter */
if (ZEND_NUM_ARGS() > 2)
WRONG_PARAM_COUNT;
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]])
Fetch a row as an array */
PHP_FUNCTION(pg_fetch_array)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0);
}
/* }}} */
/* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])
Fetch a row as an object */
PHP_FUNCTION(pg_fetch_object)
{
/* pg_fetch_object() allowed result_type used to be. 3rd parameter
must be allowed for compatibility */
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1);
}
/* }}} */
/* {{{ proto array pg_fetch_all(resource result)
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
array_init(return_value);
if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) {
zval_dtor(return_value);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto array pg_fetch_all_columns(resource result [, int column_number])
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all_columns)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
unsigned long colno=0;
int pg_numrows, pg_row;
size_t num_fields;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
num_fields = PQnfields(pgsql_result);
if (colno >= num_fields || colno < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno);
RETURN_FALSE;
}
array_init(return_value);
if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
return;
}
for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
if (PQgetisnull(pgsql_result, pg_row, colno)) {
add_next_index_null(return_value);
} else {
add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1);
}
}
}
/* }}} */
/* {{{ proto bool pg_result_seek(resource result, int offset)
Set internal row offset */
PHP_FUNCTION(pg_result_seek)
{
zval *result;
long row;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (row < 0 || row >= PQntuples(pg_result->result)) {
RETURN_FALSE;
}
/* seek to offset */
pg_result->row = row;
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DATA_LENGTH 1
#define PHP_PG_DATA_ISNULL 2
/* {{{ php_pgsql_data_info
*/
static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result, **field;
long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
pgsql_row = row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
}
switch(Z_TYPE_PP(field)) {
case IS_STRING:
convert_to_string_ex(field);
field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
break;
default:
convert_to_long_ex(field);
field_offset = Z_LVAL_PP(field);
break;
}
if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_DATA_LENGTH:
Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset);
break;
case PHP_PG_DATA_ISNULL:
Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset);
break;
}
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)
Returns the printed length */
PHP_FUNCTION(pg_field_prtlen)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH);
}
/* }}} */
/* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)
Test if a field is NULL */
PHP_FUNCTION(pg_field_is_null)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL);
}
/* }}} */
/* {{{ proto bool pg_free_result(resource result)
Free result memory */
PHP_FUNCTION(pg_free_result)
{
zval *result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (Z_LVAL_P(result) == 0) {
RETURN_FALSE;
}
zend_list_delete(Z_RESVAL_P(result));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string pg_last_oid(resource result)
Returns the last object identifier */
PHP_FUNCTION(pg_last_oid)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
#ifdef HAVE_PQOIDVALUE
Oid oid;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
#ifdef HAVE_PQOIDVALUE
oid = PQoidValue(pgsql_result);
if (oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(oid);
#else
Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result);
if (Z_STRVAL_P(return_value)) {
RETURN_STRING(Z_STRVAL_P(return_value), 1);
}
RETURN_STRING("", 1);
#endif
}
/* }}} */
/* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]])
Enable tracing a PostgreSQL connection */
PHP_FUNCTION(pg_trace)
{
char *z_filename, *mode = "w";
int z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = PGG(default_link);
if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_untrace([resource connection])
Disable tracing of a PostgreSQL connection */
PHP_FUNCTION(pg_untrace)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
PQuntrace(pgsql);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid])
Create a large object */
PHP_FUNCTION(pg_lo_create)
{
zval *pgsql_link = NULL, *oid = NULL;
PGconn *pgsql;
Oid pgsql_oid, wanted_oid = InvalidOid;
int id = -1, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|zz", &pgsql_link, &oid) == FAILURE) {
return;
}
if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) {
oid = pgsql_link;
pgsql_link = NULL;
}
if (pgsql_link == NULL) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
if (id == -1) {
RETURN_FALSE;
}
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_CREATE
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL");
#else
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (long)InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
#endif
}
if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid)
Delete a large object */
PHP_FUNCTION(pg_lo_unlink)
{
zval *pgsql_link = NULL;
long oid_long;
char *oid_string, *end_ptr;
int oid_strlen;
PGconn *pgsql;
Oid oid;
int id = -1;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid type is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rl", &pgsql_link, &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"s", &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"l", &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_unlink(pgsql, oid) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode)
Open a large object and return fd */
PHP_FUNCTION(pg_lo_open)
{
zval *pgsql_link = NULL;
long oid_long;
char *oid_string, *end_ptr, *mode_string;
int oid_strlen, mode_strlen;
PGconn *pgsql;
Oid oid;
int id = -1, pgsql_mode=0, pgsql_lofd;
int create=0;
pgLofp *pgsql_lofp;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of
faster to type. Unfortunately, doesn't behave the same way as fopen()...
(Jouni)
*/
if (strchr(mode_string, 'r') == mode_string) {
pgsql_mode |= INV_READ;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_WRITE;
}
}
if (strchr(mode_string, 'w') == mode_string) {
pgsql_mode |= INV_WRITE;
create = 1;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_READ;
}
}
pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp));
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (create) {
if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
} else {
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (lo_unlink(pgsql, oid) == -1) {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP");
RETURN_FALSE;
}
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC);
Z_TYPE_P(return_value) = IS_LONG;
}
}
} else {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
}
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
}
}
/* }}} */
/* {{{ proto bool pg_lo_close(resource large_object)
Close a large object */
PHP_FUNCTION(pg_lo_close)
{
zval *pgsql_lofp;
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_lofp) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_lofp, -1, "PostgreSQL large object", le_lofp);
if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd);
RETVAL_FALSE;
} else {
RETVAL_TRUE;
}
zend_list_delete(Z_RESVAL_P(pgsql_lofp));
return;
}
/* }}} */
#define PGSQL_LO_READ_BUF_SIZE 8192
/* {{{ proto string pg_lo_read(resource large_object [, int len])
Read a large object */
PHP_FUNCTION(pg_lo_read)
{
zval *pgsql_id;
long len;
int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes, argc = ZEND_NUM_ARGS();
char *buf;
pgLofp *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &pgsql_id, &len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (argc > 1) {
buf_len = len;
}
buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0);
if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) {
efree(buf);
RETURN_FALSE;
}
buf[nbytes] = '\0';
RETURN_STRINGL(buf, nbytes, 0);
}
/* }}} */
/* {{{ proto int pg_lo_write(resource large_object, string buf [, int len])
Write a large object */
PHP_FUNCTION(pg_lo_write)
{
zval *pgsql_id;
char *str;
long z_len;
int str_len, nbytes;
int len;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) {
return;
}
if (argc > 2) {
if (z_len > str_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld", str_len, z_len);
RETURN_FALSE;
}
if (z_len < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", z_len);
RETURN_FALSE;
}
len = z_len;
}
else {
len = str_len;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) {
RETURN_FALSE;
}
RETURN_LONG(nbytes);
}
/* }}} */
/* {{{ proto int pg_lo_read_all(resource large_object)
Read a large object and send straight to browser */
PHP_FUNCTION(pg_lo_read_all)
{
zval *pgsql_id;
int tbytes;
volatile int nbytes;
char buf[PGSQL_LO_READ_BUF_SIZE];
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
tbytes = 0;
while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) {
PHPWRITE(buf, nbytes);
tbytes += nbytes;
}
RETURN_LONG(tbytes);
}
/* }}} */
/* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid])
Import large object direct from filesystem */
PHP_FUNCTION(pg_lo_import)
{
zval *pgsql_link = NULL, *oid = NULL;
char *file_in;
int id = -1, name_len;
int argc = ZEND_NUM_ARGS();
PGconn *pgsql;
Oid returned_oid;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) {
;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"p|z", &file_in, &name_len, &oid) == SUCCESS) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
/* old calling convention, deprecated since PHP 4.2 */
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
}
else {
WRONG_PARAM_COUNT;
}
if (php_check_open_basedir(file_in TSRMLS_CC)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_IMPORT_WITH_OID
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "OID value passing not supported");
#else
Oid wanted_oid;
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (long)InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
#endif
}
returned_oid = lo_import(pgsql, file_in);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename)
Export large object direct to filesystem */
PHP_FUNCTION(pg_lo_export)
{
zval *pgsql_link = NULL;
char *file_out, *oid_string, *end_ptr;
int oid_strlen;
int id = -1, name_len;
long oid_long;
Oid oid;
PGconn *pgsql;
int argc = ZEND_NUM_ARGS();
/* allow string to handle large OID value correctly */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"lp", &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments");
RETURN_FALSE;
}
if (php_check_open_basedir(file_out TSRMLS_CC)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_export(pgsql, oid, file_out)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence])
Seeks position of large object */
PHP_FUNCTION(pg_lo_seek)
{
zval *pgsql_id = NULL;
long offset = 0, whence = SEEK_CUR;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) {
return;
}
if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter");
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence) > -1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int pg_lo_tell(resource large_object)
Returns current position of large object */
PHP_FUNCTION(pg_lo_tell)
{
zval *pgsql_id = NULL;
int offset = 0;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
RETURN_LONG(offset);
}
/* }}} */
#if HAVE_PQSETERRORVERBOSITY
/* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity)
Set error verbosity */
PHP_FUNCTION(pg_set_error_verbosity)
{
zval *pgsql_link = NULL;
long verbosity;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "l", &verbosity) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_link, &verbosity) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) {
Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, verbosity);
Z_TYPE_P(return_value) = IS_LONG;
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
#ifdef HAVE_PQCLIENTENCODING
/* {{{ proto int pg_set_client_encoding([resource connection,] string encoding)
Set client encoding */
PHP_FUNCTION(pg_set_client_encoding)
{
char *encoding;
int encoding_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "s", &encoding, &encoding_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, encoding);
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto string pg_client_encoding([resource connection])
Get the current client encoding */
PHP_FUNCTION(pg_client_encoding)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* Just do the same as found in PostgreSQL sources... */
Z_STRVAL_P(return_value) = (char *) pg_encoding_to_char(PQclientEncoding(pgsql));
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
}
/* }}} */
#endif
#if !HAVE_PQGETCOPYDATA
#define COPYBUFSIZ 8192
#endif
/* {{{ proto bool pg_end_copy([resource connection])
Sync with backend. Completes the Copy command */
PHP_FUNCTION(pg_end_copy)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
int result = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQendcopy(pgsql);
if (result!=0) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_put_line([resource connection,] string query)
Send null-terminated string to backend server*/
PHP_FUNCTION(pg_put_line)
{
char *query;
zval *pgsql_link = NULL;
int query_len, id = -1;
PGconn *pgsql;
int result = 0, argc = ZEND_NUM_ARGS();
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQputline(pgsql, query);
if (result==EOF) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])
Copy table to array */
PHP_FUNCTION(pg_copy_to)
{
zval *pgsql_link;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
int table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0;
char *query;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int copydone = 0;
#if !HAVE_PQGETCOPYDATA
char copybuf[COPYBUFSIZ];
#endif
char *csv = (char *)NULL;
int ret;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss",
&pgsql_link, &table_name, &table_name_len,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!pg_null_as) {
pg_null_as = safe_estrdup("\\\\N");
free_pg_null = 1;
}
spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (free_pg_null) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_OUT:
if (pgsql_result) {
PQclear(pgsql_result);
array_init(return_value);
#if HAVE_PQGETCOPYDATA
while (!copydone)
{
ret = PQgetCopyData(pgsql, &csv, 0);
switch (ret) {
case -1:
copydone = 1;
break;
case 0:
case -2:
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
break;
default:
add_next_index_string(return_value, csv, 1);
PQfreemem(csv);
break;
}
}
#else
while (!copydone)
{
if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) {
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
}
if (copybuf[0] == '\\' &&
copybuf[1] == '.' &&
copybuf[2] == '\0')
{
copydone = 1;
}
else
{
if (csv == (char *)NULL) {
csv = estrdup(copybuf);
} else {
csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1));
strcat(csv, copybuf);
}
switch (ret)
{
case EOF:
copydone = 1;
case 0:
add_next_index_string(return_value, csv, 1);
efree(csv);
csv = (char *)NULL;
break;
case 1:
break;
}
}
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])
Copy table from array */
PHP_FUNCTION(pg_copy_from)
{
zval *pgsql_link = NULL, *pg_rows;
zval **tmp;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
int table_name_len, pg_delim_len, pg_null_as_len;
int pg_null_as_free = 0;
char *query;
HashPosition pos;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rsa|ss",
&pgsql_link, &table_name, &table_name_len, &pg_rows,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
if (!pg_null_as) {
pg_null_as = safe_estrdup("\\\\N");
pg_null_as_free = 1;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (pg_null_as_free) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_IN:
if (pgsql_result) {
int command_failed = 0;
PQclear(pgsql_result);
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
#if HAVE_PQPUTCOPYDATA
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
}
if (PQputCopyData(pgsql, query, strlen(query)) != 1) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
}
if (PQputCopyEnd(pgsql, NULL) != 1) {
PHP_PQ_ERROR("putcopyend failed: %s", pgsql);
RETURN_FALSE;
}
#else
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
}
if (PQputline(pgsql, query)==EOF) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
}
if (PQputline(pgsql, "\\.\n") == EOF) {
PHP_PQ_ERROR("putline failed: %s", pgsql);
RETURN_FALSE;
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
command_failed = 1;
}
PQclear(pgsql_result);
}
if (command_failed) {
RETURN_FALSE;
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
RETURN_TRUE;
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
#ifdef HAVE_PQESCAPE
/* {{{ proto string pg_escape_string([resource connection,] string data)
Escape string for text/char type */
PHP_FUNCTION(pg_escape_string)
{
char *from = NULL, *to = NULL;
zval *pgsql_link;
#ifdef HAVE_PQESCAPE_CONN
PGconn *pgsql;
#endif
int to_len;
int from_len;
int id = -1;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = PGG(default_link);
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
to = (char *) safe_emalloc(from_len, 2, 1);
#ifdef HAVE_PQESCAPE_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL);
} else
#endif
to_len = (int) PQescapeString(to, from, (size_t)from_len);
RETURN_STRINGL(to, to_len, 0);
}
/* }}} */
/* {{{ proto string pg_escape_bytea([resource connection,] string data)
Escape binary for bytea type */
PHP_FUNCTION(pg_escape_bytea)
{
char *from = NULL, *to = NULL;
size_t to_len;
int from_len, id = -1;
#ifdef HAVE_PQESCAPE_BYTEA_CONN
PGconn *pgsql;
#endif
zval *pgsql_link;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = PGG(default_link);
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
#ifdef HAVE_PQESCAPE_BYTEA_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len);
} else
#endif
to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */
PQfreemem(to);
}
/* }}} */
#if !HAVE_PQUNESCAPEBYTEA
/* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users.
Renamed to php_pgsql_unescape_bytea() */
/*
* PQunescapeBytea - converts the null terminated string representation
* of a bytea, strtext, into binary, filling a buffer. It returns a
* pointer to the buffer which is NULL on error, and the size of the
* buffer in retbuflen. The pointer may subsequently be used as an
* argument to the function free(3). It is the reverse of PQescapeBytea.
*
* The following transformations are reversed:
* '\0' == ASCII 0 == \000
* '\'' == ASCII 39 == \'
* '\\' == ASCII 92 == \\
*
* States:
* 0 normal 0->1->2->3->4
* 1 \ 1->5
* 2 \0 1->6
* 3 \00
* 4 \000
* 5 \'
* 6 \\
*/
static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen)
{
size_t buflen;
unsigned char *buffer,
*sp,
*bp;
unsigned int state = 0;
if (strtext == NULL)
return NULL;
buflen = strlen(strtext); /* will shrink, also we discover if
* strtext */
buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */
for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++)
{
Commit Message:
CWE ID: CWE-254 | static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL;
PGconn *pgsql;
smart_str str = {0};
zval **args[5];
int i, connect_type = 0;
PGresult *pg_result;
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5
|| zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) {
WRONG_PARAM_COUNT;
}
smart_str_appends(&str, "pgsql");
for (i = 0; i < ZEND_NUM_ARGS(); i++) {
/* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections
* can re-use this connection. Bug #39979
*/
if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE_PP(args[i]) == IS_LONG) {
if (Z_LVAL_PP(args[1]) == PGSQL_CONNECT_FORCE_NEW) {
continue;
} else if (Z_LVAL_PP(args[1]) & PGSQL_CONNECT_FORCE_NEW) {
smart_str_append_long(&str, Z_LVAL_PP(args[1]) ^ PGSQL_CONNECT_FORCE_NEW);
}
}
convert_to_string_ex(args[i]);
smart_str_appendc(&str, '_');
smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i]));
}
smart_str_0(&str);
if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */
connstring = Z_STRVAL_PP(args[0]);
} else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */
connstring = Z_STRVAL_PP(args[0]);
convert_to_long_ex(args[1]);
connect_type = Z_LVAL_PP(args[1]);
} else {
host = Z_STRVAL_PP(args[0]);
port = Z_STRVAL_PP(args[1]);
dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]);
switch (ZEND_NUM_ARGS()) {
case 5:
tty = Z_STRVAL_PP(args[3]);
/* fall through */
case 4:
options = Z_STRVAL_PP(args[2]);
break;
}
}
if (persistent && PGG(allow_persistent)) {
zend_rsrc_list_entry *le;
/* try to find if we already have this link in our persistent list */
if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) { /* we don't */
zend_rsrc_list_entry new_le;
if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Cannot create new link. Too many open links (%ld)", PGG(num_links));
goto err;
}
if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent));
goto err;
}
/* create the link */
if (connstring) {
pgsql=PQconnectdb(connstring);
} else {
pgsql=PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql)
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* hash it up */
Z_TYPE(new_le) = le_plink;
new_le.ptr = pgsql;
if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
goto err;
}
PGG(num_links)++;
PGG(num_persistent)++;
} else { /* we do */
if (Z_TYPE_P(le) != le_plink) {
RETURN_FALSE;
}
/* ensure that the link did not die */
if (PGG(auto_reset_persistent) & 1) {
/* need to send & get something from backend to
make sure we catch CONNECTION_BAD everytime */
PGresult *pg_result;
pg_result = PQexec(le->ptr, "select 1");
PQclear(pg_result);
}
if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */
if (le->ptr == NULL) {
if (connstring) {
le->ptr=PQconnectdb(connstring);
} else {
le->ptr=PQsetdb(host,port,options,tty,dbname);
}
}
else {
PQreset(le->ptr);
}
if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect");
zend_hash_del(&EG(persistent_list),str.c,str.len+1);
goto err;
}
}
pgsql = (PGconn *) le->ptr;
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) {
#else
if (atof(PG_VERSION) >= 7.2) {
#endif
pg_result = PQexec(pgsql, "RESET ALL;");
PQclear(pg_result);
}
}
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink);
} else { /* Non persistent connection */
zend_rsrc_list_entry *index_ptr,new_index_ptr;
/* first we check the hash for the hashed_details key. if it exists,
* it should point us to the right offset where the actual pgsql link sits.
* if it doesn't, open a new pgsql link, add it to the resource list,
* and add a pointer to it with hashed_details as the key.
*/
if (!(connect_type & PGSQL_CONNECT_FORCE_NEW)
&& zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) {
int type;
ulong link;
void *ptr;
if (Z_TYPE_P(index_ptr) != le_index_ptr) {
RETURN_FALSE;
}
link = (ulong) index_ptr->ptr;
ptr = zend_list_find(link,&type); /* check if the link is still there */
if (ptr && (type==le_link || type==le_plink)) {
Z_LVAL_P(return_value) = link;
zend_list_addref(link);
php_pgsql_set_default_link(link TSRMLS_CC);
Z_TYPE_P(return_value) = IS_RESOURCE;
goto cleanup;
} else {
zend_hash_del(&EG(regular_list),str.c,str.len+1);
}
}
if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links));
goto err;
}
if (connstring) {
pgsql = PQconnectdb(connstring);
} else {
pgsql = PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* add it to the list */
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link);
/* add it to the hash */
new_index_ptr.ptr = (void *) Z_LVAL_P(return_value);
Z_TYPE(new_index_ptr) = le_index_ptr;
if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
goto err;
}
PGG(num_links)++;
}
/* set notice processer */
if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) {
PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RESVAL_P(return_value));
}
php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC);
cleanup:
smart_str_free(&str);
return;
err:
smart_str_free(&str);
RETURN_FALSE;
}
/* }}} */
#if 0
/* {{{ php_pgsql_get_default_link
*/
static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS)
{
if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */
ht = 0;
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
return PGG(default_link);
}
/* }}} */
#endif
/* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)
Open a PostgreSQL connection */
PHP_FUNCTION(pg_connect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
/* }}} */
/* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)
Open a persistent PostgreSQL connection */
PHP_FUNCTION(pg_pconnect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1);
}
/* }}} */
/* {{{ proto bool pg_close([resource connection])
Close a PostgreSQL connection */
PHP_FUNCTION(pg_close)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (id==-1) { /* explicit resource number */
zend_list_delete(Z_RESVAL_P(pgsql_link));
}
if (id!=-1
|| (pgsql_link && Z_RESVAL_P(pgsql_link)==PGG(default_link))) {
zend_list_delete(PGG(default_link));
PGG(default_link) = -1;
}
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DBNAME 1
#define PHP_PG_ERROR_MESSAGE 2
#define PHP_PG_OPTIONS 3
#define PHP_PG_PORT 4
#define PHP_PG_TTY 5
#define PHP_PG_HOST 6
#define PHP_PG_VERSION 7
/* {{{ php_pgsql_get_link_info
*/
static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
char *msgbuf;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
switch(entry_type) {
case PHP_PG_DBNAME:
Z_STRVAL_P(return_value) = PQdb(pgsql);
break;
case PHP_PG_ERROR_MESSAGE:
RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0);
return;
case PHP_PG_OPTIONS:
Z_STRVAL_P(return_value) = PQoptions(pgsql);
break;
case PHP_PG_PORT:
Z_STRVAL_P(return_value) = PQport(pgsql);
break;
case PHP_PG_TTY:
Z_STRVAL_P(return_value) = PQtty(pgsql);
break;
case PHP_PG_HOST:
Z_STRVAL_P(return_value) = PQhost(pgsql);
break;
case PHP_PG_VERSION:
array_init(return_value);
add_assoc_string(return_value, "client", PG_VERSION, 1);
#if HAVE_PQPROTOCOLVERSION
add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql));
#if HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3) {
add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1);
}
#endif
#endif
return;
default:
RETURN_FALSE;
}
if (Z_STRVAL_P(return_value)) {
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
} else {
Z_STRLEN_P(return_value) = 0;
Z_STRVAL_P(return_value) = (char *) estrdup("");
}
Z_TYPE_P(return_value) = IS_STRING;
}
/* }}} */
/* {{{ proto string pg_dbname([resource connection])
Get the database name */
PHP_FUNCTION(pg_dbname)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME);
}
/* }}} */
/* {{{ proto string pg_last_error([resource connection])
Get the error message string */
PHP_FUNCTION(pg_last_error)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE);
}
/* }}} */
/* {{{ proto string pg_options([resource connection])
Get the options associated with the connection */
PHP_FUNCTION(pg_options)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS);
}
/* }}} */
/* {{{ proto int pg_port([resource connection])
Return the port number associated with the connection */
PHP_FUNCTION(pg_port)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT);
}
/* }}} */
/* {{{ proto string pg_tty([resource connection])
Return the tty name associated with the connection */
PHP_FUNCTION(pg_tty)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY);
}
/* }}} */
/* {{{ proto string pg_host([resource connection])
Returns the host name associated with the connection */
PHP_FUNCTION(pg_host)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST);
}
/* }}} */
/* {{{ proto array pg_version([resource connection])
Returns an array with client, protocol and server version (when available) */
PHP_FUNCTION(pg_version)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION);
}
/* }}} */
#if HAVE_PQPARAMETERSTATUS
/* {{{ proto string|false pg_parameter_status([resource connection,] string param_name)
Returns the value of a server parameter */
PHP_FUNCTION(pg_parameter_status)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
char *param;
int len;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, ¶m, &len) == SUCCESS) {
id = -1;
} else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", ¶m, &len) == SUCCESS) {
pgsql_link = NULL;
id = PGG(default_link);
} else {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
param = (char*)PQparameterStatus(pgsql, param);
if (param) {
RETURN_STRING(param, 1);
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
/* {{{ proto bool pg_ping([resource connection])
Ping database. If connection is bad, try to reconnect. */
PHP_FUNCTION(pg_ping)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
PGresult *res;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) {
id = -1;
} else {
pgsql_link = NULL;
id = PGG(default_link);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* ping connection */
res = PQexec(pgsql, "SELECT 1;");
PQclear(res);
/* check status. */
if (PQstatus(pgsql) == CONNECTION_OK)
RETURN_TRUE;
/* reset connection if it's broken */
PQreset(pgsql);
if (PQstatus(pgsql) == CONNECTION_OK) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto resource pg_query([resource connection,] string query)
Execute a query */
PHP_FUNCTION(pg_query)
{
zval *pgsql_link = NULL;
char *query;
int id = -1, query_len, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQexec(pgsql, query);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexec(pgsql, query);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED
/* {{{ _php_pgsql_free_params */
static void _php_pgsql_free_params(char **params, int num_params)
{
if (num_params > 0) {
int i;
for (i = 0; i < num_params; i++) {
if (params[i]) {
efree(params[i]);
}
}
efree(params);
}
}
/* }}} */
#endif
#if HAVE_PQEXECPARAMS
/* {{{ proto resource pg_query_params([resource connection,] string query, array params)
Execute a query */
PHP_FUNCTION(pg_query_params)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, **tmp;
char *query;
int query_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "sa", &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
for(i = 0; i < num_params; i++) {
if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
if (Z_TYPE_PP(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val = **tmp;
zval_copy_ctor(&tmp_val);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
zval_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_dtor(&tmp_val);
}
zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
}
}
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQPREPARE
/* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query)
Prepare a query for future execution */
PHP_FUNCTION(pg_prepare)
{
zval *pgsql_link = NULL;
char *query, *stmtname;
int query_len, stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQEXECPREPARED
/* {{{ proto resource pg_execute([resource connection,] string stmtname, array params)
Execute a prepared query */
PHP_FUNCTION(pg_execute)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, **tmp;
char *stmtname;
int stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
for(i = 0; i < num_params; i++) {
if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
if (Z_TYPE_PP(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val = **tmp;
zval_copy_ctor(&tmp_val);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
zval_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_dtor(&tmp_val);
}
zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
}
}
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#define PHP_PG_NUM_ROWS 1
#define PHP_PG_NUM_FIELDS 2
#define PHP_PG_CMD_TUPLES 3
/* {{{ php_pgsql_get_result_info
*/
static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
switch (entry_type) {
case PHP_PG_NUM_ROWS:
Z_LVAL_P(return_value) = PQntuples(pgsql_result);
break;
case PHP_PG_NUM_FIELDS:
Z_LVAL_P(return_value) = PQnfields(pgsql_result);
break;
case PHP_PG_CMD_TUPLES:
#if HAVE_PQCMDTUPLES
Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result));
#else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build");
Z_LVAL_P(return_value) = 0;
#endif
break;
default:
RETURN_FALSE;
}
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto int pg_num_rows(resource result)
Return the number of rows in the result */
PHP_FUNCTION(pg_num_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS);
}
/* }}} */
/* {{{ proto int pg_num_fields(resource result)
Return the number of fields in the result */
PHP_FUNCTION(pg_num_fields)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
}
/* }}} */
#if HAVE_PQCMDTUPLES
/* {{{ proto int pg_affected_rows(resource result)
Returns the number of affected tuples */
PHP_FUNCTION(pg_affected_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES);
}
/* }}} */
#endif
/* {{{ proto string pg_last_notice(resource connection)
Returns the last notice set by the backend */
PHP_FUNCTION(pg_last_notice)
{
zval *pgsql_link;
PGconn *pg_link;
int id = -1;
php_pgsql_notice **notice;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
return;
}
/* Just to check if user passed valid resoruce */
ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)¬ice) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL((*notice)->message, (*notice)->len, 1);
}
/* }}} */
/* {{{ get_field_name
*/
static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC)
{
PGresult *result;
smart_str str = {0};
zend_rsrc_list_entry *field_type;
char *ret=NULL;
/* try to lookup the type in the resource list */
smart_str_appends(&str, "pgsql_oid_");
smart_str_append_unsigned(&str, oid);
smart_str_0(&str);
if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) {
ret = estrdup((char *)field_type->ptr);
} else { /* hash all oid's */
int i,num_rows;
int oid_offset,name_offset;
char *tmp_oid, *end_ptr, *tmp_name;
zend_rsrc_list_entry new_oid_entry;
if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) {
if (result) {
PQclear(result);
}
smart_str_free(&str);
return STR_EMPTY_ALLOC();
}
num_rows = PQntuples(result);
oid_offset = PQfnumber(result,"oid");
name_offset = PQfnumber(result,"typname");
for (i=0; i<num_rows; i++) {
if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) {
continue;
}
str.len = 0;
smart_str_appends(&str, "pgsql_oid_");
smart_str_appends(&str, tmp_oid);
smart_str_0(&str);
if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) {
continue;
}
Z_TYPE(new_oid_entry) = le_string;
new_oid_entry.ptr = estrdup(tmp_name);
zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(zend_rsrc_list_entry), NULL);
if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) {
ret = estrdup(tmp_name);
}
}
PQclear(result);
}
smart_str_free(&str);
return ret;
}
/* }}} */
#ifdef HAVE_PQFTABLE
/* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only])
Returns the name of the table field belongs to, or table's oid if oid_only is true */
PHP_FUNCTION(pg_field_table)
{
zval *result;
pgsql_result_handle *pg_result;
long fnum = -1;
zend_bool return_oid = 0;
Oid oid;
smart_str hash_key = {0};
char *table_name;
zend_rsrc_list_entry *field_table;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|b", &result, &fnum, &return_oid) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (fnum < 0 || fnum >= PQnfields(pg_result->result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
oid = PQftable(pg_result->result, fnum);
if (InvalidOid == oid) {
RETURN_FALSE;
}
if (return_oid) {
#if UINT_MAX > LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */
if (oid > LONG_MAX) {
smart_str oidstr = {0};
smart_str_append_unsigned(&oidstr, oid);
smart_str_0(&oidstr);
RETURN_STRINGL(oidstr.c, oidstr.len, 0);
} else
#endif
RETURN_LONG((long)oid);
}
/* try to lookup the table name in the resource list */
smart_str_appends(&hash_key, "pgsql_table_oid_");
smart_str_append_unsigned(&hash_key, oid);
smart_str_0(&hash_key);
if (zend_hash_find(&EG(regular_list), hash_key.c, hash_key.len+1, (void **) &field_table) == SUCCESS) {
smart_str_free(&hash_key);
RETURN_STRING((char *)field_table->ptr, 1);
} else { /* Not found, lookup by querying PostgreSQL system tables */
PGresult *tmp_res;
smart_str querystr = {0};
zend_rsrc_list_entry new_field_table;
smart_str_appends(&querystr, "select relname from pg_class where oid=");
smart_str_append_unsigned(&querystr, oid);
smart_str_0(&querystr);
if ((tmp_res = PQexec(pg_result->conn, querystr.c)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
if (tmp_res) {
PQclear(tmp_res);
}
smart_str_free(&querystr);
smart_str_free(&hash_key);
RETURN_FALSE;
}
smart_str_free(&querystr);
if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
PQclear(tmp_res);
smart_str_free(&hash_key);
RETURN_FALSE;
}
Z_TYPE(new_field_table) = le_string;
new_field_table.ptr = estrdup(table_name);
zend_hash_update(&EG(regular_list), hash_key.c, hash_key.len+1, (void *) &new_field_table, sizeof(zend_rsrc_list_entry), NULL);
smart_str_free(&hash_key);
PQclear(tmp_res);
RETURN_STRING(table_name, 1);
}
}
/* }}} */
#endif
#define PHP_PG_FIELD_NAME 1
#define PHP_PG_FIELD_SIZE 2
#define PHP_PG_FIELD_TYPE 3
#define PHP_PG_FIELD_TYPE_OID 4
/* {{{ php_pgsql_get_field_info
*/
static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
long field;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
Oid oid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &field) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (field < 0 || field >= PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_FIELD_NAME:
Z_STRVAL_P(return_value) = PQfname(pgsql_result, field);
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
break;
case PHP_PG_FIELD_SIZE:
Z_LVAL_P(return_value) = PQfsize(pgsql_result, field);
Z_TYPE_P(return_value) = IS_LONG;
break;
case PHP_PG_FIELD_TYPE:
Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, field), &EG(regular_list) TSRMLS_CC);
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
break;
case PHP_PG_FIELD_TYPE_OID:
oid = PQftype(pgsql_result, field);
#if UINT_MAX > LONG_MAX
if (oid > LONG_MAX) {
smart_str s = {0};
smart_str_append_unsigned(&s, oid);
smart_str_0(&s);
Z_STRVAL_P(return_value) = s.c;
Z_STRLEN_P(return_value) = s.len;
Z_TYPE_P(return_value) = IS_STRING;
} else
#endif
{
Z_LVAL_P(return_value) = (long)oid;
Z_TYPE_P(return_value) = IS_LONG;
}
break;
default:
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string pg_field_name(resource result, int field_number)
Returns the name of the field */
PHP_FUNCTION(pg_field_name)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME);
}
/* }}} */
/* {{{ proto int pg_field_size(resource result, int field_number)
Returns the internal size of the field */
PHP_FUNCTION(pg_field_size)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE);
}
/* }}} */
/* {{{ proto string pg_field_type(resource result, int field_number)
Returns the type name for the given field */
PHP_FUNCTION(pg_field_type)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE);
}
/* }}} */
/* {{{ proto string pg_field_type_oid(resource result, int field_number)
Returns the type oid for the given field */
PHP_FUNCTION(pg_field_type_oid)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID);
}
/* }}} */
/* {{{ proto int pg_field_num(resource result, string field_name)
Returns the field number of the named field */
PHP_FUNCTION(pg_field_num)
{
zval *result;
char *field;
int field_len;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result, &field, &field_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
Z_LVAL_P(return_value) = PQfnumber(pgsql_result, field);
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)
Returns values from a result identifier */
PHP_FUNCTION(pg_fetch_result)
{
zval *result, **field=NULL;
long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
pgsql_row = row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
}
switch(Z_TYPE_PP(field)) {
case IS_STRING:
field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
break;
default:
convert_to_long_ex(field);
field_offset = Z_LVAL_PP(field);
break;
}
if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
Z_TYPE_P(return_value) = IS_NULL;
} else {
char *value = PQgetvalue(pgsql_result, pgsql_row, field_offset);
int value_len = PQgetlength(pgsql_result, pgsql_row, field_offset);
ZVAL_STRINGL(return_value, value, value_len, 1);
}
}
/* }}} */
/* {{{ void php_pgsql_fetch_hash */
static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object)
{
zval *result, *zrow = NULL;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int i, num_fields, pgsql_row, use_row;
long row = -1;
char *field_name;
zval *ctor_params = NULL;
zend_class_entry *ce = NULL;
if (into_object) {
char *class_name = NULL;
int class_name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!sz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) {
return;
}
if (!class_name) {
ce = zend_standard_class_def;
} else {
ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
}
if (!ce) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name);
return;
}
result_type = PGSQL_ASSOC;
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!l", &result, &zrow, &result_type) == FAILURE) {
return;
}
}
if (zrow == NULL) {
row = -1;
} else {
convert_to_long(zrow);
row = Z_LVAL_P(zrow);
if (row < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The row parameter must be greater or equal to zero");
RETURN_FALSE;
}
}
use_row = ZEND_NUM_ARGS() > 1 && row != -1;
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (use_row) {
pgsql_row = row;
pg_result->row = pgsql_row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
} else {
/* If 2nd param is NULL, use internal row counter to access next row */
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
pg_result->row++;
}
array_init(return_value);
for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) {
if (PQgetisnull(pgsql_result, pgsql_row, i)) {
if (result_type & PGSQL_NUM) {
add_index_null(return_value, i);
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_null(return_value, field_name);
}
} else {
char *element = PQgetvalue(pgsql_result, pgsql_row, i);
if (element) {
char *data;
int data_len;
int should_copy=0;
const uint element_len = strlen(element);
data = safe_estrndup(element, element_len);
data_len = element_len;
if (result_type & PGSQL_NUM) {
add_index_stringl(return_value, i, data, data_len, should_copy);
should_copy=1;
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_stringl(return_value, field_name, data, data_len, should_copy);
}
}
}
}
if (into_object) {
zval dataset = *return_value;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *retval_ptr;
object_and_properties_init(return_value, ce, NULL);
zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
if (ce->constructor) {
fci.size = sizeof(fci);
fci.function_table = &ce->function_table;
fci.function_name = NULL;
fci.symbol_table = NULL;
fci.object_ptr = return_value;
fci.retval_ptr_ptr = &retval_ptr;
if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
if (Z_TYPE_P(ctor_params) == IS_ARRAY) {
HashTable *ht = Z_ARRVAL_P(ctor_params);
Bucket *p;
fci.param_count = 0;
fci.params = safe_emalloc(sizeof(zval***), ht->nNumOfElements, 0);
p = ht->pListHead;
while (p != NULL) {
fci.params[fci.param_count++] = (zval**)p->pData;
p = p->pListNext;
}
} else {
/* Two problems why we throw exceptions here: PHP is typeless
* and hence passing one argument that's not an array could be
* by mistake and the other way round is possible, too. The
* single value is an array. Also we'd have to make that one
* argument passed by reference.
*/
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC);
return;
}
} else {
fci.param_count = 0;
fci.params = NULL;
}
fci.no_separation = 1;
fcc.initialized = 1;
fcc.function_handler = ce->constructor;
fcc.calling_scope = EG(scope);
fcc.called_scope = Z_OBJCE_P(return_value);
fcc.object_ptr = return_value;
if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name);
} else {
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
}
if (fci.params) {
efree(fci.params);
}
} else if (ctor_params) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name);
}
}
}
/* }}} */
/* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]])
Get a row as an enumerated array */
PHP_FUNCTION(pg_fetch_row)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_assoc(resource result [, int row])
Fetch a row as an assoc array */
PHP_FUNCTION(pg_fetch_assoc)
{
/* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when
there is 3rd parameter */
if (ZEND_NUM_ARGS() > 2)
WRONG_PARAM_COUNT;
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]])
Fetch a row as an array */
PHP_FUNCTION(pg_fetch_array)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0);
}
/* }}} */
/* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])
Fetch a row as an object */
PHP_FUNCTION(pg_fetch_object)
{
/* pg_fetch_object() allowed result_type used to be. 3rd parameter
must be allowed for compatibility */
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1);
}
/* }}} */
/* {{{ proto array pg_fetch_all(resource result)
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
array_init(return_value);
if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) {
zval_dtor(return_value);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto array pg_fetch_all_columns(resource result [, int column_number])
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all_columns)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
unsigned long colno=0;
int pg_numrows, pg_row;
size_t num_fields;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
num_fields = PQnfields(pgsql_result);
if (colno >= num_fields || colno < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno);
RETURN_FALSE;
}
array_init(return_value);
if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
return;
}
for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
if (PQgetisnull(pgsql_result, pg_row, colno)) {
add_next_index_null(return_value);
} else {
add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1);
}
}
}
/* }}} */
/* {{{ proto bool pg_result_seek(resource result, int offset)
Set internal row offset */
PHP_FUNCTION(pg_result_seek)
{
zval *result;
long row;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (row < 0 || row >= PQntuples(pg_result->result)) {
RETURN_FALSE;
}
/* seek to offset */
pg_result->row = row;
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DATA_LENGTH 1
#define PHP_PG_DATA_ISNULL 2
/* {{{ php_pgsql_data_info
*/
static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result, **field;
long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
pgsql_row = row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
}
switch(Z_TYPE_PP(field)) {
case IS_STRING:
convert_to_string_ex(field);
field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
break;
default:
convert_to_long_ex(field);
field_offset = Z_LVAL_PP(field);
break;
}
if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_DATA_LENGTH:
Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset);
break;
case PHP_PG_DATA_ISNULL:
Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset);
break;
}
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)
Returns the printed length */
PHP_FUNCTION(pg_field_prtlen)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH);
}
/* }}} */
/* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)
Test if a field is NULL */
PHP_FUNCTION(pg_field_is_null)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL);
}
/* }}} */
/* {{{ proto bool pg_free_result(resource result)
Free result memory */
PHP_FUNCTION(pg_free_result)
{
zval *result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
if (Z_LVAL_P(result) == 0) {
RETURN_FALSE;
}
zend_list_delete(Z_RESVAL_P(result));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string pg_last_oid(resource result)
Returns the last object identifier */
PHP_FUNCTION(pg_last_oid)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
#ifdef HAVE_PQOIDVALUE
Oid oid;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
#ifdef HAVE_PQOIDVALUE
oid = PQoidValue(pgsql_result);
if (oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(oid);
#else
Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result);
if (Z_STRVAL_P(return_value)) {
RETURN_STRING(Z_STRVAL_P(return_value), 1);
}
RETURN_STRING("", 1);
#endif
}
/* }}} */
/* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]])
Enable tracing a PostgreSQL connection */
PHP_FUNCTION(pg_trace)
{
char *z_filename, *mode = "w";
int z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = PGG(default_link);
if (zend_parse_parameters(argc TSRMLS_CC, "p|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_untrace([resource connection])
Disable tracing of a PostgreSQL connection */
PHP_FUNCTION(pg_untrace)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
PQuntrace(pgsql);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid])
Create a large object */
PHP_FUNCTION(pg_lo_create)
{
zval *pgsql_link = NULL, *oid = NULL;
PGconn *pgsql;
Oid pgsql_oid, wanted_oid = InvalidOid;
int id = -1, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|zz", &pgsql_link, &oid) == FAILURE) {
return;
}
if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) {
oid = pgsql_link;
pgsql_link = NULL;
}
if (pgsql_link == NULL) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
if (id == -1) {
RETURN_FALSE;
}
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_CREATE
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL");
#else
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (long)InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
#endif
}
if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid)
Delete a large object */
PHP_FUNCTION(pg_lo_unlink)
{
zval *pgsql_link = NULL;
long oid_long;
char *oid_string, *end_ptr;
int oid_strlen;
PGconn *pgsql;
Oid oid;
int id = -1;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid type is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rl", &pgsql_link, &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"s", &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"l", &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_unlink(pgsql, oid) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode)
Open a large object and return fd */
PHP_FUNCTION(pg_lo_open)
{
zval *pgsql_link = NULL;
long oid_long;
char *oid_string, *end_ptr, *mode_string;
int oid_strlen, mode_strlen;
PGconn *pgsql;
Oid oid;
int id = -1, pgsql_mode=0, pgsql_lofd;
int create=0;
pgLofp *pgsql_lofp;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of
faster to type. Unfortunately, doesn't behave the same way as fopen()...
(Jouni)
*/
if (strchr(mode_string, 'r') == mode_string) {
pgsql_mode |= INV_READ;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_WRITE;
}
}
if (strchr(mode_string, 'w') == mode_string) {
pgsql_mode |= INV_WRITE;
create = 1;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_READ;
}
}
pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp));
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (create) {
if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
} else {
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (lo_unlink(pgsql, oid) == -1) {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP");
RETURN_FALSE;
}
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC);
Z_TYPE_P(return_value) = IS_LONG;
}
}
} else {
efree(pgsql_lofp);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
}
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
}
}
/* }}} */
/* {{{ proto bool pg_lo_close(resource large_object)
Close a large object */
PHP_FUNCTION(pg_lo_close)
{
zval *pgsql_lofp;
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_lofp) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_lofp, -1, "PostgreSQL large object", le_lofp);
if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd);
RETVAL_FALSE;
} else {
RETVAL_TRUE;
}
zend_list_delete(Z_RESVAL_P(pgsql_lofp));
return;
}
/* }}} */
#define PGSQL_LO_READ_BUF_SIZE 8192
/* {{{ proto string pg_lo_read(resource large_object [, int len])
Read a large object */
PHP_FUNCTION(pg_lo_read)
{
zval *pgsql_id;
long len;
int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes, argc = ZEND_NUM_ARGS();
char *buf;
pgLofp *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &pgsql_id, &len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (argc > 1) {
buf_len = len;
}
buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0);
if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) {
efree(buf);
RETURN_FALSE;
}
buf[nbytes] = '\0';
RETURN_STRINGL(buf, nbytes, 0);
}
/* }}} */
/* {{{ proto int pg_lo_write(resource large_object, string buf [, int len])
Write a large object */
PHP_FUNCTION(pg_lo_write)
{
zval *pgsql_id;
char *str;
long z_len;
int str_len, nbytes;
int len;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) {
return;
}
if (argc > 2) {
if (z_len > str_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld", str_len, z_len);
RETURN_FALSE;
}
if (z_len < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", z_len);
RETURN_FALSE;
}
len = z_len;
}
else {
len = str_len;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) {
RETURN_FALSE;
}
RETURN_LONG(nbytes);
}
/* }}} */
/* {{{ proto int pg_lo_read_all(resource large_object)
Read a large object and send straight to browser */
PHP_FUNCTION(pg_lo_read_all)
{
zval *pgsql_id;
int tbytes;
volatile int nbytes;
char buf[PGSQL_LO_READ_BUF_SIZE];
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
tbytes = 0;
while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) {
PHPWRITE(buf, nbytes);
tbytes += nbytes;
}
RETURN_LONG(tbytes);
}
/* }}} */
/* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid])
Import large object direct from filesystem */
PHP_FUNCTION(pg_lo_import)
{
zval *pgsql_link = NULL, *oid = NULL;
char *file_in;
int id = -1, name_len;
int argc = ZEND_NUM_ARGS();
PGconn *pgsql;
Oid returned_oid;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) {
;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"p|z", &file_in, &name_len, &oid) == SUCCESS) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
/* old calling convention, deprecated since PHP 4.2 */
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
}
else {
WRONG_PARAM_COUNT;
}
if (php_check_open_basedir(file_in TSRMLS_CC)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_IMPORT_WITH_OID
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "OID value passing not supported");
#else
Oid wanted_oid;
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (long)InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
#endif
}
returned_oid = lo_import(pgsql, file_in);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename)
Export large object direct to filesystem */
PHP_FUNCTION(pg_lo_export)
{
zval *pgsql_link = NULL;
char *file_out, *oid_string, *end_ptr;
int oid_strlen;
int id = -1, name_len;
long oid_long;
Oid oid;
PGconn *pgsql;
int argc = ZEND_NUM_ARGS();
/* allow string to handle large OID value correctly */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"lp", &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
"lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
if (oid_long <= InvalidOid) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments");
RETURN_FALSE;
}
if (php_check_open_basedir(file_out TSRMLS_CC)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_export(pgsql, oid, file_out)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence])
Seeks position of large object */
PHP_FUNCTION(pg_lo_seek)
{
zval *pgsql_id = NULL;
long offset = 0, whence = SEEK_CUR;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) {
return;
}
if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter");
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence) > -1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int pg_lo_tell(resource large_object)
Returns current position of large object */
PHP_FUNCTION(pg_lo_tell)
{
zval *pgsql_id = NULL;
int offset = 0;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
RETURN_LONG(offset);
}
/* }}} */
#if HAVE_PQSETERRORVERBOSITY
/* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity)
Set error verbosity */
PHP_FUNCTION(pg_set_error_verbosity)
{
zval *pgsql_link = NULL;
long verbosity;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "l", &verbosity) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_link, &verbosity) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) {
Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, verbosity);
Z_TYPE_P(return_value) = IS_LONG;
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
#ifdef HAVE_PQCLIENTENCODING
/* {{{ proto int pg_set_client_encoding([resource connection,] string encoding)
Set client encoding */
PHP_FUNCTION(pg_set_client_encoding)
{
char *encoding;
int encoding_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "s", &encoding, &encoding_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, encoding);
Z_TYPE_P(return_value) = IS_LONG;
}
/* }}} */
/* {{{ proto string pg_client_encoding([resource connection])
Get the current client encoding */
PHP_FUNCTION(pg_client_encoding)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* Just do the same as found in PostgreSQL sources... */
Z_STRVAL_P(return_value) = (char *) pg_encoding_to_char(PQclientEncoding(pgsql));
Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
Z_TYPE_P(return_value) = IS_STRING;
}
/* }}} */
#endif
#if !HAVE_PQGETCOPYDATA
#define COPYBUFSIZ 8192
#endif
/* {{{ proto bool pg_end_copy([resource connection])
Sync with backend. Completes the Copy command */
PHP_FUNCTION(pg_end_copy)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
int result = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQendcopy(pgsql);
if (result!=0) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_put_line([resource connection,] string query)
Send null-terminated string to backend server*/
PHP_FUNCTION(pg_put_line)
{
char *query;
zval *pgsql_link = NULL;
int query_len, id = -1;
PGconn *pgsql;
int result = 0, argc = ZEND_NUM_ARGS();
if (argc == 1) {
if (zend_parse_parameters(argc TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
return;
}
id = PGG(default_link);
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQputline(pgsql, query);
if (result==EOF) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])
Copy table to array */
PHP_FUNCTION(pg_copy_to)
{
zval *pgsql_link;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
int table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0;
char *query;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int copydone = 0;
#if !HAVE_PQGETCOPYDATA
char copybuf[COPYBUFSIZ];
#endif
char *csv = (char *)NULL;
int ret;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss",
&pgsql_link, &table_name, &table_name_len,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!pg_null_as) {
pg_null_as = safe_estrdup("\\\\N");
free_pg_null = 1;
}
spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (free_pg_null) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_OUT:
if (pgsql_result) {
PQclear(pgsql_result);
array_init(return_value);
#if HAVE_PQGETCOPYDATA
while (!copydone)
{
ret = PQgetCopyData(pgsql, &csv, 0);
switch (ret) {
case -1:
copydone = 1;
break;
case 0:
case -2:
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
break;
default:
add_next_index_string(return_value, csv, 1);
PQfreemem(csv);
break;
}
}
#else
while (!copydone)
{
if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) {
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
}
if (copybuf[0] == '\\' &&
copybuf[1] == '.' &&
copybuf[2] == '\0')
{
copydone = 1;
}
else
{
if (csv == (char *)NULL) {
csv = estrdup(copybuf);
} else {
csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1));
strcat(csv, copybuf);
}
switch (ret)
{
case EOF:
copydone = 1;
case 0:
add_next_index_string(return_value, csv, 1);
efree(csv);
csv = (char *)NULL;
break;
case 1:
break;
}
}
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])
Copy table from array */
PHP_FUNCTION(pg_copy_from)
{
zval *pgsql_link = NULL, *pg_rows;
zval **tmp;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
int table_name_len, pg_delim_len, pg_null_as_len;
int pg_null_as_free = 0;
char *query;
HashPosition pos;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "rsa|ss",
&pgsql_link, &table_name, &table_name_len, &pg_rows,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
if (!pg_null_as) {
pg_null_as = safe_estrdup("\\\\N");
pg_null_as_free = 1;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (pg_null_as_free) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_IN:
if (pgsql_result) {
int command_failed = 0;
PQclear(pgsql_result);
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
#if HAVE_PQPUTCOPYDATA
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
}
if (PQputCopyData(pgsql, query, strlen(query)) != 1) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
}
if (PQputCopyEnd(pgsql, NULL) != 1) {
PHP_PQ_ERROR("putcopyend failed: %s", pgsql);
RETURN_FALSE;
}
#else
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
}
if (PQputline(pgsql, query)==EOF) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
}
if (PQputline(pgsql, "\\.\n") == EOF) {
PHP_PQ_ERROR("putline failed: %s", pgsql);
RETURN_FALSE;
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
command_failed = 1;
}
PQclear(pgsql_result);
}
if (command_failed) {
RETURN_FALSE;
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
RETURN_TRUE;
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
#ifdef HAVE_PQESCAPE
/* {{{ proto string pg_escape_string([resource connection,] string data)
Escape string for text/char type */
PHP_FUNCTION(pg_escape_string)
{
char *from = NULL, *to = NULL;
zval *pgsql_link;
#ifdef HAVE_PQESCAPE_CONN
PGconn *pgsql;
#endif
int to_len;
int from_len;
int id = -1;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = PGG(default_link);
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
to = (char *) safe_emalloc(from_len, 2, 1);
#ifdef HAVE_PQESCAPE_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL);
} else
#endif
to_len = (int) PQescapeString(to, from, (size_t)from_len);
RETURN_STRINGL(to, to_len, 0);
}
/* }}} */
/* {{{ proto string pg_escape_bytea([resource connection,] string data)
Escape binary for bytea type */
PHP_FUNCTION(pg_escape_bytea)
{
char *from = NULL, *to = NULL;
size_t to_len;
int from_len, id = -1;
#ifdef HAVE_PQESCAPE_BYTEA_CONN
PGconn *pgsql;
#endif
zval *pgsql_link;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = PGG(default_link);
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
#ifdef HAVE_PQESCAPE_BYTEA_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len);
} else
#endif
to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */
PQfreemem(to);
}
/* }}} */
#if !HAVE_PQUNESCAPEBYTEA
/* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users.
Renamed to php_pgsql_unescape_bytea() */
/*
* PQunescapeBytea - converts the null terminated string representation
* of a bytea, strtext, into binary, filling a buffer. It returns a
* pointer to the buffer which is NULL on error, and the size of the
* buffer in retbuflen. The pointer may subsequently be used as an
* argument to the function free(3). It is the reverse of PQescapeBytea.
*
* The following transformations are reversed:
* '\0' == ASCII 0 == \000
* '\'' == ASCII 39 == \'
* '\\' == ASCII 92 == \\
*
* States:
* 0 normal 0->1->2->3->4
* 1 \ 1->5
* 2 \0 1->6
* 3 \00
* 4 \000
* 5 \'
* 6 \\
*/
static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen)
{
size_t buflen;
unsigned char *buffer,
*sp,
*bp;
unsigned int state = 0;
if (strtext == NULL)
return NULL;
buflen = strlen(strtext); /* will shrink, also we discover if
* strtext */
buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */
for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++)
{
| 165,315 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
mode_t new_umask_val;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
{"umask", required_argument, NULL, 'u'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 'u':
new_umask_val = set_umask(optarg);
if (umask_cmdline)
umask_val = new_umask_val;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
mode_t new_umask_val;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
{"umask", required_argument, NULL, 'u'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 'u':
new_umask_val = set_umask(optarg);
if (umask_cmdline)
umask_val = new_umask_val;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
}
| 168,985 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nfc_llcp_build_gb(struct nfc_llcp_local *local)
{
u8 *gb_cur, *version_tlv, version, version_length;
u8 *lto_tlv, lto_length;
u8 *wks_tlv, wks_length;
u8 *miux_tlv, miux_length;
__be16 wks = cpu_to_be16(local->local_wks);
u8 gb_len = 0;
int ret = 0;
version = LLCP_VERSION_11;
version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version,
1, &version_length);
gb_len += version_length;
lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, <o_length);
gb_len += lto_length;
pr_debug("Local wks 0x%lx\n", local->local_wks);
wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length);
gb_len += wks_length;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0,
&miux_length);
gb_len += miux_length;
gb_len += ARRAY_SIZE(llcp_magic);
if (gb_len > NFC_MAX_GT_LEN) {
ret = -EINVAL;
goto out;
}
gb_cur = local->gb;
memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic));
gb_cur += ARRAY_SIZE(llcp_magic);
memcpy(gb_cur, version_tlv, version_length);
gb_cur += version_length;
memcpy(gb_cur, lto_tlv, lto_length);
gb_cur += lto_length;
memcpy(gb_cur, wks_tlv, wks_length);
gb_cur += wks_length;
memcpy(gb_cur, miux_tlv, miux_length);
gb_cur += miux_length;
local->gb_len = gb_len;
out:
kfree(version_tlv);
kfree(lto_tlv);
kfree(wks_tlv);
kfree(miux_tlv);
return ret;
}
Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails
KASAN report this:
BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc]
Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401
CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xfa/0x1ce lib/dump_stack.c:113
kasan_report+0x171/0x18d mm/kasan/report.c:321
memcpy+0x1f/0x50 mm/kasan/common.c:130
nfc_llcp_build_gb+0x37f/0x540 [nfc]
nfc_llcp_register_device+0x6eb/0xb50 [nfc]
nfc_register_device+0x50/0x1d0 [nfc]
nfcsim_device_new+0x394/0x67d [nfcsim]
? 0xffffffffc1080000
nfcsim_init+0x6b/0x1000 [nfcsim]
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003
RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc
R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004
nfc_llcp_build_tlv will return NULL on fails, caller should check it,
otherwise will trigger a NULL dereference.
Reported-by: Hulk Robot <[email protected]>
Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames")
Fixes: d646960f7986 ("NFC: Initial LLCP support")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | static int nfc_llcp_build_gb(struct nfc_llcp_local *local)
{
u8 *gb_cur, version, version_length;
u8 lto_length, wks_length, miux_length;
u8 *version_tlv = NULL, *lto_tlv = NULL,
*wks_tlv = NULL, *miux_tlv = NULL;
__be16 wks = cpu_to_be16(local->local_wks);
u8 gb_len = 0;
int ret = 0;
version = LLCP_VERSION_11;
version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version,
1, &version_length);
if (!version_tlv) {
ret = -ENOMEM;
goto out;
}
gb_len += version_length;
lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, <o_length);
if (!lto_tlv) {
ret = -ENOMEM;
goto out;
}
gb_len += lto_length;
pr_debug("Local wks 0x%lx\n", local->local_wks);
wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length);
if (!wks_tlv) {
ret = -ENOMEM;
goto out;
}
gb_len += wks_length;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0,
&miux_length);
if (!miux_tlv) {
ret = -ENOMEM;
goto out;
}
gb_len += miux_length;
gb_len += ARRAY_SIZE(llcp_magic);
if (gb_len > NFC_MAX_GT_LEN) {
ret = -EINVAL;
goto out;
}
gb_cur = local->gb;
memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic));
gb_cur += ARRAY_SIZE(llcp_magic);
memcpy(gb_cur, version_tlv, version_length);
gb_cur += version_length;
memcpy(gb_cur, lto_tlv, lto_length);
gb_cur += lto_length;
memcpy(gb_cur, wks_tlv, wks_length);
gb_cur += wks_length;
memcpy(gb_cur, miux_tlv, miux_length);
gb_cur += miux_length;
local->gb_len = gb_len;
out:
kfree(version_tlv);
kfree(lto_tlv);
kfree(wks_tlv);
kfree(miux_tlv);
return ret;
}
| 169,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void migrate_page_copy(struct page *newpage, struct page *page)
{
int cpupid;
if (PageHuge(page) || PageTransHuge(page))
copy_huge_page(newpage, page);
else
copy_highpage(newpage, page);
if (PageError(page))
SetPageError(newpage);
if (PageReferenced(page))
SetPageReferenced(newpage);
if (PageUptodate(page))
SetPageUptodate(newpage);
if (TestClearPageActive(page)) {
VM_BUG_ON_PAGE(PageUnevictable(page), page);
SetPageActive(newpage);
} else if (TestClearPageUnevictable(page))
SetPageUnevictable(newpage);
if (PageChecked(page))
SetPageChecked(newpage);
if (PageMappedToDisk(page))
SetPageMappedToDisk(newpage);
if (PageDirty(page)) {
clear_page_dirty_for_io(page);
/*
* Want to mark the page and the radix tree as dirty, and
* redo the accounting that clear_page_dirty_for_io undid,
* but we can't use set_page_dirty because that function
* is actually a signal that all of the page has become dirty.
* Whereas only part of our page may be dirty.
*/
if (PageSwapBacked(page))
SetPageDirty(newpage);
else
__set_page_dirty_nobuffers(newpage);
}
if (page_is_young(page))
set_page_young(newpage);
if (page_is_idle(page))
set_page_idle(newpage);
/*
* Copy NUMA information to the new page, to prevent over-eager
* future migrations of this same page.
*/
cpupid = page_cpupid_xchg_last(page, -1);
page_cpupid_xchg_last(newpage, cpupid);
ksm_migrate_page(newpage, page);
/*
* Please do not reorder this without considering how mm/ksm.c's
* get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
*/
if (PageSwapCache(page))
ClearPageSwapCache(page);
ClearPagePrivate(page);
set_page_private(page, 0);
/*
* If any waiters have accumulated on the new page then
* wake them up.
*/
if (PageWriteback(newpage))
end_page_writeback(newpage);
}
Commit Message: mm: migrate dirty page without clear_page_dirty_for_io etc
clear_page_dirty_for_io() has accumulated writeback and memcg subtleties
since v2.6.16 first introduced page migration; and the set_page_dirty()
which completed its migration of PageDirty, later had to be moderated to
__set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too.
No actual problems seen with this procedure recently, but if you look into
what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually
achieving, it turns out to be nothing more than moving the PageDirty flag,
and its NR_FILE_DIRTY stat from one zone to another.
It would be good to avoid a pile of irrelevant decrementations and
incrementations, and improper event counting, and unnecessary descent of
the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which
radix_tree_replace_slot() left in place anyway).
Do the NR_FILE_DIRTY movement, like the other stats movements, while
interrupts still disabled in migrate_page_move_mapping(); and don't even
bother if the zone is the same. Do the PageDirty movement there under
tree_lock too, where old page is frozen and newpage not yet visible:
bearing in mind that as soon as newpage becomes visible in radix_tree, an
un-page-locked set_page_dirty() might interfere (or perhaps that's just
not possible: anything doing so should already hold an additional
reference to the old page, preventing its migration; but play safe).
But we do still need to transfer PageDirty in migrate_page_copy(), for
those who don't go the mapping route through migrate_page_move_mapping().
Signed-off-by: Hugh Dickins <[email protected]>
Cc: Christoph Lameter <[email protected]>
Cc: "Kirill A. Shutemov" <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Sasha Levin <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: KOSAKI Motohiro <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476 | void migrate_page_copy(struct page *newpage, struct page *page)
{
int cpupid;
if (PageHuge(page) || PageTransHuge(page))
copy_huge_page(newpage, page);
else
copy_highpage(newpage, page);
if (PageError(page))
SetPageError(newpage);
if (PageReferenced(page))
SetPageReferenced(newpage);
if (PageUptodate(page))
SetPageUptodate(newpage);
if (TestClearPageActive(page)) {
VM_BUG_ON_PAGE(PageUnevictable(page), page);
SetPageActive(newpage);
} else if (TestClearPageUnevictable(page))
SetPageUnevictable(newpage);
if (PageChecked(page))
SetPageChecked(newpage);
if (PageMappedToDisk(page))
SetPageMappedToDisk(newpage);
/* Move dirty on pages not done by migrate_page_move_mapping() */
if (PageDirty(page))
SetPageDirty(newpage);
if (page_is_young(page))
set_page_young(newpage);
if (page_is_idle(page))
set_page_idle(newpage);
/*
* Copy NUMA information to the new page, to prevent over-eager
* future migrations of this same page.
*/
cpupid = page_cpupid_xchg_last(page, -1);
page_cpupid_xchg_last(newpage, cpupid);
ksm_migrate_page(newpage, page);
/*
* Please do not reorder this without considering how mm/ksm.c's
* get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
*/
if (PageSwapCache(page))
ClearPageSwapCache(page);
ClearPagePrivate(page);
set_page_private(page, 0);
/*
* If any waiters have accumulated on the new page then
* wake them up.
*/
if (PageWriteback(newpage))
end_page_writeback(newpage);
}
| 167,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CreateSymbolicLink(const FilePath& target, const FilePath& symlink) {
ASSERT_TRUE(file_util::CreateSymbolicLink(target, symlink))
<< ": " << target.value() << ": " << symlink.value();
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void CreateSymbolicLink(const FilePath& target, const FilePath& symlink) {
virtual void TearDown() OVERRIDE {
metadata_.reset();
}
| 170,870 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: armv6pmu_handle_irq(int irq_num,
void *dev)
{
unsigned long pmcr = armv6_pmcr_read();
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int idx;
if (!armv6_pmcr_has_overflowed(pmcr))
return IRQ_NONE;
regs = get_irq_regs();
/*
* The interrupts are cleared by writing the overflow flags back to
* the control register. All of the other bits don't have any effect
* if they are rewritten, so write the whole value back.
*/
armv6_pmcr_write(pmcr);
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx <= armpmu->num_events; ++idx) {
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc;
if (!test_bit(idx, cpuc->active_mask))
continue;
/*
* We have a single interrupt for all counters. Check that
* each counter has overflowed before we process it.
*/
if (!armv6_pmcr_counter_has_overflowed(pmcr, idx))
continue;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx, 1);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, 0, &data, regs))
armpmu->disable(hwc, idx);
}
/*
* Handle the pending perf events.
*
* Note: this call *must* be run with interrupts disabled. For
* platforms that can have the PMU interrupts raised as an NMI, this
* will not work.
*/
irq_work_run();
return IRQ_HANDLED;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | armv6pmu_handle_irq(int irq_num,
void *dev)
{
unsigned long pmcr = armv6_pmcr_read();
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int idx;
if (!armv6_pmcr_has_overflowed(pmcr))
return IRQ_NONE;
regs = get_irq_regs();
/*
* The interrupts are cleared by writing the overflow flags back to
* the control register. All of the other bits don't have any effect
* if they are rewritten, so write the whole value back.
*/
armv6_pmcr_write(pmcr);
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx <= armpmu->num_events; ++idx) {
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc;
if (!test_bit(idx, cpuc->active_mask))
continue;
/*
* We have a single interrupt for all counters. Check that
* each counter has overflowed before we process it.
*/
if (!armv6_pmcr_counter_has_overflowed(pmcr, idx))
continue;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx, 1);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, &data, regs))
armpmu->disable(hwc, idx);
}
/*
* Handle the pending perf events.
*
* Note: this call *must* be run with interrupts disabled. For
* platforms that can have the PMU interrupts raised as an NMI, this
* will not work.
*/
irq_work_run();
return IRQ_HANDLED;
}
| 165,773 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_get_cert_verify(SSL *s)
{
EVP_PKEY *pkey=NULL;
unsigned char *p;
int al,ok,ret=0;
long n;
int type=0,i,j;
X509 *peer;
const EVP_MD *md = NULL;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
n=s->method->ssl_get_message(s,
SSL3_ST_SR_CERT_VRFY_A,
SSL3_ST_SR_CERT_VRFY_B,
-1,
SSL3_RT_MAX_PLAIN_LENGTH,
&ok);
if (!ok) return((int)n);
if (s->session->peer != NULL)
{
peer=s->session->peer;
pkey=X509_get_pubkey(peer);
type=X509_certificate_type(peer,pkey);
}
else
{
peer=NULL;
pkey=NULL;
}
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
{
s->s3->tmp.reuse_message=1;
if ((peer != NULL) && (type & EVP_PKT_SIGN))
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
goto f_err;
}
ret=1;
goto end;
}
if (peer == NULL)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
al=SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
if (!(type & EVP_PKT_SIGN))
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
al=SSL_AD_ILLEGAL_PARAMETER;
goto f_err;
}
if (s->s3->change_cipher_spec)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
al=SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
/* we now have a signature that we need to verify */
p=(unsigned char *)s->init_msg;
/* Check for broken implementations of GOST ciphersuites */
/* If key is GOST and n is exactly 64, it is bare
* signature without length field */
if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
pkey->type == NID_id_GostR3410_2001) )
{
i=64;
}
else
{
if (SSL_USE_SIGALGS(s))
{
int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
if (rv == -1)
{
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
else if (rv == 0)
{
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
p += 2;
n -= 2;
}
n2s(p,i);
n-=2;
if (i > n)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
al=SSL_AD_DECODE_ERROR;
goto f_err;
}
}
j=EVP_PKEY_size(pkey);
if ((i > j) || (n > j) || (n <= 0))
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
al=SSL_AD_DECODE_ERROR;
goto f_err;
}
if (SSL_USE_SIGALGS(s))
{
long hdatalen = 0;
void *hdata;
hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
if (hdatalen <= 0)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
al=SSL_AD_INTERNAL_ERROR;
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
EVP_MD_name(md));
#endif
if (!EVP_VerifyInit_ex(&mctx, md, NULL)
|| !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
al=SSL_AD_INTERNAL_ERROR;
goto f_err;
}
if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
else
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA)
{
i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i,
pkey->pkey.rsa);
if (i < 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
goto f_err;
}
if (i == 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
goto f_err;
}
}
else
#endif
#ifndef OPENSSL_NO_DSA
if (pkey->type == EVP_PKEY_DSA)
{
j=DSA_verify(pkey->save_type,
&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
if (j <= 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
goto f_err;
}
}
else
#endif
#ifndef OPENSSL_NO_ECDSA
if (pkey->type == EVP_PKEY_EC)
{
j=ECDSA_verify(pkey->save_type,
&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
if (j <= 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
SSL_R_BAD_ECDSA_SIGNATURE);
goto f_err;
}
}
else
#endif
if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
{ unsigned char signature[64];
int idx;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
EVP_PKEY_verify_init(pctx);
if (i!=64) {
fprintf(stderr,"GOST signature length is %d",i);
}
for (idx=0;idx<64;idx++) {
signature[63-idx]=p[idx];
}
j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
EVP_PKEY_CTX_free(pctx);
if (j<=0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
SSL_R_BAD_ECDSA_SIGNATURE);
goto f_err;
}
}
else
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
al=SSL_AD_UNSUPPORTED_CERTIFICATE;
goto f_err;
}
ret=1;
if (0)
{
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
}
end:
if (s->s3->handshake_buffer)
{
BIO_free(s->s3->handshake_buffer);
s->s3->handshake_buffer = NULL;
s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
}
EVP_MD_CTX_cleanup(&mctx);
EVP_PKEY_free(pkey);
return(ret);
}
Commit Message: Unauthenticated DH client certificate fix.
Fix to prevent use of DH client certificates without sending
certificate verify message.
If we've used a client certificate to generate the premaster secret
ssl3_get_client_key_exchange returns 2 and ssl3_get_cert_verify is
never called.
We can only skip the certificate verify message in
ssl3_get_cert_verify if the client didn't send a certificate.
Thanks to Karthikeyan Bhargavan for reporting this issue.
CVE-2015-0205
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: CWE-310 | int ssl3_get_cert_verify(SSL *s)
{
EVP_PKEY *pkey=NULL;
unsigned char *p;
int al,ok,ret=0;
long n;
int type=0,i,j;
X509 *peer;
const EVP_MD *md = NULL;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
n=s->method->ssl_get_message(s,
SSL3_ST_SR_CERT_VRFY_A,
SSL3_ST_SR_CERT_VRFY_B,
-1,
SSL3_RT_MAX_PLAIN_LENGTH,
&ok);
if (!ok) return((int)n);
if (s->session->peer != NULL)
{
peer=s->session->peer;
pkey=X509_get_pubkey(peer);
type=X509_certificate_type(peer,pkey);
}
else
{
peer=NULL;
pkey=NULL;
}
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
{
s->s3->tmp.reuse_message=1;
if (peer != NULL)
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
goto f_err;
}
ret=1;
goto end;
}
if (peer == NULL)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
al=SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
if (!(type & EVP_PKT_SIGN))
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
al=SSL_AD_ILLEGAL_PARAMETER;
goto f_err;
}
if (s->s3->change_cipher_spec)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
al=SSL_AD_UNEXPECTED_MESSAGE;
goto f_err;
}
/* we now have a signature that we need to verify */
p=(unsigned char *)s->init_msg;
/* Check for broken implementations of GOST ciphersuites */
/* If key is GOST and n is exactly 64, it is bare
* signature without length field */
if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
pkey->type == NID_id_GostR3410_2001) )
{
i=64;
}
else
{
if (SSL_USE_SIGALGS(s))
{
int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
if (rv == -1)
{
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
else if (rv == 0)
{
al = SSL_AD_DECODE_ERROR;
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
p += 2;
n -= 2;
}
n2s(p,i);
n-=2;
if (i > n)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
al=SSL_AD_DECODE_ERROR;
goto f_err;
}
}
j=EVP_PKEY_size(pkey);
if ((i > j) || (n > j) || (n <= 0))
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
al=SSL_AD_DECODE_ERROR;
goto f_err;
}
if (SSL_USE_SIGALGS(s))
{
long hdatalen = 0;
void *hdata;
hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
if (hdatalen <= 0)
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
al=SSL_AD_INTERNAL_ERROR;
goto f_err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
EVP_MD_name(md));
#endif
if (!EVP_VerifyInit_ex(&mctx, md, NULL)
|| !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
al=SSL_AD_INTERNAL_ERROR;
goto f_err;
}
if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
goto f_err;
}
}
else
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA)
{
i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i,
pkey->pkey.rsa);
if (i < 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
goto f_err;
}
if (i == 0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
goto f_err;
}
}
else
#endif
#ifndef OPENSSL_NO_DSA
if (pkey->type == EVP_PKEY_DSA)
{
j=DSA_verify(pkey->save_type,
&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
if (j <= 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
goto f_err;
}
}
else
#endif
#ifndef OPENSSL_NO_ECDSA
if (pkey->type == EVP_PKEY_EC)
{
j=ECDSA_verify(pkey->save_type,
&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
if (j <= 0)
{
/* bad signature */
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
SSL_R_BAD_ECDSA_SIGNATURE);
goto f_err;
}
}
else
#endif
if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
{ unsigned char signature[64];
int idx;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
EVP_PKEY_verify_init(pctx);
if (i!=64) {
fprintf(stderr,"GOST signature length is %d",i);
}
for (idx=0;idx<64;idx++) {
signature[63-idx]=p[idx];
}
j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
EVP_PKEY_CTX_free(pctx);
if (j<=0)
{
al=SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
SSL_R_BAD_ECDSA_SIGNATURE);
goto f_err;
}
}
else
{
SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
al=SSL_AD_UNSUPPORTED_CERTIFICATE;
goto f_err;
}
ret=1;
if (0)
{
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
}
end:
if (s->s3->handshake_buffer)
{
BIO_free(s->s3->handshake_buffer);
s->s3->handshake_buffer = NULL;
s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
}
EVP_MD_CTX_cleanup(&mctx);
EVP_PKEY_free(pkey);
return(ret);
}
| 166,750 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
Commit Message: Do some random sanity checking for stratum message parsing
CWE ID: CWE-119 | bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
snprintf(url_address, 254, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
| 166,304 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
Commit Message:
CWE ID: CWE-119 | ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
| 164,897 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int svc_rdma_recvfrom(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma_xprt =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct svc_rdma_op_ctxt *ctxt = NULL;
struct rpcrdma_msg *rmsgp;
int ret = 0;
dprintk("svcrdma: rqstp=%p\n", rqstp);
spin_lock(&rdma_xprt->sc_rq_dto_lock);
if (!list_empty(&rdma_xprt->sc_read_complete_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
rdma_read_complete(rqstp, ctxt);
goto complete;
} else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
} else {
atomic_inc(&rdma_stat_rq_starve);
clear_bit(XPT_DATA, &xprt->xpt_flags);
ctxt = NULL;
}
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
if (!ctxt) {
/* This is the EAGAIN path. The svc_recv routine will
* return -EAGAIN, the nfsd thread will go to call into
* svc_recv again and we shouldn't be on the active
* transport list
*/
if (test_bit(XPT_CLOSE, &xprt->xpt_flags))
goto defer;
goto out;
}
dprintk("svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\n",
ctxt, rdma_xprt, rqstp);
atomic_inc(&rdma_stat_recv);
/* Build up the XDR from the receive buffers. */
rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len);
/* Decode the RDMA header. */
rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base;
ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg);
if (ret < 0)
goto out_err;
if (ret == 0)
goto out_drop;
rqstp->rq_xprt_hlen = ret;
if (svc_rdma_is_backchannel_reply(xprt, rmsgp)) {
ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, rmsgp,
&rqstp->rq_arg);
svc_rdma_put_context(ctxt, 0);
if (ret)
goto repost;
return ret;
}
/* Read read-list data. */
ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt);
if (ret > 0) {
/* read-list posted, defer until data received from client. */
goto defer;
} else if (ret < 0) {
/* Post of read-list failed, free context. */
svc_rdma_put_context(ctxt, 1);
return 0;
}
complete:
ret = rqstp->rq_arg.head[0].iov_len
+ rqstp->rq_arg.page_len
+ rqstp->rq_arg.tail[0].iov_len;
svc_rdma_put_context(ctxt, 0);
out:
dprintk("svcrdma: ret=%d, rq_arg.len=%u, "
"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\n",
ret, rqstp->rq_arg.len,
rqstp->rq_arg.head[0].iov_base,
rqstp->rq_arg.head[0].iov_len);
rqstp->rq_prot = IPPROTO_MAX;
svc_xprt_copy_addrs(rqstp, xprt);
return ret;
out_err:
svc_rdma_send_error(rdma_xprt, rmsgp, ret);
svc_rdma_put_context(ctxt, 0);
return 0;
defer:
return 0;
out_drop:
svc_rdma_put_context(ctxt, 1);
repost:
return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | int svc_rdma_recvfrom(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma_xprt =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct svc_rdma_op_ctxt *ctxt = NULL;
struct rpcrdma_msg *rmsgp;
int ret = 0;
dprintk("svcrdma: rqstp=%p\n", rqstp);
spin_lock(&rdma_xprt->sc_rq_dto_lock);
if (!list_empty(&rdma_xprt->sc_read_complete_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
rdma_read_complete(rqstp, ctxt);
goto complete;
} else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
} else {
atomic_inc(&rdma_stat_rq_starve);
clear_bit(XPT_DATA, &xprt->xpt_flags);
ctxt = NULL;
}
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
if (!ctxt) {
/* This is the EAGAIN path. The svc_recv routine will
* return -EAGAIN, the nfsd thread will go to call into
* svc_recv again and we shouldn't be on the active
* transport list
*/
if (test_bit(XPT_CLOSE, &xprt->xpt_flags))
goto defer;
goto out;
}
dprintk("svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\n",
ctxt, rdma_xprt, rqstp);
atomic_inc(&rdma_stat_recv);
/* Build up the XDR from the receive buffers. */
rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len);
/* Decode the RDMA header. */
rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base;
ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg);
if (ret < 0)
goto out_err;
if (ret == 0)
goto out_drop;
rqstp->rq_xprt_hlen = ret;
if (svc_rdma_is_backchannel_reply(xprt, &rmsgp->rm_xid)) {
ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt,
&rmsgp->rm_xid,
&rqstp->rq_arg);
svc_rdma_put_context(ctxt, 0);
if (ret)
goto repost;
return ret;
}
/* Read read-list data. */
ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt);
if (ret > 0) {
/* read-list posted, defer until data received from client. */
goto defer;
} else if (ret < 0) {
/* Post of read-list failed, free context. */
svc_rdma_put_context(ctxt, 1);
return 0;
}
complete:
ret = rqstp->rq_arg.head[0].iov_len
+ rqstp->rq_arg.page_len
+ rqstp->rq_arg.tail[0].iov_len;
svc_rdma_put_context(ctxt, 0);
out:
dprintk("svcrdma: ret=%d, rq_arg.len=%u, "
"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\n",
ret, rqstp->rq_arg.len,
rqstp->rq_arg.head[0].iov_base,
rqstp->rq_arg.head[0].iov_len);
rqstp->rq_prot = IPPROTO_MAX;
svc_xprt_copy_addrs(rqstp, xprt);
return ret;
out_err:
svc_rdma_send_error(rdma_xprt, &rmsgp->rm_xid, ret);
svc_rdma_put_context(ctxt, 0);
return 0;
defer:
return 0;
out_drop:
svc_rdma_put_context(ctxt, 1);
repost:
return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL);
}
| 168,165 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options,
struct rusage32 __user *, ur)
{
struct rusage r;
long ret, err;
mm_segment_t old_fs;
if (!ur)
return sys_wait4(pid, ustatus, options, NULL);
old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_wait4(pid, ustatus, options, (struct rusage __user *) &r);
set_fs (old_fs);
if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur)))
return -EFAULT;
err = 0;
err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec);
err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec);
err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec);
err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec);
err |= __put_user(r.ru_maxrss, &ur->ru_maxrss);
err |= __put_user(r.ru_ixrss, &ur->ru_ixrss);
err |= __put_user(r.ru_idrss, &ur->ru_idrss);
err |= __put_user(r.ru_isrss, &ur->ru_isrss);
err |= __put_user(r.ru_minflt, &ur->ru_minflt);
err |= __put_user(r.ru_majflt, &ur->ru_majflt);
err |= __put_user(r.ru_nswap, &ur->ru_nswap);
err |= __put_user(r.ru_inblock, &ur->ru_inblock);
err |= __put_user(r.ru_oublock, &ur->ru_oublock);
err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd);
err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv);
err |= __put_user(r.ru_nsignals, &ur->ru_nsignals);
err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw);
err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw);
return err ? err : ret;
}
Commit Message: alpha: fix several security issues
Fix several security issues in Alpha-specific syscalls. Untested, but
mostly trivial.
1. Signedness issue in osf_getdomainname allows copying out-of-bounds
kernel memory to userland.
2. Signedness issue in osf_sysinfo allows copying large amounts of
kernel memory to userland.
3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy
size, allowing copying large amounts of kernel memory to userland.
4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows
privilege escalation via writing return value of sys_wait4 to kernel
memory.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Richard Henderson <[email protected]>
Cc: Ivan Kokshaysky <[email protected]>
Cc: Matt Turner <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options,
struct rusage32 __user *, ur)
{
struct rusage r;
long ret, err;
unsigned int status = 0;
mm_segment_t old_fs;
if (!ur)
return sys_wait4(pid, ustatus, options, NULL);
old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_wait4(pid, (unsigned int __user *) &status, options,
(struct rusage __user *) &r);
set_fs (old_fs);
if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur)))
return -EFAULT;
err = 0;
err |= put_user(status, ustatus);
err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec);
err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec);
err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec);
err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec);
err |= __put_user(r.ru_maxrss, &ur->ru_maxrss);
err |= __put_user(r.ru_ixrss, &ur->ru_ixrss);
err |= __put_user(r.ru_idrss, &ur->ru_idrss);
err |= __put_user(r.ru_isrss, &ur->ru_isrss);
err |= __put_user(r.ru_minflt, &ur->ru_minflt);
err |= __put_user(r.ru_majflt, &ur->ru_majflt);
err |= __put_user(r.ru_nswap, &ur->ru_nswap);
err |= __put_user(r.ru_inblock, &ur->ru_inblock);
err |= __put_user(r.ru_oublock, &ur->ru_oublock);
err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd);
err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv);
err |= __put_user(r.ru_nsignals, &ur->ru_nsignals);
err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw);
err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw);
return err ? err : ret;
}
| 165,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Block::Lacing Block::GetLacing() const
{
const int value = int(m_flags & 0x06) >> 1;
return static_cast<Lacing>(value);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Block::Lacing Block::GetLacing() const
const long status = pReader->Read(pos, len, buf);
return status;
}
| 174,335 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sgi_timer_get(struct k_itimer *timr, struct itimerspec *cur_setting)
{
if (timr->it.mmtimer.clock == TIMER_OFF) {
cur_setting->it_interval.tv_nsec = 0;
cur_setting->it_interval.tv_sec = 0;
cur_setting->it_value.tv_nsec = 0;
cur_setting->it_value.tv_sec =0;
return;
}
ns_to_timespec(cur_setting->it_interval, timr->it.mmtimer.incr * sgi_clock_period);
ns_to_timespec(cur_setting->it_value, (timr->it.mmtimer.expires - rtc_time())* sgi_clock_period);
return;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static void sgi_timer_get(struct k_itimer *timr, struct itimerspec *cur_setting)
{
if (timr->it.mmtimer.clock == TIMER_OFF) {
cur_setting->it_interval.tv_nsec = 0;
cur_setting->it_interval.tv_sec = 0;
cur_setting->it_value.tv_nsec = 0;
cur_setting->it_value.tv_sec =0;
return;
}
cur_setting->it_interval = ns_to_timespec(timr->it.mmtimer.incr * sgi_clock_period);
cur_setting->it_value = ns_to_timespec((timr->it.mmtimer.expires - rtc_time()) * sgi_clock_period);
}
| 165,751 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct16x16_c(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
void fdct16x16_ref(const int16_t *in, tran_low_t *out, int stride,
int /*tx_type*/) {
vpx_fdct16x16_c(in, out, stride);
}
| 174,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void scheduleBeginFrameAndCommit()
{
CCMainThread::postTask(m_proxy->createBeginFrameAndCommitTaskOnCCThread());
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | virtual void scheduleBeginFrameAndCommit()
{
m_proxy->postBeginFrameAndCommitOnCCThread();
}
| 170,288 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebView* RenderViewImpl::createView(
WebFrame* creator,
const WebURLRequest& request,
const WebWindowFeatures& features,
const WebString& frame_name,
WebNavigationPolicy policy) {
if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups)
return NULL;
ViewHostMsg_CreateWindow_Params params;
params.opener_id = routing_id_;
params.user_gesture = creator->isProcessingUserGesture();
params.window_container_type = WindowFeaturesToContainerType(features);
params.session_storage_namespace_id = session_storage_namespace_id_;
params.frame_name = frame_name;
params.opener_frame_id = creator->identifier();
params.opener_url = creator->document().url();
params.opener_security_origin =
creator->document().securityOrigin().toString().utf8();
params.opener_suppressed = creator->willSuppressOpenerInNewFrame();
params.disposition = NavigationPolicyToDisposition(policy);
if (!request.isNull())
params.target_url = request.url();
int32 routing_id = MSG_ROUTING_NONE;
int32 surface_id = 0;
int64 cloned_session_storage_namespace_id;
RenderThread::Get()->Send(
new ViewHostMsg_CreateWindow(params,
&routing_id,
&surface_id,
&cloned_session_storage_namespace_id));
if (routing_id == MSG_ROUTING_NONE)
return NULL;
creator->consumeUserGesture();
RenderViewImpl* view = RenderViewImpl::Create(
routing_id_,
renderer_preferences_,
webkit_preferences_,
shared_popup_counter_,
routing_id,
surface_id,
cloned_session_storage_namespace_id,
frame_name,
true,
false,
1,
screen_info_,
accessibility_mode_);
view->opened_by_user_gesture_ = params.user_gesture;
view->opener_suppressed_ = params.opener_suppressed;
view->alternate_error_page_url_ = alternate_error_page_url_;
return view->webview();
}
Commit Message: Filter more incoming URLs in the CreateWindow path.
BUG=170532
Review URL: https://chromiumcodereview.appspot.com/12036002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | WebView* RenderViewImpl::createView(
WebFrame* creator,
const WebURLRequest& request,
const WebWindowFeatures& features,
const WebString& frame_name,
WebNavigationPolicy policy) {
if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups)
return NULL;
ViewHostMsg_CreateWindow_Params params;
params.opener_id = routing_id_;
params.user_gesture = creator->isProcessingUserGesture();
params.window_container_type = WindowFeaturesToContainerType(features);
params.session_storage_namespace_id = session_storage_namespace_id_;
params.frame_name = frame_name;
params.opener_frame_id = creator->identifier();
params.opener_url = creator->document().url();
GURL security_url(creator->document().securityOrigin().toString().utf8());
if (!security_url.is_valid())
security_url = GURL();
params.opener_security_origin = security_url;
params.opener_suppressed = creator->willSuppressOpenerInNewFrame();
params.disposition = NavigationPolicyToDisposition(policy);
if (!request.isNull())
params.target_url = request.url();
int32 routing_id = MSG_ROUTING_NONE;
int32 surface_id = 0;
int64 cloned_session_storage_namespace_id;
RenderThread::Get()->Send(
new ViewHostMsg_CreateWindow(params,
&routing_id,
&surface_id,
&cloned_session_storage_namespace_id));
if (routing_id == MSG_ROUTING_NONE)
return NULL;
creator->consumeUserGesture();
RenderViewImpl* view = RenderViewImpl::Create(
routing_id_,
renderer_preferences_,
webkit_preferences_,
shared_popup_counter_,
routing_id,
surface_id,
cloned_session_storage_namespace_id,
frame_name,
true,
false,
1,
screen_info_,
accessibility_mode_);
view->opened_by_user_gesture_ = params.user_gesture;
view->opener_suppressed_ = params.opener_suppressed;
view->alternate_error_page_url_ = alternate_error_page_url_;
return view->webview();
}
| 171,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection(ExecState* exec)
{
JSDeprecatedPeerConnectionConstructor* jsConstructor = static_cast<JSDeprecatedPeerConnectionConstructor*>(exec->callee());
ScriptExecutionContext* context = jsConstructor->scriptExecutionContext();
if (!context)
return throwVMError(exec, createReferenceError(exec, "DeprecatedPeerConnection constructor associated document is unavailable"));
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
String serverConfiguration = ustringToString(exec->argument(0).toString(exec)->value(exec));
if (exec->hadException())
return JSValue::encode(JSValue());
RefPtr<SignalingCallback> signalingCallback = createFunctionOnlyCallback<JSSignalingCallback>(exec, static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), exec->argument(1));
if (exec->hadException())
return JSValue::encode(JSValue());
RefPtr<DeprecatedPeerConnection> peerConnection = DeprecatedPeerConnection::create(context, serverConfiguration, signalingCallback.release());
return JSValue::encode(CREATE_DOM_WRAPPER(exec, jsConstructor->globalObject(), DeprecatedPeerConnection, peerConnection.get()));
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection(ExecState* exec)
{
JSDeprecatedPeerConnectionConstructor* jsConstructor = static_cast<JSDeprecatedPeerConnectionConstructor*>(exec->callee());
ScriptExecutionContext* context = jsConstructor->scriptExecutionContext();
if (!context)
return throwVMError(exec, createReferenceError(exec, "DeprecatedPeerConnection constructor associated document is unavailable"));
if (exec->argumentCount() < 2)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
String serverConfiguration = ustringToString(exec->argument(0).toString(exec)->value(exec));
if (exec->hadException())
return JSValue::encode(JSValue());
RefPtr<SignalingCallback> signalingCallback = createFunctionOnlyCallback<JSSignalingCallback>(exec, static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), exec->argument(1));
if (exec->hadException())
return JSValue::encode(JSValue());
RefPtr<DeprecatedPeerConnection> peerConnection = DeprecatedPeerConnection::create(context, serverConfiguration, signalingCallback.release());
return JSValue::encode(CREATE_DOM_WRAPPER(exec, jsConstructor->globalObject(), DeprecatedPeerConnection, peerConnection.get()));
}
| 170,559 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
const struct xfrm_link *link;
int type, err;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
return -EOPNOTSUPP;
#endif
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!netlink_net_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs,
link->nla_max ? : XFRMA_MAX,
link->nla_pol ? : xfrma_policy, extack);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
Commit Message: ipsec: Fix aborted xfrm policy dump crash
An independent security researcher, Mohamed Ghannam, has reported
this vulnerability to Beyond Security's SecuriTeam Secure Disclosure
program.
The xfrm_dump_policy_done function expects xfrm_dump_policy to
have been called at least once or it will crash. This can be
triggered if a dump fails because the target socket's receive
buffer is full.
This patch fixes it by using the cb->start mechanism to ensure that
the initialisation is always done regardless of the buffer situation.
Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list")
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
CWE ID: CWE-416 | static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
const struct xfrm_link *link;
int type, err;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
return -EOPNOTSUPP;
#endif
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (!netlink_net_capable(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
{
struct netlink_dump_control c = {
.start = link->start,
.dump = link->dump,
.done = link->done,
};
return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
}
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs,
link->nla_max ? : XFRMA_MAX,
link->nla_pol ? : xfrma_policy, extack);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
| 167,664 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] Avoid index out of bounds access to pi->include[]
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-20 | static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
| 169,770 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
const EAS_SAMPLE *loopEnd;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
/*lint -e{713} truncation is OK */
phaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* check for loop end */
acc0 = (EAS_I32) (pSamples - loopEnd);
if (acc0 >= 0)
pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0;
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119 | void WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
const EAS_SAMPLE *loopEnd;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
/*lint -e{713} truncation is OK */
phaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* check for loop end */
acc0 = (EAS_I32) (pSamples - loopEnd);
if (acc0 >= 0)
pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0;
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
| 173,917 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
| 173,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cmsPipeline* DefaultICCintents(cmsContext ContextID,
cmsUInt32Number nProfiles,
cmsUInt32Number TheIntents[],
cmsHPROFILE hProfiles[],
cmsBool BPC[],
cmsFloat64Number AdaptationStates[],
cmsUInt32Number dwFlags)
{
cmsPipeline* Lut = NULL;
cmsPipeline* Result;
cmsHPROFILE hProfile;
cmsMAT3 m;
cmsVEC3 off;
cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace;
cmsProfileClassSignature ClassSig;
cmsUInt32Number i, Intent;
if (nProfiles == 0) return NULL;
Result = cmsPipelineAlloc(ContextID, 0, 0);
if (Result == NULL) return NULL;
CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
for (i=0; i < nProfiles; i++) {
cmsBool lIsDeviceLink, lIsInput;
hProfile = hProfiles[i];
ClassSig = cmsGetDeviceClass(hProfile);
lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass );
if ((i == 0) && !lIsDeviceLink) {
lIsInput = TRUE;
}
else {
lIsInput = (CurrentColorSpace != cmsSigXYZData) &&
(CurrentColorSpace != cmsSigLabData);
}
Intent = TheIntents[i];
if (lIsInput || lIsDeviceLink) {
ColorSpaceIn = cmsGetColorSpace(hProfile);
ColorSpaceOut = cmsGetPCS(hProfile);
}
else {
ColorSpaceIn = cmsGetPCS(hProfile);
ColorSpaceOut = cmsGetColorSpace(hProfile);
}
if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) {
cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch");
goto Error;
}
if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) {
Lut = _cmsReadDevicelinkLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
if (ClassSig == cmsSigAbstractClass && i > 0) {
if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
}
else {
_cmsMAT3identity(&m);
_cmsVEC3init(&off, 0, 0, 0);
}
if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
}
else {
if (lIsInput) {
Lut = _cmsReadInputLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
}
else {
Lut = _cmsReadOutputLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
}
}
if (!cmsPipelineCat(Result, Lut))
goto Error;
cmsPipelineFree(Lut);
CurrentColorSpace = ColorSpaceOut;
}
return Result;
Error:
cmsPipelineFree(Lut);
if (Result != NULL) cmsPipelineFree(Result);
return NULL;
cmsUNUSED_PARAMETER(dwFlags);
}
Commit Message: Fix a double free on error recovering
CWE ID: | cmsPipeline* DefaultICCintents(cmsContext ContextID,
cmsUInt32Number nProfiles,
cmsUInt32Number TheIntents[],
cmsHPROFILE hProfiles[],
cmsBool BPC[],
cmsFloat64Number AdaptationStates[],
cmsUInt32Number dwFlags)
{
cmsPipeline* Lut = NULL;
cmsPipeline* Result;
cmsHPROFILE hProfile;
cmsMAT3 m;
cmsVEC3 off;
cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace;
cmsProfileClassSignature ClassSig;
cmsUInt32Number i, Intent;
if (nProfiles == 0) return NULL;
Result = cmsPipelineAlloc(ContextID, 0, 0);
if (Result == NULL) return NULL;
CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
for (i=0; i < nProfiles; i++) {
cmsBool lIsDeviceLink, lIsInput;
hProfile = hProfiles[i];
ClassSig = cmsGetDeviceClass(hProfile);
lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass );
if ((i == 0) && !lIsDeviceLink) {
lIsInput = TRUE;
}
else {
lIsInput = (CurrentColorSpace != cmsSigXYZData) &&
(CurrentColorSpace != cmsSigLabData);
}
Intent = TheIntents[i];
if (lIsInput || lIsDeviceLink) {
ColorSpaceIn = cmsGetColorSpace(hProfile);
ColorSpaceOut = cmsGetPCS(hProfile);
}
else {
ColorSpaceIn = cmsGetPCS(hProfile);
ColorSpaceOut = cmsGetColorSpace(hProfile);
}
if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) {
cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch");
goto Error;
}
if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) {
Lut = _cmsReadDevicelinkLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
if (ClassSig == cmsSigAbstractClass && i > 0) {
if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
}
else {
_cmsMAT3identity(&m);
_cmsVEC3init(&off, 0, 0, 0);
}
if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
}
else {
if (lIsInput) {
Lut = _cmsReadInputLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
}
else {
Lut = _cmsReadOutputLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
}
}
if (!cmsPipelineCat(Result, Lut))
goto Error;
cmsPipelineFree(Lut);
Lut = NULL;
CurrentColorSpace = ColorSpaceOut;
}
return Result;
Error:
if (Lut != NULL) cmsPipelineFree(Lut);
if (Result != NULL) cmsPipelineFree(Result);
return NULL;
cmsUNUSED_PARAMETER(dwFlags);
}
| 167,592 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderParamsFromPrintSettings(const PrintSettings& settings,
PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->printable_area.SetRect(
settings.page_setup_device_units().printable_area().x(),
settings.page_setup_device_units().printable_area().y(),
settings.page_setup_device_units().printable_area().width(),
settings.page_setup_device_units().printable_area().height());
params->margin_top = settings.page_setup_device_units().content_area().y();
params->margin_left = settings.page_setup_device_units().content_area().x();
params->dpi = settings.dpi();
params->scale_factor = settings.scale_factor();
params->rasterize_pdf = settings.rasterize_pdf();
params->document_cookie = 0;
params->selection_only = settings.selection_only();
params->supports_alpha_blend = settings.supports_alpha_blend();
params->should_print_backgrounds = settings.should_print_backgrounds();
params->display_header_footer = settings.display_header_footer();
params->title = settings.title();
params->url = settings.url();
params->printed_doc_type = SkiaDocumentType::PDF;
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | void RenderParamsFromPrintSettings(const PrintSettings& settings,
PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->printable_area.SetRect(
settings.page_setup_device_units().printable_area().x(),
settings.page_setup_device_units().printable_area().y(),
settings.page_setup_device_units().printable_area().width(),
settings.page_setup_device_units().printable_area().height());
params->margin_top = settings.page_setup_device_units().content_area().y();
params->margin_left = settings.page_setup_device_units().content_area().x();
params->dpi = settings.dpi();
params->scale_factor = settings.scale_factor();
params->rasterize_pdf = settings.rasterize_pdf();
params->document_cookie = 0;
params->selection_only = settings.selection_only();
params->supports_alpha_blend = settings.supports_alpha_blend();
params->should_print_backgrounds = settings.should_print_backgrounds();
params->display_header_footer = settings.display_header_footer();
params->title = settings.title();
params->url = settings.url();
params->printed_doc_type =
IsOopifEnabled() ? SkiaDocumentType::MSKP : SkiaDocumentType::PDF;
}
| 171,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool BackgroundLoaderOffliner::LoadAndSave(
const SavePageRequest& request,
CompletionCallback completion_callback,
const ProgressCallback& progress_callback) {
DCHECK(completion_callback);
DCHECK(progress_callback);
DCHECK(offline_page_model_);
if (pending_request_) {
DVLOG(1) << "Already have pending request";
return false;
}
ClientPolicyController* policy_controller =
offline_page_model_->GetPolicyController();
if (policy_controller->RequiresSpecificUserSettings(
request.client_id().name_space) &&
(AreThirdPartyCookiesBlocked(browser_context_) ||
IsNetworkPredictionDisabled(browser_context_))) {
DVLOG(1) << "WARNING: Unable to load when 3rd party cookies blocked or "
<< "prediction disabled";
if (AreThirdPartyCookiesBlocked(browser_context_)) {
UMA_HISTOGRAM_ENUMERATION(
"OfflinePages.Background.CctApiDisableStatus",
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
THIRD_PARTY_COOKIES_DISABLED),
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED) +
1);
}
if (IsNetworkPredictionDisabled(browser_context_)) {
UMA_HISTOGRAM_ENUMERATION(
"OfflinePages.Background.CctApiDisableStatus",
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED),
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED) +
1);
}
return false;
}
if (request.client_id().name_space == kCCTNamespace) {
UMA_HISTOGRAM_ENUMERATION(
"OfflinePages.Background.CctApiDisableStatus",
static_cast<int>(
OfflinePagesCctApiPrerenderAllowedStatus::PRERENDER_ALLOWED),
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED) +
1);
}
if (!OfflinePageModel::CanSaveURL(request.url())) {
DVLOG(1) << "Not able to save page for requested url: " << request.url();
return false;
}
ResetLoader();
AttachObservers();
MarkLoadStartTime();
pending_request_.reset(new SavePageRequest(request));
completion_callback_ = std::move(completion_callback);
progress_callback_ = progress_callback;
if (IsOfflinePagesRenovationsEnabled()) {
if (!page_renovation_loader_)
page_renovation_loader_ = std::make_unique<PageRenovationLoader>();
auto script_injector = std::make_unique<RenderFrameScriptInjector>(
loader_->web_contents()->GetMainFrame(),
ISOLATED_WORLD_ID_CHROME_INTERNAL);
page_renovator_ = std::make_unique<PageRenovator>(
page_renovation_loader_.get(), std::move(script_injector),
request.url());
}
loader_.get()->LoadPage(request.url());
snapshot_controller_ = std::make_unique<BackgroundSnapshotController>(
base::ThreadTaskRunnerHandle::Get(), this,
static_cast<bool>(page_renovator_));
return true;
}
Commit Message: Remove unused histograms from the background loader offliner.
Bug: 975512
Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361
Reviewed-by: Cathy Li <[email protected]>
Reviewed-by: Steven Holte <[email protected]>
Commit-Queue: Peter Williamson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#675332}
CWE ID: CWE-119 | bool BackgroundLoaderOffliner::LoadAndSave(
const SavePageRequest& request,
CompletionCallback completion_callback,
const ProgressCallback& progress_callback) {
DCHECK(completion_callback);
DCHECK(progress_callback);
DCHECK(offline_page_model_);
if (pending_request_) {
DVLOG(1) << "Already have pending request";
return false;
}
ClientPolicyController* policy_controller =
offline_page_model_->GetPolicyController();
if (policy_controller->RequiresSpecificUserSettings(
request.client_id().name_space) &&
(AreThirdPartyCookiesBlocked(browser_context_) ||
IsNetworkPredictionDisabled(browser_context_))) {
DVLOG(1) << "WARNING: Unable to load when 3rd party cookies blocked or "
<< "prediction disabled";
return false;
}
if (!OfflinePageModel::CanSaveURL(request.url())) {
DVLOG(1) << "Not able to save page for requested url: " << request.url();
return false;
}
ResetLoader();
AttachObservers();
MarkLoadStartTime();
pending_request_.reset(new SavePageRequest(request));
completion_callback_ = std::move(completion_callback);
progress_callback_ = progress_callback;
if (IsOfflinePagesRenovationsEnabled()) {
if (!page_renovation_loader_)
page_renovation_loader_ = std::make_unique<PageRenovationLoader>();
auto script_injector = std::make_unique<RenderFrameScriptInjector>(
loader_->web_contents()->GetMainFrame(),
ISOLATED_WORLD_ID_CHROME_INTERNAL);
page_renovator_ = std::make_unique<PageRenovator>(
page_renovation_loader_.get(), std::move(script_injector),
request.url());
}
loader_.get()->LoadPage(request.url());
snapshot_controller_ = std::make_unique<BackgroundSnapshotController>(
base::ThreadTaskRunnerHandle::Get(), this,
static_cast<bool>(page_renovator_));
return true;
}
| 172,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse)
{
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
PixelInfo
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetPixelInfo(image,&mean_pixel);
GetPixelInfoPixel(image,p,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
PixelInfo
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetPixelInfo(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelInfo
pixel;
status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.alpha+=pixel.alpha;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.alpha=gamma*sum_pixel.alpha;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q);
SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q);
SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q);
SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(mean_image);
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1552
CWE ID: CWE-369 | MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse)
{
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
PixelInfo
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetPixelInfo(image,&mean_pixel);
GetPixelInfoPixel(image,p,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
PixelInfo
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetPixelInfo(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelInfo
pixel;
status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.alpha+=pixel.alpha;
count++;
}
}
}
}
gamma=PerceptibleReciprocal(count);
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.alpha=gamma*sum_pixel.alpha;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q);
SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q);
SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q);
SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(mean_image);
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
| 170,189 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rtadv_read (struct thread *thread)
{
int sock;
int len;
u_char buf[RTADV_MSG_SIZE];
struct sockaddr_in6 from;
ifindex_t ifindex = 0;
int hoplimit = -1;
struct zebra_vrf *zvrf = THREAD_ARG (thread);
sock = THREAD_FD (thread);
zvrf->rtadv.ra_read = NULL;
/* Register myself. */
rtadv_event (zvrf, RTADV_READ, sock);
len = rtadv_recv_packet (sock, buf, BUFSIZ, &from, &ifindex, &hoplimit);
if (len < 0)
{
zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno));
return len;
}
rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id);
return 0;
}
Commit Message: zebra: stack overrun in IPv6 RA receive code (CVE-2016-1245)
The IPv6 RA code also receives ICMPv6 RS and RA messages.
Unfortunately, by bad coding practice, the buffer size specified on
receiving such messages mixed up 2 constants that in fact have
different values.
The code itself has:
#define RTADV_MSG_SIZE 4096
While BUFSIZ is system-dependent, in my case (x86_64 glibc):
/usr/include/_G_config.h:#define _G_BUFSIZ 8192
/usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ
/usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ
FreeBSD, OpenBSD, NetBSD and Illumos are not affected, since all of them
have BUFSIZ == 1024.
As the latter is passed to the kernel on recvmsg(), it's possible to
overwrite 4kB of stack -- with ICMPv6 packets that can be globally sent
to any of the system's addresses (using fragmentation to get to 8k).
(The socket has filters installed limiting this to RS and RA packets,
but does not have a filter for source address or TTL.)
Issue discovered by trying to test other stuff, which randomly caused
the stack to be smaller than 8kB in that code location, which then
causes the kernel to report EFAULT (Bad address).
Signed-off-by: David Lamparter <[email protected]>
Reviewed-by: Donald Sharp <[email protected]>
CWE ID: CWE-119 | rtadv_read (struct thread *thread)
{
int sock;
int len;
u_char buf[RTADV_MSG_SIZE];
struct sockaddr_in6 from;
ifindex_t ifindex = 0;
int hoplimit = -1;
struct zebra_vrf *zvrf = THREAD_ARG (thread);
sock = THREAD_FD (thread);
zvrf->rtadv.ra_read = NULL;
/* Register myself. */
rtadv_event (zvrf, RTADV_READ, sock);
len = rtadv_recv_packet (sock, buf, sizeof (buf), &from, &ifindex, &hoplimit);
if (len < 0)
{
zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno));
return len;
}
rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id);
return 0;
}
| 168,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CoordinatorImpl::RequestGlobalMemoryDumpForPid(
base::ProcessId pid,
const RequestGlobalMemoryDumpForPidCallback& callback) {
if (pid == base::kNullProcessId) {
callback.Run(false, nullptr);
return;
}
auto adapter = [](const RequestGlobalMemoryDumpForPidCallback& callback,
bool success, uint64_t,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
base::trace_event::MemoryDumpType::SUMMARY_ONLY,
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND, {},
false /* addToTrace */, pid);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void CoordinatorImpl::RequestGlobalMemoryDumpForPid(
base::ProcessId pid,
const RequestGlobalMemoryDumpForPidCallback& callback) {
if (pid == base::kNullProcessId) {
callback.Run(false, nullptr);
return;
}
auto adapter = [](const RequestGlobalMemoryDumpForPidCallback& callback,
bool success, uint64_t,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
base::trace_event::MemoryDumpType::SUMMARY_ONLY,
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND, {},
false /* add_to_trace */, pid);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
| 172,917 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
downmix_module_t *pDwmModule = (downmix_module_t *) self;
downmix_object_t *pDownmixer;
int retsize;
if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) {
return -EINVAL;
}
pDownmixer = (downmix_object_t*) &pDwmModule->context;
ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize);
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Init(pDwmModule);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Configure(pDwmModule,
(effect_config_t *)pCmdData, false);
break;
case EFFECT_CMD_RESET:
Downmix_Reset(pDownmixer, false);
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p",
pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL ||
*replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *rep = (effect_param_t *) pReplyData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t));
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32,
*(int32_t *)rep->data, rep->vsize);
rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize,
rep->data + sizeof(int32_t));
*replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize;
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32
", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || *replySize != (int)sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *cmd = (effect_param_t *) pCmdData;
*(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data,
cmd->vsize, cmd->data + sizeof(int32_t));
break;
case EFFECT_CMD_SET_PARAM_DEFERRED:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME");
break;
case EFFECT_CMD_SET_PARAM_COMMIT:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME");
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_ACTIVE) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_SET_DEVICE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_VOLUME: {
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) {
return -EINVAL;
}
ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME");
float left = (float)(*(uint32_t *)pCmdData) / (1 << 24);
float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24);
ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right);
break;
}
case EFFECT_CMD_SET_AUDIO_MODE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_CONFIG_REVERSE:
case EFFECT_CMD_SET_INPUT_DEVICE:
break;
default:
ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119 | static int Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
downmix_module_t *pDwmModule = (downmix_module_t *) self;
downmix_object_t *pDownmixer;
int retsize;
if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) {
return -EINVAL;
}
pDownmixer = (downmix_object_t*) &pDwmModule->context;
ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize);
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Init(pDwmModule);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Configure(pDwmModule,
(effect_config_t *)pCmdData, false);
break;
case EFFECT_CMD_RESET:
Downmix_Reset(pDownmixer, false);
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p",
pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *rep = (effect_param_t *) pReplyData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t));
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32,
*(int32_t *)rep->data, rep->vsize);
rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize,
rep->data + sizeof(int32_t));
*replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize;
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32
", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || replySize == NULL || *replySize != (int)sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *cmd = (effect_param_t *) pCmdData;
*(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data,
cmd->vsize, cmd->data + sizeof(int32_t));
break;
case EFFECT_CMD_SET_PARAM_DEFERRED:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME");
break;
case EFFECT_CMD_SET_PARAM_COMMIT:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME");
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_ACTIVE) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_SET_DEVICE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_VOLUME: {
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) {
return -EINVAL;
}
ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME");
float left = (float)(*(uint32_t *)pCmdData) / (1 << 24);
float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24);
ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right);
break;
}
case EFFECT_CMD_SET_AUDIO_MODE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_CONFIG_REVERSE:
case EFFECT_CMD_SET_INPUT_DEVICE:
break;
default:
ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
| 173,344 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret, key_tries, sign_tries, blind_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
sign_tries = 0;
do
{
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
key_tries = 0;
do
{
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) );
if( key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( r, 0 ) == 0 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
blind_tries = 0;
do
{
size_t n_size = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) );
/* See mbedtls_ecp_gen_keypair() */
if( ++blind_tries > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
if( sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200 | int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
static int ecdsa_sign_internal( mbedtls_ecp_group *grp, mbedtls_mpi *r,
mbedtls_mpi *s, const mbedtls_mpi *d,
const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
int (*f_rng_blind)(void *, unsigned char *,
size_t),
void *p_rng_blind )
{
int ret, key_tries, sign_tries, blind_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
sign_tries = 0;
do
{
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
key_tries = 0;
do
{
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &k, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &R, &k, &grp->G,
f_rng_blind, p_rng_blind ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) );
if( key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( r, 0 ) == 0 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*
* This loop does the same job as mbedtls_ecp_gen_privkey() and it is
* replaced by a call to it in the mainline. This change is not
* necessary to backport the fix separating the blinding and ephemeral
* key generating RNGs, therefore the original code is kept.
*/
blind_tries = 0;
do
{
size_t n_size = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng_blind,
p_rng_blind ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) );
if( ++blind_tries > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
if( sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
return( ret );
}
| 170,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Track* Tracks::GetTrackByNumber(long tn) const
{
if (tn < 0)
return NULL;
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j)
{
Track* const pTrack = *i++;
if (pTrack == NULL)
continue;
if (tn == pTrack->GetNumber())
return pTrack;
}
return NULL; //not found
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Track* Tracks::GetTrackByNumber(long tn) const
| 174,371 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserTabStripController::TabDetachedAt(TabContents* contents,
int model_index) {
hover_tab_selector_.CancelTabTransition();
tabstrip_->RemoveTabAt(model_index);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserTabStripController::TabDetachedAt(TabContents* contents,
void BrowserTabStripController::TabDetachedAt(WebContents* contents,
int model_index) {
hover_tab_selector_.CancelTabTransition();
tabstrip_->RemoveTabAt(model_index);
}
| 171,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static void commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
n->mounts += n->pending_mounts;
n->pending_mounts = 0;
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
| 167,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cuse_channel_release(struct inode *inode, struct file *file)
{
struct fuse_dev *fud = file->private_data;
struct cuse_conn *cc = fc_to_cc(fud->fc);
int rc;
/* remove from the conntbl, no more access from this point on */
mutex_lock(&cuse_lock);
list_del_init(&cc->list);
mutex_unlock(&cuse_lock);
/* remove device */
if (cc->dev)
device_unregister(cc->dev);
if (cc->cdev) {
unregister_chrdev_region(cc->cdev->dev, 1);
cdev_del(cc->cdev);
}
rc = fuse_dev_release(inode, file); /* puts the base reference */
return rc;
}
Commit Message: cuse: fix memory leak
The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc,
and the original ref count is never dropped.
Reported-by: Colin Ian King <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure")
Cc: <[email protected]> # v4.2+
CWE ID: CWE-399 | static int cuse_channel_release(struct inode *inode, struct file *file)
{
struct fuse_dev *fud = file->private_data;
struct cuse_conn *cc = fc_to_cc(fud->fc);
int rc;
/* remove from the conntbl, no more access from this point on */
mutex_lock(&cuse_lock);
list_del_init(&cc->list);
mutex_unlock(&cuse_lock);
/* remove device */
if (cc->dev)
device_unregister(cc->dev);
if (cc->cdev) {
unregister_chrdev_region(cc->cdev->dev, 1);
cdev_del(cc->cdev);
}
/* Base reference is now owned by "fud" */
fuse_conn_put(&cc->fc);
rc = fuse_dev_release(inode, file); /* puts the base reference */
return rc;
}
| 167,573 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: JSValue JSDirectoryEntry::getDirectory(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl());
const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
if (exec->hadException())
return jsUndefined();
int argsCount = exec->argumentCount();
if (argsCount <= 1) {
imp->getDirectory(path);
return jsUndefined();
}
RefPtr<WebKitFlags> flags;
if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) {
JSObject* object = exec->argument(1).getObject();
flags = WebKitFlags::create();
JSValue jsCreate = object->get(exec, Identifier(exec, "create"));
flags->setCreate(jsCreate.toBoolean(exec));
JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive"));
flags->setExclusive(jsExclusive.toBoolean(exec));
}
if (exec->hadException())
return jsUndefined();
RefPtr<EntryCallback> successCallback;
if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) {
if (!exec->argument(2).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject());
}
RefPtr<ErrorCallback> errorCallback;
if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) {
if (!exec->argument(3).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject());
}
imp->getDirectory(path, flags, successCallback, errorCallback);
return jsUndefined();
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | JSValue JSDirectoryEntry::getDirectory(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwError(exec, createNotEnoughArgumentsError(exec));
DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl());
const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
if (exec->hadException())
return jsUndefined();
int argsCount = exec->argumentCount();
if (argsCount <= 1) {
imp->getDirectory(path);
return jsUndefined();
}
RefPtr<WebKitFlags> flags;
if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) {
JSObject* object = exec->argument(1).getObject();
flags = WebKitFlags::create();
JSValue jsCreate = object->get(exec, Identifier(exec, "create"));
flags->setCreate(jsCreate.toBoolean(exec));
JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive"));
flags->setExclusive(jsExclusive.toBoolean(exec));
}
if (exec->hadException())
return jsUndefined();
RefPtr<EntryCallback> successCallback;
if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) {
if (!exec->argument(2).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject());
}
RefPtr<ErrorCallback> errorCallback;
if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) {
if (!exec->argument(3).isObject()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject());
}
imp->getDirectory(path, flags, successCallback, errorCallback);
return jsUndefined();
}
| 170,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: flatpak_proxy_client_init (FlatpakProxyClient *client)
{
init_side (client, &client->client_side);
init_side (client, &client->bus_side);
client->auth_end_offset = AUTH_END_INIT_OFFSET;
client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436 | flatpak_proxy_client_init (FlatpakProxyClient *client)
{
init_side (client, &client->client_side);
init_side (client, &client->bus_side);
client->auth_buffer = g_byte_array_new ();
client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
| 169,342 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1608
CWE ID: CWE-125 | MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
| 170,207 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
double
scale;
Image
*clone_image;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickSignature;
clone_image->storage_class=image->storage_class;
clone_image->channels=image->channels;
clone_image->colorspace=image->colorspace;
clone_image->matte=image->matte;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelPacket *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelPacket *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
InitializeExceptionInfo(&clone_image->exception);
InheritException(&clone_image->exception,&image->exception);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MaxTextExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent);
(void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
clone_image->clip_mask=NewImageList();
clone_image->mask=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AllocateSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
if ((columns == image->columns) && (rows == image->rows))
{
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows) == MagickFalse)
{
InheritException(exception,&clone_image->exception);
clone_image=DestroyImage(clone_image);
}
return(clone_image);
}
Commit Message: Fixed incorrect call to DestroyImage reported in #491.
CWE ID: CWE-617 | MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
double
scale;
Image
*clone_image;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickSignature;
clone_image->storage_class=image->storage_class;
clone_image->channels=image->channels;
clone_image->colorspace=image->colorspace;
clone_image->matte=image->matte;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelPacket *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelPacket *) NULL)
{
image=(Image *) RelinquishMagickMemory(image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
InitializeExceptionInfo(&clone_image->exception);
InheritException(&clone_image->exception,&image->exception);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MaxTextExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent);
(void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
clone_image->clip_mask=NewImageList();
clone_image->mask=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AllocateSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
if ((columns == image->columns) && (rows == image->rows))
{
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows) == MagickFalse)
{
InheritException(exception,&clone_image->exception);
clone_image=DestroyImage(clone_image);
}
return(clone_image);
}
| 168,096 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue()
{
return JSStringCreateWithCharacters(0, 0);
}
Commit Message: [GTK][WTR] Implement AccessibilityUIElement::stringValue
https://bugs.webkit.org/show_bug.cgi?id=102951
Reviewed by Martin Robinson.
Implement AccessibilityUIElement::stringValue in the ATK backend
in the same manner it is implemented in DumpRenderTree.
* WebKitTestRunner/InjectedBundle/atk/AccessibilityUIElementAtk.cpp:
(WTR::replaceCharactersForResults):
(WTR):
(WTR::AccessibilityUIElement::stringValue):
git-svn-id: svn://svn.chromium.org/blink/trunk@135485 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue()
{
if (!m_element || !ATK_IS_TEXT(m_element))
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<gchar> text(atk_text_get_text(ATK_TEXT(m_element), 0, -1));
GOwnPtr<gchar> textWithReplacedCharacters(replaceCharactersForResults(text.get()));
GOwnPtr<gchar> axValue(g_strdup_printf("AXValue: %s", textWithReplacedCharacters.get()));
return JSStringCreateWithUTF8CString(axValue.get());
}
| 170,899 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FakePluginServiceFilter::IsPluginEnabled(int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
std::map<FilePath, bool>::iterator it = plugin_state_.find(plugin->path);
if (it == plugin_state_.end()) {
ADD_FAILURE() << "No plug-in state for '" << plugin->path.value() << "'";
return false;
}
return it->second;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | bool FakePluginServiceFilter::IsPluginEnabled(int render_process_id,
bool FakePluginServiceFilter::IsPluginAvailable(int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
std::map<FilePath, bool>::iterator it = plugin_state_.find(plugin->path);
if (it == plugin_state_.end()) {
ADD_FAILURE() << "No plug-in state for '" << plugin->path.value() << "'";
return false;
}
return it->second;
}
| 171,474 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void xgroupCommand(client *c) {
const char *help[] = {
"CREATE <key> <groupname> <id or $> -- Create a new consumer group.",
"SETID <key> <groupname> <id or $> -- Set the current group ID.",
"DELGROUP <key> <groupname> -- Remove the specified group.",
"DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.",
"HELP -- Prints this help.",
NULL
};
stream *s = NULL;
sds grpname = NULL;
streamCG *cg = NULL;
char *opt = c->argv[1]->ptr; /* Subcommand name. */
/* Lookup the key now, this is common for all the subcommands but HELP. */
if (c->argc >= 4) {
robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr);
if (o == NULL) return;
s = o->ptr;
grpname = c->argv[3]->ptr;
/* Certain subcommands require the group to exist. */
if ((cg = streamLookupCG(s,grpname)) == NULL &&
(!strcasecmp(opt,"SETID") ||
!strcasecmp(opt,"DELCONSUMER")))
{
addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' "
"for key name '%s'",
(char*)grpname, (char*)c->argv[2]->ptr);
return;
}
}
/* Dispatch the different subcommands. */
if (!strcasecmp(opt,"CREATE") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id);
if (cg) {
addReply(c,shared.ok);
server.dirty++;
} else {
addReplySds(c,
sdsnew("-BUSYGROUP Consumer Group name already exists\r\n"));
}
} else if (!strcasecmp(opt,"SETID") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
cg->last_id = id;
addReply(c,shared.ok);
} else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) {
if (cg) {
raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL);
streamFreeCG(cg);
addReply(c,shared.cone);
} else {
addReply(c,shared.czero);
}
} else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) {
/* Delete the consumer and returns the number of pending messages
* that were yet associated with such a consumer. */
long long pending = streamDelConsumer(cg,c->argv[4]->ptr);
addReplyLongLong(c,pending);
server.dirty++;
} else if (!strcasecmp(opt,"HELP")) {
addReplyHelp(c, help);
} else {
addReply(c,shared.syntaxerr);
}
}
Commit Message: Abort in XGROUP if the key is not a stream
CWE ID: CWE-704 | void xgroupCommand(client *c) {
const char *help[] = {
"CREATE <key> <groupname> <id or $> -- Create a new consumer group.",
"SETID <key> <groupname> <id or $> -- Set the current group ID.",
"DELGROUP <key> <groupname> -- Remove the specified group.",
"DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.",
"HELP -- Prints this help.",
NULL
};
stream *s = NULL;
sds grpname = NULL;
streamCG *cg = NULL;
char *opt = c->argv[1]->ptr; /* Subcommand name. */
/* Lookup the key now, this is common for all the subcommands but HELP. */
if (c->argc >= 4) {
robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr);
if (o == NULL || checkType(c,o,OBJ_STREAM)) return;
s = o->ptr;
grpname = c->argv[3]->ptr;
/* Certain subcommands require the group to exist. */
if ((cg = streamLookupCG(s,grpname)) == NULL &&
(!strcasecmp(opt,"SETID") ||
!strcasecmp(opt,"DELCONSUMER")))
{
addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' "
"for key name '%s'",
(char*)grpname, (char*)c->argv[2]->ptr);
return;
}
}
/* Dispatch the different subcommands. */
if (!strcasecmp(opt,"CREATE") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id);
if (cg) {
addReply(c,shared.ok);
server.dirty++;
} else {
addReplySds(c,
sdsnew("-BUSYGROUP Consumer Group name already exists\r\n"));
}
} else if (!strcasecmp(opt,"SETID") && c->argc == 5) {
streamID id;
if (!strcmp(c->argv[4]->ptr,"$")) {
id = s->last_id;
} else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) {
return;
}
cg->last_id = id;
addReply(c,shared.ok);
} else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) {
if (cg) {
raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL);
streamFreeCG(cg);
addReply(c,shared.cone);
} else {
addReply(c,shared.czero);
}
} else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) {
/* Delete the consumer and returns the number of pending messages
* that were yet associated with such a consumer. */
long long pending = streamDelConsumer(cg,c->argv[4]->ptr);
addReplyLongLong(c,pending);
server.dirty++;
} else if (!strcasecmp(opt,"HELP")) {
addReplyHelp(c, help);
} else {
addReply(c,shared.syntaxerr);
}
}
| 169,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Commit Message: Fix #8685 - Crash in ELF version parsing
CWE ID: CWE-119 | static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
| 167,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
| 170,220 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len;
size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
&varint_len);
size_t last_len = strlen(last);
size_t prefix_len = last_len - strip_len;
size_t suffix_len = strlen(path_ptr + varint_len);
size_t path_len;
if (varint_len == 0)
return index_error_invalid("incorrect prefix length");
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
Commit Message: index: fix out-of-bounds read with invalid index entry prefix length
The index format in version 4 has prefix-compressed entries, where every
index entry can compress its path by using a path prefix of the previous
entry. Since implmenting support for this index format version in commit
5625d86b9 (index: support index v4, 2016-05-17), though, we do not
correctly verify that the prefix length that we want to reuse is
actually smaller or equal to the amount of characters than the length of
the previous index entry's path. This can lead to a an integer underflow
and subsequently to an out-of-bounds read.
Fix this by verifying that the prefix is actually smaller than the
previous entry's path length.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-190 | static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len, last_len, prefix_len, suffix_len, path_len;
uintmax_t strip_len;
strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);
last_len = strlen(last);
if (varint_len == 0 || last_len < strip_len)
return index_error_invalid("incorrect prefix length");
prefix_len = last_len - strip_len;
suffix_len = strlen(path_ptr + varint_len);
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
| 169,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(readlink)
{
char *link;
int link_len;
char buff[MAXPATHLEN];
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &link, &link_len) == FAILURE) {
return;
}
if (php_check_open_basedir(link TSRMLS_CC)) {
RETURN_FALSE;
}
ret = php_sys_readlink(link, buff, MAXPATHLEN-1);
if (ret == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno));
RETURN_FALSE;
}
/* Append NULL to the end of the string */
buff[ret] = '\0';
RETURN_STRING(buff, 1);
}
Commit Message:
CWE ID: CWE-254 | PHP_FUNCTION(readlink)
{
char *link;
int link_len;
char buff[MAXPATHLEN];
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &link, &link_len) == FAILURE) {
return;
}
if (php_check_open_basedir(link TSRMLS_CC)) {
RETURN_FALSE;
}
ret = php_sys_readlink(link, buff, MAXPATHLEN-1);
if (ret == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno));
RETURN_FALSE;
}
/* Append NULL to the end of the string */
buff[ret] = '\0';
RETURN_STRING(buff, 1);
}
| 165,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t map_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos,
int cap_setid,
struct uid_gid_map *map,
struct uid_gid_map *parent_map)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct uid_gid_map new_map;
unsigned idx;
struct uid_gid_extent *extent = NULL;
unsigned long page = 0;
char *kbuf, *pos, *next_line;
ssize_t ret = -EINVAL;
/*
* The id_map_mutex serializes all writes to any given map.
*
* Any map is only ever written once.
*
* An id map fits within 1 cache line on most architectures.
*
* On read nothing needs to be done unless you are on an
* architecture with a crazy cache coherency model like alpha.
*
* There is a one time data dependency between reading the
* count of the extents and the values of the extents. The
* desired behavior is to see the values of the extents that
* were written before the count of the extents.
*
* To achieve this smp_wmb() is used on guarantee the write
* order and smp_read_barrier_depends() is guaranteed that we
* don't have crazy architectures returning stale data.
*
*/
mutex_lock(&id_map_mutex);
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
goto out;
/* Require the appropriate privilege CAP_SETUID or CAP_SETGID
* over the user namespace in order to set the id mapping.
*/
if (cap_valid(cap_setid) && !ns_capable(ns, cap_setid))
goto out;
/* Get a buffer */
ret = -ENOMEM;
page = __get_free_page(GFP_TEMPORARY);
kbuf = (char *) page;
if (!page)
goto out;
/* Only allow <= page size writes at the beginning of the file */
ret = -EINVAL;
if ((*ppos != 0) || (count >= PAGE_SIZE))
goto out;
/* Slurp in the user data */
ret = -EFAULT;
if (copy_from_user(kbuf, buf, count))
goto out;
kbuf[count] = '\0';
/* Parse the user data */
ret = -EINVAL;
pos = kbuf;
new_map.nr_extents = 0;
for (;pos; pos = next_line) {
extent = &new_map.extent[new_map.nr_extents];
/* Find the end of line and ensure I don't look past it */
next_line = strchr(pos, '\n');
if (next_line) {
*next_line = '\0';
next_line++;
if (*next_line == '\0')
next_line = NULL;
}
pos = skip_spaces(pos);
extent->first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent->lower_first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent->count = simple_strtoul(pos, &pos, 10);
if (*pos && !isspace(*pos))
goto out;
/* Verify there is not trailing junk on the line */
pos = skip_spaces(pos);
if (*pos != '\0')
goto out;
/* Verify we have been given valid starting values */
if ((extent->first == (u32) -1) ||
(extent->lower_first == (u32) -1 ))
goto out;
/* Verify count is not zero and does not cause the extent to wrap */
if ((extent->first + extent->count) <= extent->first)
goto out;
if ((extent->lower_first + extent->count) <= extent->lower_first)
goto out;
/* Do the ranges in extent overlap any previous extents? */
if (mappings_overlap(&new_map, extent))
goto out;
new_map.nr_extents++;
/* Fail if the file contains too many extents */
if ((new_map.nr_extents == UID_GID_MAP_MAX_EXTENTS) &&
(next_line != NULL))
goto out;
}
/* Be very certaint the new map actually exists */
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
/* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(ns, cap_setid, &new_map))
goto out;
/* Map the lower ids from the parent user namespace to the
* kernel global id space.
*/
for (idx = 0; idx < new_map.nr_extents; idx++) {
u32 lower_first;
extent = &new_map.extent[idx];
lower_first = map_id_range_down(parent_map,
extent->lower_first,
extent->count);
/* Fail if we can not map the specified extent to
* the kernel global id space.
*/
if (lower_first == (u32) -1)
goto out;
extent->lower_first = lower_first;
}
/* Install the map */
memcpy(map->extent, new_map.extent,
new_map.nr_extents*sizeof(new_map.extent[0]));
smp_wmb();
map->nr_extents = new_map.nr_extents;
*ppos = count;
ret = count;
out:
mutex_unlock(&id_map_mutex);
if (page)
free_page(page);
return ret;
}
Commit Message: userns: Don't let unprivileged users trick privileged users into setting the id_map
When we require privilege for setting /proc/<pid>/uid_map or
/proc/<pid>/gid_map no longer allow an unprivileged user to
open the file and pass it to a privileged program to write
to the file.
Instead when privilege is required require both the opener and the
writer to have the necessary capabilities.
I have tested this code and verified that setting /proc/<pid>/uid_map
fails when an unprivileged user opens the file and a privielged user
attempts to set the mapping, that unprivileged users can still map
their own id, and that a privileged users can still setup an arbitrary
mapping.
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Andy Lutomirski <[email protected]>
CWE ID: CWE-264 | static ssize_t map_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos,
int cap_setid,
struct uid_gid_map *map,
struct uid_gid_map *parent_map)
{
struct seq_file *seq = file->private_data;
struct user_namespace *ns = seq->private;
struct uid_gid_map new_map;
unsigned idx;
struct uid_gid_extent *extent = NULL;
unsigned long page = 0;
char *kbuf, *pos, *next_line;
ssize_t ret = -EINVAL;
/*
* The id_map_mutex serializes all writes to any given map.
*
* Any map is only ever written once.
*
* An id map fits within 1 cache line on most architectures.
*
* On read nothing needs to be done unless you are on an
* architecture with a crazy cache coherency model like alpha.
*
* There is a one time data dependency between reading the
* count of the extents and the values of the extents. The
* desired behavior is to see the values of the extents that
* were written before the count of the extents.
*
* To achieve this smp_wmb() is used on guarantee the write
* order and smp_read_barrier_depends() is guaranteed that we
* don't have crazy architectures returning stale data.
*
*/
mutex_lock(&id_map_mutex);
ret = -EPERM;
/* Only allow one successful write to the map */
if (map->nr_extents != 0)
goto out;
/* Require the appropriate privilege CAP_SETUID or CAP_SETGID
* over the user namespace in order to set the id mapping.
*/
if (cap_valid(cap_setid) && !ns_capable(ns, cap_setid))
goto out;
/* Get a buffer */
ret = -ENOMEM;
page = __get_free_page(GFP_TEMPORARY);
kbuf = (char *) page;
if (!page)
goto out;
/* Only allow <= page size writes at the beginning of the file */
ret = -EINVAL;
if ((*ppos != 0) || (count >= PAGE_SIZE))
goto out;
/* Slurp in the user data */
ret = -EFAULT;
if (copy_from_user(kbuf, buf, count))
goto out;
kbuf[count] = '\0';
/* Parse the user data */
ret = -EINVAL;
pos = kbuf;
new_map.nr_extents = 0;
for (;pos; pos = next_line) {
extent = &new_map.extent[new_map.nr_extents];
/* Find the end of line and ensure I don't look past it */
next_line = strchr(pos, '\n');
if (next_line) {
*next_line = '\0';
next_line++;
if (*next_line == '\0')
next_line = NULL;
}
pos = skip_spaces(pos);
extent->first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent->lower_first = simple_strtoul(pos, &pos, 10);
if (!isspace(*pos))
goto out;
pos = skip_spaces(pos);
extent->count = simple_strtoul(pos, &pos, 10);
if (*pos && !isspace(*pos))
goto out;
/* Verify there is not trailing junk on the line */
pos = skip_spaces(pos);
if (*pos != '\0')
goto out;
/* Verify we have been given valid starting values */
if ((extent->first == (u32) -1) ||
(extent->lower_first == (u32) -1 ))
goto out;
/* Verify count is not zero and does not cause the extent to wrap */
if ((extent->first + extent->count) <= extent->first)
goto out;
if ((extent->lower_first + extent->count) <= extent->lower_first)
goto out;
/* Do the ranges in extent overlap any previous extents? */
if (mappings_overlap(&new_map, extent))
goto out;
new_map.nr_extents++;
/* Fail if the file contains too many extents */
if ((new_map.nr_extents == UID_GID_MAP_MAX_EXTENTS) &&
(next_line != NULL))
goto out;
}
/* Be very certaint the new map actually exists */
if (new_map.nr_extents == 0)
goto out;
ret = -EPERM;
/* Validate the user is allowed to use user id's mapped to. */
if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
goto out;
/* Map the lower ids from the parent user namespace to the
* kernel global id space.
*/
for (idx = 0; idx < new_map.nr_extents; idx++) {
u32 lower_first;
extent = &new_map.extent[idx];
lower_first = map_id_range_down(parent_map,
extent->lower_first,
extent->count);
/* Fail if we can not map the specified extent to
* the kernel global id space.
*/
if (lower_first == (u32) -1)
goto out;
extent->lower_first = lower_first;
}
/* Install the map */
memcpy(map->extent, new_map.extent,
new_map.nr_extents*sizeof(new_map.extent[0]));
smp_wmb();
map->nr_extents = new_map.nr_extents;
*ppos = count;
ret = count;
out:
mutex_unlock(&id_map_mutex);
if (page)
free_page(page);
return ret;
}
| 166,091 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs_delegation *delegation;
struct nfs4_opendata *opendata;
int delegation_type = 0;
int status;
opendata = nfs4_open_recoverdata_alloc(ctx, state);
if (IS_ERR(opendata))
return PTR_ERR(opendata);
opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS;
opendata->o_arg.fh = NFS_FH(state->inode);
rcu_read_lock();
delegation = rcu_dereference(NFS_I(state->inode)->delegation);
if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)
delegation_type = delegation->type;
rcu_read_unlock();
opendata->o_arg.u.delegation_type = delegation_type;
status = nfs4_open_recover(opendata, state);
nfs4_opendata_put(opendata);
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs_delegation *delegation;
struct nfs4_opendata *opendata;
fmode_t delegation_type = 0;
int status;
opendata = nfs4_open_recoverdata_alloc(ctx, state);
if (IS_ERR(opendata))
return PTR_ERR(opendata);
opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS;
opendata->o_arg.fh = NFS_FH(state->inode);
rcu_read_lock();
delegation = rcu_dereference(NFS_I(state->inode)->delegation);
if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)
delegation_type = delegation->type;
rcu_read_unlock();
opendata->o_arg.u.delegation_type = delegation_type;
status = nfs4_open_recover(opendata, state);
nfs4_opendata_put(opendata);
return status;
}
| 165,685 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE5(add_key, const char __user *, _type,
const char __user *, _description,
const void __user *, _payload,
size_t, plen,
key_serial_t, ringid)
{
key_ref_t keyring_ref, key_ref;
char type[32], *description;
void *payload;
long ret;
ret = -EINVAL;
if (plen > 1024 * 1024 - 1)
goto error;
/* draw all the data into kernel space */
ret = key_get_type_from_user(type, _type, sizeof(type));
if (ret < 0)
goto error;
description = NULL;
if (_description) {
description = strndup_user(_description, KEY_MAX_DESC_SIZE);
if (IS_ERR(description)) {
ret = PTR_ERR(description);
goto error;
}
if (!*description) {
kfree(description);
description = NULL;
} else if ((description[0] == '.') &&
(strncmp(type, "keyring", 7) == 0)) {
ret = -EPERM;
goto error2;
}
}
/* pull the payload in if one was supplied */
payload = NULL;
if (_payload) {
ret = -ENOMEM;
payload = kvmalloc(plen, GFP_KERNEL);
if (!payload)
goto error2;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error3;
}
/* find the target keyring (which must be writable) */
keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
if (IS_ERR(keyring_ref)) {
ret = PTR_ERR(keyring_ref);
goto error3;
}
/* create or update the requested key and add it to the target
* keyring */
key_ref = key_create_or_update(keyring_ref, type, description,
payload, plen, KEY_PERM_UNDEF,
KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key_ref)) {
ret = key_ref_to_ptr(key_ref)->serial;
key_ref_put(key_ref);
}
else {
ret = PTR_ERR(key_ref);
}
key_ref_put(keyring_ref);
error3:
kvfree(payload);
error2:
kfree(description);
error:
return ret;
}
Commit Message: KEYS: fix dereferencing NULL payload with nonzero length
sys_add_key() and the KEYCTL_UPDATE operation of sys_keyctl() allowed a
NULL payload with nonzero length to be passed to the key type's
->preparse(), ->instantiate(), and/or ->update() methods. Various key
types including asymmetric, cifs.idmap, cifs.spnego, and pkcs7_test did
not handle this case, allowing an unprivileged user to trivially cause a
NULL pointer dereference (kernel oops) if one of these key types was
present. Fix it by doing the copy_from_user() when 'plen' is nonzero
rather than when '_payload' is non-NULL, causing the syscall to fail
with EFAULT as expected when an invalid buffer is specified.
Cc: [email protected] # 2.6.10+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-476 | SYSCALL_DEFINE5(add_key, const char __user *, _type,
const char __user *, _description,
const void __user *, _payload,
size_t, plen,
key_serial_t, ringid)
{
key_ref_t keyring_ref, key_ref;
char type[32], *description;
void *payload;
long ret;
ret = -EINVAL;
if (plen > 1024 * 1024 - 1)
goto error;
/* draw all the data into kernel space */
ret = key_get_type_from_user(type, _type, sizeof(type));
if (ret < 0)
goto error;
description = NULL;
if (_description) {
description = strndup_user(_description, KEY_MAX_DESC_SIZE);
if (IS_ERR(description)) {
ret = PTR_ERR(description);
goto error;
}
if (!*description) {
kfree(description);
description = NULL;
} else if ((description[0] == '.') &&
(strncmp(type, "keyring", 7) == 0)) {
ret = -EPERM;
goto error2;
}
}
/* pull the payload in if one was supplied */
payload = NULL;
if (plen) {
ret = -ENOMEM;
payload = kvmalloc(plen, GFP_KERNEL);
if (!payload)
goto error2;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error3;
}
/* find the target keyring (which must be writable) */
keyring_ref = lookup_user_key(ringid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
if (IS_ERR(keyring_ref)) {
ret = PTR_ERR(keyring_ref);
goto error3;
}
/* create or update the requested key and add it to the target
* keyring */
key_ref = key_create_or_update(keyring_ref, type, description,
payload, plen, KEY_PERM_UNDEF,
KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key_ref)) {
ret = key_ref_to_ptr(key_ref)->serial;
key_ref_put(key_ref);
}
else {
ret = PTR_ERR(key_ref);
}
key_ref_put(keyring_ref);
error3:
kvfree(payload);
error2:
kfree(description);
error:
return ret;
}
| 167,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int udhcpc_main(int argc UNUSED_PARAM, char **argv)
{
uint8_t *message;
const char *str_V, *str_h, *str_F, *str_r;
IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";)
IF_FEATURE_UDHCP_PORT(char *str_P;)
void *clientid_mac_ptr;
llist_t *list_O = NULL;
llist_t *list_x = NULL;
int tryagain_timeout = 20;
int discover_timeout = 3;
int discover_retries = 3;
uint32_t server_addr = server_addr; /* for compiler */
uint32_t requested_ip = 0;
uint32_t xid = xid; /* for compiler */
int packet_num;
int timeout; /* must be signed */
unsigned already_waited_sec;
unsigned opt;
IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;)
int retval;
setup_common_bufsiz();
/* Default options */
IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
client_config.interface = "eth0";
client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
str_V = "udhcp "BB_VER;
/* Parse command line */
opt = getopt32long(argv, "^"
/* O,x: list; -T,-t,-A take numeric param */
"CV:H:h:F:i:np:qRr:s:T:+t:+SA:+O:*ox:*fB"
USE_FOR_MMU("b")
IF_FEATURE_UDHCPC_ARPING("a::")
IF_FEATURE_UDHCP_PORT("P:")
"v"
"\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
, udhcpc_longopts
, &str_V, &str_h, &str_h, &str_F
, &client_config.interface, &client_config.pidfile /* i,p */
, &str_r /* r */
, &client_config.script /* s */
, &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
, &list_O
, &list_x
IF_FEATURE_UDHCPC_ARPING(, &str_a)
IF_FEATURE_UDHCP_PORT(, &str_P)
IF_UDHCP_VERBOSE(, &dhcp_verbose)
);
if (opt & (OPT_h|OPT_H)) {
bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
}
if (opt & OPT_F) {
/* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
/* Flag bits: 0000NEOS
* S: 1 = Client requests server to update A RR in DNS as well as PTR
* O: 1 = Server indicates to client that DNS has been updated regardless
* E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
* not "host.domain.com". Format 0 is obsolete.
* N: 1 = Client requests server to not update DNS (S must be 0 then)
* Two [0] bytes which follow are deprecated and must be 0.
*/
client_config.fqdn[OPT_DATA + 0] = 0x1;
/*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
/*client_config.fqdn[OPT_DATA + 2] = 0; */
}
if (opt & OPT_r)
requested_ip = inet_addr(str_r);
#if ENABLE_FEATURE_UDHCP_PORT
if (opt & OPT_P) {
CLIENT_PORT = xatou16(str_P);
SERVER_PORT = CLIENT_PORT - 1;
}
#endif
IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);)
while (list_O) {
char *optstr = llist_pop(&list_O);
unsigned n = bb_strtou(optstr, NULL, 0);
if (errno || n > 254) {
n = udhcp_option_idx(optstr, dhcp_option_strings);
n = dhcp_optflags[n].code;
}
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
if (!(opt & OPT_o)) {
unsigned i, n;
for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
if (dhcp_optflags[i].flags & OPTION_REQ) {
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
}
}
while (list_x) {
char *optstr = xstrdup(llist_pop(&list_x));
udhcp_str2optset(optstr, &client_config.options,
dhcp_optflags, dhcp_option_strings,
/*dhcpv6:*/ 0
);
free(optstr);
}
if (udhcp_read_interface(client_config.interface,
&client_config.ifindex,
NULL,
client_config.client_mac)
) {
return 1;
}
clientid_mac_ptr = NULL;
if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
/* not suppressed and not set, set the default client ID */
client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
}
if (str_V[0] != '\0') {
client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
}
#if !BB_MMU
/* on NOMMU reexec (i.e., background) early */
if (!(opt & OPT_f)) {
bb_daemonize_or_rexec(0 /* flags */, argv);
logmode = LOGMODE_NONE;
}
#endif
if (opt & OPT_S) {
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
/* Make sure fd 0,1,2 are open */
bb_sanitize_stdio();
/* Create pidfile */
write_pidfile(client_config.pidfile);
/* Goes to stdout (unless NOMMU) and possibly syslog */
bb_error_msg("started, v"BB_VER);
/* Set up the signal pipe */
udhcp_sp_setup();
/* We want random_xid to be random... */
srand(monotonic_us());
state = INIT_SELECTING;
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
packet_num = 0;
timeout = 0;
already_waited_sec = 0;
/* Main event loop. select() waits on signal pipe and possibly
* on sockfd.
* "continue" statements in code below jump to the top of the loop.
*/
for (;;) {
int tv;
struct pollfd pfds[2];
struct dhcp_packet packet;
/* silence "uninitialized!" warning */
unsigned timestamp_before_wait = timestamp_before_wait;
/* Was opening raw or udp socket here
* if (listen_mode != LISTEN_NONE && sockfd < 0),
* but on fast network renew responses return faster
* than we open sockets. Thus this code is moved
* to change_listen_mode(). Thus we open listen socket
* BEFORE we send renew request (see "case BOUND:"). */
udhcp_sp_fd_set(pfds, sockfd);
tv = timeout - already_waited_sec;
retval = 0;
/* If we already timed out, fall through with retval = 0, else... */
if (tv > 0) {
log1("waiting %u seconds", tv);
timestamp_before_wait = (unsigned)monotonic_sec();
retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
if (retval < 0) {
/* EINTR? A signal was caught, don't panic */
if (errno == EINTR) {
already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
continue;
}
/* Else: an error occurred, panic! */
bb_perror_msg_and_die("poll");
}
}
/* If timeout dropped to zero, time to become active:
* resend discover/renew/whatever
*/
if (retval == 0) {
/* When running on a bridge, the ifindex may have changed
* (e.g. if member interfaces were added/removed
* or if the status of the bridge changed).
* Refresh ifindex and client_mac:
*/
if (udhcp_read_interface(client_config.interface,
&client_config.ifindex,
NULL,
client_config.client_mac)
) {
goto ret0; /* iface is gone? */
}
if (clientid_mac_ptr)
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
/* We will restart the wait in any case */
already_waited_sec = 0;
switch (state) {
case INIT_SELECTING:
if (!discover_retries || packet_num < discover_retries) {
if (packet_num == 0)
xid = random_xid();
/* broadcast */
send_discover(xid, requested_ip);
timeout = discover_timeout;
packet_num++;
continue;
}
leasefail:
udhcp_run_script(NULL, "leasefail");
#if BB_MMU /* -b is not supported on NOMMU */
if (opt & OPT_b) { /* background if no lease */
bb_error_msg("no lease, forking to background");
client_background();
/* do not background again! */
opt = ((opt & ~OPT_b) | OPT_f);
} else
#endif
if (opt & OPT_n) { /* abort if no lease */
bb_error_msg("no lease, failing");
retval = 1;
goto ret;
}
/* wait before trying again */
timeout = tryagain_timeout;
packet_num = 0;
continue;
case REQUESTING:
if (packet_num < 3) {
/* send broadcast select packet */
send_select(xid, server_addr, requested_ip);
timeout = discover_timeout;
packet_num++;
continue;
}
/* Timed out, go back to init state.
* "discover...select...discover..." loops
* were seen in the wild. Treat them similarly
* to "no response to discover" case */
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
goto leasefail;
case BOUND:
/* 1/2 lease passed, enter renewing state */
state = RENEWING;
client_config.first_secs = 0; /* make secs field count from 0 */
change_listen_mode(LISTEN_KERNEL);
log1("entering renew state");
/* fall right through */
case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
case_RENEW_REQUESTED:
case RENEWING:
if (timeout >= 60) {
/* send an unicast renew request */
/* Sometimes observed to fail (EADDRNOTAVAIL) to bind
* a new UDP socket for sending inside send_renew.
* I hazard to guess existing listening socket
* is somehow conflicting with it, but why is it
* not deterministic then?! Strange.
* Anyway, it does recover by eventually failing through
* into INIT_SELECTING state.
*/
if (send_renew(xid, server_addr, requested_ip) >= 0) {
timeout >>= 1;
continue;
}
/* else: error sending.
* example: ENETUNREACH seen with server
* which gave us bogus server ID 1.1.1.1
* which wasn't reachable (and probably did not exist).
*/
}
/* Timed out or error, enter rebinding state */
log1("entering rebinding state");
state = REBINDING;
/* fall right through */
case REBINDING:
/* Switch to bcast receive */
change_listen_mode(LISTEN_RAW);
/* Lease is *really* about to run out,
* try to find DHCP server using broadcast */
if (timeout > 0) {
/* send a broadcast renew request */
send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
timeout >>= 1;
continue;
}
/* Timed out, enter init state */
bb_error_msg("lease lost, entering init state");
udhcp_run_script(NULL, "deconfig");
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
/*timeout = 0; - already is */
packet_num = 0;
continue;
/* case RELEASED: */
}
/* yah, I know, *you* say it would never happen */
timeout = INT_MAX;
continue; /* back to main loop */
} /* if poll timed out */
/* poll() didn't timeout, something happened */
/* Is it a signal? */
switch (udhcp_sp_read()) {
case SIGUSR1:
client_config.first_secs = 0; /* make secs field count from 0 */
already_waited_sec = 0;
perform_renew();
if (state == RENEW_REQUESTED) {
/* We might be either on the same network
* (in which case renew might work),
* or we might be on a completely different one
* (in which case renew won't ever succeed).
* For the second case, must make sure timeout
* is not too big, or else we can send
* futile renew requests for hours.
*/
if (timeout > 60)
timeout = 60;
goto case_RENEW_REQUESTED;
}
/* Start things over */
packet_num = 0;
/* Kill any timeouts, user wants this to hurry along */
timeout = 0;
continue;
case SIGUSR2:
perform_release(server_addr, requested_ip);
timeout = INT_MAX;
continue;
case SIGTERM:
bb_error_msg("received %s", "SIGTERM");
goto ret0;
}
/* Is it a packet? */
if (!pfds[1].revents)
continue; /* no */
{
int len;
/* A packet is ready, read it */
if (listen_mode == LISTEN_KERNEL)
len = udhcp_recv_kernel_packet(&packet, sockfd);
else
len = udhcp_recv_raw_packet(&packet, sockfd);
if (len == -1) {
/* Error is severe, reopen socket */
bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
sleep(discover_timeout); /* 3 seconds by default */
change_listen_mode(listen_mode); /* just close and reopen */
}
/* If this packet will turn out to be unrelated/bogus,
* we will go back and wait for next one.
* Be sure timeout is properly decreased. */
already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
if (len < 0)
continue;
}
if (packet.xid != xid) {
log1("xid %x (our is %x), ignoring packet",
(unsigned)packet.xid, (unsigned)xid);
continue;
}
/* Ignore packets that aren't for us */
if (packet.hlen != 6
|| memcmp(packet.chaddr, client_config.client_mac, 6) != 0
) {
log1("chaddr does not match, ignoring packet"); // log2?
continue;
}
message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (message == NULL) {
bb_error_msg("no message type option, ignoring packet");
continue;
}
switch (state) {
case INIT_SELECTING:
/* Must be a DHCPOFFER */
if (*message == DHCPOFFER) {
uint8_t *temp;
/* What exactly is server's IP? There are several values.
* Example DHCP offer captured with tchdump:
*
* 10.34.25.254:67 > 10.34.25.202:68 // IP header's src
* BOOTP fields:
* Your-IP 10.34.25.202
* Server-IP 10.34.32.125 // "next server" IP
* Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use)
* DHCP options:
* DHCP-Message Option 53, length 1: Offer
* Server-ID Option 54, length 4: 10.34.255.7 // "server ID"
* Default-Gateway Option 3, length 4: 10.34.25.254 // router
*
* We think that real server IP (one to use in renew/release)
* is one in Server-ID option. But I am not 100% sure.
* IP header's src and Gateway-IP (same in this example)
* might work too.
* "Next server" and router are definitely wrong ones to use, though...
*/
/* We used to ignore pcakets without DHCP_SERVER_ID.
* I've got user reports from people who run "address-less" servers.
* They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all.
* They say ISC DHCP client supports this case.
*/
server_addr = 0;
temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
if (!temp) {
bb_error_msg("no server ID, using 0.0.0.0");
} else {
/* it IS unaligned sometimes, don't "optimize" */
move_from_unaligned32(server_addr, temp);
}
/*xid = packet.xid; - already is */
requested_ip = packet.yiaddr;
/* enter requesting state */
state = REQUESTING;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
}
continue;
case REQUESTING:
case RENEWING:
case RENEW_REQUESTED:
case REBINDING:
if (*message == DHCPACK) {
unsigned start;
uint32_t lease_seconds;
struct in_addr temp_addr;
uint8_t *temp;
temp = udhcp_get_option(&packet, DHCP_LEASE_TIME);
if (!temp) {
bb_error_msg("no lease time with ACK, using 1 hour lease");
lease_seconds = 60 * 60;
} else {
/* it IS unaligned sometimes, don't "optimize" */
move_from_unaligned32(lease_seconds, temp);
lease_seconds = ntohl(lease_seconds);
/* paranoia: must not be too small and not prone to overflows */
/* timeout > 60 - ensures at least one unicast renew attempt */
if (lease_seconds < 2 * 61)
lease_seconds = 2 * 61;
}
#if ENABLE_FEATURE_UDHCPC_ARPING
if (opt & OPT_a) {
/* RFC 2131 3.1 paragraph 5:
* "The client receives the DHCPACK message with configuration
* parameters. The client SHOULD perform a final check on the
* parameters (e.g., ARP for allocated network address), and notes
* the duration of the lease specified in the DHCPACK message. At this
* point, the client is configured. If the client detects that the
* address is already in use (e.g., through the use of ARP),
* the client MUST send a DHCPDECLINE message to the server and restarts
* the configuration process..." */
if (!arpping(packet.yiaddr,
NULL,
(uint32_t) 0,
client_config.client_mac,
client_config.interface,
arpping_ms)
) {
bb_error_msg("offered address is in use "
"(got ARP reply), declining");
send_decline(/*xid,*/ server_addr, packet.yiaddr);
if (state != REQUESTING)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = tryagain_timeout;
packet_num = 0;
already_waited_sec = 0;
continue; /* back to main loop */
}
}
#endif
/* enter bound state */
temp_addr.s_addr = packet.yiaddr;
bb_error_msg("lease of %s obtained, lease time %u",
inet_ntoa(temp_addr), (unsigned)lease_seconds);
requested_ip = packet.yiaddr;
start = monotonic_sec();
udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
already_waited_sec = (unsigned)monotonic_sec() - start;
timeout = lease_seconds / 2;
if ((unsigned)timeout < already_waited_sec) {
/* Something went wrong. Back to discover state */
timeout = already_waited_sec = 0;
}
state = BOUND;
change_listen_mode(LISTEN_NONE);
if (opt & OPT_q) { /* quit after lease */
goto ret0;
}
/* future renew failures should not exit (JM) */
opt &= ~OPT_n;
#if BB_MMU /* NOMMU case backgrounded earlier */
if (!(opt & OPT_f)) {
client_background();
/* do not background again! */
opt = ((opt & ~OPT_b) | OPT_f);
}
#endif
/* make future renew packets use different xid */
/* xid = random_xid(); ...but why bother? */
continue; /* back to main loop */
}
if (*message == DHCPNAK) {
/* If network has more than one DHCP server,
* "wrong" server can reply first, with a NAK.
* Do not interpret it as a NAK from "our" server.
*/
if (server_addr != 0) {
uint32_t svid;
uint8_t *temp;
temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
if (!temp) {
non_matching_svid:
log1("received DHCP NAK with wrong"
" server ID, ignoring packet");
continue;
}
move_from_unaligned32(svid, temp);
if (svid != server_addr)
goto non_matching_svid;
}
/* return to init state */
bb_error_msg("received %s", "DHCP NAK");
udhcp_run_script(&packet, "nak");
if (state != REQUESTING)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
sleep(3); /* avoid excessive network traffic */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
}
continue;
/* case BOUND: - ignore all packets */
/* case RELEASED: - ignore all packets */
}
/* back to main loop */
} /* for (;;) - main loop ends */
ret0:
if (opt & OPT_R) /* release on quit */
perform_release(server_addr, requested_ip);
retval = 0;
ret:
/*if (client_config.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_config.pidfile);
return retval;
}
Commit Message:
CWE ID: CWE-125 | int udhcpc_main(int argc UNUSED_PARAM, char **argv)
{
uint8_t *message;
const char *str_V, *str_h, *str_F, *str_r;
IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";)
IF_FEATURE_UDHCP_PORT(char *str_P;)
void *clientid_mac_ptr;
llist_t *list_O = NULL;
llist_t *list_x = NULL;
int tryagain_timeout = 20;
int discover_timeout = 3;
int discover_retries = 3;
uint32_t server_addr = server_addr; /* for compiler */
uint32_t requested_ip = 0;
uint32_t xid = xid; /* for compiler */
int packet_num;
int timeout; /* must be signed */
unsigned already_waited_sec;
unsigned opt;
IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;)
int retval;
setup_common_bufsiz();
/* Default options */
IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
client_config.interface = "eth0";
client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
str_V = "udhcp "BB_VER;
/* Parse command line */
opt = getopt32long(argv, "^"
/* O,x: list; -T,-t,-A take numeric param */
"CV:H:h:F:i:np:qRr:s:T:+t:+SA:+O:*ox:*fB"
USE_FOR_MMU("b")
IF_FEATURE_UDHCPC_ARPING("a::")
IF_FEATURE_UDHCP_PORT("P:")
"v"
"\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
, udhcpc_longopts
, &str_V, &str_h, &str_h, &str_F
, &client_config.interface, &client_config.pidfile /* i,p */
, &str_r /* r */
, &client_config.script /* s */
, &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
, &list_O
, &list_x
IF_FEATURE_UDHCPC_ARPING(, &str_a)
IF_FEATURE_UDHCP_PORT(, &str_P)
IF_UDHCP_VERBOSE(, &dhcp_verbose)
);
if (opt & (OPT_h|OPT_H)) {
bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
}
if (opt & OPT_F) {
/* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
/* Flag bits: 0000NEOS
* S: 1 = Client requests server to update A RR in DNS as well as PTR
* O: 1 = Server indicates to client that DNS has been updated regardless
* E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
* not "host.domain.com". Format 0 is obsolete.
* N: 1 = Client requests server to not update DNS (S must be 0 then)
* Two [0] bytes which follow are deprecated and must be 0.
*/
client_config.fqdn[OPT_DATA + 0] = 0x1;
/*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
/*client_config.fqdn[OPT_DATA + 2] = 0; */
}
if (opt & OPT_r)
requested_ip = inet_addr(str_r);
#if ENABLE_FEATURE_UDHCP_PORT
if (opt & OPT_P) {
CLIENT_PORT = xatou16(str_P);
SERVER_PORT = CLIENT_PORT - 1;
}
#endif
IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);)
while (list_O) {
char *optstr = llist_pop(&list_O);
unsigned n = bb_strtou(optstr, NULL, 0);
if (errno || n > 254) {
n = udhcp_option_idx(optstr, dhcp_option_strings);
n = dhcp_optflags[n].code;
}
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
if (!(opt & OPT_o)) {
unsigned i, n;
for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
if (dhcp_optflags[i].flags & OPTION_REQ) {
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
}
}
while (list_x) {
char *optstr = xstrdup(llist_pop(&list_x));
udhcp_str2optset(optstr, &client_config.options,
dhcp_optflags, dhcp_option_strings,
/*dhcpv6:*/ 0
);
free(optstr);
}
if (udhcp_read_interface(client_config.interface,
&client_config.ifindex,
NULL,
client_config.client_mac)
) {
return 1;
}
clientid_mac_ptr = NULL;
if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
/* not suppressed and not set, set the default client ID */
client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
}
if (str_V[0] != '\0') {
client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
}
#if !BB_MMU
/* on NOMMU reexec (i.e., background) early */
if (!(opt & OPT_f)) {
bb_daemonize_or_rexec(0 /* flags */, argv);
logmode = LOGMODE_NONE;
}
#endif
if (opt & OPT_S) {
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
/* Make sure fd 0,1,2 are open */
bb_sanitize_stdio();
/* Create pidfile */
write_pidfile(client_config.pidfile);
/* Goes to stdout (unless NOMMU) and possibly syslog */
bb_error_msg("started, v"BB_VER);
/* Set up the signal pipe */
udhcp_sp_setup();
/* We want random_xid to be random... */
srand(monotonic_us());
state = INIT_SELECTING;
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
packet_num = 0;
timeout = 0;
already_waited_sec = 0;
/* Main event loop. select() waits on signal pipe and possibly
* on sockfd.
* "continue" statements in code below jump to the top of the loop.
*/
for (;;) {
int tv;
struct pollfd pfds[2];
struct dhcp_packet packet;
/* silence "uninitialized!" warning */
unsigned timestamp_before_wait = timestamp_before_wait;
/* Was opening raw or udp socket here
* if (listen_mode != LISTEN_NONE && sockfd < 0),
* but on fast network renew responses return faster
* than we open sockets. Thus this code is moved
* to change_listen_mode(). Thus we open listen socket
* BEFORE we send renew request (see "case BOUND:"). */
udhcp_sp_fd_set(pfds, sockfd);
tv = timeout - already_waited_sec;
retval = 0;
/* If we already timed out, fall through with retval = 0, else... */
if (tv > 0) {
log1("waiting %u seconds", tv);
timestamp_before_wait = (unsigned)monotonic_sec();
retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
if (retval < 0) {
/* EINTR? A signal was caught, don't panic */
if (errno == EINTR) {
already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
continue;
}
/* Else: an error occurred, panic! */
bb_perror_msg_and_die("poll");
}
}
/* If timeout dropped to zero, time to become active:
* resend discover/renew/whatever
*/
if (retval == 0) {
/* When running on a bridge, the ifindex may have changed
* (e.g. if member interfaces were added/removed
* or if the status of the bridge changed).
* Refresh ifindex and client_mac:
*/
if (udhcp_read_interface(client_config.interface,
&client_config.ifindex,
NULL,
client_config.client_mac)
) {
goto ret0; /* iface is gone? */
}
if (clientid_mac_ptr)
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
/* We will restart the wait in any case */
already_waited_sec = 0;
switch (state) {
case INIT_SELECTING:
if (!discover_retries || packet_num < discover_retries) {
if (packet_num == 0)
xid = random_xid();
/* broadcast */
send_discover(xid, requested_ip);
timeout = discover_timeout;
packet_num++;
continue;
}
leasefail:
udhcp_run_script(NULL, "leasefail");
#if BB_MMU /* -b is not supported on NOMMU */
if (opt & OPT_b) { /* background if no lease */
bb_error_msg("no lease, forking to background");
client_background();
/* do not background again! */
opt = ((opt & ~OPT_b) | OPT_f);
} else
#endif
if (opt & OPT_n) { /* abort if no lease */
bb_error_msg("no lease, failing");
retval = 1;
goto ret;
}
/* wait before trying again */
timeout = tryagain_timeout;
packet_num = 0;
continue;
case REQUESTING:
if (packet_num < 3) {
/* send broadcast select packet */
send_select(xid, server_addr, requested_ip);
timeout = discover_timeout;
packet_num++;
continue;
}
/* Timed out, go back to init state.
* "discover...select...discover..." loops
* were seen in the wild. Treat them similarly
* to "no response to discover" case */
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
goto leasefail;
case BOUND:
/* 1/2 lease passed, enter renewing state */
state = RENEWING;
client_config.first_secs = 0; /* make secs field count from 0 */
change_listen_mode(LISTEN_KERNEL);
log1("entering renew state");
/* fall right through */
case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
case_RENEW_REQUESTED:
case RENEWING:
if (timeout >= 60) {
/* send an unicast renew request */
/* Sometimes observed to fail (EADDRNOTAVAIL) to bind
* a new UDP socket for sending inside send_renew.
* I hazard to guess existing listening socket
* is somehow conflicting with it, but why is it
* not deterministic then?! Strange.
* Anyway, it does recover by eventually failing through
* into INIT_SELECTING state.
*/
if (send_renew(xid, server_addr, requested_ip) >= 0) {
timeout >>= 1;
continue;
}
/* else: error sending.
* example: ENETUNREACH seen with server
* which gave us bogus server ID 1.1.1.1
* which wasn't reachable (and probably did not exist).
*/
}
/* Timed out or error, enter rebinding state */
log1("entering rebinding state");
state = REBINDING;
/* fall right through */
case REBINDING:
/* Switch to bcast receive */
change_listen_mode(LISTEN_RAW);
/* Lease is *really* about to run out,
* try to find DHCP server using broadcast */
if (timeout > 0) {
/* send a broadcast renew request */
send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
timeout >>= 1;
continue;
}
/* Timed out, enter init state */
bb_error_msg("lease lost, entering init state");
udhcp_run_script(NULL, "deconfig");
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
/*timeout = 0; - already is */
packet_num = 0;
continue;
/* case RELEASED: */
}
/* yah, I know, *you* say it would never happen */
timeout = INT_MAX;
continue; /* back to main loop */
} /* if poll timed out */
/* poll() didn't timeout, something happened */
/* Is it a signal? */
switch (udhcp_sp_read()) {
case SIGUSR1:
client_config.first_secs = 0; /* make secs field count from 0 */
already_waited_sec = 0;
perform_renew();
if (state == RENEW_REQUESTED) {
/* We might be either on the same network
* (in which case renew might work),
* or we might be on a completely different one
* (in which case renew won't ever succeed).
* For the second case, must make sure timeout
* is not too big, or else we can send
* futile renew requests for hours.
*/
if (timeout > 60)
timeout = 60;
goto case_RENEW_REQUESTED;
}
/* Start things over */
packet_num = 0;
/* Kill any timeouts, user wants this to hurry along */
timeout = 0;
continue;
case SIGUSR2:
perform_release(server_addr, requested_ip);
timeout = INT_MAX;
continue;
case SIGTERM:
bb_error_msg("received %s", "SIGTERM");
goto ret0;
}
/* Is it a packet? */
if (!pfds[1].revents)
continue; /* no */
{
int len;
/* A packet is ready, read it */
if (listen_mode == LISTEN_KERNEL)
len = udhcp_recv_kernel_packet(&packet, sockfd);
else
len = udhcp_recv_raw_packet(&packet, sockfd);
if (len == -1) {
/* Error is severe, reopen socket */
bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
sleep(discover_timeout); /* 3 seconds by default */
change_listen_mode(listen_mode); /* just close and reopen */
}
/* If this packet will turn out to be unrelated/bogus,
* we will go back and wait for next one.
* Be sure timeout is properly decreased. */
already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
if (len < 0)
continue;
}
if (packet.xid != xid) {
log1("xid %x (our is %x), ignoring packet",
(unsigned)packet.xid, (unsigned)xid);
continue;
}
/* Ignore packets that aren't for us */
if (packet.hlen != 6
|| memcmp(packet.chaddr, client_config.client_mac, 6) != 0
) {
log1("chaddr does not match, ignoring packet"); // log2?
continue;
}
message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (message == NULL) {
bb_error_msg("no message type option, ignoring packet");
continue;
}
switch (state) {
case INIT_SELECTING:
/* Must be a DHCPOFFER */
if (*message == DHCPOFFER) {
uint8_t *temp;
/* What exactly is server's IP? There are several values.
* Example DHCP offer captured with tchdump:
*
* 10.34.25.254:67 > 10.34.25.202:68 // IP header's src
* BOOTP fields:
* Your-IP 10.34.25.202
* Server-IP 10.34.32.125 // "next server" IP
* Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use)
* DHCP options:
* DHCP-Message Option 53, length 1: Offer
* Server-ID Option 54, length 4: 10.34.255.7 // "server ID"
* Default-Gateway Option 3, length 4: 10.34.25.254 // router
*
* We think that real server IP (one to use in renew/release)
* is one in Server-ID option. But I am not 100% sure.
* IP header's src and Gateway-IP (same in this example)
* might work too.
* "Next server" and router are definitely wrong ones to use, though...
*/
/* We used to ignore pcakets without DHCP_SERVER_ID.
* I've got user reports from people who run "address-less" servers.
* They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all.
* They say ISC DHCP client supports this case.
*/
server_addr = 0;
temp = udhcp_get_option32(&packet, DHCP_SERVER_ID);
if (!temp) {
bb_error_msg("no server ID, using 0.0.0.0");
} else {
/* it IS unaligned sometimes, don't "optimize" */
move_from_unaligned32(server_addr, temp);
}
/*xid = packet.xid; - already is */
requested_ip = packet.yiaddr;
/* enter requesting state */
state = REQUESTING;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
}
continue;
case REQUESTING:
case RENEWING:
case RENEW_REQUESTED:
case REBINDING:
if (*message == DHCPACK) {
unsigned start;
uint32_t lease_seconds;
struct in_addr temp_addr;
uint8_t *temp;
temp = udhcp_get_option32(&packet, DHCP_LEASE_TIME);
if (!temp) {
bb_error_msg("no lease time with ACK, using 1 hour lease");
lease_seconds = 60 * 60;
} else {
/* it IS unaligned sometimes, don't "optimize" */
move_from_unaligned32(lease_seconds, temp);
lease_seconds = ntohl(lease_seconds);
/* paranoia: must not be too small and not prone to overflows */
/* timeout > 60 - ensures at least one unicast renew attempt */
if (lease_seconds < 2 * 61)
lease_seconds = 2 * 61;
}
#if ENABLE_FEATURE_UDHCPC_ARPING
if (opt & OPT_a) {
/* RFC 2131 3.1 paragraph 5:
* "The client receives the DHCPACK message with configuration
* parameters. The client SHOULD perform a final check on the
* parameters (e.g., ARP for allocated network address), and notes
* the duration of the lease specified in the DHCPACK message. At this
* point, the client is configured. If the client detects that the
* address is already in use (e.g., through the use of ARP),
* the client MUST send a DHCPDECLINE message to the server and restarts
* the configuration process..." */
if (!arpping(packet.yiaddr,
NULL,
(uint32_t) 0,
client_config.client_mac,
client_config.interface,
arpping_ms)
) {
bb_error_msg("offered address is in use "
"(got ARP reply), declining");
send_decline(/*xid,*/ server_addr, packet.yiaddr);
if (state != REQUESTING)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = tryagain_timeout;
packet_num = 0;
already_waited_sec = 0;
continue; /* back to main loop */
}
}
#endif
/* enter bound state */
temp_addr.s_addr = packet.yiaddr;
bb_error_msg("lease of %s obtained, lease time %u",
inet_ntoa(temp_addr), (unsigned)lease_seconds);
requested_ip = packet.yiaddr;
start = monotonic_sec();
udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
already_waited_sec = (unsigned)monotonic_sec() - start;
timeout = lease_seconds / 2;
if ((unsigned)timeout < already_waited_sec) {
/* Something went wrong. Back to discover state */
timeout = already_waited_sec = 0;
}
state = BOUND;
change_listen_mode(LISTEN_NONE);
if (opt & OPT_q) { /* quit after lease */
goto ret0;
}
/* future renew failures should not exit (JM) */
opt &= ~OPT_n;
#if BB_MMU /* NOMMU case backgrounded earlier */
if (!(opt & OPT_f)) {
client_background();
/* do not background again! */
opt = ((opt & ~OPT_b) | OPT_f);
}
#endif
/* make future renew packets use different xid */
/* xid = random_xid(); ...but why bother? */
continue; /* back to main loop */
}
if (*message == DHCPNAK) {
/* If network has more than one DHCP server,
* "wrong" server can reply first, with a NAK.
* Do not interpret it as a NAK from "our" server.
*/
if (server_addr != 0) {
uint32_t svid;
uint8_t *temp;
temp = udhcp_get_option32(&packet, DHCP_SERVER_ID);
if (!temp) {
non_matching_svid:
log1("received DHCP NAK with wrong"
" server ID, ignoring packet");
continue;
}
move_from_unaligned32(svid, temp);
if (svid != server_addr)
goto non_matching_svid;
}
/* return to init state */
bb_error_msg("received %s", "DHCP NAK");
udhcp_run_script(&packet, "nak");
if (state != REQUESTING)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
sleep(3); /* avoid excessive network traffic */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
}
continue;
/* case BOUND: - ignore all packets */
/* case RELEASED: - ignore all packets */
}
/* back to main loop */
} /* for (;;) - main loop ends */
ret0:
if (opt & OPT_R) /* release on quit */
perform_release(server_addr, requested_ip);
retval = 0;
ret:
/*if (client_config.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_config.pidfile);
return retval;
}
| 165,224 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval,
int __user *optlen)
{
int olr;
int val;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
switch (optname) {
case MRT6_VERSION:
val = 0x0305;
break;
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
val = mrt->mroute_do_pim;
break;
#endif
case MRT6_ASSERT:
val = mrt->mroute_do_assert;
break;
default:
return -ENOPROTOOPT;
}
if (get_user(olr, optlen))
return -EFAULT;
olr = min_t(int, olr, sizeof(int));
if (olr < 0)
return -EINVAL;
if (put_user(olr, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, olr))
return -EFAULT;
return 0;
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval,
int __user *optlen)
{
int olr;
int val;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
if (sk->sk_type != SOCK_RAW ||
inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
switch (optname) {
case MRT6_VERSION:
val = 0x0305;
break;
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
val = mrt->mroute_do_pim;
break;
#endif
case MRT6_ASSERT:
val = mrt->mroute_do_assert;
break;
default:
return -ENOPROTOOPT;
}
if (get_user(olr, optlen))
return -EFAULT;
olr = min_t(int, olr, sizeof(int));
if (olr < 0)
return -EINVAL;
if (put_user(olr, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, olr))
return -EFAULT;
return 0;
}
| 169,857 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: id3_skip (SF_PRIVATE * psf)
{ unsigned char buf [10] ;
memset (buf, 0, sizeof (buf)) ;
psf_binheader_readf (psf, "pb", 0, buf, 10) ;
if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')
{ int offset = buf [6] & 0x7f ;
offset = (offset << 7) | (buf [7] & 0x7f) ;
offset = (offset << 7) | (buf [8] & 0x7f) ;
offset = (offset << 7) | (buf [9] & 0x7f) ;
psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ;
/* Never want to jump backwards in a file. */
if (offset < 0)
return 0 ;
/* Calculate new file offset and position ourselves there. */
psf->fileoffset += offset + 10 ;
psf_binheader_readf (psf, "p", psf->fileoffset) ;
return 1 ;
} ;
return 0 ;
} /* id3_skip */
Commit Message: src/id3.c : Improve error handling
CWE ID: CWE-119 | id3_skip (SF_PRIVATE * psf)
{ unsigned char buf [10] ;
memset (buf, 0, sizeof (buf)) ;
psf_binheader_readf (psf, "pb", 0, buf, 10) ;
if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3')
{ int offset = buf [6] & 0x7f ;
offset = (offset << 7) | (buf [7] & 0x7f) ;
offset = (offset << 7) | (buf [8] & 0x7f) ;
offset = (offset << 7) | (buf [9] & 0x7f) ;
psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ;
/* Never want to jump backwards in a file. */
if (offset < 0)
return 0 ;
/* Calculate new file offset and position ourselves there. */
psf->fileoffset += offset + 10 ;
if (psf->fileoffset < psf->filelength)
{ psf_binheader_readf (psf, "p", psf->fileoffset) ;
return 1 ;
} ;
} ;
return 0 ;
} /* id3_skip */
| 168,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pkinit_server_return_padata(krb5_context context,
krb5_pa_data * padata,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_kdc_rep * reply,
krb5_keyblock * encrypting_key,
krb5_pa_data ** send_pa,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_modreq modreq)
{
krb5_error_code retval = 0;
krb5_data scratch = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
int i = 0;
unsigned char *subjectPublicKey = NULL;
unsigned char *dh_pubkey = NULL, *server_key = NULL;
unsigned int subjectPublicKey_len = 0;
unsigned int server_key_len = 0, dh_pubkey_len = 0;
krb5_kdc_dh_key_info dhkey_info;
krb5_data *encoded_dhkey_info = NULL;
krb5_pa_pk_as_rep *rep = NULL;
krb5_pa_pk_as_rep_draft9 *rep9 = NULL;
krb5_data *out_data = NULL;
krb5_octet_data secret;
krb5_enctype enctype = -1;
krb5_reply_key_pack *key_pack = NULL;
krb5_reply_key_pack_draft9 *key_pack9 = NULL;
krb5_data *encoded_key_pack = NULL;
pkinit_kdc_context plgctx;
pkinit_kdc_req_context reqctx;
int fixed_keypack = 0;
*send_pa = NULL;
if (padata->pa_type == KRB5_PADATA_PKINIT_KX) {
return return_pkinit_kx(context, request, reply,
encrypting_key, send_pa);
}
if (padata->length <= 0 || padata->contents == NULL)
return 0;
if (modreq == NULL) {
pkiDebug("missing request context \n");
return EINVAL;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
pkiDebug("Unable to locate correct realm context\n");
return ENOENT;
}
pkiDebug("pkinit_return_padata: entered!\n");
reqctx = (pkinit_kdc_req_context)modreq;
if (encrypting_key->contents) {
free(encrypting_key->contents);
encrypting_key->length = 0;
encrypting_key->contents = NULL;
}
for(i = 0; i < request->nktypes; i++) {
enctype = request->ktype[i];
if (!krb5_c_valid_enctype(enctype))
continue;
else {
pkiDebug("KDC picked etype = %d\n", enctype);
break;
}
}
if (i == request->nktypes) {
retval = KRB5KDC_ERR_ETYPE_NOSUPP;
goto cleanup;
}
switch((int)reqctx->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
init_krb5_pa_pk_as_rep(&rep);
if (rep == NULL) {
retval = ENOMEM;
goto cleanup;
}
/* let's assume it's RSA. we'll reset it to DH if needed */
rep->choice = choice_pa_pk_as_rep_encKeyPack;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
init_krb5_pa_pk_as_rep_draft9(&rep9);
if (rep9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
break;
default:
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->clientPublicValue != NULL) {
subjectPublicKey =
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.length;
rep->choice = choice_pa_pk_as_rep_dhInfo;
} else if (reqctx->rcv_auth_pack9 != NULL &&
reqctx->rcv_auth_pack9->clientPublicValue != NULL) {
subjectPublicKey =
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.length;
rep9->choice = choice_pa_pk_as_rep_draft9_dhSignedData;
}
/* if this DH, then process finish computing DH key */
if (rep != NULL && (rep->choice == choice_pa_pk_as_rep_dhInfo ||
rep->choice == choice_pa_pk_as_rep_draft9_dhSignedData)) {
pkiDebug("received DH key delivery AS REQ\n");
retval = server_process_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, subjectPublicKey,
subjectPublicKey_len, &dh_pubkey, &dh_pubkey_len,
&server_key, &server_key_len);
if (retval) {
pkiDebug("failed to process/create dh paramters\n");
goto cleanup;
}
}
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/*
* This is DH, so don't generate the key until after we
* encode the reply, because the encoded reply is needed
* to generate the key in some cases.
*/
dhkey_info.subjectPublicKey.length = dh_pubkey_len;
dhkey_info.subjectPublicKey.data = dh_pubkey;
dhkey_info.nonce = request->nonce;
dhkey_info.dhKeyExpiration = 0;
retval = k5int_encode_krb5_kdc_dh_key_info(&dhkey_info,
&encoded_dhkey_info);
if (retval) {
pkiDebug("encode_krb5_kdc_dh_key_info failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
"/tmp/kdc_dh_key_info");
#endif
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_SERVER, 1,
(unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
&rep->u.dh_Info.dhSignedData.data,
&rep->u.dh_Info.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, 1,
(unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
&rep9->u.dhSignedData.data,
&rep9->u.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
}
} else {
pkiDebug("received RSA key delivery AS REQ\n");
retval = krb5_c_make_random_key(context, enctype, encrypting_key);
if (retval) {
pkiDebug("unable to make a session key\n");
goto cleanup;
}
/* check if PA_TYPE of 132 is present which means the client is
* requesting that a checksum is send back instead of the nonce
*/
for (i = 0; request->padata[i] != NULL; i++) {
pkiDebug("%s: Checking pa_type 0x%08x\n",
__FUNCTION__, request->padata[i]->pa_type);
if (request->padata[i]->pa_type == 132)
fixed_keypack = 1;
}
pkiDebug("%s: return checksum instead of nonce = %d\n",
__FUNCTION__, fixed_keypack);
/* if this is an RFC reply or draft9 client requested a checksum
* in the reply instead of the nonce, create an RFC-style keypack
*/
if ((int)padata->pa_type == KRB5_PADATA_PK_AS_REQ || fixed_keypack) {
init_krb5_reply_key_pack(&key_pack);
if (key_pack == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = krb5_c_make_checksum(context, 0,
encrypting_key, KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM,
req_pkt, &key_pack->asChecksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size = %d\n", req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("checksum size = %d\n", key_pack->asChecksum.length);
print_buffer(key_pack->asChecksum.contents,
key_pack->asChecksum.length);
pkiDebug("encrypting key (%d)\n", encrypting_key->length);
print_buffer(encrypting_key->contents, encrypting_key->length);
#endif
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack->replyKey);
retval = k5int_encode_krb5_reply_key_pack(key_pack,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
rep->choice = choice_pa_pk_as_rep_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
&rep->u.encKeyPack.data, &rep->u.encKeyPack.length);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
/* if the request is from the broken draft9 client that
* expects back a nonce, create it now
*/
if (!fixed_keypack) {
init_krb5_reply_key_pack_draft9(&key_pack9);
if (key_pack9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
key_pack9->nonce = reqctx->rcv_auth_pack9->pkAuthenticator.nonce;
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack9->replyKey);
retval = k5int_encode_krb5_reply_key_pack_draft9(key_pack9,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
&rep9->u.encKeyPack.data, &rep9->u.encKeyPack.length);
break;
}
if (retval) {
pkiDebug("failed to create pkcs7 enveloped data: %s\n",
error_message(retval));
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
"/tmp/kdc_key_pack");
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
print_buffer_bin(rep->u.encKeyPack.data,
rep->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
print_buffer_bin(rep9->u.encKeyPack.data,
rep9->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
}
#endif
}
if ((rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo) &&
((reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL))) {
/* If using the alg-agility KDF, put the algorithm in the reply
* before encoding it.
*/
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL) {
retval = pkinit_pick_kdf_alg(context, reqctx->rcv_auth_pack->supportedKDFs,
&(rep->u.dh_Info.kdfID));
if (retval) {
pkiDebug("pkinit_pick_kdf_alg failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_encode_krb5_pa_pk_as_rep(rep, &out_data);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_encode_krb5_pa_pk_as_rep_draft9(rep9, &out_data);
break;
}
if (retval) {
pkiDebug("failed to encode AS_REP\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
if (out_data != NULL)
print_buffer_bin((unsigned char *)out_data->data, out_data->length,
"/tmp/kdc_as_rep");
#endif
/* If this is DH, we haven't computed the key yet, so do it now. */
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/* If mutually supported KDFs were found, use the alg agility KDF */
if (rep->u.dh_Info.kdfID) {
secret.data = server_key;
secret.length = server_key_len;
retval = pkinit_alg_agility_kdf(context, &secret,
rep->u.dh_Info.kdfID,
request->client, request->server,
enctype,
(krb5_octet_data *)req_pkt,
(krb5_octet_data *)out_data,
encrypting_key);
if (retval) {
pkiDebug("pkinit_alg_agility_kdf failed: %s\n",
error_message(retval));
goto cleanup;
}
/* Otherwise, use the older octetstring2key() function */
} else {
retval = pkinit_octetstring2key(context, enctype, server_key,
server_key_len, encrypting_key);
if (retval) {
pkiDebug("pkinit_octetstring2key failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
*send_pa = malloc(sizeof(krb5_pa_data));
if (*send_pa == NULL) {
retval = ENOMEM;
free(out_data->data);
free(out_data);
out_data = NULL;
goto cleanup;
}
(*send_pa)->magic = KV5M_PA_DATA;
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP;
break;
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP_OLD;
break;
}
(*send_pa)->length = out_data->length;
(*send_pa)->contents = (krb5_octet *) out_data->data;
cleanup:
pkinit_fini_kdc_req_context(context, reqctx);
free(scratch.data);
free(out_data);
if (encoded_dhkey_info != NULL)
krb5_free_data(context, encoded_dhkey_info);
if (encoded_key_pack != NULL)
krb5_free_data(context, encoded_key_pack);
free(dh_pubkey);
free(server_key);
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free_krb5_pa_pk_as_rep(&rep);
free_krb5_reply_key_pack(&key_pack);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
free_krb5_pa_pk_as_rep_draft9(&rep9);
if (!fixed_keypack)
free_krb5_reply_key_pack_draft9(&key_pack9);
else
free_krb5_reply_key_pack(&key_pack);
break;
}
if (retval)
pkiDebug("pkinit_verify_padata failure");
return retval;
}
Commit Message: PKINIT (draft9) null ptr deref [CVE-2012-1016]
Don't check for an agility KDF identifier in the non-draft9 reply
structure when we're building a draft9 reply, because it'll be NULL.
The KDC plugin for PKINIT can dereference a null pointer when handling
a draft9 request, leading to a crash of the KDC process. An attacker
would need to have a valid PKINIT certificate, or an unauthenticated
attacker could execute the attack if anonymous PKINIT is enabled.
CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:P/RL:O/RC:C
[[email protected]: reformat comment and edit log message]
(back ported from commit cd5ff932c9d1439c961b0cf9ccff979356686aff)
ticket: 7527 (new)
version_fixed: 1.10.4
status: resolved
CWE ID: | pkinit_server_return_padata(krb5_context context,
krb5_pa_data * padata,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_kdc_rep * reply,
krb5_keyblock * encrypting_key,
krb5_pa_data ** send_pa,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_modreq modreq)
{
krb5_error_code retval = 0;
krb5_data scratch = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
int i = 0;
unsigned char *subjectPublicKey = NULL;
unsigned char *dh_pubkey = NULL, *server_key = NULL;
unsigned int subjectPublicKey_len = 0;
unsigned int server_key_len = 0, dh_pubkey_len = 0;
krb5_kdc_dh_key_info dhkey_info;
krb5_data *encoded_dhkey_info = NULL;
krb5_pa_pk_as_rep *rep = NULL;
krb5_pa_pk_as_rep_draft9 *rep9 = NULL;
krb5_data *out_data = NULL;
krb5_octet_data secret;
krb5_enctype enctype = -1;
krb5_reply_key_pack *key_pack = NULL;
krb5_reply_key_pack_draft9 *key_pack9 = NULL;
krb5_data *encoded_key_pack = NULL;
pkinit_kdc_context plgctx;
pkinit_kdc_req_context reqctx;
int fixed_keypack = 0;
*send_pa = NULL;
if (padata->pa_type == KRB5_PADATA_PKINIT_KX) {
return return_pkinit_kx(context, request, reply,
encrypting_key, send_pa);
}
if (padata->length <= 0 || padata->contents == NULL)
return 0;
if (modreq == NULL) {
pkiDebug("missing request context \n");
return EINVAL;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
pkiDebug("Unable to locate correct realm context\n");
return ENOENT;
}
pkiDebug("pkinit_return_padata: entered!\n");
reqctx = (pkinit_kdc_req_context)modreq;
if (encrypting_key->contents) {
free(encrypting_key->contents);
encrypting_key->length = 0;
encrypting_key->contents = NULL;
}
for(i = 0; i < request->nktypes; i++) {
enctype = request->ktype[i];
if (!krb5_c_valid_enctype(enctype))
continue;
else {
pkiDebug("KDC picked etype = %d\n", enctype);
break;
}
}
if (i == request->nktypes) {
retval = KRB5KDC_ERR_ETYPE_NOSUPP;
goto cleanup;
}
switch((int)reqctx->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
init_krb5_pa_pk_as_rep(&rep);
if (rep == NULL) {
retval = ENOMEM;
goto cleanup;
}
/* let's assume it's RSA. we'll reset it to DH if needed */
rep->choice = choice_pa_pk_as_rep_encKeyPack;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
init_krb5_pa_pk_as_rep_draft9(&rep9);
if (rep9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
break;
default:
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->clientPublicValue != NULL) {
subjectPublicKey =
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.length;
rep->choice = choice_pa_pk_as_rep_dhInfo;
} else if (reqctx->rcv_auth_pack9 != NULL &&
reqctx->rcv_auth_pack9->clientPublicValue != NULL) {
subjectPublicKey =
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.length;
rep9->choice = choice_pa_pk_as_rep_draft9_dhSignedData;
}
/* if this DH, then process finish computing DH key */
if (rep != NULL && (rep->choice == choice_pa_pk_as_rep_dhInfo ||
rep->choice == choice_pa_pk_as_rep_draft9_dhSignedData)) {
pkiDebug("received DH key delivery AS REQ\n");
retval = server_process_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, subjectPublicKey,
subjectPublicKey_len, &dh_pubkey, &dh_pubkey_len,
&server_key, &server_key_len);
if (retval) {
pkiDebug("failed to process/create dh paramters\n");
goto cleanup;
}
}
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/*
* This is DH, so don't generate the key until after we
* encode the reply, because the encoded reply is needed
* to generate the key in some cases.
*/
dhkey_info.subjectPublicKey.length = dh_pubkey_len;
dhkey_info.subjectPublicKey.data = dh_pubkey;
dhkey_info.nonce = request->nonce;
dhkey_info.dhKeyExpiration = 0;
retval = k5int_encode_krb5_kdc_dh_key_info(&dhkey_info,
&encoded_dhkey_info);
if (retval) {
pkiDebug("encode_krb5_kdc_dh_key_info failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
"/tmp/kdc_dh_key_info");
#endif
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_SERVER, 1,
(unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
&rep->u.dh_Info.dhSignedData.data,
&rep->u.dh_Info.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, 1,
(unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
&rep9->u.dhSignedData.data,
&rep9->u.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
}
} else {
pkiDebug("received RSA key delivery AS REQ\n");
retval = krb5_c_make_random_key(context, enctype, encrypting_key);
if (retval) {
pkiDebug("unable to make a session key\n");
goto cleanup;
}
/* check if PA_TYPE of 132 is present which means the client is
* requesting that a checksum is send back instead of the nonce
*/
for (i = 0; request->padata[i] != NULL; i++) {
pkiDebug("%s: Checking pa_type 0x%08x\n",
__FUNCTION__, request->padata[i]->pa_type);
if (request->padata[i]->pa_type == 132)
fixed_keypack = 1;
}
pkiDebug("%s: return checksum instead of nonce = %d\n",
__FUNCTION__, fixed_keypack);
/* if this is an RFC reply or draft9 client requested a checksum
* in the reply instead of the nonce, create an RFC-style keypack
*/
if ((int)padata->pa_type == KRB5_PADATA_PK_AS_REQ || fixed_keypack) {
init_krb5_reply_key_pack(&key_pack);
if (key_pack == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = krb5_c_make_checksum(context, 0,
encrypting_key, KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM,
req_pkt, &key_pack->asChecksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size = %d\n", req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("checksum size = %d\n", key_pack->asChecksum.length);
print_buffer(key_pack->asChecksum.contents,
key_pack->asChecksum.length);
pkiDebug("encrypting key (%d)\n", encrypting_key->length);
print_buffer(encrypting_key->contents, encrypting_key->length);
#endif
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack->replyKey);
retval = k5int_encode_krb5_reply_key_pack(key_pack,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
rep->choice = choice_pa_pk_as_rep_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
&rep->u.encKeyPack.data, &rep->u.encKeyPack.length);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
/* if the request is from the broken draft9 client that
* expects back a nonce, create it now
*/
if (!fixed_keypack) {
init_krb5_reply_key_pack_draft9(&key_pack9);
if (key_pack9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
key_pack9->nonce = reqctx->rcv_auth_pack9->pkAuthenticator.nonce;
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack9->replyKey);
retval = k5int_encode_krb5_reply_key_pack_draft9(key_pack9,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
&rep9->u.encKeyPack.data, &rep9->u.encKeyPack.length);
break;
}
if (retval) {
pkiDebug("failed to create pkcs7 enveloped data: %s\n",
error_message(retval));
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
"/tmp/kdc_key_pack");
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
print_buffer_bin(rep->u.encKeyPack.data,
rep->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
print_buffer_bin(rep9->u.encKeyPack.data,
rep9->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
}
#endif
}
if ((rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo) &&
((reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL))) {
/* If using the alg-agility KDF, put the algorithm in the reply
* before encoding it.
*/
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL) {
retval = pkinit_pick_kdf_alg(context, reqctx->rcv_auth_pack->supportedKDFs,
&(rep->u.dh_Info.kdfID));
if (retval) {
pkiDebug("pkinit_pick_kdf_alg failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_encode_krb5_pa_pk_as_rep(rep, &out_data);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_encode_krb5_pa_pk_as_rep_draft9(rep9, &out_data);
break;
}
if (retval) {
pkiDebug("failed to encode AS_REP\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
if (out_data != NULL)
print_buffer_bin((unsigned char *)out_data->data, out_data->length,
"/tmp/kdc_as_rep");
#endif
/* If this is DH, we haven't computed the key yet, so do it now. */
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/* If we're not doing draft 9, and mutually supported KDFs were found,
* use the algorithm agility KDF. */
if (rep != NULL && rep->u.dh_Info.kdfID) {
secret.data = (char *)server_key;
secret.length = server_key_len;
retval = pkinit_alg_agility_kdf(context, &secret,
rep->u.dh_Info.kdfID,
request->client, request->server,
enctype,
(krb5_octet_data *)req_pkt,
(krb5_octet_data *)out_data,
encrypting_key);
if (retval) {
pkiDebug("pkinit_alg_agility_kdf failed: %s\n",
error_message(retval));
goto cleanup;
}
/* Otherwise, use the older octetstring2key() function */
} else {
retval = pkinit_octetstring2key(context, enctype, server_key,
server_key_len, encrypting_key);
if (retval) {
pkiDebug("pkinit_octetstring2key failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
*send_pa = malloc(sizeof(krb5_pa_data));
if (*send_pa == NULL) {
retval = ENOMEM;
free(out_data->data);
free(out_data);
out_data = NULL;
goto cleanup;
}
(*send_pa)->magic = KV5M_PA_DATA;
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP;
break;
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP_OLD;
break;
}
(*send_pa)->length = out_data->length;
(*send_pa)->contents = (krb5_octet *) out_data->data;
cleanup:
pkinit_fini_kdc_req_context(context, reqctx);
free(scratch.data);
free(out_data);
if (encoded_dhkey_info != NULL)
krb5_free_data(context, encoded_dhkey_info);
if (encoded_key_pack != NULL)
krb5_free_data(context, encoded_key_pack);
free(dh_pubkey);
free(server_key);
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free_krb5_pa_pk_as_rep(&rep);
free_krb5_reply_key_pack(&key_pack);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
free_krb5_pa_pk_as_rep_draft9(&rep9);
if (!fixed_keypack)
free_krb5_reply_key_pack_draft9(&key_pack9);
else
free_krb5_reply_key_pack(&key_pack);
break;
}
if (retval)
pkiDebug("pkinit_verify_padata failure");
return retval;
}
| 166,206 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/573
CWE ID: CWE-772 | static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
{
if (colormap != (unsigned char *) NULL)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
if (pixels != (unsigned char *) NULL)
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Write colormap to file.
*/
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) &
0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) &
0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| 167,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate());
}
Commit Message: binding: Removes unused code in templates/attributes.cpp.
Faking {{cpp_class}} and {{c8_class}} doesn't make sense.
Probably it made sense before the introduction of virtual
ScriptWrappable::wrap().
Checking the existence of window->document() doesn't seem
making sense to me, and CQ tests seem passing without the
check.
BUG=
Review-Url: https://codereview.chromium.org/2268433002
Cr-Commit-Position: refs/heads/master@{#413375}
CWE ID: CWE-189 | static void reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate());
}
| 171,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAMR::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (amrParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
if (!isConfigured()) {
amrParams->nBitRate = 0;
amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused;
} else {
amrParams->nBitRate = 0;
amrParams->eAMRBandMode =
mMode == MODE_NARROW
? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->nChannels = 1;
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->nSamplingRate =
(mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAMR::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (!isValidOMXParam(amrParams)) {
return OMX_ErrorBadParameter;
}
if (amrParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
if (!isConfigured()) {
amrParams->nBitRate = 0;
amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused;
} else {
amrParams->nBitRate = 0;
amrParams->eAMRBandMode =
mMode == MODE_NARROW
? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->nChannels = 1;
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->nSamplingRate =
(mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,192 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_pslice(dec_struct_t *ps_dec, UWORD16 u2_first_mb_in_slice)
{
dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps;
dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice;
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD8 u1_mbaff = ps_dec->ps_cur_slice->u1_mbaff_frame_flag; //ps_dec->ps_cur_sps->u1_mb_aff_flag;
UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag;
UWORD32 u4_temp;
WORD32 i_temp;
WORD32 ret;
/*--------------------------------------------------------------------*/
/* Read remaining contents of the slice header */
/*--------------------------------------------------------------------*/
{
WORD8 *pi1_buf;
WORD16 *pi2_mv = ps_dec->s_default_mv_pred.i2_mv;
WORD32 *pi4_mv = (WORD32*)pi2_mv;
WORD16 *pi16_refFrame;
pi1_buf = ps_dec->s_default_mv_pred.i1_ref_frame;
pi16_refFrame = (WORD16*)pi1_buf;
*pi4_mv = 0;
*(pi4_mv + 1) = 0;
*pi16_refFrame = OUT_OF_RANGE_REF;
ps_dec->s_default_mv_pred.u1_col_ref_pic_idx = (UWORD8)-1;
ps_dec->s_default_mv_pred.u1_pic_type = (UWORD8)-1;
}
ps_cur_slice->u1_num_ref_idx_active_override_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: num_ref_idx_override_flag",
ps_cur_slice->u1_num_ref_idx_active_override_flag);
u4_temp = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[0];
if(ps_cur_slice->u1_num_ref_idx_active_override_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf) + 1;
}
{
UWORD8 u1_max_ref_idx = MAX_FRAMES << u1_field_pic_flag;
if(u4_temp > u1_max_ref_idx)
{
return ERROR_NUM_REF;
}
ps_cur_slice->u1_num_ref_idx_lx_active[0] = u4_temp;
COPYTHECONTEXT("SH: num_ref_idx_l0_active_minus1",
ps_cur_slice->u1_num_ref_idx_lx_active[0] - 1);
}
{
UWORD8 uc_refIdxReFlagL0 = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l0",uc_refIdxReFlagL0);
/* Initialize the Reference list once in Picture if the slice type */
/* of first slice is between 5 to 9 defined in table 7.3 of standard */
/* If picture contains both P & B slices then Initialize the Reference*/
/* List only when it switches from P to B and B to P */
{
UWORD8 init_idx_flg = (ps_dec->u1_pr_sl_type
!= ps_dec->ps_cur_slice->u1_slice_type);
if(ps_dec->u1_first_pb_nal_in_pic
|| (init_idx_flg & !ps_dec->u1_sl_typ_5_9)
|| ps_dec->u1_num_ref_idx_lx_active_prev
!= ps_cur_slice->u1_num_ref_idx_lx_active[0])
{
ih264d_init_ref_idx_lx_p(ps_dec);
}
if(ps_dec->u1_first_pb_nal_in_pic & ps_dec->u1_sl_typ_5_9)
ps_dec->u1_first_pb_nal_in_pic = 0;
}
/* Store the value for future slices in the same picture */
ps_dec->u1_num_ref_idx_lx_active_prev =
ps_cur_slice->u1_num_ref_idx_lx_active[0];
/* Modified temporarily */
if(uc_refIdxReFlagL0)
{
WORD8 ret;
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0];
ret = ih264d_ref_idx_reordering(ps_dec, 0);
if(ret == -1)
return ERROR_REFIDX_ORDER_T;
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0];
}
else
ps_dec->ps_ref_pic_buf_lx[0] =
ps_dec->ps_dpb_mgr->ps_init_dpb[0];
}
/* Create refIdx to POC mapping */
{
void **pui_map_ref_idx_to_poc_lx0, **pui_map_ref_idx_to_poc_lx1;
WORD8 idx;
struct pic_buffer_t *ps_pic;
pui_map_ref_idx_to_poc_lx0 = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L0;
pui_map_ref_idx_to_poc_lx0[0] = 0; //For ref_idx = -1
pui_map_ref_idx_to_poc_lx0++;
for(idx = 0; idx < ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx];
pui_map_ref_idx_to_poc_lx0[idx] = (ps_pic->pu1_buf1);
}
/* Bug Fix Deblocking */
pui_map_ref_idx_to_poc_lx1 = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L1;
pui_map_ref_idx_to_poc_lx1[0] = 0;
if(u1_mbaff)
{
void **ppv_map_ref_idx_to_poc_lx_t, **ppv_map_ref_idx_to_poc_lx_b;
void **ppv_map_ref_idx_to_poc_lx_t1, **ppv_map_ref_idx_to_poc_lx_b1;
ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc
+ TOP_LIST_FLD_L0;
ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc
+ BOT_LIST_FLD_L0;
ppv_map_ref_idx_to_poc_lx_t[0] = 0; // For ref_idx = -1
ppv_map_ref_idx_to_poc_lx_t++;
ppv_map_ref_idx_to_poc_lx_b[0] = 0; // For ref_idx = -1
ppv_map_ref_idx_to_poc_lx_b++;
idx = 0;
for(idx = 0; idx < ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx];
ppv_map_ref_idx_to_poc_lx_t[0] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[1] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[0] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t[1] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t += 2;
ppv_map_ref_idx_to_poc_lx_b += 2;
}
ppv_map_ref_idx_to_poc_lx_t1 = ps_dec->ppv_map_ref_idx_to_poc
+ TOP_LIST_FLD_L1;
ppv_map_ref_idx_to_poc_lx_t1[0] = 0;
ppv_map_ref_idx_to_poc_lx_b1 = ps_dec->ppv_map_ref_idx_to_poc
+ BOT_LIST_FLD_L1;
ppv_map_ref_idx_to_poc_lx_b1[0] = 0;
}
if(ps_dec->u4_num_cores >= 3)
{
WORD32 num_entries;
WORD32 size;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
memcpy((void *)ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc,
ps_dec->ppv_map_ref_idx_to_poc,
size);
}
}
if(ps_pps->u1_wted_pred_flag)
{
ret = ih264d_parse_pred_weight_table(ps_cur_slice, ps_bitstrm);
if(ret != OK)
return ret;
ih264d_form_pred_weight_matrix(ps_dec);
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
}
else
{
ps_dec->ps_cur_slice->u2_log2Y_crwd = 0;
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
}
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd =
ps_dec->ps_cur_slice->u2_log2Y_crwd;
if(u1_mbaff && (u1_field_pic_flag == 0))
{
ih264d_convert_frm_mbaff_list(ps_dec);
}
/* G050 */
if(ps_cur_slice->u1_nal_ref_idc != 0)
{
if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read)
ps_dec->u4_bitoffset = ih264d_read_mmco_commands(ps_dec);
else
ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset;
}
/* G050 */
if(ps_pps->u1_entropy_coding_mode == CABAC)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_CABAC_INIT_IDC)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_cur_slice->u1_cabac_init_idc = u4_temp;
COPYTHECONTEXT("SH: cabac_init_idc",ps_cur_slice->u1_cabac_init_idc);
}
/* Read slice_qp_delta */
i_temp = ps_pps->u1_pic_init_qp
+ ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if((i_temp < 0) || (i_temp > 51))
{
return ERROR_INV_RANGE_QP_T;
}
ps_cur_slice->u1_slice_qp = i_temp;
COPYTHECONTEXT("SH: slice_qp_delta",
(WORD8)(ps_cur_slice->u1_slice_qp - ps_pps->u1_pic_init_qp));
if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED)
{
return ERROR_INV_SLICE_HDR_T;
}
COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp);
ps_cur_slice->u1_disable_dblk_filter_idc = u4_temp;
if(u4_temp != 1)
{
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_cur_slice->i1_slice_alpha_c0_offset = i_temp;
COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2",
ps_cur_slice->i1_slice_alpha_c0_offset >> 1);
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_cur_slice->i1_slice_beta_offset = i_temp;
COPYTHECONTEXT("SH: slice_beta_offset_div2",
ps_cur_slice->i1_slice_beta_offset >> 1);
}
else
{
ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_cur_slice->i1_slice_beta_offset = 0;
}
}
else
{
ps_cur_slice->u1_disable_dblk_filter_idc = 0;
ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_cur_slice->i1_slice_beta_offset = 0;
}
ps_dec->u1_slice_header_done = 2;
if(ps_pps->u1_entropy_coding_mode)
{
SWITCHOFFTRACE; SWITCHONTRACECABAC;
ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cabac;
ps_dec->pf_parse_inter_mb = ih264d_parse_pmb_cabac;
ih264d_init_cabac_contexts(P_SLICE, ps_dec);
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff;
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff;
}
else
{
SWITCHONTRACE; SWITCHOFFTRACECABAC;
ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cavlc;
ps_dec->pf_parse_inter_mb = ih264d_parse_pmb_cavlc;
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff;
}
ps_dec->u1_B = 0;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb;
ret = ps_dec->pf_parse_inter_slice(ps_dec, ps_cur_slice, u2_first_mb_in_slice);
if(ret != OK)
return ret;
return OK;
}
Commit Message: Return error when there are more mmco params than allocated size
Bug: 25818142
Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d
CWE ID: CWE-119 | WORD32 ih264d_parse_pslice(dec_struct_t *ps_dec, UWORD16 u2_first_mb_in_slice)
{
dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps;
dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice;
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD8 u1_mbaff = ps_dec->ps_cur_slice->u1_mbaff_frame_flag; //ps_dec->ps_cur_sps->u1_mb_aff_flag;
UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag;
UWORD32 u4_temp;
WORD32 i_temp;
WORD32 ret;
/*--------------------------------------------------------------------*/
/* Read remaining contents of the slice header */
/*--------------------------------------------------------------------*/
{
WORD8 *pi1_buf;
WORD16 *pi2_mv = ps_dec->s_default_mv_pred.i2_mv;
WORD32 *pi4_mv = (WORD32*)pi2_mv;
WORD16 *pi16_refFrame;
pi1_buf = ps_dec->s_default_mv_pred.i1_ref_frame;
pi16_refFrame = (WORD16*)pi1_buf;
*pi4_mv = 0;
*(pi4_mv + 1) = 0;
*pi16_refFrame = OUT_OF_RANGE_REF;
ps_dec->s_default_mv_pred.u1_col_ref_pic_idx = (UWORD8)-1;
ps_dec->s_default_mv_pred.u1_pic_type = (UWORD8)-1;
}
ps_cur_slice->u1_num_ref_idx_active_override_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: num_ref_idx_override_flag",
ps_cur_slice->u1_num_ref_idx_active_override_flag);
u4_temp = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[0];
if(ps_cur_slice->u1_num_ref_idx_active_override_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf) + 1;
}
{
UWORD8 u1_max_ref_idx = MAX_FRAMES << u1_field_pic_flag;
if(u4_temp > u1_max_ref_idx)
{
return ERROR_NUM_REF;
}
ps_cur_slice->u1_num_ref_idx_lx_active[0] = u4_temp;
COPYTHECONTEXT("SH: num_ref_idx_l0_active_minus1",
ps_cur_slice->u1_num_ref_idx_lx_active[0] - 1);
}
{
UWORD8 uc_refIdxReFlagL0 = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l0",uc_refIdxReFlagL0);
/* Initialize the Reference list once in Picture if the slice type */
/* of first slice is between 5 to 9 defined in table 7.3 of standard */
/* If picture contains both P & B slices then Initialize the Reference*/
/* List only when it switches from P to B and B to P */
{
UWORD8 init_idx_flg = (ps_dec->u1_pr_sl_type
!= ps_dec->ps_cur_slice->u1_slice_type);
if(ps_dec->u1_first_pb_nal_in_pic
|| (init_idx_flg & !ps_dec->u1_sl_typ_5_9)
|| ps_dec->u1_num_ref_idx_lx_active_prev
!= ps_cur_slice->u1_num_ref_idx_lx_active[0])
{
ih264d_init_ref_idx_lx_p(ps_dec);
}
if(ps_dec->u1_first_pb_nal_in_pic & ps_dec->u1_sl_typ_5_9)
ps_dec->u1_first_pb_nal_in_pic = 0;
}
/* Store the value for future slices in the same picture */
ps_dec->u1_num_ref_idx_lx_active_prev =
ps_cur_slice->u1_num_ref_idx_lx_active[0];
/* Modified temporarily */
if(uc_refIdxReFlagL0)
{
WORD8 ret;
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0];
ret = ih264d_ref_idx_reordering(ps_dec, 0);
if(ret == -1)
return ERROR_REFIDX_ORDER_T;
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0];
}
else
ps_dec->ps_ref_pic_buf_lx[0] =
ps_dec->ps_dpb_mgr->ps_init_dpb[0];
}
/* Create refIdx to POC mapping */
{
void **pui_map_ref_idx_to_poc_lx0, **pui_map_ref_idx_to_poc_lx1;
WORD8 idx;
struct pic_buffer_t *ps_pic;
pui_map_ref_idx_to_poc_lx0 = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L0;
pui_map_ref_idx_to_poc_lx0[0] = 0; //For ref_idx = -1
pui_map_ref_idx_to_poc_lx0++;
for(idx = 0; idx < ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx];
pui_map_ref_idx_to_poc_lx0[idx] = (ps_pic->pu1_buf1);
}
/* Bug Fix Deblocking */
pui_map_ref_idx_to_poc_lx1 = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L1;
pui_map_ref_idx_to_poc_lx1[0] = 0;
if(u1_mbaff)
{
void **ppv_map_ref_idx_to_poc_lx_t, **ppv_map_ref_idx_to_poc_lx_b;
void **ppv_map_ref_idx_to_poc_lx_t1, **ppv_map_ref_idx_to_poc_lx_b1;
ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc
+ TOP_LIST_FLD_L0;
ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc
+ BOT_LIST_FLD_L0;
ppv_map_ref_idx_to_poc_lx_t[0] = 0; // For ref_idx = -1
ppv_map_ref_idx_to_poc_lx_t++;
ppv_map_ref_idx_to_poc_lx_b[0] = 0; // For ref_idx = -1
ppv_map_ref_idx_to_poc_lx_b++;
idx = 0;
for(idx = 0; idx < ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx];
ppv_map_ref_idx_to_poc_lx_t[0] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[1] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[0] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t[1] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t += 2;
ppv_map_ref_idx_to_poc_lx_b += 2;
}
ppv_map_ref_idx_to_poc_lx_t1 = ps_dec->ppv_map_ref_idx_to_poc
+ TOP_LIST_FLD_L1;
ppv_map_ref_idx_to_poc_lx_t1[0] = 0;
ppv_map_ref_idx_to_poc_lx_b1 = ps_dec->ppv_map_ref_idx_to_poc
+ BOT_LIST_FLD_L1;
ppv_map_ref_idx_to_poc_lx_b1[0] = 0;
}
if(ps_dec->u4_num_cores >= 3)
{
WORD32 num_entries;
WORD32 size;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
memcpy((void *)ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc,
ps_dec->ppv_map_ref_idx_to_poc,
size);
}
}
if(ps_pps->u1_wted_pred_flag)
{
ret = ih264d_parse_pred_weight_table(ps_cur_slice, ps_bitstrm);
if(ret != OK)
return ret;
ih264d_form_pred_weight_matrix(ps_dec);
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
}
else
{
ps_dec->ps_cur_slice->u2_log2Y_crwd = 0;
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
}
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd =
ps_dec->ps_cur_slice->u2_log2Y_crwd;
if(u1_mbaff && (u1_field_pic_flag == 0))
{
ih264d_convert_frm_mbaff_list(ps_dec);
}
/* G050 */
if(ps_cur_slice->u1_nal_ref_idc != 0)
{
if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read)
{
i_temp = ih264d_read_mmco_commands(ps_dec);
if (i_temp < 0)
{
return ERROR_DBP_MANAGER_T;
}
ps_dec->u4_bitoffset = i_temp;
}
else
ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset;
}
/* G050 */
if(ps_pps->u1_entropy_coding_mode == CABAC)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_CABAC_INIT_IDC)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_cur_slice->u1_cabac_init_idc = u4_temp;
COPYTHECONTEXT("SH: cabac_init_idc",ps_cur_slice->u1_cabac_init_idc);
}
/* Read slice_qp_delta */
i_temp = ps_pps->u1_pic_init_qp
+ ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if((i_temp < 0) || (i_temp > 51))
{
return ERROR_INV_RANGE_QP_T;
}
ps_cur_slice->u1_slice_qp = i_temp;
COPYTHECONTEXT("SH: slice_qp_delta",
(WORD8)(ps_cur_slice->u1_slice_qp - ps_pps->u1_pic_init_qp));
if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED)
{
return ERROR_INV_SLICE_HDR_T;
}
COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp);
ps_cur_slice->u1_disable_dblk_filter_idc = u4_temp;
if(u4_temp != 1)
{
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_cur_slice->i1_slice_alpha_c0_offset = i_temp;
COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2",
ps_cur_slice->i1_slice_alpha_c0_offset >> 1);
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_cur_slice->i1_slice_beta_offset = i_temp;
COPYTHECONTEXT("SH: slice_beta_offset_div2",
ps_cur_slice->i1_slice_beta_offset >> 1);
}
else
{
ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_cur_slice->i1_slice_beta_offset = 0;
}
}
else
{
ps_cur_slice->u1_disable_dblk_filter_idc = 0;
ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_cur_slice->i1_slice_beta_offset = 0;
}
ps_dec->u1_slice_header_done = 2;
if(ps_pps->u1_entropy_coding_mode)
{
SWITCHOFFTRACE; SWITCHONTRACECABAC;
ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cabac;
ps_dec->pf_parse_inter_mb = ih264d_parse_pmb_cabac;
ih264d_init_cabac_contexts(P_SLICE, ps_dec);
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff;
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff;
}
else
{
SWITCHONTRACE; SWITCHOFFTRACECABAC;
ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cavlc;
ps_dec->pf_parse_inter_mb = ih264d_parse_pmb_cavlc;
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff;
}
ps_dec->u1_B = 0;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb;
ret = ps_dec->pf_parse_inter_slice(ps_dec, ps_cur_slice, u2_first_mb_in_slice);
if(ret != OK)
return ret;
return OK;
}
| 173,910 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LocalFileSystem::resolveURLInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
const KURL& fileSystemURL,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
fileSystem()->resolveURL(fileSystemURL, callbacks->release());
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void LocalFileSystem::resolveURLInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
const KURL& fileSystemURL,
CallbackWrapper* callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
fileSystem()->resolveURL(fileSystemURL, callbacks->release());
}
| 171,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: Fix several ineffective integer overflow checks
Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added
several integer overflow checks. Unfortunately, those checks fail to take into
account integer promotion rules and are thus themselves subject to an integer
overflow. Cast the sizeof() operator to a uint64_t to force promotion while
multiplying.
Bug: 20139950
(cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32)
Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b
CWE ID: CWE-189 | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * (uint64_t)sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
| 173,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter,
param_type* r) {
const char *data;
int data_size = 0;
bool result = m->ReadData(iter, &data, &data_size);
if (result && data_size == sizeof(LOGFONT)) {
memcpy(r, data, sizeof(LOGFONT));
} else {
result = false;
NOTREACHED();
}
return result;
}
Commit Message: Verify lfFaceName is NUL terminated in IPC deserializer.
BUG=162066
Review URL: https://chromiumcodereview.appspot.com/11416115
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168937 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter,
param_type* r) {
const char *data;
int data_size = 0;
if (m->ReadData(iter, &data, &data_size) && data_size == sizeof(LOGFONT)) {
const LOGFONT *font = reinterpret_cast<LOGFONT*>(const_cast<char*>(data));
if (_tcsnlen(font->lfFaceName, LF_FACESIZE) < LF_FACESIZE) {
memcpy(r, data, sizeof(LOGFONT));
return true;
}
}
NOTREACHED();
return false;
}
| 171,588 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: FromMojom(media::mojom::VideoCaptureError input,
media::VideoCaptureError* output) {
switch (input) {
case media::mojom::VideoCaptureError::kNone:
*output = media::VideoCaptureError::kNone;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested:
*output = media::VideoCaptureError::
kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureControllerIsAlreadyInErrorState:
*output = media::VideoCaptureError::
kVideoCaptureControllerIsAlreadyInErrorState;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureManagerDeviceConnectionLost:
*output =
media::VideoCaptureError::kVideoCaptureManagerDeviceConnectionLost;
return true;
case media::mojom::VideoCaptureError::
kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError:
*output = media::VideoCaptureError::
kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError;
return true;
case media::mojom::VideoCaptureError::
kFrameSinkVideoCaptureDeviceEncounteredFatalError:
*output = media::VideoCaptureError::
kFrameSinkVideoCaptureDeviceEncounteredFatalError;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile:
*output = media::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile;
return true;
case media::mojom::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice:
*output = media::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kV4L2FailedToFindASupportedCameraFormat:
*output =
media::VideoCaptureError::kV4L2FailedToFindASupportedCameraFormat;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat:
*output = media::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat;
return true;
case media::mojom::VideoCaptureError::kV4L2UnsupportedPixelFormat:
*output = media::VideoCaptureError::kV4L2UnsupportedPixelFormat;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToSetCameraFramerate:
*output = media::VideoCaptureError::kV4L2FailedToSetCameraFramerate;
return true;
case media::mojom::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers:
*output = media::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers;
return true;
case media::mojom::VideoCaptureError::kV4L2AllocateBufferFailed:
*output = media::VideoCaptureError::kV4L2AllocateBufferFailed;
return true;
case media::mojom::VideoCaptureError::kV4L2VidiocStreamonFailed:
*output = media::VideoCaptureError::kV4L2VidiocStreamonFailed;
return true;
case media::mojom::VideoCaptureError::kV4L2VidiocStreamoffFailed:
*output = media::VideoCaptureError::kV4L2VidiocStreamoffFailed;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0:
*output = media::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0;
return true;
case media::mojom::VideoCaptureError::kV4L2PollFailed:
*output = media::VideoCaptureError::kV4L2PollFailed;
return true;
case media::mojom::VideoCaptureError::
kV4L2MultipleContinuousTimeoutsWhileReadPolling:
*output = media::VideoCaptureError::
kV4L2MultipleContinuousTimeoutsWhileReadPolling;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer:
*output = media::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer:
*output = media::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer;
return true;
case media::mojom::VideoCaptureError::
kSingleClientVideoCaptureHostLostConnectionToDevice:
*output = media::VideoCaptureError::
kSingleClientVideoCaptureHostLostConnectionToDevice;
return true;
case media::mojom::VideoCaptureError::
kSingleClientVideoCaptureDeviceLaunchAborted:
*output = media::VideoCaptureError::
kSingleClientVideoCaptureDeviceLaunchAborted;
return true;
case media::mojom::VideoCaptureError::
kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed:
*output = media::VideoCaptureError::
kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed;
return true;
case media::mojom::VideoCaptureError::
kFileVideoCaptureDeviceCouldNotOpenVideoFile:
*output = media::VideoCaptureError::
kFileVideoCaptureDeviceCouldNotOpenVideoFile;
return true;
case media::mojom::VideoCaptureError::
kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate:
*output = media::VideoCaptureError::
kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate;
return true;
case media::mojom::VideoCaptureError::
kErrorFakeDeviceIntentionallyEmittingErrorEvent:
*output = media::VideoCaptureError::
kErrorFakeDeviceIntentionallyEmittingErrorEvent;
return true;
case media::mojom::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16:
*output = media::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16;
return true;
case media::mojom::VideoCaptureError::
kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType:
*output = media::VideoCaptureError::
kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound:
*output = media::VideoCaptureError::
kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound;
return true;
case media::mojom::VideoCaptureError::
kInProcessDeviceLauncherFailedToCreateDeviceInstance:
*output = media::VideoCaptureError::
kInProcessDeviceLauncherFailedToCreateDeviceInstance;
return true;
case media::mojom::VideoCaptureError::
kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart:
*output = media::VideoCaptureError::
kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart;
return true;
case media::mojom::VideoCaptureError::
kServiceDeviceLauncherServiceRespondedWithDeviceNotFound:
*output = media::VideoCaptureError::
kServiceDeviceLauncherServiceRespondedWithDeviceNotFound;
return true;
case media::mojom::VideoCaptureError::
kServiceDeviceLauncherConnectionLostWhileWaitingForCallback:
*output = media::VideoCaptureError::
kServiceDeviceLauncherConnectionLostWhileWaitingForCallback;
return true;
case media::mojom::VideoCaptureError::kIntentionalErrorRaisedByUnitTest:
*output = media::VideoCaptureError::kIntentionalErrorRaisedByUnitTest;
return true;
case media::mojom::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread:
*output = media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateMojoConnectionError:
*output =
media::VideoCaptureError::kCrosHalV3DeviceDelegateMojoConnectionError;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetCameraInfo:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetCameraInfo;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateMissingSensorOrientationInfo:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateMissingSensorOrientationInfo;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToOpenCameraDevice:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToOpenCameraDevice;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToConfigureStreams:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToConfigureStreams;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerHalRequestedTooManyBuffers:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerHalRequestedTooManyBuffers;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerUnsupportedVideoPixelFormat:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerUnsupportedVideoPixelFormat;
return true;
case media::mojom::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd:
*output = media::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToRegisterBuffer:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToRegisterBuffer;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerProcessCaptureRequestFailed:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerProcessCaptureRequestFailed;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerInvalidPendingResultId:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerInvalidPendingResultId;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedInvalidShutterTime:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedInvalidShutterTime;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFatalDeviceError:
*output =
media::VideoCaptureError::kCrosHalV3BufferManagerFatalDeviceError;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerInvalidJpegBlob:
*output =
media::VideoCaptureError::kCrosHalV3BufferManagerInvalidJpegBlob;
return true;
case media::mojom::VideoCaptureError::kAndroidFailedToAllocate:
*output = media::VideoCaptureError::kAndroidFailedToAllocate;
return true;
case media::mojom::VideoCaptureError::kAndroidFailedToStartCapture:
*output = media::VideoCaptureError::kAndroidFailedToStartCapture;
return true;
case media::mojom::VideoCaptureError::kAndroidFailedToStopCapture:
*output = media::VideoCaptureError::kAndroidFailedToStopCapture;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi1CameraErrorCallbackReceived:
*output =
media::VideoCaptureError::kAndroidApi1CameraErrorCallbackReceived;
return true;
case media::mojom::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived:
*output = media::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi2CaptureSessionConfigureFailed:
*output =
media::VideoCaptureError::kAndroidApi2CaptureSessionConfigureFailed;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi2ImageReaderUnexpectedImageFormat:
*output = media::VideoCaptureError::
kAndroidApi2ImageReaderUnexpectedImageFormat;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi2ImageReaderSizeDidNotMatchImageSize:
*output = media::VideoCaptureError::
kAndroidApi2ImageReaderSizeDidNotMatchImageSize;
return true;
case media::mojom::VideoCaptureError::kAndroidApi2ErrorRestartingPreview:
*output = media::VideoCaptureError::kAndroidApi2ErrorRestartingPreview;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureUnsupportedFormat:
*output =
media::VideoCaptureError::kAndroidScreenCaptureUnsupportedFormat;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureFailedToStartCaptureMachine:
*output = media::VideoCaptureError::
kAndroidScreenCaptureFailedToStartCaptureMachine;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureTheUserDeniedScreenCapture:
*output = media::VideoCaptureError::
kAndroidScreenCaptureTheUserDeniedScreenCapture;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureFailedToStartScreenCapture:
*output = media::VideoCaptureError::
kAndroidScreenCaptureFailedToStartScreenCapture;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowCantGetCaptureFormatSettings:
*output =
media::VideoCaptureError::kWinDirectShowCantGetCaptureFormatSettings;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToGetNumberOfCapabilities:
*output = media::VideoCaptureError::
kWinDirectShowFailedToGetNumberOfCapabilities;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToGetCaptureDeviceCapabilities:
*output = media::VideoCaptureError::
kWinDirectShowFailedToGetCaptureDeviceCapabilities;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToSetCaptureDeviceOutputFormat:
*output = media::VideoCaptureError::
kWinDirectShowFailedToSetCaptureDeviceOutputFormat;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToConnectTheCaptureGraph:
*output = media::VideoCaptureError::
kWinDirectShowFailedToConnectTheCaptureGraph;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToPauseTheCaptureDevice:
*output =
media::VideoCaptureError::kWinDirectShowFailedToPauseTheCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToStartTheCaptureDevice:
*output =
media::VideoCaptureError::kWinDirectShowFailedToStartTheCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToStopTheCaptureGraph:
*output =
media::VideoCaptureError::kWinDirectShowFailedToStopTheCaptureGraph;
return true;
case media::mojom::VideoCaptureError::kWinMediaFoundationEngineIsNull:
*output = media::VideoCaptureError::kWinMediaFoundationEngineIsNull;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationEngineGetSourceFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationEngineGetSourceFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationFillPhotoCapabilitiesFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationFillPhotoCapabilitiesFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationFillVideoCapabilitiesFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationFillVideoCapabilitiesFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationNoVideoCapabilityFound:
*output =
media::VideoCaptureError::kWinMediaFoundationNoVideoCapabilityFound;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationGetAvailableDeviceMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationGetAvailableDeviceMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSetCurrentDeviceMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSetCurrentDeviceMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationEngineGetSinkFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationEngineGetSinkFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkRemoveAllStreamsFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSinkRemoveAllStreamsFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationCreateSinkVideoMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationCreateSinkVideoMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationConvertToVideoSinkMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationConvertToVideoSinkMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkAddStreamFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationSinkAddStreamFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkSetSampleCallbackFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSinkSetSampleCallbackFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationEngineStartPreviewFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationEngineStartPreviewFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationGetMediaEventStatusFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationGetMediaEventStatusFailed;
return true;
case media::mojom::VideoCaptureError::kMacSetCaptureDeviceFailed:
*output = media::VideoCaptureError::kMacSetCaptureDeviceFailed;
return true;
case media::mojom::VideoCaptureError::kMacCouldNotStartCaptureDevice:
*output = media::VideoCaptureError::kMacCouldNotStartCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kMacReceivedFrameWithUnexpectedResolution:
*output =
media::VideoCaptureError::kMacReceivedFrameWithUnexpectedResolution;
return true;
case media::mojom::VideoCaptureError::kMacUpdateCaptureResolutionFailed:
*output = media::VideoCaptureError::kMacUpdateCaptureResolutionFailed;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkDeviceIdNotFoundInTheSystem:
*output =
media::VideoCaptureError::kMacDeckLinkDeviceIdNotFoundInTheSystem;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkErrorQueryingInputInterface:
*output =
media::VideoCaptureError::kMacDeckLinkErrorQueryingInputInterface;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkErrorCreatingDisplayModeIterator:
*output = media::VideoCaptureError::
kMacDeckLinkErrorCreatingDisplayModeIterator;
return true;
case media::mojom::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode:
*output = media::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkCouldNotSelectTheVideoFormatWeLike:
*output = media::VideoCaptureError::
kMacDeckLinkCouldNotSelectTheVideoFormatWeLike;
return true;
case media::mojom::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing:
*output = media::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing;
return true;
case media::mojom::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat:
*output = media::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat;
return true;
case media::mojom::VideoCaptureError::
kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification:
*output = media::VideoCaptureError::
kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification;
return true;
case media::mojom::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera:
*output = media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera;
return true;
case media::mojom::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush:
*output = media::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush;
return true;
}
NOTREACHED();
return false;
}
Commit Message: Revert "Enable camera blob stream when needed"
This reverts commit 10f4b93635e12f9fa0cba1641a10938ca38ed448.
Reason for revert:
Findit (https://goo.gl/kROfz5) identified CL at revision 601492 as the
culprit for failures in the build cycles as shown on:
https://findit-for-me.appspot.com/waterfall/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyRAsSDVdmU3VzcGVjdGVkQ0wiMWNocm9taXVtLzEwZjRiOTM2MzVlMTJmOWZhMGNiYTE2NDFhMTA5MzhjYTM4ZWQ0NDgM
Sample Failed Build: https://ci.chromium.org/buildbot/chromium.memory/Linux%20ChromiumOS%20MSan%20Tests/9190
Sample Failed Step: capture_unittests
Original change's description:
> Enable camera blob stream when needed
>
> Since blob stream needs higher resolution, it causes higher cpu loading
> to require higher resolution and resize to smaller resolution.
> In hangout app, we don't need blob stream. Enabling blob stream when
> needed can save a lot of cpu usage.
>
> BUG=b:114676133
> TEST=manually test in apprtc and CCA. make sure picture taking still
> works in CCA.
>
> Change-Id: I9144461bc76627903d0b3b359ce9cf962ff3628c
> Reviewed-on: https://chromium-review.googlesource.com/c/1261242
> Commit-Queue: Heng-ruey Hsu <[email protected]>
> Reviewed-by: Ricky Liang <[email protected]>
> Reviewed-by: Xiaohan Wang <[email protected]>
> Reviewed-by: Robert Sesek <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#601492}
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
BUG=b:114676133
Change-Id: If173ffe9259f7eca849b184806bd56e2a9fbaac4
Reviewed-on: https://chromium-review.googlesource.com/c/1292256
Cr-Commit-Position: refs/heads/master@{#601538}
CWE ID: CWE-19 | FromMojom(media::mojom::VideoCaptureError input,
media::VideoCaptureError* output) {
switch (input) {
case media::mojom::VideoCaptureError::kNone:
*output = media::VideoCaptureError::kNone;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested:
*output = media::VideoCaptureError::
kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureControllerIsAlreadyInErrorState:
*output = media::VideoCaptureError::
kVideoCaptureControllerIsAlreadyInErrorState;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureManagerDeviceConnectionLost:
*output =
media::VideoCaptureError::kVideoCaptureManagerDeviceConnectionLost;
return true;
case media::mojom::VideoCaptureError::
kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError:
*output = media::VideoCaptureError::
kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError;
return true;
case media::mojom::VideoCaptureError::
kFrameSinkVideoCaptureDeviceEncounteredFatalError:
*output = media::VideoCaptureError::
kFrameSinkVideoCaptureDeviceEncounteredFatalError;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile:
*output = media::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile;
return true;
case media::mojom::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice:
*output = media::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kV4L2FailedToFindASupportedCameraFormat:
*output =
media::VideoCaptureError::kV4L2FailedToFindASupportedCameraFormat;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat:
*output = media::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat;
return true;
case media::mojom::VideoCaptureError::kV4L2UnsupportedPixelFormat:
*output = media::VideoCaptureError::kV4L2UnsupportedPixelFormat;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToSetCameraFramerate:
*output = media::VideoCaptureError::kV4L2FailedToSetCameraFramerate;
return true;
case media::mojom::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers:
*output = media::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers;
return true;
case media::mojom::VideoCaptureError::kV4L2AllocateBufferFailed:
*output = media::VideoCaptureError::kV4L2AllocateBufferFailed;
return true;
case media::mojom::VideoCaptureError::kV4L2VidiocStreamonFailed:
*output = media::VideoCaptureError::kV4L2VidiocStreamonFailed;
return true;
case media::mojom::VideoCaptureError::kV4L2VidiocStreamoffFailed:
*output = media::VideoCaptureError::kV4L2VidiocStreamoffFailed;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0:
*output = media::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0;
return true;
case media::mojom::VideoCaptureError::kV4L2PollFailed:
*output = media::VideoCaptureError::kV4L2PollFailed;
return true;
case media::mojom::VideoCaptureError::
kV4L2MultipleContinuousTimeoutsWhileReadPolling:
*output = media::VideoCaptureError::
kV4L2MultipleContinuousTimeoutsWhileReadPolling;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer:
*output = media::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer;
return true;
case media::mojom::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer:
*output = media::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer;
return true;
case media::mojom::VideoCaptureError::
kSingleClientVideoCaptureHostLostConnectionToDevice:
*output = media::VideoCaptureError::
kSingleClientVideoCaptureHostLostConnectionToDevice;
return true;
case media::mojom::VideoCaptureError::
kSingleClientVideoCaptureDeviceLaunchAborted:
*output = media::VideoCaptureError::
kSingleClientVideoCaptureDeviceLaunchAborted;
return true;
case media::mojom::VideoCaptureError::
kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed:
*output = media::VideoCaptureError::
kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed;
return true;
case media::mojom::VideoCaptureError::
kFileVideoCaptureDeviceCouldNotOpenVideoFile:
*output = media::VideoCaptureError::
kFileVideoCaptureDeviceCouldNotOpenVideoFile;
return true;
case media::mojom::VideoCaptureError::
kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate:
*output = media::VideoCaptureError::
kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate;
return true;
case media::mojom::VideoCaptureError::
kErrorFakeDeviceIntentionallyEmittingErrorEvent:
*output = media::VideoCaptureError::
kErrorFakeDeviceIntentionallyEmittingErrorEvent;
return true;
case media::mojom::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16:
*output = media::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16;
return true;
case media::mojom::VideoCaptureError::
kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType:
*output = media::VideoCaptureError::
kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType;
return true;
case media::mojom::VideoCaptureError::
kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound:
*output = media::VideoCaptureError::
kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound;
return true;
case media::mojom::VideoCaptureError::
kInProcessDeviceLauncherFailedToCreateDeviceInstance:
*output = media::VideoCaptureError::
kInProcessDeviceLauncherFailedToCreateDeviceInstance;
return true;
case media::mojom::VideoCaptureError::
kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart:
*output = media::VideoCaptureError::
kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart;
return true;
case media::mojom::VideoCaptureError::
kServiceDeviceLauncherServiceRespondedWithDeviceNotFound:
*output = media::VideoCaptureError::
kServiceDeviceLauncherServiceRespondedWithDeviceNotFound;
return true;
case media::mojom::VideoCaptureError::
kServiceDeviceLauncherConnectionLostWhileWaitingForCallback:
*output = media::VideoCaptureError::
kServiceDeviceLauncherConnectionLostWhileWaitingForCallback;
return true;
case media::mojom::VideoCaptureError::kIntentionalErrorRaisedByUnitTest:
*output = media::VideoCaptureError::kIntentionalErrorRaisedByUnitTest;
return true;
case media::mojom::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread:
*output = media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateMojoConnectionError:
*output =
media::VideoCaptureError::kCrosHalV3DeviceDelegateMojoConnectionError;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetCameraInfo:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetCameraInfo;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateMissingSensorOrientationInfo:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateMissingSensorOrientationInfo;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToOpenCameraDevice:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToOpenCameraDevice;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToConfigureStreams:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToConfigureStreams;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings:
*output = media::VideoCaptureError::
kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerHalRequestedTooManyBuffers:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerHalRequestedTooManyBuffers;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerUnsupportedVideoPixelFormat:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerUnsupportedVideoPixelFormat;
return true;
case media::mojom::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd:
*output = media::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToRegisterBuffer:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToRegisterBuffer;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerProcessCaptureRequestFailed:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerProcessCaptureRequestFailed;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerInvalidPendingResultId:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerInvalidPendingResultId;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedInvalidShutterTime:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedInvalidShutterTime;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFatalDeviceError:
*output =
media::VideoCaptureError::kCrosHalV3BufferManagerFatalDeviceError;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut:
*output = media::VideoCaptureError::
kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut;
return true;
case media::mojom::VideoCaptureError::
kCrosHalV3BufferManagerInvalidJpegBlob:
*output =
media::VideoCaptureError::kCrosHalV3BufferManagerInvalidJpegBlob;
return true;
case media::mojom::VideoCaptureError::kAndroidFailedToAllocate:
*output = media::VideoCaptureError::kAndroidFailedToAllocate;
return true;
case media::mojom::VideoCaptureError::kAndroidFailedToStartCapture:
*output = media::VideoCaptureError::kAndroidFailedToStartCapture;
return true;
case media::mojom::VideoCaptureError::kAndroidFailedToStopCapture:
*output = media::VideoCaptureError::kAndroidFailedToStopCapture;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi1CameraErrorCallbackReceived:
*output =
media::VideoCaptureError::kAndroidApi1CameraErrorCallbackReceived;
return true;
case media::mojom::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived:
*output = media::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi2CaptureSessionConfigureFailed:
*output =
media::VideoCaptureError::kAndroidApi2CaptureSessionConfigureFailed;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi2ImageReaderUnexpectedImageFormat:
*output = media::VideoCaptureError::
kAndroidApi2ImageReaderUnexpectedImageFormat;
return true;
case media::mojom::VideoCaptureError::
kAndroidApi2ImageReaderSizeDidNotMatchImageSize:
*output = media::VideoCaptureError::
kAndroidApi2ImageReaderSizeDidNotMatchImageSize;
return true;
case media::mojom::VideoCaptureError::kAndroidApi2ErrorRestartingPreview:
*output = media::VideoCaptureError::kAndroidApi2ErrorRestartingPreview;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureUnsupportedFormat:
*output =
media::VideoCaptureError::kAndroidScreenCaptureUnsupportedFormat;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureFailedToStartCaptureMachine:
*output = media::VideoCaptureError::
kAndroidScreenCaptureFailedToStartCaptureMachine;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureTheUserDeniedScreenCapture:
*output = media::VideoCaptureError::
kAndroidScreenCaptureTheUserDeniedScreenCapture;
return true;
case media::mojom::VideoCaptureError::
kAndroidScreenCaptureFailedToStartScreenCapture:
*output = media::VideoCaptureError::
kAndroidScreenCaptureFailedToStartScreenCapture;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowCantGetCaptureFormatSettings:
*output =
media::VideoCaptureError::kWinDirectShowCantGetCaptureFormatSettings;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToGetNumberOfCapabilities:
*output = media::VideoCaptureError::
kWinDirectShowFailedToGetNumberOfCapabilities;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToGetCaptureDeviceCapabilities:
*output = media::VideoCaptureError::
kWinDirectShowFailedToGetCaptureDeviceCapabilities;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToSetCaptureDeviceOutputFormat:
*output = media::VideoCaptureError::
kWinDirectShowFailedToSetCaptureDeviceOutputFormat;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToConnectTheCaptureGraph:
*output = media::VideoCaptureError::
kWinDirectShowFailedToConnectTheCaptureGraph;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToPauseTheCaptureDevice:
*output =
media::VideoCaptureError::kWinDirectShowFailedToPauseTheCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToStartTheCaptureDevice:
*output =
media::VideoCaptureError::kWinDirectShowFailedToStartTheCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kWinDirectShowFailedToStopTheCaptureGraph:
*output =
media::VideoCaptureError::kWinDirectShowFailedToStopTheCaptureGraph;
return true;
case media::mojom::VideoCaptureError::kWinMediaFoundationEngineIsNull:
*output = media::VideoCaptureError::kWinMediaFoundationEngineIsNull;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationEngineGetSourceFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationEngineGetSourceFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationFillPhotoCapabilitiesFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationFillPhotoCapabilitiesFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationFillVideoCapabilitiesFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationFillVideoCapabilitiesFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationNoVideoCapabilityFound:
*output =
media::VideoCaptureError::kWinMediaFoundationNoVideoCapabilityFound;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationGetAvailableDeviceMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationGetAvailableDeviceMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSetCurrentDeviceMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSetCurrentDeviceMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationEngineGetSinkFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationEngineGetSinkFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkRemoveAllStreamsFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSinkRemoveAllStreamsFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationCreateSinkVideoMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationCreateSinkVideoMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationConvertToVideoSinkMediaTypeFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationConvertToVideoSinkMediaTypeFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkAddStreamFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationSinkAddStreamFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationSinkSetSampleCallbackFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationSinkSetSampleCallbackFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationEngineStartPreviewFailed:
*output =
media::VideoCaptureError::kWinMediaFoundationEngineStartPreviewFailed;
return true;
case media::mojom::VideoCaptureError::
kWinMediaFoundationGetMediaEventStatusFailed:
*output = media::VideoCaptureError::
kWinMediaFoundationGetMediaEventStatusFailed;
return true;
case media::mojom::VideoCaptureError::kMacSetCaptureDeviceFailed:
*output = media::VideoCaptureError::kMacSetCaptureDeviceFailed;
return true;
case media::mojom::VideoCaptureError::kMacCouldNotStartCaptureDevice:
*output = media::VideoCaptureError::kMacCouldNotStartCaptureDevice;
return true;
case media::mojom::VideoCaptureError::
kMacReceivedFrameWithUnexpectedResolution:
*output =
media::VideoCaptureError::kMacReceivedFrameWithUnexpectedResolution;
return true;
case media::mojom::VideoCaptureError::kMacUpdateCaptureResolutionFailed:
*output = media::VideoCaptureError::kMacUpdateCaptureResolutionFailed;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkDeviceIdNotFoundInTheSystem:
*output =
media::VideoCaptureError::kMacDeckLinkDeviceIdNotFoundInTheSystem;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkErrorQueryingInputInterface:
*output =
media::VideoCaptureError::kMacDeckLinkErrorQueryingInputInterface;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkErrorCreatingDisplayModeIterator:
*output = media::VideoCaptureError::
kMacDeckLinkErrorCreatingDisplayModeIterator;
return true;
case media::mojom::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode:
*output = media::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode;
return true;
case media::mojom::VideoCaptureError::
kMacDeckLinkCouldNotSelectTheVideoFormatWeLike:
*output = media::VideoCaptureError::
kMacDeckLinkCouldNotSelectTheVideoFormatWeLike;
return true;
case media::mojom::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing:
*output = media::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing;
return true;
case media::mojom::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat:
*output = media::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat;
return true;
case media::mojom::VideoCaptureError::
kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification:
*output = media::VideoCaptureError::
kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification;
return true;
case media::mojom::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera:
*output = media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera;
return true;
}
NOTREACHED();
return false;
}
| 172,512 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response ServiceWorkerHandler::DeliverPushMessage(
const std::string& origin,
const std::string& registration_id,
const std::string& data) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!process_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
PushEventPayload payload;
if (data.size() > 0)
payload.setData(data);
BrowserContext::DeliverPushMessage(process_->GetBrowserContext(),
GURL(origin), id, payload,
base::Bind(&PushDeliveryNoOp));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | Response ServiceWorkerHandler::DeliverPushMessage(
const std::string& origin,
const std::string& registration_id,
const std::string& data) {
if (!enabled_)
return CreateDomainNotEnabledErrorResponse();
if (!browser_context_)
return CreateContextErrorResponse();
int64_t id = 0;
if (!base::StringToInt64(registration_id, &id))
return CreateInvalidVersionIdErrorResponse();
PushEventPayload payload;
if (data.size() > 0)
payload.setData(data);
BrowserContext::DeliverPushMessage(
browser_context_, GURL(origin), id, payload,
base::BindRepeating([](mojom::PushDeliveryStatus status) {}));
return Response::OK();
}
| 172,766 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const SeekHead* Segment::GetSeekHead() const
{
return m_pSeekHead;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const SeekHead* Segment::GetSeekHead() const
| 174,353 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long do_io_submit(aio_context_t ctx_id, long nr,
struct iocb __user *__user *iocbpp, bool compat)
{
struct kioctx *ctx;
long ret = 0;
int i = 0;
struct blk_plug plug;
struct kiocb_batch batch;
if (unlikely(nr < 0))
return -EINVAL;
if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
nr = LONG_MAX/sizeof(*iocbpp);
if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
return -EFAULT;
ctx = lookup_ioctx(ctx_id);
if (unlikely(!ctx)) {
pr_debug("EINVAL: io_submit: invalid context id\n");
return -EINVAL;
}
kiocb_batch_init(&batch, nr);
blk_start_plug(&plug);
/*
* AKPM: should this return a partial result if some of the IOs were
* successfully submitted?
*/
for (i=0; i<nr; i++) {
struct iocb __user *user_iocb;
struct iocb tmp;
if (unlikely(__get_user(user_iocb, iocbpp + i))) {
ret = -EFAULT;
break;
}
if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
ret = -EFAULT;
break;
}
ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat);
if (ret)
break;
}
blk_finish_plug(&plug);
kiocb_batch_free(&batch);
put_ioctx(ctx);
return i ? i : ret;
}
Commit Message: Unused iocbs in a batch should not be accounted as active.
commit 69e4747ee9727d660b88d7e1efe0f4afcb35db1b upstream.
Since commit 080d676de095 ("aio: allocate kiocbs in batches") iocbs are
allocated in a batch during processing of first iocbs. All iocbs in a
batch are automatically added to ctx->active_reqs list and accounted in
ctx->reqs_active.
If one (not the last one) of iocbs submitted by an user fails, further
iocbs are not processed, but they are still present in ctx->active_reqs
and accounted in ctx->reqs_active. This causes process to stuck in a D
state in wait_for_all_aios() on exit since ctx->reqs_active will never
go down to zero. Furthermore since kiocb_batch_free() frees iocb
without removing it from active_reqs list the list become corrupted
which may cause oops.
Fix this by removing iocb from ctx->active_reqs and updating
ctx->reqs_active in kiocb_batch_free().
Signed-off-by: Gleb Natapov <[email protected]>
Reviewed-by: Jeff Moyer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-399 | long do_io_submit(aio_context_t ctx_id, long nr,
struct iocb __user *__user *iocbpp, bool compat)
{
struct kioctx *ctx;
long ret = 0;
int i = 0;
struct blk_plug plug;
struct kiocb_batch batch;
if (unlikely(nr < 0))
return -EINVAL;
if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
nr = LONG_MAX/sizeof(*iocbpp);
if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
return -EFAULT;
ctx = lookup_ioctx(ctx_id);
if (unlikely(!ctx)) {
pr_debug("EINVAL: io_submit: invalid context id\n");
return -EINVAL;
}
kiocb_batch_init(&batch, nr);
blk_start_plug(&plug);
/*
* AKPM: should this return a partial result if some of the IOs were
* successfully submitted?
*/
for (i=0; i<nr; i++) {
struct iocb __user *user_iocb;
struct iocb tmp;
if (unlikely(__get_user(user_iocb, iocbpp + i))) {
ret = -EFAULT;
break;
}
if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
ret = -EFAULT;
break;
}
ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat);
if (ret)
break;
}
blk_finish_plug(&plug);
kiocb_batch_free(ctx, &batch);
put_ioctx(ctx);
return i ? i : ret;
}
| 165,652 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, static_cast<OMX_U8 *>(params->pointer()));
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, static_cast<OMX_U8 *>(params->pointer()));
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
| 173,533 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
scale_factor(1.0f),
rasterize_pdf(false),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_id(-1),
preview_request_id(0),
is_first_request(false),
print_scaling_option(blink::kWebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
title(),
url(),
should_print_backgrounds(false),
printed_doc_type(printing::SkiaDocumentType::PDF) {}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Jianzhou Feng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20 | PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
scale_factor(1.0f),
rasterize_pdf(false),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_id(-1),
preview_request_id(0),
is_first_request(false),
print_scaling_option(blink::kWebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
title(),
url(),
header_template(),
footer_template(),
should_print_backgrounds(false),
printed_doc_type(printing::SkiaDocumentType::PDF) {}
| 172,897 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
Commit Message: Prevent invalid columnPos() call in formUpdateBuffer()
Bug-Debian: https://github.com/tats/w3m/issues/89
CWE ID: CWE-476 | formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (l == NULL)
break;
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
| 169,347 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintPreviewUI::OnDidPreviewPage(int page_number,
int preview_request_id) {
DCHECK_GE(page_number, 0);
base::FundamentalValue number(page_number);
StringValue ui_identifier(preview_ui_addr_str_);
base::FundamentalValue request_id(preview_request_id);
web_ui()->CallJavascriptFunction(
"onDidPreviewPage", number, ui_identifier, request_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::OnDidPreviewPage(int page_number,
int preview_request_id) {
DCHECK_GE(page_number, 0);
base::FundamentalValue number(page_number);
base::FundamentalValue ui_identifier(id_);
base::FundamentalValue request_id(preview_request_id);
web_ui()->CallJavascriptFunction(
"onDidPreviewPage", number, ui_identifier, request_id);
}
| 170,837 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool CCLayerTreeHost::initialize()
{
TRACE_EVENT("CCLayerTreeHost::initialize", this, 0);
if (m_settings.enableCompositorThread) {
m_settings.acceleratePainting = false;
m_settings.showFPSCounter = false;
m_settings.showPlatformLayerTree = false;
m_proxy = CCThreadProxy::create(this);
} else
m_proxy = CCSingleThreadProxy::create(this);
m_proxy->start();
if (!m_proxy->initializeLayerRenderer())
return false;
m_compositorIdentifier = m_proxy->compositorIdentifier();
m_settings.acceleratePainting = m_proxy->layerRendererCapabilities().usingAcceleratedPainting;
setNeedsCommitThenRedraw();
m_contentsTextureManager = TextureManager::create(TextureManager::highLimitBytes(), m_proxy->layerRendererCapabilities().maxTextureSize);
return true;
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | bool CCLayerTreeHost::initialize()
{
TRACE_EVENT("CCLayerTreeHost::initialize", this, 0);
if (m_settings.enableCompositorThread) {
m_settings.acceleratePainting = false;
m_settings.showFPSCounter = false;
m_settings.showPlatformLayerTree = false;
m_proxy = CCThreadProxy::create(this);
} else
m_proxy = CCSingleThreadProxy::create(this);
m_proxy->start();
if (!m_proxy->initializeLayerRenderer())
return false;
m_compositorIdentifier = m_proxy->compositorIdentifier();
m_settings.acceleratePainting = m_proxy->layerRendererCapabilities().usingAcceleratedPainting;
m_contentsTextureManager = TextureManager::create(TextureManager::highLimitBytes(), m_proxy->layerRendererCapabilities().maxTextureSize);
return true;
}
| 170,286 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
return ret;
}
Commit Message:
CWE ID: CWE-190 | int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
if (sn->l1_size > QCOW_MAX_L1_SIZE) {
error_setg(errp, "Snapshot L1 table too large");
return -EFBIG;
}
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
return ret;
}
| 165,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void btsnoop_write(const void *data, size_t length) {
if (logfile_fd != INVALID_FD)
write(logfile_fd, data, length);
btsnoop_net_write(data, length);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static void btsnoop_write(const void *data, size_t length) {
if (logfile_fd != INVALID_FD)
TEMP_FAILURE_RETRY(write(logfile_fd, data, length));
btsnoop_net_write(data, length);
}
| 173,472 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t ESDS::parseESDescriptor(size_t offset, size_t size) {
if (size < 3) {
return ERROR_MALFORMED;
}
offset += 2; // skip ES_ID
size -= 2;
unsigned streamDependenceFlag = mData[offset] & 0x80;
unsigned URL_Flag = mData[offset] & 0x40;
unsigned OCRstreamFlag = mData[offset] & 0x20;
++offset;
--size;
if (streamDependenceFlag) {
offset += 2;
size -= 2;
}
if (URL_Flag) {
if (offset >= size) {
return ERROR_MALFORMED;
}
unsigned URLlength = mData[offset];
offset += URLlength + 1;
size -= URLlength + 1;
}
if (OCRstreamFlag) {
offset += 2;
size -= 2;
if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor)
&& offset - 2 < size
&& mData[offset - 2] == kTag_DecoderConfigDescriptor) {
offset -= 2;
size += 2;
ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id.");
}
}
if (offset >= size) {
return ERROR_MALFORMED;
}
uint8_t tag;
size_t sub_offset, sub_size;
status_t err = skipDescriptorHeader(
offset, size, &tag, &sub_offset, &sub_size);
if (err != OK) {
return err;
}
if (tag != kTag_DecoderConfigDescriptor) {
return ERROR_MALFORMED;
}
err = parseDecoderConfigDescriptor(sub_offset, sub_size);
return err;
}
Commit Message: Fix integer underflow in ESDS processing
Several arithmetic operations within parseESDescriptor could underflow, leading
to an out-of-bounds read operation. Ensure that subtractions from 'size' do not
cause it to wrap around.
Bug: 20139950
(cherry picked from commit 07c0f59d6c48874982d2b5c713487612e5af465a)
Change-Id: I377d21051e07ca654ea1f7037120429d3f71924a
CWE ID: CWE-189 | status_t ESDS::parseESDescriptor(size_t offset, size_t size) {
if (size < 3) {
return ERROR_MALFORMED;
}
offset += 2; // skip ES_ID
size -= 2;
unsigned streamDependenceFlag = mData[offset] & 0x80;
unsigned URL_Flag = mData[offset] & 0x40;
unsigned OCRstreamFlag = mData[offset] & 0x20;
++offset;
--size;
if (streamDependenceFlag) {
if (size < 2)
return ERROR_MALFORMED;
offset += 2;
size -= 2;
}
if (URL_Flag) {
if (offset >= size) {
return ERROR_MALFORMED;
}
unsigned URLlength = mData[offset];
if (URLlength >= size)
return ERROR_MALFORMED;
offset += URLlength + 1;
size -= URLlength + 1;
}
if (OCRstreamFlag) {
if (size < 2)
return ERROR_MALFORMED;
offset += 2;
size -= 2;
if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor)
&& offset - 2 < size
&& mData[offset - 2] == kTag_DecoderConfigDescriptor) {
offset -= 2;
size += 2;
ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id.");
}
}
if (offset >= size) {
return ERROR_MALFORMED;
}
uint8_t tag;
size_t sub_offset, sub_size;
status_t err = skipDescriptorHeader(
offset, size, &tag, &sub_offset, &sub_size);
if (err != OK) {
return err;
}
if (tag != kTag_DecoderConfigDescriptor) {
return ERROR_MALFORMED;
}
err = parseDecoderConfigDescriptor(sub_offset, sub_size);
return err;
}
| 173,370 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadController::StartAndroidDownloadInternal(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info, bool allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!allowed)
return;
WebContents* web_contents = wc_getter.Run();
if (!web_contents)
return;
base::string16 filename = net::GetSuggestedFilename(
info.url, info.content_disposition,
std::string(), // referrer_charset
std::string(), // suggested_name
info.original_mime_type,
default_file_name_);
ChromeDownloadDelegate::FromWebContents(web_contents)->RequestHTTPGetDownload(
info.url.spec(), info.user_agent,
info.content_disposition, info.original_mime_type,
info.cookie, info.referer, filename,
info.total_bytes, info.has_user_gesture,
must_download);
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254 | void DownloadController::StartAndroidDownloadInternal(
| 171,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Segment::CreateInstance(IMkvReader* pReader, long long pos,
Segment*& pSegment) {
assert(pReader);
assert(pos >= 0);
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) // error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
for (;;) {
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return id;
pos += len; // consume ID
result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) { // Segment ID
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(pReader, idpos,
pos, size);
if (pSegment == 0)
return -1; // generic error
return 0; // success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; // consume payload
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long long Segment::CreateInstance(IMkvReader* pReader, long long pos,
Segment*& pSegment) {
if (pReader == NULL || pos < 0)
return E_PARSE_FAILED;
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) // error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
for (;;) {
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
result = GetUIntLength(pReader, pos, len);
if (result) // error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) { // Segment ID
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(pReader, idpos,
pos, size);
if (pSegment == 0)
return -1; // generic error
return 0; // success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; // consume payload
}
}
| 173,807 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, &unmounted);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
umount_mnt(p);
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
Commit Message: mnt: Honor MNT_LOCKED when detaching mounts
Modify umount(MNT_DETACH) to keep mounts in the hash table that are
locked to their parent mounts, when the parent is lazily unmounted.
In mntput_no_expire detach the children from the hash table, depending
on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children.
In __detach_mounts if there are any mounts that have been unmounted
but still are on the list of mounts of a mountpoint, remove their
children from the mount hash table and those children to the unmounted
list so they won't linger potentially indefinitely waiting for their
final mntput, now that the mounts serve no purpose.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-284 | static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = !IS_MNT_LOCKED_AND_LAZY(p);
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
| 167,590 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cf2_hintmap_build( CF2_HintMap hintmap,
CF2_ArrStack hStemHintArray,
CF2_ArrStack vStemHintArray,
CF2_HintMask hintMask,
CF2_Fixed hintOrigin,
FT_Bool initialMap )
{
FT_Byte* maskPtr;
CF2_Font font = hintmap->font;
CF2_HintMaskRec tempHintMask;
size_t bitCount, i;
FT_Byte maskByte;
/* check whether initial map is constructed */
if ( !initialMap && !cf2_hintmap_isValid( hintmap->initialHintMap ) )
{
/* make recursive call with initialHintMap and temporary mask; */
/* temporary mask will get all bits set, below */
cf2_hintmask_init( &tempHintMask, hintMask->error );
cf2_hintmap_build( hintmap->initialHintMap,
hStemHintArray,
vStemHintArray,
&tempHintMask,
hintOrigin,
TRUE );
}
if ( !cf2_hintmask_isValid( hintMask ) )
{
/* without a hint mask, assume all hints are active */
cf2_hintmask_setAll( hintMask,
cf2_arrstack_size( hStemHintArray ) +
cf2_arrstack_size( vStemHintArray ) );
if ( !cf2_hintmask_isValid( hintMask ) )
return; /* too many stem hints */
}
/* begin by clearing the map */
hintmap->count = 0;
hintmap->lastIndex = 0;
/* make a copy of the hint mask so we can modify it */
tempHintMask = *hintMask;
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
/* use the hStem hints only, which are first in the mask */
/* TODO: compare this to cffhintmaskGetBitCount */
bitCount = cf2_arrstack_size( hStemHintArray );
/* synthetic embox hints get highest priority */
if ( font->blues.doEmBoxHints )
{
cf2_hint_initZero( &dummy ); /* invalid hint map element */
/* ghost bottom */
cf2_hintmap_insertHint( hintmap,
&font->blues.emBoxBottomEdge,
&dummy );
/* ghost top */
cf2_hintmap_insertHint( hintmap,
&dummy,
&font->blues.emBoxTopEdge );
}
/* insert hints captured by a blue zone or already locked (higher */
/* priority) */
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
/* expand StemHint into two `CF2_Hint' elements */
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
if ( cf2_hint_isLocked( &bottomHintEdge ) ||
cf2_hint_isLocked( &topHintEdge ) ||
cf2_blues_capture( &font->blues,
&bottomHintEdge,
&topHintEdge ) )
{
/* insert captured hint into map */
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
*maskPtr &= ~maskByte; /* turn off the bit for this hint */
}
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
/* initial hint map includes only captured hints plus maybe one at 0 */
/*
* TODO: There is a problem here because we are trying to build a
* single hint map containing all captured hints. It is
* possible for there to be conflicts between captured hints,
* either because of darkening or because the hints are in
* separate hint zones (we are ignoring hint zones for the
* initial map). An example of the latter is MinionPro-Regular
* v2.030 glyph 883 (Greek Capital Alpha with Psili) at 15ppem.
* A stem hint for the psili conflicts with the top edge hint
* for the base character. The stem hint gets priority because
* of its sort order. In glyph 884 (Greek Capital Alpha with
* Psili and Oxia), the top of the base character gets a stem
* hint, and the psili does not. This creates different initial
* maps for the two glyphs resulting in different renderings of
* the base character. Will probably defer this either as not
* worth the cost or as a font bug. I don't think there is any
* good reason for an accent to be captured by an alignment
* zone. -darnold 2/12/10
*/
if ( initialMap )
{
/* Apply a heuristic that inserts a point for (0,0), unless it's */
/* already covered by a mapping. This locks the baseline for glyphs */
/* that have no baseline hints. */
if ( hintmap->count == 0 ||
hintmap->edge[0].csCoord > 0 ||
hintmap->edge[hintmap->count - 1].csCoord < 0 )
{
/* all edges are above 0 or all edges are below 0; */
/* construct a locked edge hint at 0 */
CF2_HintRec edge, invalid;
cf2_hint_initZero( &edge );
edge.flags = CF2_GhostBottom |
CF2_Locked |
CF2_Synthetic;
edge.scale = hintmap->scale;
cf2_hint_initZero( &invalid );
cf2_hintmap_insertHint( hintmap, &edge, &invalid );
}
}
else
{
/* insert remaining hints */
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
}
/*
* Note: The following line is a convenient place to break when
* debugging hinting. Examine `hintmap->edge' for the list of
* enabled hints, then step over the call to see the effect of
* adjustment. We stop here first on the recursive call that
* creates the initial map, and then on each counter group and
* hint zone.
*/
/* adjust positions of hint edges that are not locked to blue zones */
cf2_hintmap_adjustHints( hintmap );
/* save the position of all hints that were used in this hint map; */
/* if we use them again, we'll locate them in the same position */
if ( !initialMap )
{
for ( i = 0; i < hintmap->count; i++ )
{
if ( !cf2_hint_isSynthetic( &hintmap->edge[i] ) )
{
/* Note: include both valid and invalid edges */
/* Note: top and bottom edges are copied back separately */
CF2_StemHint stemhint = (CF2_StemHint)
cf2_arrstack_getPointer( hStemHintArray,
hintmap->edge[i].index );
if ( cf2_hint_isTop( &hintmap->edge[i] ) )
stemhint->maxDS = hintmap->edge[i].dsCoord;
else
stemhint->minDS = hintmap->edge[i].dsCoord;
stemhint->used = TRUE;
}
}
}
/* hint map is ready to use */
hintmap->isValid = TRUE;
/* remember this mask has been used */
cf2_hintmask_setNew( hintMask, FALSE );
}
Commit Message:
CWE ID: CWE-119 | cf2_hintmap_build( CF2_HintMap hintmap,
CF2_ArrStack hStemHintArray,
CF2_ArrStack vStemHintArray,
CF2_HintMask hintMask,
CF2_Fixed hintOrigin,
FT_Bool initialMap )
{
FT_Byte* maskPtr;
CF2_Font font = hintmap->font;
CF2_HintMaskRec tempHintMask;
size_t bitCount, i;
FT_Byte maskByte;
/* check whether initial map is constructed */
if ( !initialMap && !cf2_hintmap_isValid( hintmap->initialHintMap ) )
{
/* make recursive call with initialHintMap and temporary mask; */
/* temporary mask will get all bits set, below */
cf2_hintmask_init( &tempHintMask, hintMask->error );
cf2_hintmap_build( hintmap->initialHintMap,
hStemHintArray,
vStemHintArray,
&tempHintMask,
hintOrigin,
TRUE );
}
if ( !cf2_hintmask_isValid( hintMask ) )
{
/* without a hint mask, assume all hints are active */
cf2_hintmask_setAll( hintMask,
cf2_arrstack_size( hStemHintArray ) +
cf2_arrstack_size( vStemHintArray ) );
if ( !cf2_hintmask_isValid( hintMask ) )
return; /* too many stem hints */
}
/* begin by clearing the map */
hintmap->count = 0;
hintmap->lastIndex = 0;
/* make a copy of the hint mask so we can modify it */
tempHintMask = *hintMask;
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
/* use the hStem hints only, which are first in the mask */
bitCount = cf2_arrstack_size( hStemHintArray );
/* Defense-in-depth. Should never return here. */
if ( bitCount > hintMask->bitCount )
return;
/* synthetic embox hints get highest priority */
if ( font->blues.doEmBoxHints )
{
cf2_hint_initZero( &dummy ); /* invalid hint map element */
/* ghost bottom */
cf2_hintmap_insertHint( hintmap,
&font->blues.emBoxBottomEdge,
&dummy );
/* ghost top */
cf2_hintmap_insertHint( hintmap,
&dummy,
&font->blues.emBoxTopEdge );
}
/* insert hints captured by a blue zone or already locked (higher */
/* priority) */
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
/* expand StemHint into two `CF2_Hint' elements */
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
if ( cf2_hint_isLocked( &bottomHintEdge ) ||
cf2_hint_isLocked( &topHintEdge ) ||
cf2_blues_capture( &font->blues,
&bottomHintEdge,
&topHintEdge ) )
{
/* insert captured hint into map */
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
*maskPtr &= ~maskByte; /* turn off the bit for this hint */
}
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
/* initial hint map includes only captured hints plus maybe one at 0 */
/*
* TODO: There is a problem here because we are trying to build a
* single hint map containing all captured hints. It is
* possible for there to be conflicts between captured hints,
* either because of darkening or because the hints are in
* separate hint zones (we are ignoring hint zones for the
* initial map). An example of the latter is MinionPro-Regular
* v2.030 glyph 883 (Greek Capital Alpha with Psili) at 15ppem.
* A stem hint for the psili conflicts with the top edge hint
* for the base character. The stem hint gets priority because
* of its sort order. In glyph 884 (Greek Capital Alpha with
* Psili and Oxia), the top of the base character gets a stem
* hint, and the psili does not. This creates different initial
* maps for the two glyphs resulting in different renderings of
* the base character. Will probably defer this either as not
* worth the cost or as a font bug. I don't think there is any
* good reason for an accent to be captured by an alignment
* zone. -darnold 2/12/10
*/
if ( initialMap )
{
/* Apply a heuristic that inserts a point for (0,0), unless it's */
/* already covered by a mapping. This locks the baseline for glyphs */
/* that have no baseline hints. */
if ( hintmap->count == 0 ||
hintmap->edge[0].csCoord > 0 ||
hintmap->edge[hintmap->count - 1].csCoord < 0 )
{
/* all edges are above 0 or all edges are below 0; */
/* construct a locked edge hint at 0 */
CF2_HintRec edge, invalid;
cf2_hint_initZero( &edge );
edge.flags = CF2_GhostBottom |
CF2_Locked |
CF2_Synthetic;
edge.scale = hintmap->scale;
cf2_hint_initZero( &invalid );
cf2_hintmap_insertHint( hintmap, &edge, &invalid );
}
}
else
{
/* insert remaining hints */
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
}
/*
* Note: The following line is a convenient place to break when
* debugging hinting. Examine `hintmap->edge' for the list of
* enabled hints, then step over the call to see the effect of
* adjustment. We stop here first on the recursive call that
* creates the initial map, and then on each counter group and
* hint zone.
*/
/* adjust positions of hint edges that are not locked to blue zones */
cf2_hintmap_adjustHints( hintmap );
/* save the position of all hints that were used in this hint map; */
/* if we use them again, we'll locate them in the same position */
if ( !initialMap )
{
for ( i = 0; i < hintmap->count; i++ )
{
if ( !cf2_hint_isSynthetic( &hintmap->edge[i] ) )
{
/* Note: include both valid and invalid edges */
/* Note: top and bottom edges are copied back separately */
CF2_StemHint stemhint = (CF2_StemHint)
cf2_arrstack_getPointer( hStemHintArray,
hintmap->edge[i].index );
if ( cf2_hint_isTop( &hintmap->edge[i] ) )
stemhint->maxDS = hintmap->edge[i].dsCoord;
else
stemhint->minDS = hintmap->edge[i].dsCoord;
stemhint->used = TRUE;
}
}
}
/* hint map is ready to use */
hintmap->isValid = TRUE;
/* remember this mask has been used */
cf2_hintmask_setNew( hintMask, FALSE );
}
| 164,863 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DecodeNumberField(int len, char *str, int fmask,
int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits)
{
char *cp;
/*
* Have a decimal point? Then this is a date or something with a seconds
* field...
*/
if ((cp = strchr(str, '.')) != NULL)
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[MAXDATELEN + 1];
/*
* OK, we have at most six digits to care about. Let's construct a
* string and then do the conversion to an integer.
*/
strcpy(fstr, (cp + 1));
strcpy(fstr + strlen(fstr), "000000");
*(fstr + 6) = '\0';
*fsec = strtol(fstr, NULL, 10);
#else
*fsec = strtod(cp, NULL);
#endif
*cp = '\0';
len = strlen(str);
}
/* No decimal point and no complete date yet? */
else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
{
/* yyyymmdd? */
if (len == 8)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 6);
*(str + 6) = '\0';
tm->tm_mon = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_year = atoi(str + 0);
return DTK_DATE;
}
/* yymmdd? */
else if (len == 6)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_mon = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
/* yyddd? */
else if (len == 5)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_mon = 1;
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
}
/* not all time fields are specified? */
if ((fmask & DTK_TIME_M) != DTK_TIME_M)
{
/* hhmmss */
if (len == 6)
{
*tmask = DTK_TIME_M;
tm->tm_sec = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
/* hhmm? */
else if (len == 4)
{
*tmask = DTK_TIME_M;
tm->tm_sec = 0;
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
}
return -1;
} /* DecodeNumberField() */
Commit Message: Fix handling of wide datetime input/output.
Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value. It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer. ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own. In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly. Back-patch to 8.4
(all supported versions).
Reported by Daniel Schüssler, reviewed by Tom Lane.
Security: CVE-2014-0063
CWE ID: CWE-119 | DecodeNumberField(int len, char *str, int fmask,
int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits)
{
char *cp;
/*
* Have a decimal point? Then this is a date or something with a seconds
* field...
*/
if ((cp = strchr(str, '.')) != NULL)
{
#ifdef HAVE_INT64_TIMESTAMP
char fstr[7];
int i;
cp++;
/*
* OK, we have at most six digits to care about. Let's construct a
* string with those digits, zero-padded on the right, and then do
* the conversion to an integer.
*
* XXX This truncates the seventh digit, unlike rounding it as do
* the backend and the !HAVE_INT64_TIMESTAMP case.
*/
for (i = 0; i < 6; i++)
fstr[i] = *cp != '\0' ? *cp++ : '0';
fstr[i] = '\0';
*fsec = strtol(fstr, NULL, 10);
#else
*fsec = strtod(cp, NULL);
#endif
*cp = '\0';
len = strlen(str);
}
/* No decimal point and no complete date yet? */
else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
{
/* yyyymmdd? */
if (len == 8)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 6);
*(str + 6) = '\0';
tm->tm_mon = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_year = atoi(str + 0);
return DTK_DATE;
}
/* yymmdd? */
else if (len == 6)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_mon = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
/* yyddd? */
else if (len == 5)
{
*tmask = DTK_DATE_M;
tm->tm_mday = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_mon = 1;
tm->tm_year = atoi(str + 0);
*is2digits = TRUE;
return DTK_DATE;
}
}
/* not all time fields are specified? */
if ((fmask & DTK_TIME_M) != DTK_TIME_M)
{
/* hhmmss */
if (len == 6)
{
*tmask = DTK_TIME_M;
tm->tm_sec = atoi(str + 4);
*(str + 4) = '\0';
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
/* hhmm? */
else if (len == 4)
{
*tmask = DTK_TIME_M;
tm->tm_sec = 0;
tm->tm_min = atoi(str + 2);
*(str + 2) = '\0';
tm->tm_hour = atoi(str + 0);
return DTK_TIME;
}
}
return -1;
} /* DecodeNumberField() */
| 166,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void net_checksum_calculate(uint8_t *data, int length)
{
int hlen, plen, proto, csum_offset;
uint16_t csum;
if ((data[14] & 0xf0) != 0x40)
return; /* not IPv4 */
hlen = (data[14] & 0x0f) * 4;
csum_offset = 16;
break;
case PROTO_UDP:
csum_offset = 6;
break;
default:
return;
}
Commit Message:
CWE ID: CWE-119 | void net_checksum_calculate(uint8_t *data, int length)
{
int hlen, plen, proto, csum_offset;
uint16_t csum;
/* Ensure data has complete L2 & L3 headers. */
if (length < 14 + 20) {
return;
}
if ((data[14] & 0xf0) != 0x40)
return; /* not IPv4 */
hlen = (data[14] & 0x0f) * 4;
csum_offset = 16;
break;
case PROTO_UDP:
csum_offset = 6;
break;
default:
return;
}
| 165,182 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: TIFFNumberOfStrips(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
uint32 nstrips;
/* If the value was already computed and store in td_nstrips, then return it,
since ChopUpSingleUncompressedStrip might have altered and resized the
since the td_stripbytecount and td_stripoffset arrays to the new value
after the initial affectation of td_nstrips = TIFFNumberOfStrips() in
tif_dirread.c ~line 3612.
See http://bugzilla.maptools.org/show_bug.cgi?id=2587 */
if( td->td_nstrips )
return td->td_nstrips;
nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 :
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip));
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel,
"TIFFNumberOfStrips");
return (nstrips);
}
Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to
instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip),
instead of a logic based on the total size of data. Which is faulty is
the total size of data is not sufficient to fill the whole image, and thus
results in reading outside of the StripByCounts/StripOffsets arrays when
using TIFFReadScanline().
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608.
* libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done
for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since
the above change is a better fix that makes it unnecessary.
CWE ID: CWE-125 | TIFFNumberOfStrips(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
uint32 nstrips;
nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 :
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip));
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel,
"TIFFNumberOfStrips");
return (nstrips);
}
| 168,463 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)
{
struct dentry *parent;
struct inode *p_inode;
int ret = 0;
if (!dentry)
dentry = path->dentry;
if (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))
return 0;
parent = dget_parent(dentry);
p_inode = parent->d_inode;
if (unlikely(!fsnotify_inode_watches_children(p_inode)))
__fsnotify_update_child_dentry_flags(p_inode);
else if (p_inode->i_fsnotify_mask & mask) {
/* we are notifying a parent so come up with the new mask which
* specifies these are events which came from a child. */
mask |= FS_EVENT_ON_CHILD;
if (path)
ret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,
dentry->d_name.name, 0);
else
ret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,
dentry->d_name.name, 0);
}
dput(parent);
return ret;
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-362 | int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)
{
struct dentry *parent;
struct inode *p_inode;
int ret = 0;
if (!dentry)
dentry = path->dentry;
if (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))
return 0;
parent = dget_parent(dentry);
p_inode = parent->d_inode;
if (unlikely(!fsnotify_inode_watches_children(p_inode)))
__fsnotify_update_child_dentry_flags(p_inode);
else if (p_inode->i_fsnotify_mask & mask) {
struct name_snapshot name;
/* we are notifying a parent so come up with the new mask which
* specifies these are events which came from a child. */
mask |= FS_EVENT_ON_CHILD;
take_dentry_name_snapshot(&name, dentry);
if (path)
ret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,
name.name, 0);
else
ret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,
name.name, 0);
release_dentry_name_snapshot(&name);
}
dput(parent);
return ret;
}
| 168,264 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
Commit Message: CVE-2017-12899/DECnet: Fix bounds checking.
If we're skipping over padding before the *real* flags, check whether
the real flags are in the captured data before fetching it. This fixes
a buffer over-read discovered by Kamil Frankowicz.
Note one place where we don't need to do bounds checking as it's already
been done.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | print_decnet_ctlmsg(netdissect_options *ndo,
register const union routehdr *rhp, u_int length,
u_int caplen)
{
/* Our caller has already checked for mflags */
int mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
register const union controlmsg *cmp = (const union controlmsg *)rhp;
int src, dst, info, blksize, eco, ueco, hello, other, vers;
etheraddr srcea, rtea;
int priority;
const char *rhpx = (const char *)rhp;
int ret;
switch (mflags & RMF_CTLMASK) {
case RMF_INIT:
ND_PRINT((ndo, "init "));
if (length < sizeof(struct initmsg))
goto trunc;
ND_TCHECK(cmp->cm_init);
src = EXTRACT_LE_16BITS(cmp->cm_init.in_src);
info = EXTRACT_LE_8BITS(cmp->cm_init.in_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_init.in_blksize);
vers = EXTRACT_LE_8BITS(cmp->cm_init.in_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_init.in_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_init.in_ueco);
hello = EXTRACT_LE_16BITS(cmp->cm_init.in_hello);
print_t_info(ndo, info);
ND_PRINT((ndo,
"src %sblksize %d vers %d eco %d ueco %d hello %d",
dnaddr_string(ndo, src), blksize, vers, eco, ueco,
hello));
ret = 1;
break;
case RMF_VER:
ND_PRINT((ndo, "verification "));
if (length < sizeof(struct verifmsg))
goto trunc;
ND_TCHECK(cmp->cm_ver);
src = EXTRACT_LE_16BITS(cmp->cm_ver.ve_src);
other = EXTRACT_LE_8BITS(cmp->cm_ver.ve_fcnval);
ND_PRINT((ndo, "src %s fcnval %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_TEST:
ND_PRINT((ndo, "test "));
if (length < sizeof(struct testmsg))
goto trunc;
ND_TCHECK(cmp->cm_test);
src = EXTRACT_LE_16BITS(cmp->cm_test.te_src);
other = EXTRACT_LE_8BITS(cmp->cm_test.te_data);
ND_PRINT((ndo, "src %s data %o", dnaddr_string(ndo, src), other));
ret = 1;
break;
case RMF_L1ROUT:
ND_PRINT((ndo, "lev-1-routing "));
if (length < sizeof(struct l1rout))
goto trunc;
ND_TCHECK(cmp->cm_l1rou);
src = EXTRACT_LE_16BITS(cmp->cm_l1rou.r1_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l1_routes(ndo, &(rhpx[sizeof(struct l1rout)]),
length - sizeof(struct l1rout));
break;
case RMF_L2ROUT:
ND_PRINT((ndo, "lev-2-routing "));
if (length < sizeof(struct l2rout))
goto trunc;
ND_TCHECK(cmp->cm_l2rout);
src = EXTRACT_LE_16BITS(cmp->cm_l2rout.r2_src);
ND_PRINT((ndo, "src %s ", dnaddr_string(ndo, src)));
ret = print_l2_routes(ndo, &(rhpx[sizeof(struct l2rout)]),
length - sizeof(struct l2rout));
break;
case RMF_RHELLO:
ND_PRINT((ndo, "router-hello "));
if (length < sizeof(struct rhellomsg))
goto trunc;
ND_TCHECK(cmp->cm_rhello);
vers = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_rhello.rh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_blksize);
priority = EXTRACT_LE_8BITS(cmp->cm_rhello.rh_priority);
hello = EXTRACT_LE_16BITS(cmp->cm_rhello.rh_hello);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d pri %d hello %d",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, priority, hello));
ret = print_elist(&(rhpx[sizeof(struct rhellomsg)]),
length - sizeof(struct rhellomsg));
break;
case RMF_EHELLO:
ND_PRINT((ndo, "endnode-hello "));
if (length < sizeof(struct ehellomsg))
goto trunc;
ND_TCHECK(cmp->cm_ehello);
vers = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_vers);
eco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_eco);
ueco = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_ueco);
memcpy((char *)&srcea, (const char *)&(cmp->cm_ehello.eh_src),
sizeof(srcea));
src = EXTRACT_LE_16BITS(srcea.dne_remote.dne_nodeaddr);
info = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_info);
blksize = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_blksize);
/*seed*/
memcpy((char *)&rtea, (const char *)&(cmp->cm_ehello.eh_router),
sizeof(rtea));
dst = EXTRACT_LE_16BITS(rtea.dne_remote.dne_nodeaddr);
hello = EXTRACT_LE_16BITS(cmp->cm_ehello.eh_hello);
other = EXTRACT_LE_8BITS(cmp->cm_ehello.eh_data);
print_i_info(ndo, info);
ND_PRINT((ndo,
"vers %d eco %d ueco %d src %s blksize %d rtr %s hello %d data %o",
vers, eco, ueco, dnaddr_string(ndo, src),
blksize, dnaddr_string(ndo, dst), hello, other));
ret = 1;
break;
default:
ND_PRINT((ndo, "unknown control message"));
ND_DEFAULTPRINT((const u_char *)rhp, min(length, caplen));
ret = 1;
break;
}
return (ret);
trunc:
return (0);
}
| 170,034 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void vmxnet3_complete_packet(VMXNET3State *s, int qidx, uint32_t tx_ridx)
{
struct Vmxnet3_TxCompDesc txcq_descr;
PCIDevice *d = PCI_DEVICE(s);
VMXNET3_RING_DUMP(VMW_RIPRN, "TXC", qidx, &s->txq_descr[qidx].comp_ring);
txcq_descr.txdIdx = tx_ridx;
txcq_descr.gen = vmxnet3_ring_curr_gen(&s->txq_descr[qidx].comp_ring);
/* Flush changes in TX descriptor before changing the counter value */
smp_wmb();
vmxnet3_inc_tx_completion_counter(s, qidx);
vmxnet3_trigger_interrupt(s, s->txq_descr[qidx].intr_idx);
}
Commit Message:
CWE ID: CWE-200 | static void vmxnet3_complete_packet(VMXNET3State *s, int qidx, uint32_t tx_ridx)
{
struct Vmxnet3_TxCompDesc txcq_descr;
PCIDevice *d = PCI_DEVICE(s);
VMXNET3_RING_DUMP(VMW_RIPRN, "TXC", qidx, &s->txq_descr[qidx].comp_ring);
memset(&txcq_descr, 0, sizeof(txcq_descr));
txcq_descr.txdIdx = tx_ridx;
txcq_descr.gen = vmxnet3_ring_curr_gen(&s->txq_descr[qidx].comp_ring);
/* Flush changes in TX descriptor before changing the counter value */
smp_wmb();
vmxnet3_inc_tx_completion_counter(s, qidx);
vmxnet3_trigger_interrupt(s, s->txq_descr[qidx].intr_idx);
}
| 164,948 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Label::SizeToFit(int max_width) {
DCHECK(is_multi_line_);
std::vector<std::wstring> lines;
base::SplitString(UTF16ToWideHack(text_), L'\n', &lines);
int label_width = 0;
for (std::vector<std::wstring>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
label_width = std::max(label_width,
font_.GetStringWidth(WideToUTF16Hack(*iter)));
}
label_width += GetInsets().width();
if (max_width > 0)
label_width = std::min(label_width, max_width);
SetBounds(x(), y(), label_width, 0);
SizeToPreferredSize();
}
Commit Message: wstring: remove wstring version of SplitString
Retry of r84336.
BUG=23581
Review URL: http://codereview.chromium.org/6930047
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void Label::SizeToFit(int max_width) {
DCHECK(is_multi_line_);
std::vector<string16> lines;
base::SplitString(text_, '\n', &lines);
int label_width = 0;
for (std::vector<string16>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
label_width = std::max(label_width, font_.GetStringWidth(*iter));
}
label_width += GetInsets().width();
if (max_width > 0)
label_width = std::min(label_width, max_width);
SetBounds(x(), y(), label_width, 0);
SizeToPreferredSize();
}
| 170,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLMediaElement::NoneSupported(const String& message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='" << message
<< "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200 | void HTMLMediaElement::NoneSupported(const String& message) {
void HTMLMediaElement::NoneSupported(const String& input_message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='"
<< input_message << "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
String empty_string;
const String& message = MediaShouldBeOpaque() ? empty_string : input_message;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
| 173,163 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
Commit Message: Check context is attached before creating MediaRecorder
Bug: 896736
Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34
Reviewed-on: https://chromium-review.googlesource.com/c/1324231
Commit-Queue: Emircan Uysaler <[email protected]>
Reviewed-by: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606242}
CWE ID: CWE-119 | MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
if (context->IsContextDestroyed()) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError,
"Execution context is detached.");
return;
}
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
| 172,605 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long madvise_remove(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
loff_t offset;
int error;
*prev = NULL; /* tell sys_madvise we drop mmap_sem */
if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB))
return -EINVAL;
if (!vma->vm_file || !vma->vm_file->f_mapping
|| !vma->vm_file->f_mapping->host) {
return -EINVAL;
}
if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
return -EACCES;
offset = (loff_t)(start - vma->vm_start)
+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
/* filesystem's fallocate may need to take i_mutex */
up_read(¤t->mm->mmap_sem);
error = do_fallocate(vma->vm_file,
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, end - start);
down_read(¤t->mm->mmap_sem);
return error;
}
Commit Message: mm: Hold a file reference in madvise_remove
Otherwise the code races with munmap (causing a use-after-free
of the vma) or with close (causing a use-after-free of the struct
file).
The bug was introduced by commit 90ed52ebe481 ("[PATCH] holepunch: fix
mmap_sem i_mutex deadlock")
Cc: Hugh Dickins <[email protected]>
Cc: Miklos Szeredi <[email protected]>
Cc: Badari Pulavarty <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static long madvise_remove(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
loff_t offset;
int error;
struct file *f;
*prev = NULL; /* tell sys_madvise we drop mmap_sem */
if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB))
return -EINVAL;
f = vma->vm_file;
if (!f || !f->f_mapping || !f->f_mapping->host) {
return -EINVAL;
}
if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
return -EACCES;
offset = (loff_t)(start - vma->vm_start)
+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
/*
* Filesystem's fallocate may need to take i_mutex. We need to
* explicitly grab a reference because the vma (and hence the
* vma's reference to the file) can go away as soon as we drop
* mmap_sem.
*/
get_file(f);
up_read(¤t->mm->mmap_sem);
error = do_fallocate(f,
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, end - start);
fput(f);
down_read(¤t->mm->mmap_sem);
return error;
}
| 165,581 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(DirectoryIterator, isDot)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name));
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, isDot)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name));
}
| 167,037 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderThreadImpl::EnsureWebKitInitialized() {
if (webkit_platform_support_.get())
return;
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
v8::V8::SetCreateHistogramFunction(CreateHistogram);
v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
WebKit::initialize(webkit_platform_support_.get());
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableThreadedCompositing)) {
compositor_thread_.reset(new CompositorThread(this));
AddFilter(compositor_thread_->GetMessageFilter());
WebKit::WebCompositor::initialize(compositor_thread_->GetWebThread());
} else
WebKit::WebCompositor::initialize(NULL);
compositor_initialized_ = true;
WebScriptController::enableV8SingleThreadMode();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
webkit_glue::EnableWebCoreLogChannels(
command_line.GetSwitchValueASCII(switches::kWebCoreLogChannels));
if (command_line.HasSwitch(switches::kPlaybackMode) ||
command_line.HasSwitch(switches::kRecordMode) ||
command_line.HasSwitch(switches::kNoJsRandomness)) {
RegisterExtension(extensions_v8::PlaybackExtension::Get());
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
base::StringPiece extension = content::GetContentClient()->GetDataResource(
IDR_DOM_AUTOMATION_JS);
RegisterExtension(new v8::Extension(
"dom_automation.js", extension.data(), 0, NULL, extension.size()));
}
web_database_observer_impl_.reset(
new WebDatabaseObserverImpl(sync_message_filter()));
WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
WebRuntimeFeatures::enableSockets(
!command_line.HasSwitch(switches::kDisableWebSockets));
WebRuntimeFeatures::enableDatabase(
!command_line.HasSwitch(switches::kDisableDatabases));
WebRuntimeFeatures::enableDataTransferItems(
!command_line.HasSwitch(switches::kDisableDataTransferItems));
WebRuntimeFeatures::enableApplicationCache(
!command_line.HasSwitch(switches::kDisableApplicationCache));
WebRuntimeFeatures::enableNotifications(
!command_line.HasSwitch(switches::kDisableDesktopNotifications));
WebRuntimeFeatures::enableLocalStorage(
!command_line.HasSwitch(switches::kDisableLocalStorage));
WebRuntimeFeatures::enableSessionStorage(
!command_line.HasSwitch(switches::kDisableSessionStorage));
WebRuntimeFeatures::enableIndexedDatabase(true);
WebRuntimeFeatures::enableGeolocation(
!command_line.HasSwitch(switches::kDisableGeolocation));
WebKit::WebRuntimeFeatures::enableMediaSource(
command_line.HasSwitch(switches::kEnableMediaSource));
WebRuntimeFeatures::enableMediaPlayer(
media::IsMediaLibraryInitialized());
WebKit::WebRuntimeFeatures::enableMediaStream(
command_line.HasSwitch(switches::kEnableMediaStream));
WebKit::WebRuntimeFeatures::enableFullScreenAPI(
!command_line.HasSwitch(switches::kDisableFullScreen));
WebKit::WebRuntimeFeatures::enablePointerLock(
command_line.HasSwitch(switches::kEnablePointerLock));
WebKit::WebRuntimeFeatures::enableVideoTrack(
command_line.HasSwitch(switches::kEnableVideoTrack));
#if defined(OS_CHROMEOS)
WebRuntimeFeatures::enableWebAudio(false);
#else
WebRuntimeFeatures::enableWebAudio(
!command_line.HasSwitch(switches::kDisableWebAudio));
#endif
WebRuntimeFeatures::enablePushState(true);
WebRuntimeFeatures::enableTouch(
command_line.HasSwitch(switches::kEnableTouchEvents));
WebRuntimeFeatures::enableDeviceMotion(
command_line.HasSwitch(switches::kEnableDeviceMotion));
WebRuntimeFeatures::enableDeviceOrientation(
!command_line.HasSwitch(switches::kDisableDeviceOrientation));
WebRuntimeFeatures::enableSpeechInput(
!command_line.HasSwitch(switches::kDisableSpeechInput));
WebRuntimeFeatures::enableScriptedSpeech(
command_line.HasSwitch(switches::kEnableScriptedSpeech));
WebRuntimeFeatures::enableFileSystem(
!command_line.HasSwitch(switches::kDisableFileSystem));
WebRuntimeFeatures::enableJavaScriptI18NAPI(
!command_line.HasSwitch(switches::kDisableJavaScriptI18NAPI));
WebRuntimeFeatures::enableGamepad(
command_line.HasSwitch(switches::kEnableGamepad));
WebRuntimeFeatures::enableQuota(true);
WebRuntimeFeatures::enableShadowDOM(
command_line.HasSwitch(switches::kEnableShadowDOM));
WebRuntimeFeatures::enableStyleScoped(
command_line.HasSwitch(switches::kEnableStyleScoped));
FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
if (content::GetContentClient()->renderer()->
RunIdleHandlerWhenWidgetsHidden()) {
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
}
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderThreadImpl::EnsureWebKitInitialized() {
if (webkit_platform_support_.get())
return;
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
v8::V8::SetCreateHistogramFunction(CreateHistogram);
v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
WebKit::initialize(webkit_platform_support_.get());
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableThreadedCompositing)) {
compositor_thread_.reset(new CompositorThread(this));
AddFilter(compositor_thread_->GetMessageFilter());
WebKit::WebCompositor::initialize(compositor_thread_->GetWebThread());
} else
WebKit::WebCompositor::initialize(NULL);
compositor_initialized_ = true;
WebScriptController::enableV8SingleThreadMode();
RenderThreadImpl::RegisterSchemes();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
webkit_glue::EnableWebCoreLogChannels(
command_line.GetSwitchValueASCII(switches::kWebCoreLogChannels));
if (command_line.HasSwitch(switches::kPlaybackMode) ||
command_line.HasSwitch(switches::kRecordMode) ||
command_line.HasSwitch(switches::kNoJsRandomness)) {
RegisterExtension(extensions_v8::PlaybackExtension::Get());
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
base::StringPiece extension = content::GetContentClient()->GetDataResource(
IDR_DOM_AUTOMATION_JS);
RegisterExtension(new v8::Extension(
"dom_automation.js", extension.data(), 0, NULL, extension.size()));
}
web_database_observer_impl_.reset(
new WebDatabaseObserverImpl(sync_message_filter()));
WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
WebRuntimeFeatures::enableSockets(
!command_line.HasSwitch(switches::kDisableWebSockets));
WebRuntimeFeatures::enableDatabase(
!command_line.HasSwitch(switches::kDisableDatabases));
WebRuntimeFeatures::enableDataTransferItems(
!command_line.HasSwitch(switches::kDisableDataTransferItems));
WebRuntimeFeatures::enableApplicationCache(
!command_line.HasSwitch(switches::kDisableApplicationCache));
WebRuntimeFeatures::enableNotifications(
!command_line.HasSwitch(switches::kDisableDesktopNotifications));
WebRuntimeFeatures::enableLocalStorage(
!command_line.HasSwitch(switches::kDisableLocalStorage));
WebRuntimeFeatures::enableSessionStorage(
!command_line.HasSwitch(switches::kDisableSessionStorage));
WebRuntimeFeatures::enableIndexedDatabase(true);
WebRuntimeFeatures::enableGeolocation(
!command_line.HasSwitch(switches::kDisableGeolocation));
WebKit::WebRuntimeFeatures::enableMediaSource(
command_line.HasSwitch(switches::kEnableMediaSource));
WebRuntimeFeatures::enableMediaPlayer(
media::IsMediaLibraryInitialized());
WebKit::WebRuntimeFeatures::enableMediaStream(
command_line.HasSwitch(switches::kEnableMediaStream));
WebKit::WebRuntimeFeatures::enableFullScreenAPI(
!command_line.HasSwitch(switches::kDisableFullScreen));
WebKit::WebRuntimeFeatures::enablePointerLock(
command_line.HasSwitch(switches::kEnablePointerLock));
WebKit::WebRuntimeFeatures::enableVideoTrack(
command_line.HasSwitch(switches::kEnableVideoTrack));
#if defined(OS_CHROMEOS)
WebRuntimeFeatures::enableWebAudio(false);
#else
WebRuntimeFeatures::enableWebAudio(
!command_line.HasSwitch(switches::kDisableWebAudio));
#endif
WebRuntimeFeatures::enablePushState(true);
WebRuntimeFeatures::enableTouch(
command_line.HasSwitch(switches::kEnableTouchEvents));
WebRuntimeFeatures::enableDeviceMotion(
command_line.HasSwitch(switches::kEnableDeviceMotion));
WebRuntimeFeatures::enableDeviceOrientation(
!command_line.HasSwitch(switches::kDisableDeviceOrientation));
WebRuntimeFeatures::enableSpeechInput(
!command_line.HasSwitch(switches::kDisableSpeechInput));
WebRuntimeFeatures::enableScriptedSpeech(
command_line.HasSwitch(switches::kEnableScriptedSpeech));
WebRuntimeFeatures::enableFileSystem(
!command_line.HasSwitch(switches::kDisableFileSystem));
WebRuntimeFeatures::enableJavaScriptI18NAPI(
!command_line.HasSwitch(switches::kDisableJavaScriptI18NAPI));
WebRuntimeFeatures::enableGamepad(
command_line.HasSwitch(switches::kEnableGamepad));
WebRuntimeFeatures::enableQuota(true);
WebRuntimeFeatures::enableShadowDOM(
command_line.HasSwitch(switches::kEnableShadowDOM));
WebRuntimeFeatures::enableStyleScoped(
command_line.HasSwitch(switches::kEnableStyleScoped));
FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
if (content::GetContentClient()->renderer()->
RunIdleHandlerWhenWidgetsHidden()) {
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
}
}
| 171,030 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual bool IsURLAcceptableForWebUI(
BrowserContext* browser_context, const GURL& url) const {
return HasWebUIScheme(url);
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | virtual bool IsURLAcceptableForWebUI(
BrowserContext* browser_context, const GURL& url) const {
return content::GetContentClient()->HasWebUIScheme(url);
}
};
class TabContentsTestClient : public TestContentClient {
public:
TabContentsTestClient() {
}
virtual bool HasWebUIScheme(const GURL& url) const OVERRIDE {
return url.SchemeIs("tabcontentstest");
}
| 171,013 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WallpaperManagerBase::LoadWallpaper(
const AccountId& account_id,
const WallpaperInfo& info,
bool update_wallpaper,
MovableOnDestroyCallbackHolder on_finish) {
base::FilePath wallpaper_dir;
base::FilePath wallpaper_path;
if (info.type == ONLINE || info.type == DEFAULT) {
if (info.location.empty()) {
if (base::SysInfo::IsRunningOnChromeOS()) {
NOTREACHED() << "User wallpaper info appears to be broken: "
<< account_id.Serialize();
} else {
LOG(WARNING) << "User wallpaper info is empty: "
<< account_id.Serialize();
return;
}
}
}
if (info.type == ONLINE) {
std::string file_name = GURL(info.location).ExtractFileName();
WallpaperResolution resolution = GetAppropriateResolution();
if (info.layout != WALLPAPER_LAYOUT_STRETCH &&
resolution == WALLPAPER_RESOLUTION_SMALL) {
file_name = base::FilePath(file_name)
.InsertBeforeExtension(kSmallWallpaperSuffix)
.value();
}
DCHECK(dir_chromeos_wallpapers_path_id != -1);
CHECK(PathService::Get(dir_chromeos_wallpapers_path_id,
&wallpaper_dir));
wallpaper_path = wallpaper_dir.Append(file_name);
CustomWallpaperMap::iterator it = wallpaper_cache_.find(account_id);
if (it != wallpaper_cache_.end() &&
it->second.first == wallpaper_path &&
!it->second.second.isNull())
return;
loaded_wallpapers_for_test_++;
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else if (info.type == DEFAULT) {
base::FilePath user_data_dir;
DCHECK(dir_user_data_path_id != -1);
PathService::Get(dir_user_data_path_id, &user_data_dir);
wallpaper_path = user_data_dir.Append(info.location);
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else {
LOG(ERROR) << "Wallpaper reverts to default unexpected.";
DoSetDefaultWallpaper(account_id, std::move(on_finish));
}
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200 | void WallpaperManagerBase::LoadWallpaper(
const AccountId& account_id,
const WallpaperInfo& info,
bool update_wallpaper,
MovableOnDestroyCallbackHolder on_finish) {
base::FilePath wallpaper_dir;
base::FilePath wallpaper_path;
if (info.type == ONLINE || info.type == DEFAULT) {
if (info.location.empty()) {
if (base::SysInfo::IsRunningOnChromeOS()) {
NOTREACHED() << "User wallpaper info appears to be broken: "
<< account_id.Serialize();
} else {
LOG(WARNING) << "User wallpaper info is empty: "
<< account_id.Serialize();
return;
}
}
}
if (info.type == ONLINE) {
std::string file_name = GURL(info.location).ExtractFileName();
WallpaperResolution resolution = GetAppropriateResolution();
if (info.layout != WALLPAPER_LAYOUT_STRETCH &&
resolution == WALLPAPER_RESOLUTION_SMALL) {
file_name = base::FilePath(file_name)
.InsertBeforeExtension(kSmallWallpaperSuffix)
.value();
}
DCHECK(dir_chromeos_wallpapers_path_id != -1);
CHECK(PathService::Get(dir_chromeos_wallpapers_path_id,
&wallpaper_dir));
wallpaper_path = wallpaper_dir.Append(file_name);
CustomWallpaperMap::iterator it = wallpaper_cache_.find(account_id);
if (it != wallpaper_cache_.end() &&
it->second.first == wallpaper_path &&
!it->second.second.isNull())
return;
loaded_wallpapers_for_test_++;
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else if (info.type == DEFAULT) {
base::FilePath user_data_dir;
DCHECK(dir_user_data_path_id != -1);
PathService::Get(dir_user_data_path_id, &user_data_dir);
wallpaper_path = user_data_dir.Append(info.location);
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else {
LOG(ERROR) << "Wallpaper reverts to default unexpected.";
DoSetDefaultWallpaper(account_id, update_wallpaper, std::move(on_finish));
}
}
| 171,973 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlStopParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
if (ctxt->input != NULL) {
ctxt->input->cur = BAD_CAST"";
ctxt->input->base = ctxt->input->cur;
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlStopParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
ctxt->instate = XML_PARSER_EOF;
ctxt->errNo = XML_ERR_USER_STOP;
ctxt->disableSAX = 1;
if (ctxt->input != NULL) {
ctxt->input->cur = BAD_CAST"";
ctxt->input->base = ctxt->input->cur;
}
}
| 171,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
| 174,553 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int hns_gmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ARRAY_SIZE(g_gmac_stats_string);
return 0;
}
Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int hns_gmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS)
return ARRAY_SIZE(g_gmac_stats_string);
return 0;
}
| 169,398 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetUpCacheWithVariousFiles() {
CreateFile(persistent_directory_.AppendASCII("id_foo.md5foo"));
CreateFile(persistent_directory_.AppendASCII("id_bar.local"));
CreateFile(persistent_directory_.AppendASCII("id_baz.local"));
CreateFile(persistent_directory_.AppendASCII("id_bad.md5bad"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
persistent_directory_.AppendASCII("id_symlink"));
CreateFile(tmp_directory_.AppendASCII("id_qux.md5qux"));
CreateFile(tmp_directory_.AppendASCII("id_quux.local"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
tmp_directory_.AppendASCII("id_symlink_tmp"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"),
pinned_directory_.AppendASCII("id_foo"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
pinned_directory_.AppendASCII("id_corge"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_dangling.md5foo"),
pinned_directory_.AppendASCII("id_dangling"));
CreateSymbolicLink(tmp_directory_.AppendASCII("id_qux.md5qux"),
pinned_directory_.AppendASCII("id_outside"));
CreateFile(pinned_directory_.AppendASCII("id_not_symlink"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_bar.local"),
outgoing_directory_.AppendASCII("id_bar"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"),
outgoing_directory_.AppendASCII("id_foo"));
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void SetUpCacheWithVariousFiles() {
std::vector<FilePath> empty_cache_paths;
metadata_->Initialize(empty_cache_paths);
}
| 170,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BufferMeta(size_t size)
: mSize(size),
mIsBackup(false) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | BufferMeta(size_t size)
BufferMeta(size_t size, OMX_U32 portIndex)
: mSize(size),
mIsBackup(false),
mPortIndex(portIndex) {
}
| 173,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < le32_to_cpu(lvd->mapTableLength);
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
Commit Message: udf: Avoid run away loop when partition table length is corrupted
Check provided length of partition table so that (possibly maliciously)
corrupted partition table cannot cause accessing data beyond current buffer.
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-119 | static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
| 165,587 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static noinline int btrfs_mksubvol(struct path *parent,
char *name, int namelen,
struct btrfs_root *snap_src,
u64 *async_transid, bool readonly,
struct btrfs_qgroup_inherit **inherit)
{
struct inode *dir = parent->dentry->d_inode;
struct dentry *dentry;
int error;
mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
dentry = lookup_one_len(name, parent->dentry, namelen);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = -EEXIST;
if (dentry->d_inode)
goto out_dput;
error = btrfs_may_create(dir, dentry);
if (error)
goto out_dput;
down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
goto out_up_read;
if (snap_src) {
error = create_snapshot(snap_src, dentry, name, namelen,
async_transid, readonly, inherit);
} else {
error = create_subvol(BTRFS_I(dir)->root, dentry,
name, namelen, async_transid, inherit);
}
if (!error)
fsnotify_mkdir(dir, dentry);
out_up_read:
up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&dir->i_mutex);
return error;
}
Commit Message: Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>
CWE ID: CWE-310 | static noinline int btrfs_mksubvol(struct path *parent,
char *name, int namelen,
struct btrfs_root *snap_src,
u64 *async_transid, bool readonly,
struct btrfs_qgroup_inherit **inherit)
{
struct inode *dir = parent->dentry->d_inode;
struct dentry *dentry;
int error;
mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
dentry = lookup_one_len(name, parent->dentry, namelen);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = -EEXIST;
if (dentry->d_inode)
goto out_dput;
error = btrfs_may_create(dir, dentry);
if (error)
goto out_dput;
/*
* even if this name doesn't exist, we may get hash collisions.
* check for them now when we can safely fail
*/
error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
dir->i_ino, name,
namelen);
if (error)
goto out_dput;
down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
goto out_up_read;
if (snap_src) {
error = create_snapshot(snap_src, dentry, name, namelen,
async_transid, readonly, inherit);
} else {
error = create_subvol(BTRFS_I(dir)->root, dentry,
name, namelen, async_transid, inherit);
}
if (!error)
fsnotify_mkdir(dir, dentry);
out_up_read:
up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&dir->i_mutex);
return error;
}
| 166,195 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Cluster* Cluster::Create(
Segment* pSegment,
long idx,
long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment,
idx,
element_start);
assert(pCluster);
return pCluster;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Cluster* Cluster::Create(
| 174,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct sk_buff *skb_segment(struct sk_buff *head_skb,
netdev_features_t features)
{
struct sk_buff *segs = NULL;
struct sk_buff *tail = NULL;
struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
skb_frag_t *frag = skb_shinfo(head_skb)->frags;
unsigned int mss = skb_shinfo(head_skb)->gso_size;
unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
unsigned int offset = doffset;
unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
unsigned int headroom;
unsigned int len;
__be16 proto;
bool csum;
int sg = !!(features & NETIF_F_SG);
int nfrags = skb_shinfo(head_skb)->nr_frags;
int err = -ENOMEM;
int i = 0;
int pos;
proto = skb_network_protocol(head_skb);
if (unlikely(!proto))
return ERR_PTR(-EINVAL);
csum = !!can_checksum_protocol(features, proto);
__skb_push(head_skb, doffset);
headroom = skb_headroom(head_skb);
pos = skb_headlen(head_skb);
do {
struct sk_buff *nskb;
skb_frag_t *nskb_frag;
int hsize;
int size;
len = head_skb->len - offset;
if (len > mss)
len = mss;
hsize = skb_headlen(head_skb) - offset;
if (hsize < 0)
hsize = 0;
if (hsize > len || !sg)
hsize = len;
if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
(skb_headlen(list_skb) == len || sg)) {
BUG_ON(skb_headlen(list_skb) > len);
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
pos += skb_headlen(list_skb);
while (pos < offset + len) {
BUG_ON(i >= nfrags);
size = skb_frag_size(frag);
if (pos + size > offset + len)
break;
i++;
pos += size;
frag++;
}
nskb = skb_clone(list_skb, GFP_ATOMIC);
list_skb = list_skb->next;
if (unlikely(!nskb))
goto err;
if (unlikely(pskb_trim(nskb, len))) {
kfree_skb(nskb);
goto err;
}
hsize = skb_end_offset(nskb);
if (skb_cow_head(nskb, doffset + headroom)) {
kfree_skb(nskb);
goto err;
}
nskb->truesize += skb_end_offset(nskb) - hsize;
skb_release_head_state(nskb);
__skb_push(nskb, doffset);
} else {
nskb = __alloc_skb(hsize + doffset + headroom,
GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
NUMA_NO_NODE);
if (unlikely(!nskb))
goto err;
skb_reserve(nskb, headroom);
__skb_put(nskb, doffset);
}
if (segs)
tail->next = nskb;
else
segs = nskb;
tail = nskb;
__copy_skb_header(nskb, head_skb);
nskb->mac_len = head_skb->mac_len;
skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
nskb->data - tnl_hlen,
doffset + tnl_hlen);
if (nskb->len == len + doffset)
goto perform_csum_check;
if (!sg) {
nskb->ip_summed = CHECKSUM_NONE;
nskb->csum = skb_copy_and_csum_bits(head_skb, offset,
skb_put(nskb, len),
len, 0);
continue;
}
nskb_frag = skb_shinfo(nskb)->frags;
skb_copy_from_linear_data_offset(head_skb, offset,
skb_put(nskb, hsize), hsize);
skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
SKBTX_SHARED_FRAG;
while (pos < offset + len) {
if (i >= nfrags) {
BUG_ON(skb_headlen(list_skb));
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
BUG_ON(!nfrags);
list_skb = list_skb->next;
}
if (unlikely(skb_shinfo(nskb)->nr_frags >=
MAX_SKB_FRAGS)) {
net_warn_ratelimited(
"skb_segment: too many frags: %u %u\n",
pos, mss);
goto err;
}
*nskb_frag = *frag;
__skb_frag_ref(nskb_frag);
size = skb_frag_size(nskb_frag);
if (pos < offset) {
nskb_frag->page_offset += offset - pos;
skb_frag_size_sub(nskb_frag, offset - pos);
}
skb_shinfo(nskb)->nr_frags++;
if (pos + size <= offset + len) {
i++;
frag++;
pos += size;
} else {
skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
goto skip_fraglist;
}
nskb_frag++;
}
skip_fraglist:
nskb->data_len = len - hsize;
nskb->len += nskb->data_len;
nskb->truesize += nskb->data_len;
perform_csum_check:
if (!csum) {
nskb->csum = skb_checksum(nskb, doffset,
nskb->len - doffset, 0);
nskb->ip_summed = CHECKSUM_NONE;
}
} while ((offset += len) < head_skb->len);
return segs;
err:
kfree_skb_list(segs);
return ERR_PTR(err);
}
Commit Message: skbuff: skb_segment: orphan frags before copying
skb_segment copies frags around, so we need
to copy them carefully to avoid accessing
user memory after reporting completion to userspace
through a callback.
skb_segment doesn't normally happen on datapath:
TSO needs to be disabled - so disabling zero copy
in this case does not look like a big deal.
Signed-off-by: Michael S. Tsirkin <[email protected]>
Acked-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | struct sk_buff *skb_segment(struct sk_buff *head_skb,
netdev_features_t features)
{
struct sk_buff *segs = NULL;
struct sk_buff *tail = NULL;
struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
skb_frag_t *frag = skb_shinfo(head_skb)->frags;
unsigned int mss = skb_shinfo(head_skb)->gso_size;
unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
struct sk_buff *frag_skb = head_skb;
unsigned int offset = doffset;
unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
unsigned int headroom;
unsigned int len;
__be16 proto;
bool csum;
int sg = !!(features & NETIF_F_SG);
int nfrags = skb_shinfo(head_skb)->nr_frags;
int err = -ENOMEM;
int i = 0;
int pos;
proto = skb_network_protocol(head_skb);
if (unlikely(!proto))
return ERR_PTR(-EINVAL);
csum = !!can_checksum_protocol(features, proto);
__skb_push(head_skb, doffset);
headroom = skb_headroom(head_skb);
pos = skb_headlen(head_skb);
do {
struct sk_buff *nskb;
skb_frag_t *nskb_frag;
int hsize;
int size;
len = head_skb->len - offset;
if (len > mss)
len = mss;
hsize = skb_headlen(head_skb) - offset;
if (hsize < 0)
hsize = 0;
if (hsize > len || !sg)
hsize = len;
if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
(skb_headlen(list_skb) == len || sg)) {
BUG_ON(skb_headlen(list_skb) > len);
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
pos += skb_headlen(list_skb);
while (pos < offset + len) {
BUG_ON(i >= nfrags);
size = skb_frag_size(frag);
if (pos + size > offset + len)
break;
i++;
pos += size;
frag++;
}
nskb = skb_clone(list_skb, GFP_ATOMIC);
list_skb = list_skb->next;
if (unlikely(!nskb))
goto err;
if (unlikely(pskb_trim(nskb, len))) {
kfree_skb(nskb);
goto err;
}
hsize = skb_end_offset(nskb);
if (skb_cow_head(nskb, doffset + headroom)) {
kfree_skb(nskb);
goto err;
}
nskb->truesize += skb_end_offset(nskb) - hsize;
skb_release_head_state(nskb);
__skb_push(nskb, doffset);
} else {
nskb = __alloc_skb(hsize + doffset + headroom,
GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
NUMA_NO_NODE);
if (unlikely(!nskb))
goto err;
skb_reserve(nskb, headroom);
__skb_put(nskb, doffset);
}
if (segs)
tail->next = nskb;
else
segs = nskb;
tail = nskb;
__copy_skb_header(nskb, head_skb);
nskb->mac_len = head_skb->mac_len;
skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
nskb->data - tnl_hlen,
doffset + tnl_hlen);
if (nskb->len == len + doffset)
goto perform_csum_check;
if (!sg) {
nskb->ip_summed = CHECKSUM_NONE;
nskb->csum = skb_copy_and_csum_bits(head_skb, offset,
skb_put(nskb, len),
len, 0);
continue;
}
nskb_frag = skb_shinfo(nskb)->frags;
skb_copy_from_linear_data_offset(head_skb, offset,
skb_put(nskb, hsize), hsize);
skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
SKBTX_SHARED_FRAG;
while (pos < offset + len) {
if (i >= nfrags) {
BUG_ON(skb_headlen(list_skb));
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
BUG_ON(!nfrags);
list_skb = list_skb->next;
}
if (unlikely(skb_shinfo(nskb)->nr_frags >=
MAX_SKB_FRAGS)) {
net_warn_ratelimited(
"skb_segment: too many frags: %u %u\n",
pos, mss);
goto err;
}
if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
goto err;
*nskb_frag = *frag;
__skb_frag_ref(nskb_frag);
size = skb_frag_size(nskb_frag);
if (pos < offset) {
nskb_frag->page_offset += offset - pos;
skb_frag_size_sub(nskb_frag, offset - pos);
}
skb_shinfo(nskb)->nr_frags++;
if (pos + size <= offset + len) {
i++;
frag++;
pos += size;
} else {
skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
goto skip_fraglist;
}
nskb_frag++;
}
skip_fraglist:
nskb->data_len = len - hsize;
nskb->len += nskb->data_len;
nskb->truesize += nskb->data_len;
perform_csum_check:
if (!csum) {
nskb->csum = skb_checksum(nskb, doffset,
nskb->len - doffset, 0);
nskb->ip_summed = CHECKSUM_NONE;
}
} while ((offset += len) < head_skb->len);
return segs;
err:
kfree_skb_list(segs);
return ERR_PTR(err);
}
| 166,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
const EVP_MD *digest;
VALUE vpass, vsalt, viter, vdigest;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
ossl_raise(eCipherError, "salt must be an 8-octet string");
salt = (unsigned char *)RSTRING_PTR(vsalt);
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
(unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
ossl_raise(eCipherError, NULL);
OPENSSL_cleanse(key, sizeof key);
OPENSSL_cleanse(iv, sizeof iv);
return Qnil;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310 | ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
const EVP_MD *digest;
VALUE vpass, vsalt, viter, vdigest;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
ossl_raise(eCipherError, "salt must be an 8-octet string");
salt = (unsigned char *)RSTRING_PTR(vsalt);
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
(unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
ossl_raise(eCipherError, NULL);
OPENSSL_cleanse(key, sizeof key);
OPENSSL_cleanse(iv, sizeof iv);
rb_ivar_set(self, id_key_set, Qtrue);
return Qnil;
}
| 168,781 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.