instruction
stringclasses 1
value | input
stringlengths 56
235k
| output
int64 0
1
| __index_level_0__
int64 0
175k
|
|---|---|---|---|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int uvesafb_helper_start(void)
{
char *envp[] = {
"HOME=/",
"PATH=/sbin:/bin",
NULL,
};
char *argv[] = {
v86d_path,
NULL,
};
return call_usermodehelper(v86d_path, argv, envp, UMH_WAIT_PROC);
}
Commit Message: video: uvesafb: Fix integer overflow in allocation
cmap->len can get close to INT_MAX/2, allowing for an integer overflow in
allocation. This uses kmalloc_array() instead to catch the condition.
Reported-by: Dr Silvio Cesare of InfoSect <[email protected]>
Fixes: 8bdb3a2d7df48 ("uvesafb: the driver core")
Cc: [email protected]
Signed-off-by: Kees Cook <[email protected]>
CWE ID: CWE-190
| 0
| 79,775
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void dump_data_hex(FILE *trace, char *data, u32 dataLength)
{
u32 i;
fprintf(trace, "0x");
for (i=0; i<dataLength; i++) {
fprintf(trace, "%02X", (unsigned char) data[i]);
}
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
| 0
| 80,718
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: std::string CreateServerRedirect(const std::string& dest_url) {
const char* const kServerRedirectBase = "server-redirect?";
return kServerRedirectBase + dest_url;
}
Commit Message: Update PrerenderBrowserTests to work with new
PrerenderContents.
Also update PrerenderContents to pass plugin
and HTML5 prerender tests.
BUG=81229
TEST=PrerenderBrowserTests (Once the new code is enabled)
Review URL: http://codereview.chromium.org/6905169
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83841 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
| 0
| 99,955
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: get_key(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
char *filename, const char *fsname, EVP_PKEY **retkey,
const char *password)
{
EVP_PKEY *pkey = NULL;
BIO *tmp = NULL;
struct get_key_cb_data cb_data;
int code;
krb5_error_code retval;
if (filename == NULL || retkey == NULL)
return EINVAL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cb_data.context = context;
cb_data.id_cryptoctx = id_cryptoctx;
cb_data.filename = filename;
cb_data.fsname = fsname;
cb_data.password = password;
pkey = PEM_read_bio_PrivateKey(tmp, NULL, get_key_cb, &cb_data);
if (pkey == NULL && !id_cryptoctx->defer_id_prompt) {
retval = EIO;
pkiDebug("failed to read private key from %s\n", filename);
goto cleanup;
}
*retkey = pkey;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
Commit Message: Fix PKINIT cert matching data construction
Rewrite X509_NAME_oneline_ex() and its call sites to use dynamic
allocation and to perform proper error checking.
ticket: 8617
target_version: 1.16
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-119
| 0
| 60,735
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static long ioctl_file_clone_range(struct file *file, void __user *argp)
{
struct file_clone_range args;
if (copy_from_user(&args, argp, sizeof(args)))
return -EFAULT;
return ioctl_file_clone(file, args.src_fd, args.src_offset,
args.src_length, args.dest_offset);
}
Commit Message: vfs: ioctl: prevent double-fetch in dedupe ioctl
This prevents a double-fetch from user space that can lead to to an
undersized allocation and heap overflow.
Fixes: 54dbc1517237 ("vfs: hoist the btrfs deduplication ioctl to the vfs")
Signed-off-by: Scott Bauer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119
| 0
| 50,582
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: struct vhost_ubuf_ref *vhost_ubuf_alloc(struct vhost_virtqueue *vq,
bool zcopy)
{
struct vhost_ubuf_ref *ubufs;
/* No zero copy backend? Nothing to count. */
if (!zcopy)
return NULL;
ubufs = kmalloc(sizeof *ubufs, GFP_KERNEL);
if (!ubufs)
return ERR_PTR(-ENOMEM);
kref_init(&ubufs->kref);
init_waitqueue_head(&ubufs->wait);
ubufs->vq = vq;
return ubufs;
}
Commit Message: vhost: fix length for cross region descriptor
If a single descriptor crosses a region, the
second chunk length should be decremented
by size translated so far, instead it includes
the full descriptor length.
Signed-off-by: Michael S. Tsirkin <[email protected]>
Acked-by: Jason Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
| 0
| 33,807
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
{
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
*to_sec = ctx->byte_timeout.tv_sec;
*to_usec = ctx->byte_timeout.tv_usec;
return 0;
}
Commit Message: Fix VD-1301 and VD-1302 vulnerabilities
This patch was contributed by Maor Vermucht and Or Peles from
VDOO Connected Trust.
CWE ID: CWE-125
| 0
| 88,728
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: xfs_vn_get_link(
struct dentry *dentry,
struct inode *inode,
struct delayed_call *done)
{
char *link;
int error = -ENOMEM;
if (!dentry)
return ERR_PTR(-ECHILD);
link = kmalloc(XFS_SYMLINK_MAXLEN+1, GFP_KERNEL);
if (!link)
goto out_err;
error = xfs_readlink(XFS_I(d_inode(dentry)), link);
if (unlikely(error))
goto out_kfree;
set_delayed_call(done, kfree_link, link);
return link;
out_kfree:
kfree(link);
out_err:
return ERR_PTR(error);
}
Commit Message: xfs: fix missing ILOCK unlock when xfs_setattr_nonsize fails due to EDQUOT
Benjamin Moody reported to Debian that XFS partially wedges when a chgrp
fails on account of being out of disk quota. I ran his reproducer
script:
# adduser dummy
# adduser dummy plugdev
# dd if=/dev/zero bs=1M count=100 of=test.img
# mkfs.xfs test.img
# mount -t xfs -o gquota test.img /mnt
# mkdir -p /mnt/dummy
# chown -c dummy /mnt/dummy
# xfs_quota -xc 'limit -g bsoft=100k bhard=100k plugdev' /mnt
(and then as user dummy)
$ dd if=/dev/urandom bs=1M count=50 of=/mnt/dummy/foo
$ chgrp plugdev /mnt/dummy/foo
and saw:
================================================
WARNING: lock held when returning to user space!
5.3.0-rc5 #rc5 Tainted: G W
------------------------------------------------
chgrp/47006 is leaving the kernel with locks still held!
1 lock held by chgrp/47006:
#0: 000000006664ea2d (&xfs_nondir_ilock_class){++++}, at: xfs_ilock+0xd2/0x290 [xfs]
...which is clearly caused by xfs_setattr_nonsize failing to unlock the
ILOCK after the xfs_qm_vop_chown_reserve call fails. Add the missing
unlock.
Reported-by: [email protected]
Fixes: 253f4911f297 ("xfs: better xfs_trans_alloc interface")
Signed-off-by: Darrick J. Wong <[email protected]>
Reviewed-by: Dave Chinner <[email protected]>
Tested-by: Salvatore Bonaccorso <[email protected]>
CWE ID: CWE-399
| 0
| 88,341
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int format_set(format_list *pf, png_uint_32 format)
{
if (format < FORMAT_COUNT)
return pf->bits[format >> 5] |= ((png_uint_32)1) << (format & 31);
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
| 0
| 159,872
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: no_email_faults_handler(__attribute__((unused))vector_t *strvec)
{
global_data->no_email_faults = true;
}
Commit Message: Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-200
| 0
| 75,840
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: kadm5_modify_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask)
{
int ret, ret2, i;
kadm5_policy_ent_rec pol;
krb5_boolean have_pol = FALSE;
krb5_db_entry *kdb;
krb5_tl_data *tl_data_orig;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) ||
(mask & KADM5_LAST_FAILED))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if(entry == (kadm5_principal_ent_t) NULL)
return EINVAL;
if (mask & KADM5_TL_DATA) {
tl_data_orig = entry->tl_data;
while (tl_data_orig) {
if (tl_data_orig->tl_data_type < 256)
return KADM5_BAD_TL_TYPE;
tl_data_orig = tl_data_orig->tl_data_next;
}
}
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
if (ret)
return(ret);
/*
* This is pretty much the same as create ...
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &pol, &have_pol);
if (ret)
goto done;
/* set us up to use the new policy */
adb.aux_attributes |= KADM5_POLICY;
if (adb.policy)
free(adb.policy);
adb.policy = strdup(entry->policy);
}
if (have_pol) {
/* set pw_max_life based on new policy */
if (pol.pw_max_life) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(kdb->pw_expiration));
if (ret)
goto done;
kdb->pw_expiration += pol.pw_max_life;
} else {
kdb->pw_expiration = 0;
}
}
if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) {
free(adb.policy);
adb.policy = NULL;
adb.aux_attributes &= ~KADM5_POLICY;
kdb->pw_expiration = 0;
}
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
if (mask & KADM5_PW_EXPIRATION)
kdb->pw_expiration = entry->pw_expiration;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
if((mask & KADM5_KVNO)) {
for (i = 0; i < kdb->n_key_data; i++)
kdb->key_data[i].key_data_kvno = entry->kvno;
}
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl;
/* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */
for (tl = entry->tl_data; tl;
tl = tl->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl);
if( ret )
{
goto done;
}
}
}
/*
* Setting entry->fail_auth_count to 0 can be used to manually unlock
* an account. It is not possible to set fail_auth_count to any other
* value using kadmin.
*/
if (mask & KADM5_FAIL_AUTH_COUNT) {
if (entry->fail_auth_count != 0) {
ret = KADM5_BAD_SERVER_PARAMS;
goto done;
}
kdb->fail_auth_count = 0;
}
/* let the mask propagate to the database provider */
kdb->mask = mask;
ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask);
if (ret)
goto done;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret) goto done;
(void) k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask);
ret = KADM5_OK;
done:
if (have_pol) {
ret2 = kadm5_free_policy_ent(handle->lhandle, &pol);
ret = ret ? ret : ret2;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
Commit Message: Check for null kadm5 policy name [CVE-2015-8630]
In kadm5_create_principal_3() and kadm5_modify_principal(), check for
entry->policy being null when KADM5_POLICY is included in the mask.
CVE-2015-8630:
In MIT krb5 1.12 and later, an authenticated attacker with permission
to modify a principal entry can cause kadmind to dereference a null
pointer by supplying a null policy value but including KADM5_POLICY in
the mask.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8342 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID:
| 1
| 167,529
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
unsigned long __user *, nmask, unsigned long, maxnode,
unsigned long, addr, unsigned long, flags)
{
int err;
int uninitialized_var(pval);
nodemask_t nodes;
if (nmask != NULL && maxnode < MAX_NUMNODES)
return -EINVAL;
err = do_get_mempolicy(&pval, &nodes, addr, flags);
if (err)
return err;
if (policy && put_user(pval, policy))
return -EFAULT;
if (nmask)
err = copy_nodes_to_user(nmask, maxnode, &nodes);
return err;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
| 0
| 21,286
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: megasas_decode_evt(struct megasas_instance *instance)
{
struct megasas_evt_detail *evt_detail = instance->evt_detail;
union megasas_evt_class_locale class_locale;
class_locale.word = le32_to_cpu(evt_detail->cl.word);
if (class_locale.members.class >= MFI_EVT_CLASS_CRITICAL)
dev_info(&instance->pdev->dev, "%d (%s/0x%04x/%s) - %s\n",
le32_to_cpu(evt_detail->seq_num),
format_timestamp(le32_to_cpu(evt_detail->time_stamp)),
(class_locale.members.locale),
format_class(class_locale.members.class),
evt_detail->description);
}
Commit Message: scsi: megaraid_sas: return error when create DMA pool failed
when create DMA pool for cmd frames failed, we should return -ENOMEM,
instead of 0.
In some case in:
megasas_init_adapter_fusion()
-->megasas_alloc_cmds()
-->megasas_create_frame_pool
create DMA pool failed,
--> megasas_free_cmds() [1]
-->megasas_alloc_cmds_fusion()
failed, then goto fail_alloc_cmds.
-->megasas_free_cmds() [2]
we will call megasas_free_cmds twice, [1] will kfree cmd_list,
[2] will use cmd_list.it will cause a problem:
Unable to handle kernel NULL pointer dereference at virtual address
00000000
pgd = ffffffc000f70000
[00000000] *pgd=0000001fbf893003, *pud=0000001fbf893003,
*pmd=0000001fbf894003, *pte=006000006d000707
Internal error: Oops: 96000005 [#1] SMP
Modules linked in:
CPU: 18 PID: 1 Comm: swapper/0 Not tainted
task: ffffffdfb9290000 ti: ffffffdfb923c000 task.ti: ffffffdfb923c000
PC is at megasas_free_cmds+0x30/0x70
LR is at megasas_free_cmds+0x24/0x70
...
Call trace:
[<ffffffc0005b779c>] megasas_free_cmds+0x30/0x70
[<ffffffc0005bca74>] megasas_init_adapter_fusion+0x2f4/0x4d8
[<ffffffc0005b926c>] megasas_init_fw+0x2dc/0x760
[<ffffffc0005b9ab0>] megasas_probe_one+0x3c0/0xcd8
[<ffffffc0004a5abc>] local_pci_probe+0x4c/0xb4
[<ffffffc0004a5c40>] pci_device_probe+0x11c/0x14c
[<ffffffc00053a5e4>] driver_probe_device+0x1ec/0x430
[<ffffffc00053a92c>] __driver_attach+0xa8/0xb0
[<ffffffc000538178>] bus_for_each_dev+0x74/0xc8
[<ffffffc000539e88>] driver_attach+0x28/0x34
[<ffffffc000539a18>] bus_add_driver+0x16c/0x248
[<ffffffc00053b234>] driver_register+0x6c/0x138
[<ffffffc0004a5350>] __pci_register_driver+0x5c/0x6c
[<ffffffc000ce3868>] megasas_init+0xc0/0x1a8
[<ffffffc000082a58>] do_one_initcall+0xe8/0x1ec
[<ffffffc000ca7be8>] kernel_init_freeable+0x1c8/0x284
[<ffffffc0008d90b8>] kernel_init+0x1c/0xe4
Signed-off-by: Jason Yan <[email protected]>
Acked-by: Sumit Saxena <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-476
| 0
| 90,318
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: bool ChromeContentRendererClient::ShouldOverridePageVisibilityState(
const content::RenderView* render_view,
WebKit::WebPageVisibilityState* override_state) const {
if (!prerender::PrerenderHelper::IsPrerendering(render_view))
return false;
*override_state = WebKit::WebPageVisibilityStatePrerender;
return true;
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
| 0
| 108,155
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void reds_on_main_mouse_mode_request(void *message, size_t size)
{
switch (((SpiceMsgcMainMouseModeRequest *)message)->mode) {
case SPICE_MOUSE_MODE_CLIENT:
if (reds->is_client_mouse_allowed) {
reds_set_mouse_mode(SPICE_MOUSE_MODE_CLIENT);
} else {
spice_info("client mouse is disabled");
}
break;
case SPICE_MOUSE_MODE_SERVER:
reds_set_mouse_mode(SPICE_MOUSE_MODE_SERVER);
break;
default:
spice_warning("unsupported mouse mode");
}
}
Commit Message:
CWE ID: CWE-119
| 0
| 1,921
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void ohci_set_ctl(OHCIState *ohci, uint32_t val)
{
uint32_t old_state;
uint32_t new_state;
old_state = ohci->ctl & OHCI_CTL_HCFS;
ohci->ctl = val;
new_state = ohci->ctl & OHCI_CTL_HCFS;
/* no state change */
if (old_state == new_state)
return;
trace_usb_ohci_set_ctl(ohci->name, new_state);
switch (new_state) {
case OHCI_USB_OPERATIONAL:
ohci_bus_start(ohci);
break;
case OHCI_USB_SUSPEND:
ohci_bus_stop(ohci);
/* clear pending SF otherwise linux driver loops in ohci_irq() */
ohci->intr_status &= ~OHCI_INTR_SF;
ohci_intr_update(ohci);
break;
case OHCI_USB_RESUME:
trace_usb_ohci_resume(ohci->name);
break;
case OHCI_USB_RESET:
ohci_roothub_reset(ohci);
break;
}
}
Commit Message:
CWE ID: CWE-835
| 0
| 5,938
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void QQuickWebViewPrivate::FlickableAxisLocker::reset()
{
m_allowedDirection = QQuickFlickable::AutoFlickDirection;
m_sampleCount = 0;
}
Commit Message: [Qt][WK2] There's no way to test the gesture tap on WTR
https://bugs.webkit.org/show_bug.cgi?id=92895
Reviewed by Kenneth Rohde Christiansen.
Source/WebKit2:
Add an instance of QtViewportHandler to QQuickWebViewPrivate, so it's
now available on mobile and desktop modes, as a side effect gesture tap
events can now be created and sent to WebCore.
This is needed to test tap gestures and to get tap gestures working
when you have a WebView (in desktop mode) on notebooks equipped with
touch screens.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::onComponentComplete):
(QQuickWebViewFlickablePrivate::onComponentComplete): Implementation
moved to QQuickWebViewPrivate::onComponentComplete.
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
(QQuickWebViewFlickablePrivate):
Tools:
WTR doesn't create the QQuickItem from C++, not from QML, so a call
to componentComplete() was added to mimic the QML behaviour.
* WebKitTestRunner/qt/PlatformWebViewQt.cpp:
(WTR::PlatformWebView::PlatformWebView):
git-svn-id: svn://svn.chromium.org/blink/trunk@124625 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
| 0
| 108,029
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: TabSpecificContentSettings::SiteDataObserver::~SiteDataObserver() {
if (tab_specific_content_settings_)
tab_specific_content_settings_->RemoveSiteDataObserver(this);
}
Commit Message: Check the content setting type is valid.
BUG=169770
Review URL: https://codereview.chromium.org/11875013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176687 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
| 0
| 117,354
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int opfdivrp(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xde;
data[l++] = 0xf1;
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xde;
data[l++] = 0xf0 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
Commit Message: Fix #12372 and #12373 - Crash in x86 assembler (#12380)
0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL-
mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL-
leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL-
mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
CWE ID: CWE-125
| 0
| 75,393
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement(
const SecurityOrigin* security_origin,
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLenum format,
GLenum type,
GLint xoffset,
GLint yoffset,
GLint zoffset,
HTMLVideoElement* video,
const IntRect& source_image_rect,
GLsizei depth,
GLint unpack_image_height,
ExceptionState& exception_state) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
if (!ValidateHTMLVideoElement(security_origin, func_name, video,
exception_state))
return;
WebGLTexture* texture =
ValidateTexImageBinding(func_name, function_id, target);
if (!texture)
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement,
target, level, internalformat, video->videoWidth(),
video->videoHeight(), 1, 0, format, type, xoffset,
yoffset, zoffset))
return;
GLint adjusted_internalformat =
ConvertTexInternalFormat(internalformat, type);
WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {};
int already_uploaded_id = -1;
WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr;
if (RuntimeEnabledFeatures::ExtraWebGLVideoTextureMetadataEnabled()) {
already_uploaded_id = texture->GetLastUploadedVideoFrameId();
frame_metadata_ptr = &frame_metadata;
}
if (!source_image_rect.IsValid()) {
SynthesizeGLError(GL_INVALID_OPERATION, func_name,
"source sub-rectangle specified via pixel unpack "
"parameters is invalid");
return;
}
bool source_image_rect_is_default =
source_image_rect == SentinelEmptyRect() ||
source_image_rect ==
IntRect(0, 0, video->videoWidth(), video->videoHeight());
const bool use_copyTextureCHROMIUM = function_id == kTexImage2D &&
source_image_rect_is_default &&
depth == 1 && GL_TEXTURE_2D == target &&
CanUseTexImageViaGPU(format, type);
if (use_copyTextureCHROMIUM) {
DCHECK(Extensions3DUtil::CanUseCopyTextureCHROMIUM(target));
DCHECK_EQ(xoffset, 0);
DCHECK_EQ(yoffset, 0);
DCHECK_EQ(zoffset, 0);
if (video->CopyVideoTextureToPlatformTexture(
ContextGL(), target, texture->Object(), adjusted_internalformat,
format, type, level, unpack_premultiply_alpha_, unpack_flip_y_,
already_uploaded_id, frame_metadata_ptr)) {
texture->UpdateLastUploadedFrame(frame_metadata);
return;
}
if (video->CopyVideoYUVDataToPlatformTexture(
ContextGL(), target, texture->Object(), adjusted_internalformat,
format, type, level, unpack_premultiply_alpha_, unpack_flip_y_,
already_uploaded_id, frame_metadata_ptr)) {
texture->UpdateLastUploadedFrame(frame_metadata);
return;
}
}
if (source_image_rect_is_default) {
ScopedUnpackParametersResetRestore(
this, unpack_flip_y_ || unpack_premultiply_alpha_);
if (video->TexImageImpl(
static_cast<WebMediaPlayer::TexImageFunctionID>(function_id),
target, ContextGL(), texture->Object(), level,
adjusted_internalformat, format, type, xoffset, yoffset, zoffset,
unpack_flip_y_,
unpack_premultiply_alpha_ &&
unpack_colorspace_conversion_ == GL_NONE)) {
texture->ClearLastUploadedFrame();
return;
}
}
scoped_refptr<Image> image =
VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr);
if (!image)
return;
TexImageImpl(function_id, target, level, adjusted_internalformat, xoffset,
yoffset, zoffset, format, type, image.get(),
WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_,
unpack_premultiply_alpha_, source_image_rect, depth,
unpack_image_height);
texture->UpdateLastUploadedFrame(frame_metadata);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
| 0
| 142,292
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void perf_event_update_userpage(struct perf_event *event)
{
struct perf_event_mmap_page *userpg;
struct ring_buffer *rb;
u64 enabled, running, now;
rcu_read_lock();
/*
* compute total_time_enabled, total_time_running
* based on snapshot values taken when the event
* was last scheduled in.
*
* we cannot simply called update_context_time()
* because of locking issue as we can be called in
* NMI context
*/
calc_timer_values(event, &now, &enabled, &running);
rb = rcu_dereference(event->rb);
if (!rb)
goto unlock;
userpg = rb->user_page;
/*
* Disable preemption so as to not let the corresponding user-space
* spin too long if we get preempted.
*/
preempt_disable();
++userpg->lock;
barrier();
userpg->index = perf_event_index(event);
userpg->offset = perf_event_count(event);
if (userpg->index)
userpg->offset -= local64_read(&event->hw.prev_count);
userpg->time_enabled = enabled +
atomic64_read(&event->child_total_time_enabled);
userpg->time_running = running +
atomic64_read(&event->child_total_time_running);
arch_perf_update_userpage(userpg, now);
barrier();
++userpg->lock;
preempt_enable();
unlock:
rcu_read_unlock();
}
Commit Message: perf: Treat attr.config as u64 in perf_swevent_init()
Trinity discovered that we fail to check all 64 bits of
attr.config passed by user space, resulting to out-of-bounds
access of the perf_swevent_enabled array in
sw_perf_event_destroy().
Introduced in commit b0a873ebb ("perf: Register PMU
implementations").
Signed-off-by: Tommi Rantala <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: [email protected]
Cc: Paul Mackerras <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-189
| 0
| 31,956
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int crypto_cbcmac_digest_setkey(struct crypto_shash *parent,
const u8 *inkey, unsigned int keylen)
{
struct cbcmac_tfm_ctx *ctx = crypto_shash_ctx(parent);
return crypto_cipher_setkey(ctx->child, inkey, keylen);
}
Commit Message: crypto: ccm - move cbcmac input off the stack
Commit f15f05b0a5de ("crypto: ccm - switch to separate cbcmac driver")
refactored the CCM driver to allow separate implementations of the
underlying MAC to be provided by a platform. However, in doing so, it
moved some data from the linear region to the stack, which violates the
SG constraints when the stack is virtually mapped.
So move idata/odata back to the request ctx struct, of which we can
reasonably expect that it has been allocated using kmalloc() et al.
Reported-by: Johannes Berg <[email protected]>
Fixes: f15f05b0a5de ("crypto: ccm - switch to separate cbcmac driver")
Signed-off-by: Ard Biesheuvel <[email protected]>
Tested-by: Johannes Berg <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-119
| 0
| 66,650
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void hrtick_start(struct rq *rq, u64 delay)
{
/*
* Don't schedule slices shorter than 10000ns, that just
* doesn't make sense. Rely on vruntime for fairness.
*/
delay = max_t(u64, delay, 10000LL);
hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
HRTIMER_MODE_REL_PINNED);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119
| 0
| 55,543
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: bool CommandsIssuedQuery::End(base::subtle::Atomic32 submit_count) {
base::TimeDelta elapsed = base::TimeTicks::HighResNow() - begin_time_;
MarkAsPending(submit_count);
return MarkAsCompleted(elapsed.InMicroseconds());
}
Commit Message: Add bounds validation to AsyncPixelTransfersCompletedQuery::End
BUG=351852
[email protected], [email protected]
Review URL: https://codereview.chromium.org/198253002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@256723 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
| 0
| 121,446
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void NavigateToURL(const net::EmbeddedTestServer& test_server,
const std::string& hostname,
const std::string& relative_url) {
NavigationObserver observer(WebContents());
GURL url = test_server.GetURL(hostname, relative_url);
ui_test_utils::NavigateToURL(browser(), url);
observer.Wait();
}
Commit Message: Fix Credential Management API Store() for existing Credentials
This changes fixes the Credential Management API to correctly handle
storing of already existing credentials. In the previous version
`preferred_match()` was updated, which is not necessarily the credential
selected by the user.
Bug: 795878
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: I269f465861f44cdd784f0ce077e755191d3bd7bd
Reviewed-on: https://chromium-review.googlesource.com/843022
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Maxim Kolosovskiy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#526313}
CWE ID: CWE-125
| 0
| 155,797
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: int re_yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
re_yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
re_yyfree(yyg->yy_buffer_stack ,yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
re_yyfree(yyg->yy_start_stack ,yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* re_yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
re_yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476
| 0
| 70,493
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void user_revoke(struct key *key)
{
struct user_key_payload *upayload = key->payload.data;
/* clear the quota */
key_payload_reserve(key, 0);
if (upayload) {
rcu_assign_keypointer(key, NULL);
kfree_rcu(upayload, rcu);
}
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476
| 0
| 69,561
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void tiff_unmapproc(thandle_t h, tdata_t d, toff_t o)
{
(void)h;
(void)d;
(void)o;
}
Commit Message: Fix invalid read in gdImageCreateFromTiffPtr()
tiff_invalid_read.tiff is corrupt, and causes an invalid read in
gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit
is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case,
dynamicGetbuf() is called with a negative dp->pos, but also positive buffer
overflows have to be handled, in which case 0 has to be returned (cf. commit
75e29a9).
Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create
the image, because the return value of TIFFReadRGBAImage() is not checked.
We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6911
CWE ID: CWE-125
| 0
| 73,740
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: int Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL ||
cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL ||
*replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL ||
*replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
if (pCmdData == NULL ||
cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL ||
*replySize < (sizeof(effect_param_t) + sizeof(int32_t))){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *)pCmdData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
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
| 1
| 173,350
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void PpapiPluginProcessHost::CancelRequests() {
DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
<< "CancelRequests()";
for (size_t i = 0; i < pending_requests_.size(); i++) {
pending_requests_[i]->OnPpapiChannelOpened(IPC::ChannelHandle(), 0);
}
pending_requests_.clear();
while (!sent_requests_.empty()) {
sent_requests_.front()->OnPpapiChannelOpened(IPC::ChannelHandle(), 0);
sent_requests_.pop();
}
}
Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins.
BUG=151895
Review URL: https://chromiumcodereview.appspot.com/10956065
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
| 0
| 103,140
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static pfn_t spte_to_pfn(u64 pte)
{
return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
}
Commit Message: nEPT: Nested INVEPT
If we let L1 use EPT, we should probably also support the INVEPT instruction.
In our current nested EPT implementation, when L1 changes its EPT table
for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in
the course of this modification already calls INVEPT. But if last level
of shadow page is unsync not all L1's changes to EPT12 are intercepted,
which means roots need to be synced when L1 calls INVEPT. Global INVEPT
should not be different since roots are synced by kvm_mmu_load() each
time EPTP02 changes.
Reviewed-by: Xiao Guangrong <[email protected]>
Signed-off-by: Nadav Har'El <[email protected]>
Signed-off-by: Jun Nakajima <[email protected]>
Signed-off-by: Xinhao Xu <[email protected]>
Signed-off-by: Yang Zhang <[email protected]>
Signed-off-by: Gleb Natapov <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20
| 0
| 37,593
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: PageInfo::PageInfo(
PageInfoUI* ui,
Profile* profile,
TabSpecificContentSettings* tab_specific_content_settings,
content::WebContents* web_contents,
const GURL& url,
security_state::SecurityLevel security_level,
const security_state::VisibleSecurityState& visible_security_state)
: TabSpecificContentSettings::SiteDataObserver(
tab_specific_content_settings),
content::WebContentsObserver(web_contents),
ui_(ui),
show_info_bar_(false),
site_url_(url),
site_identity_status_(SITE_IDENTITY_STATUS_UNKNOWN),
site_connection_status_(SITE_CONNECTION_STATUS_UNKNOWN),
show_ssl_decision_revoke_button_(false),
content_settings_(HostContentSettingsMapFactory::GetForProfile(profile)),
chrome_ssl_host_state_delegate_(
ChromeSSLHostStateDelegateFactory::GetForProfile(profile)),
did_revoke_user_ssl_decisions_(false),
profile_(profile),
security_level_(security_state::NONE),
#if defined(FULL_SAFE_BROWSING)
password_protection_service_(
safe_browsing::ChromePasswordProtectionService::
GetPasswordProtectionService(profile_)),
#endif
show_change_password_buttons_(false),
did_perform_action_(false) {
ComputeUIInputs(url, security_level, visible_security_state);
PresentSitePermissions();
PresentSiteIdentity();
PresentSiteData();
PresentPageFeatureInfo();
RecordPageInfoAction(PAGE_INFO_OPENED);
start_time_ = base::TimeTicks::Now();
}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <[email protected]>
> Reviewed-by: Bret Sepulveda <[email protected]>
> Auto-Submit: Joe DeBlasio <[email protected]>
> Commit-Queue: Joe DeBlasio <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#671847}
[email protected],[email protected],[email protected]
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <[email protected]>
Commit-Queue: Takashi Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311
| 0
| 138,003
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int hns_roce_set_mac(struct hns_roce_dev *hr_dev, u8 port, u8 *addr)
{
u8 phy_port;
u32 i = 0;
if (!memcmp(hr_dev->dev_addr[port], addr, MAC_ADDR_OCTET_NUM))
return 0;
for (i = 0; i < MAC_ADDR_OCTET_NUM; i++)
hr_dev->dev_addr[port][i] = addr[i];
phy_port = hr_dev->iboe.phy_port[port];
return hr_dev->hw->set_mac(hr_dev, phy_port, addr);
}
Commit Message: RDMA/hns: Fix init resp when alloc ucontext
The data in resp will be copied from kernel to userspace, thus it needs to
be initialized to zeros to avoid copying uninited stack memory.
Reported-by: Dan Carpenter <[email protected]>
Fixes: e088a685eae9 ("RDMA/hns: Support rq record doorbell for the user space")
Signed-off-by: Yixian Liu <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-665
| 0
| 87,749
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void DownloadManagerImpl::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
Commit Message: Downloads : Fixed an issue of opening incorrect download file
When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download.
Bug: 793620
Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8
Reviewed-on: https://chromium-review.googlesource.com/826477
Reviewed-by: David Trainor <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Commit-Queue: Shakti Sahu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#525810}
CWE ID: CWE-20
| 0
| 146,412
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: HTMLDocument::~HTMLDocument()
{
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
| 0
| 110,491
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: MODRET set_anonrequirepassword(cmd_rec *cmd) {
int bool = -1;
config_rec *c = NULL;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ANON);
bool = get_boolean(cmd, 1);
if (bool == -1)
CONF_ERROR(cmd, "expected Boolean parameter");
c = add_config_param(cmd->argv[0], 1, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
*((unsigned char *) c->argv[0]) = bool;
return PR_HANDLED(cmd);
}
Commit Message: Walk the entire DefaultRoot path, checking for symlinks of any component,
when AllowChrootSymlinks is disabled.
CWE ID: CWE-59
| 0
| 67,607
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void ResourceDispatcherHostImpl::OnSSLCertificateError(
net::URLRequest* request,
const net::SSLInfo& ssl_info,
bool is_hsts_host) {
DCHECK(request);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
DCHECK(info);
GlobalRequestID request_id(info->GetChildID(), info->GetRequestID());
int render_process_id;
int render_view_id;
if(!info->GetAssociatedRenderView(&render_process_id, &render_view_id))
NOTREACHED();
SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(),
request_id, info->GetResourceType(), request->url(), render_process_id,
render_view_id, ssl_info, is_hsts_host);
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
| 1
| 170,989
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: write_VD_boot_record(struct archive_write *a)
{
struct iso9660 *iso9660;
unsigned char *bp;
iso9660 = a->format_data;
bp = wb_buffptr(a) -1;
/* Volume Descriptor Type */
set_VD_bp(bp, VDT_BOOT_RECORD, 1);
/* Boot System Identifier */
memcpy(bp+8, "EL TORITO SPECIFICATION", 23);
set_unused_field_bp(bp, 8+23, 39);
/* Unused */
set_unused_field_bp(bp, 40, 71);
/* Absolute pointer to first sector of Boot Catalog */
set_num_731(bp+72,
iso9660->el_torito.catalog->file->content.location);
/* Unused */
set_unused_field_bp(bp, 76, LOGICAL_BLOCK_SIZE);
return (wb_consume(a, LOGICAL_BLOCK_SIZE));
}
Commit Message: Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives
* Don't cast size_t to int, since this can lead to overflow
on machines where sizeof(int) < sizeof(size_t)
* Check a + b > limit by writing it as
a > limit || b > limit || a + b > limit
to avoid problems when a + b wraps around.
CWE ID: CWE-190
| 0
| 50,893
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void Layer::SetNextCommitWaitsForActivation() {
if (!layer_tree_host_)
return;
layer_tree_host_->SetNextCommitWaitsForActivation();
}
Commit Message: Removed pinch viewport scroll offset distribution
The associated change in Blink makes the pinch viewport a proper
ScrollableArea meaning the normal path for synchronizing layer scroll
offsets is used.
This is a 2 sided patch, the other CL:
https://codereview.chromium.org/199253002/
BUG=349941
Review URL: https://codereview.chromium.org/210543002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
| 0
| 111,922
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static PassRefPtr<CSSValue> getDelayValue(const AnimationList* animList)
{
RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
if (animList) {
for (size_t i = 0; i < animList->size(); ++i)
list->append(cssValuePool().createValue(animList->animation(i)->delay(), CSSPrimitiveValue::CSS_S));
} else {
list->append(cssValuePool().createValue(Animation::initialAnimationDelay(), CSSPrimitiveValue::CSS_S));
}
return list.release();
}
Commit Message: Rename isPositioned to isOutOfFlowPositioned for clarity
https://bugs.webkit.org/show_bug.cgi?id=89836
Reviewed by Antti Koivisto.
RenderObject and RenderStyle had an isPositioned() method that was
confusing, because it excluded relative positioning. Rename to
isOutOfFlowPositioned(), which makes it clearer that it only applies
to absolute and fixed positioning.
Simple rename; no behavior change.
Source/WebCore:
* css/CSSComputedStyleDeclaration.cpp:
(WebCore::getPositionOffsetValue):
* css/StyleResolver.cpp:
(WebCore::StyleResolver::collectMatchingRulesForList):
* dom/Text.cpp:
(WebCore::Text::rendererIsNeeded):
* editing/DeleteButtonController.cpp:
(WebCore::isDeletableElement):
* editing/TextIterator.cpp:
(WebCore::shouldEmitNewlinesBeforeAndAfterNode):
* rendering/AutoTableLayout.cpp:
(WebCore::shouldScaleColumns):
* rendering/InlineFlowBox.cpp:
(WebCore::InlineFlowBox::addToLine):
(WebCore::InlineFlowBox::placeBoxesInInlineDirection):
(WebCore::InlineFlowBox::requiresIdeographicBaseline):
(WebCore::InlineFlowBox::adjustMaxAscentAndDescent):
(WebCore::InlineFlowBox::computeLogicalBoxHeights):
(WebCore::InlineFlowBox::placeBoxesInBlockDirection):
(WebCore::InlineFlowBox::flipLinesInBlockDirection):
(WebCore::InlineFlowBox::computeOverflow):
(WebCore::InlineFlowBox::computeOverAnnotationAdjustment):
(WebCore::InlineFlowBox::computeUnderAnnotationAdjustment):
* rendering/InlineIterator.h:
(WebCore::isIteratorTarget):
* rendering/LayoutState.cpp:
(WebCore::LayoutState::LayoutState):
* rendering/RenderBlock.cpp:
(WebCore::RenderBlock::MarginInfo::MarginInfo):
(WebCore::RenderBlock::styleWillChange):
(WebCore::RenderBlock::styleDidChange):
(WebCore::RenderBlock::addChildToContinuation):
(WebCore::RenderBlock::addChildToAnonymousColumnBlocks):
(WebCore::RenderBlock::containingColumnsBlock):
(WebCore::RenderBlock::columnsBlockForSpanningElement):
(WebCore::RenderBlock::addChildIgnoringAnonymousColumnBlocks):
(WebCore::getInlineRun):
(WebCore::RenderBlock::isSelfCollapsingBlock):
(WebCore::RenderBlock::layoutBlock):
(WebCore::RenderBlock::addOverflowFromBlockChildren):
(WebCore::RenderBlock::expandsToEncloseOverhangingFloats):
(WebCore::RenderBlock::handlePositionedChild):
(WebCore::RenderBlock::moveRunInUnderSiblingBlockIfNeeded):
(WebCore::RenderBlock::collapseMargins):
(WebCore::RenderBlock::clearFloatsIfNeeded):
(WebCore::RenderBlock::simplifiedNormalFlowLayout):
(WebCore::RenderBlock::isSelectionRoot):
(WebCore::RenderBlock::blockSelectionGaps):
(WebCore::RenderBlock::clearFloats):
(WebCore::RenderBlock::markAllDescendantsWithFloatsForLayout):
(WebCore::RenderBlock::markSiblingsWithFloatsForLayout):
(WebCore::isChildHitTestCandidate):
(WebCore::InlineMinMaxIterator::next):
(WebCore::RenderBlock::computeBlockPreferredLogicalWidths):
(WebCore::RenderBlock::firstLineBoxBaseline):
(WebCore::RenderBlock::lastLineBoxBaseline):
(WebCore::RenderBlock::updateFirstLetter):
(WebCore::shouldCheckLines):
(WebCore::getHeightForLineCount):
(WebCore::RenderBlock::adjustForBorderFit):
(WebCore::inNormalFlow):
(WebCore::RenderBlock::adjustLinePositionForPagination):
(WebCore::RenderBlock::adjustBlockChildForPagination):
(WebCore::RenderBlock::renderName):
* rendering/RenderBlock.h:
(WebCore::RenderBlock::shouldSkipCreatingRunsForObject):
* rendering/RenderBlockLineLayout.cpp:
(WebCore::RenderBlock::setMarginsForRubyRun):
(WebCore::RenderBlock::computeInlineDirectionPositionsForLine):
(WebCore::RenderBlock::computeBlockDirectionPositionsForLine):
(WebCore::RenderBlock::layoutInlineChildren):
(WebCore::requiresLineBox):
(WebCore::RenderBlock::LineBreaker::skipTrailingWhitespace):
(WebCore::RenderBlock::LineBreaker::skipLeadingWhitespace):
(WebCore::RenderBlock::LineBreaker::nextLineBreak):
* rendering/RenderBox.cpp:
(WebCore::RenderBox::removeFloatingOrPositionedChildFromBlockLists):
(WebCore::RenderBox::styleWillChange):
(WebCore::RenderBox::styleDidChange):
(WebCore::RenderBox::updateBoxModelInfoFromStyle):
(WebCore::RenderBox::offsetFromContainer):
(WebCore::RenderBox::positionLineBox):
(WebCore::RenderBox::computeRectForRepaint):
(WebCore::RenderBox::computeLogicalWidthInRegion):
(WebCore::RenderBox::renderBoxRegionInfo):
(WebCore::RenderBox::computeLogicalHeight):
(WebCore::RenderBox::computePercentageLogicalHeight):
(WebCore::RenderBox::computeReplacedLogicalWidthUsing):
(WebCore::RenderBox::computeReplacedLogicalHeightUsing):
(WebCore::RenderBox::availableLogicalHeightUsing):
(WebCore::percentageLogicalHeightIsResolvable):
* rendering/RenderBox.h:
(WebCore::RenderBox::stretchesToViewport):
(WebCore::RenderBox::isDeprecatedFlexItem):
* rendering/RenderBoxModelObject.cpp:
(WebCore::RenderBoxModelObject::adjustedPositionRelativeToOffsetParent):
(WebCore::RenderBoxModelObject::mapAbsoluteToLocalPoint):
* rendering/RenderBoxModelObject.h:
(WebCore::RenderBoxModelObject::requiresLayer):
* rendering/RenderDeprecatedFlexibleBox.cpp:
(WebCore::childDoesNotAffectWidthOrFlexing):
(WebCore::RenderDeprecatedFlexibleBox::layoutBlock):
(WebCore::RenderDeprecatedFlexibleBox::layoutHorizontalBox):
(WebCore::RenderDeprecatedFlexibleBox::layoutVerticalBox):
(WebCore::RenderDeprecatedFlexibleBox::renderName):
* rendering/RenderFieldset.cpp:
(WebCore::RenderFieldset::findLegend):
* rendering/RenderFlexibleBox.cpp:
(WebCore::RenderFlexibleBox::computePreferredLogicalWidths):
(WebCore::RenderFlexibleBox::autoMarginOffsetInMainAxis):
(WebCore::RenderFlexibleBox::availableAlignmentSpaceForChild):
(WebCore::RenderFlexibleBox::computeMainAxisPreferredSizes):
(WebCore::RenderFlexibleBox::computeNextFlexLine):
(WebCore::RenderFlexibleBox::resolveFlexibleLengths):
(WebCore::RenderFlexibleBox::prepareChildForPositionedLayout):
(WebCore::RenderFlexibleBox::layoutAndPlaceChildren):
(WebCore::RenderFlexibleBox::layoutColumnReverse):
(WebCore::RenderFlexibleBox::adjustAlignmentForChild):
(WebCore::RenderFlexibleBox::flipForRightToLeftColumn):
* rendering/RenderGrid.cpp:
(WebCore::RenderGrid::renderName):
* rendering/RenderImage.cpp:
(WebCore::RenderImage::computeIntrinsicRatioInformation):
* rendering/RenderInline.cpp:
(WebCore::RenderInline::addChildIgnoringContinuation):
(WebCore::RenderInline::addChildToContinuation):
(WebCore::RenderInline::generateCulledLineBoxRects):
(WebCore):
(WebCore::RenderInline::culledInlineFirstLineBox):
(WebCore::RenderInline::culledInlineLastLineBox):
(WebCore::RenderInline::culledInlineVisualOverflowBoundingBox):
(WebCore::RenderInline::computeRectForRepaint):
(WebCore::RenderInline::dirtyLineBoxes):
* rendering/RenderLayer.cpp:
(WebCore::checkContainingBlockChainForPagination):
(WebCore::RenderLayer::updateLayerPosition):
(WebCore::isPositionedContainer):
(WebCore::RenderLayer::calculateClipRects):
(WebCore::RenderLayer::shouldBeNormalFlowOnly):
* rendering/RenderLayerCompositor.cpp:
(WebCore::RenderLayerCompositor::requiresCompositingForPosition):
* rendering/RenderLineBoxList.cpp:
(WebCore::RenderLineBoxList::dirtyLinesFromChangedChild):
* rendering/RenderListItem.cpp:
(WebCore::getParentOfFirstLineBox):
* rendering/RenderMultiColumnBlock.cpp:
(WebCore::RenderMultiColumnBlock::renderName):
* rendering/RenderObject.cpp:
(WebCore::RenderObject::markContainingBlocksForLayout):
(WebCore::RenderObject::setPreferredLogicalWidthsDirty):
(WebCore::RenderObject::invalidateContainerPreferredLogicalWidths):
(WebCore::RenderObject::styleWillChange):
(WebCore::RenderObject::offsetParent):
* rendering/RenderObject.h:
(WebCore::RenderObject::isOutOfFlowPositioned):
(WebCore::RenderObject::isInFlowPositioned):
(WebCore::RenderObject::hasClip):
(WebCore::RenderObject::isFloatingOrOutOfFlowPositioned):
* rendering/RenderObjectChildList.cpp:
(WebCore::RenderObjectChildList::removeChildNode):
* rendering/RenderReplaced.cpp:
(WebCore::hasAutoHeightOrContainingBlockWithAutoHeight):
* rendering/RenderRubyRun.cpp:
(WebCore::RenderRubyRun::rubyText):
* rendering/RenderTable.cpp:
(WebCore::RenderTable::addChild):
(WebCore::RenderTable::computeLogicalWidth):
(WebCore::RenderTable::layout):
* rendering/style/RenderStyle.h:
Source/WebKit/blackberry:
* Api/WebPage.cpp:
(BlackBerry::WebKit::isPositionedContainer):
(BlackBerry::WebKit::isNonRenderViewFixedPositionedContainer):
(BlackBerry::WebKit::isFixedPositionedContainer):
Source/WebKit2:
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::updateOffsetFromViewportForSelf):
git-svn-id: svn://svn.chromium.org/blink/trunk@121123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
| 0
| 99,476
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: nfsd4_decode_release_lockowner(struct nfsd4_compoundargs *argp, struct nfsd4_release_lockowner *rlockowner)
{
DECODE_HEAD;
if (argp->minorversion >= 1)
return nfserr_notsupp;
READ_BUF(12);
COPYMEM(&rlockowner->rl_clientid, sizeof(clientid_t));
rlockowner->rl_owner.len = be32_to_cpup(p++);
READ_BUF(rlockowner->rl_owner.len);
READMEM(rlockowner->rl_owner.data, rlockowner->rl_owner.len);
if (argp->minorversion && !zero_clientid(&rlockowner->rl_clientid))
return nfserr_inval;
DECODE_TAIL;
}
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
| 0
| 65,770
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void V8Console::undebugFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ConsoleHelper helper(info);
v8::Local<v8::Function> function;
if (!helper.firstArgAsFunction().ToLocal(&function))
return;
setFunctionBreakpoint(helper, function, V8DebuggerAgentImpl::DebugCommandBreakpointSource, String16(), false);
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79
| 0
| 130,344
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void virgl_cmd_submit_3d(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_cmd_submit cs;
void *buf;
size_t s;
VIRTIO_GPU_FILL_CMD(cs);
trace_virtio_gpu_cmd_ctx_submit(cs.hdr.ctx_id, cs.size);
buf = g_malloc(cs.size);
s = iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num,
sizeof(cs), buf, cs.size);
if (s != cs.size) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: size mismatch (%zd/%d)",
__func__, s, cs.size);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
goto out;
}
if (virtio_gpu_stats_enabled(g->conf)) {
g->stats.req_3d++;
g->stats.bytes_3d += cs.size;
}
virgl_renderer_submit_cmd(buf, cs.hdr.ctx_id, cs.size / 4);
out:
g_free(buf);
}
Commit Message:
CWE ID: CWE-772
| 0
| 9,759
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: WebContentsView* InterstitialPageImpl::CreateWebContentsView() {
if (!enabled() || !create_view_)
return NULL;
WebContentsView* wcv =
static_cast<WebContentsImpl*>(web_contents())->GetView();
RenderWidgetHostViewBase* view =
wcv->CreateViewForWidget(render_view_host_->GetWidget(), false);
RenderWidgetHostImpl::From(render_view_host_->GetWidget())->SetView(view);
render_view_host_->GetMainFrame()->AllowBindings(
BINDINGS_POLICY_DOM_AUTOMATION);
render_view_host_->CreateRenderView(MSG_ROUTING_NONE,
MSG_ROUTING_NONE,
FrameReplicationState(),
false);
controller_->delegate()->RenderFrameForInterstitialPageCreated(
frame_tree_->root()->current_frame_host());
view->SetSize(web_contents()->GetContainerBounds().size());
view->Hide();
return wcv;
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
| 0
| 136,085
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void VoidMethodUSVStringArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodUSVStringArg");
TestObject* impl = V8TestObject::ToImpl(info.Holder());
if (UNLIKELY(info.Length() < 1)) {
exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length()));
return;
}
V8StringResource<> usv_string_arg;
usv_string_arg = NativeValueTraits<IDLUSVString>::NativeValue(info.GetIsolate(), info[0], exception_state);
if (exception_state.HadException())
return;
impl->voidMethodUSVStringArg(usv_string_arg);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
| 0
| 135,503
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void GraphicsContext::setImageInterpolationQuality(InterpolationQuality)
{
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
| 0
| 100,104
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void copy_flags(unsigned long clone_flags, struct task_struct *p)
{
unsigned long new_flags = p->flags;
new_flags &= ~PF_SUPERPRIV;
new_flags |= PF_FORKNOEXEC;
new_flags |= PF_STARTING;
p->flags = new_flags;
clear_freeze_flag(p);
}
Commit Message: Move "exit_robust_list" into mm_release()
We don't want to get rid of the futexes just at exit() time, we want to
drop them when doing an execve() too, since that gets rid of the
previous VM image too.
Doing it at mm_release() time means that we automatically always do it
when we disassociate a VM map from the task.
Reported-by: [email protected]
Cc: Andrew Morton <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Brad Spengler <[email protected]>
Cc: Alex Efros <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
| 0
| 22,151
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void LiveSyncTest::TearDown() {
InProcessBrowserTest::TearDown();
TearDownLocalPythonTestServer();
TearDownLocalTestServer();
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
| 0
| 100,196
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int jas_icccurv_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
othattrval = 0;
/* Not yet implemented. */
abort();
return -1;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190
| 0
| 72,690
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int ctr_des3_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_des_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
blkcipher_walk_init(&walk, dst, src, nbytes);
return ctr_desall_crypt(desc, KMCTR_TDEA_192_DECRYPT, ctx, &walk);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
| 0
| 46,690
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static ssize_t snd_compr_write(struct file *f, const char __user *buf,
size_t count, loff_t *offset)
{
struct snd_compr_file *data = f->private_data;
struct snd_compr_stream *stream;
size_t avail;
int retval;
if (snd_BUG_ON(!data))
return -EFAULT;
stream = &data->stream;
mutex_lock(&stream->device->lock);
/* write is allowed when stream is running or has been steup */
if (stream->runtime->state != SNDRV_PCM_STATE_SETUP &&
stream->runtime->state != SNDRV_PCM_STATE_RUNNING) {
mutex_unlock(&stream->device->lock);
return -EBADFD;
}
avail = snd_compr_get_avail(stream);
pr_debug("avail returned %ld\n", (unsigned long)avail);
/* calculate how much we can write to buffer */
if (avail > count)
avail = count;
if (stream->ops->copy)
retval = stream->ops->copy(stream, buf, avail);
else
retval = snd_compr_write_data(stream, buf, avail);
if (retval > 0)
stream->runtime->total_bytes_available += retval;
/* while initiating the stream, write should be called before START
* call, so in setup move state */
if (stream->runtime->state == SNDRV_PCM_STATE_SETUP) {
stream->runtime->state = SNDRV_PCM_STATE_PREPARED;
pr_debug("stream prepared, Houston we are good to go\n");
}
mutex_unlock(&stream->device->lock);
return retval;
}
Commit Message: ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()
These are 32 bit values that come from the user, we need to check for
integer overflows or we could end up allocating a smaller buffer than
expected.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID:
| 0
| 58,698
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: e1000e_set_phy_oem_bits(E1000ECore *core, int index, uint16_t val)
{
core->phy[0][PHY_OEM_BITS] = val & ~BIT(10);
if (val & BIT(10)) {
e1000x_restart_autoneg(core->mac, core->phy[0], core->autoneg_timer);
}
}
Commit Message:
CWE ID: CWE-835
| 0
| 6,071
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
struct sshbuf *b = NULL;
int r;
const u_char *inblob, *outblob;
size_t inl, outl;
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
(r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
goto out;
if (inl == 0)
state->compression_in_started = 0;
else if (inl != sizeof(state->compression_in_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_in_started = 1;
memcpy(&state->compression_in_stream, inblob, inl);
}
if (outl == 0)
state->compression_out_started = 0;
else if (outl != sizeof(state->compression_out_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_out_started = 1;
memcpy(&state->compression_out_stream, outblob, outl);
}
r = 0;
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
| 1
| 168,654
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: ofpacts_pull(struct ofpbuf *ofpacts)
{
size_t ofs;
ofs = ofpacts->size;
ofpbuf_pull(ofpacts, ofs);
return ofs;
}
Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052
Signed-off-by: Ben Pfaff <[email protected]>
Acked-by: Justin Pettit <[email protected]>
CWE ID:
| 0
| 77,024
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: DOMHighResTimeStamp PerformanceNavigationTiming::loadEventStart() const {
DocumentLoadTiming* timing = GetDocumentLoadTiming();
if (!timing)
return 0.0;
return Performance::MonotonicTimeToDOMHighResTimeStamp(
TimeOrigin(), timing->LoadEventStart(), false /* allow_negative_value */);
}
Commit Message: Fix the |name| of PerformanceNavigationTiming
Previously, the |name| of a PerformanceNavigationTiming entry was the initial
URL (the request URL). After this CL, it is the response URL, so for example
a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|.
Bug: 797465
Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40
Reviewed-on: https://chromium-review.googlesource.com/996579
Reviewed-by: Yoav Weiss <[email protected]>
Commit-Queue: Nicolás Peña Moreno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548773}
CWE ID: CWE-200
| 0
| 155,551
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: dhcp_message_add_addr(struct dhcp_message *dhcp,
uint8_t type, struct in_addr addr)
{
uint8_t *p;
size_t len;
p = dhcp->options;
while (*p != DHO_END) {
p++;
p += *p + 1;
}
len = p - (uint8_t *)dhcp;
if (len + 6 > sizeof(*dhcp)) {
errno = ENOMEM;
return -1;
}
PUTADDR(type, addr);
*p = DHO_END;
return 0;
}
Commit Message: Improve length checks in DHCP Options parsing of dhcpcd.
Bug: 26461634
Change-Id: Ic4c2eb381a6819e181afc8ab13891f3fc58b7deb
CWE ID: CWE-119
| 0
| 161,352
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: explicit MessageLoopObserver(base::WeakPtr<IOThreadContext> context)
: context_(context) {
base::MessageLoop::current()->AddDestructionObserver(this);
}
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947}
CWE ID: CWE-119
| 0
| 127,472
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: asn1_der_decoding (asn1_node * element, const void *ider, int ider_len,
char *errorDescription)
{
return asn1_der_decoding2 (element, ider, &ider_len, 0, errorDescription);
}
Commit Message:
CWE ID: CWE-399
| 0
| 11,282
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: bool swipe_up() const { return swipe_up_; }
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
| 0
| 112,131
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void hns_rcb_set_rx_ring_bs(struct hnae_queue *q, u32 buf_size)
{
u32 bd_size_type = hns_rcb_buf_size2type(buf_size);
dsaf_write_dev(q, RCB_RING_RX_RING_BD_LEN_REG,
bd_size_type);
}
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
| 0
| 85,619
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void RestoreCurrentTextureBindings(ContextState* state,
GLenum target,
GLuint texture_unit) {
DCHECK(!state->texture_units.empty());
DCHECK_LT(texture_unit, state->texture_units.size());
TextureUnit& info = state->texture_units[texture_unit];
GLuint last_id;
TextureRef* texture_ref = info.GetInfoForTarget(target);
if (texture_ref) {
last_id = texture_ref->service_id();
} else {
last_id = 0;
}
state->api()->glBindTextureFn(target, last_id);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
| 0
| 141,653
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: rend_service_check_dir_and_add(smartlist_t *service_list,
const or_options_t *options,
rend_service_t *service,
int validate_only)
{
if (!service) {
/* It is ok for a service to be NULL, this means there are no services */
return 0;
}
if (rend_service_check_private_dir(options, service, !validate_only)
< 0) {
rend_service_free(service);
return -1;
}
smartlist_t *s_list = rend_get_service_list_mutable(service_list);
/* We must have a service list, even if it's a temporary one, so we can
* check for duplicate services */
if (BUG(!s_list)) {
return -1;
}
return rend_add_service(s_list, service);
}
Commit Message: Fix log-uninitialized-stack bug in rend_service_intro_established.
Fixes bug 23490; bugfix on 0.2.7.2-alpha.
TROVE-2017-008
CVE-2017-0380
CWE ID: CWE-532
| 0
| 69,605
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void LocalFrameClientImpl::DispatchWillSendSubmitEvent(HTMLFormElement* form) {
if (web_frame_->Client())
web_frame_->Client()->WillSendSubmitEvent(WebFormElement(form));
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254
| 0
| 145,269
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: auth_pin_change_pinpad(struct sc_card *card, struct sc_pin_cmd_data *data,
int *tries_left)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
struct sc_pin_cmd_data pin_cmd;
struct sc_apdu apdu;
unsigned char ffs1[0x100];
unsigned char ffs2[0x100];
int rv, pin_reference;
LOG_FUNC_CALLED(card->ctx);
pin_reference = data->pin_reference & ~OBERTHUR_PIN_LOCAL;
memset(ffs1, 0xFF, sizeof(ffs1));
memset(ffs2, 0xFF, sizeof(ffs2));
memset(&pin_cmd, 0, sizeof(pin_cmd));
if (data->pin1.len > OBERTHUR_AUTH_MAX_LENGTH_PIN)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "'PIN CHANGE' failed");
if (data->pin1.data && data->pin1.len)
memcpy(ffs1, data->pin1.data, data->pin1.len);
pin_cmd.flags |= SC_PIN_CMD_NEED_PADDING;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x00, pin_reference);
apdu.lc = OBERTHUR_AUTH_MAX_LENGTH_PIN * 2;
apdu.datalen = OBERTHUR_AUTH_MAX_LENGTH_PIN * 2;
apdu.data = ffs1;
pin_cmd.apdu = &apdu;
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.cmd = SC_PIN_CMD_CHANGE;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
pin_cmd.pin_reference = pin_reference;
if (pin_cmd.pin1.min_length < 4)
pin_cmd.pin1.min_length = 4;
pin_cmd.pin1.max_length = 8;
pin_cmd.pin1.encoding = SC_PIN_ENCODING_ASCII;
pin_cmd.pin1.offset = 5 + OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin_cmd.pin1.data = ffs1;
pin_cmd.pin1.len = OBERTHUR_AUTH_MAX_LENGTH_PIN;
pin_cmd.pin1.pad_length = 0;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin2));
pin_cmd.pin1.offset = 5;
pin_cmd.pin2.data = ffs2;
rv = iso_drv->ops->pin_cmd(card, &pin_cmd, tries_left);
LOG_TEST_RET(card->ctx, rv, "PIN CMD 'VERIFY' with pinpad failed");
LOG_FUNC_RETURN(card->ctx, rv);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
| 0
| 78,550
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int nfs4_map_errors(int err)
{
if (err >= -1000)
return err;
switch (err) {
case -NFS4ERR_RESOURCE:
return -EREMOTEIO;
case -NFS4ERR_WRONGSEC:
return -EPERM;
case -NFS4ERR_BADOWNER:
case -NFS4ERR_BADNAME:
return -EINVAL;
default:
dprintk("%s could not handle NFSv4 error %d\n",
__func__, -err);
break;
}
return -EIO;
}
Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached
_copy_from_pages() used to copy data from the temporary buffer to the
user passed buffer is passed the wrong size parameter when copying
data. res.acl_len contains both the bitmap and acl lenghts while
acl_len contains the acl length after adjusting for the bitmap size.
Signed-off-by: Sachin Prabhu <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189
| 0
| 19,940
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: u16 channel_to_chanspec(struct brcmu_d11inf *d11inf,
struct ieee80211_channel *ch)
{
struct brcmu_chan ch_inf;
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq);
ch_inf.bw = BRCMU_CHAN_BW_20;
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
Commit Message: brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap()
User-space can choose to omit NL80211_ATTR_SSID and only provide raw
IE TLV data. When doing so it can provide SSID IE with length exceeding
the allowed size. The driver further processes this IE copying it
into a local variable without checking the length. Hence stack can be
corrupted and used as exploit.
Cc: [email protected] # v4.7
Reported-by: Daxing Guo <[email protected]>
Reviewed-by: Hante Meuleman <[email protected]>
Reviewed-by: Pieter-Paul Giesberts <[email protected]>
Reviewed-by: Franky Lin <[email protected]>
Signed-off-by: Arend van Spriel <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>
CWE ID: CWE-119
| 0
| 49,139
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
: params(p),
completion(c) {
}
Commit Message: Let the browser handle external navigations from DevTools.
BUG=180555
Review URL: https://chromiumcodereview.appspot.com/12531004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
| 0
| 115,578
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
if (c->fc->nb_streams >= 1) {
AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
par->codec_id == AV_CODEC_ID_H264 &&
atom.size > 11) {
int cid;
avio_skip(pb, 10);
cid = avio_rb16(pb);
/* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
if (cid == 0xd4d || cid == 0xd4e)
par->width = 1440;
return 0;
} else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
atom.size >= 24) {
int num, den;
avio_skip(pb, 12);
num = avio_rb32(pb);
den = avio_rb32(pb);
if (num <= 0 || den <= 0)
return 0;
switch (avio_rb32(pb)) {
case 2:
if (den >= INT_MAX / 2)
return 0;
den *= 2;
case 1:
c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
default:
return 0;
}
}
}
return mov_read_avid(c, pb, atom);
}
Commit Message: avformat/mov: Fix DoS in read_tfra()
Fixes: Missing EOF check in loop
No testcase
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
| 0
| 61,408
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: bool LoadEntryPointsFromLibrary(const base::NativeLibrary& library,
PluginModule::EntryPoints* entry_points) {
entry_points->get_interface =
reinterpret_cast<PluginModule::GetInterfaceFunc>(
base::GetFunctionPointerFromNativeLibrary(library,
"PPP_GetInterface"));
if (!entry_points->get_interface) {
LOG(WARNING) << "No PPP_GetInterface in plugin library";
return false;
}
entry_points->initialize_module =
reinterpret_cast<PluginModule::PPP_InitializeModuleFunc>(
base::GetFunctionPointerFromNativeLibrary(library,
"PPP_InitializeModule"));
if (!entry_points->initialize_module) {
LOG(WARNING) << "No PPP_InitializeModule in plugin library";
return false;
}
entry_points->shutdown_module =
reinterpret_cast<PluginModule::PPP_ShutdownModuleFunc>(
base::GetFunctionPointerFromNativeLibrary(library,
"PPP_ShutdownModule"));
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
| 0
| 103,438
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: authentic_decipher(struct sc_card *card, const unsigned char *in, size_t in_len,
unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u",
in_len, out_len);
if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
apdu.data = in;
apdu.datalen = in_len;
apdu.lc = in_len;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Card returned error");
if (out_len > apdu.resplen)
out_len = apdu.resplen;
memcpy(out, apdu.resp, out_len);
rv = out_len;
LOG_FUNC_RETURN(ctx, rv);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
| 0
| 78,180
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: dissect_usb_video_endpoint_descriptor(proto_tree *parent_tree, tvbuff_t *tvb,
guint8 descriptor_len)
{
proto_tree *tree = NULL;
int offset = 0;
guint8 subtype;
subtype = tvb_get_guint8(tvb, offset+2);
if (parent_tree)
{
const gchar* subtype_str;
subtype_str = val_to_str(subtype, vc_ep_descriptor_subtypes, "Unknown (0x%x)");
tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len,
ett_descriptor_video_endpoint, NULL, "VIDEO CONTROL ENDPOINT DESCRIPTOR [%s]",
subtype_str);
}
dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext);
proto_tree_add_item(tree, hf_usb_vid_epdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN);
offset += 3;
if (subtype == EP_INTERRUPT)
{
proto_tree_add_item(tree, hf_usb_vid_epdesc_max_transfer_sz, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
}
/* Soak up descriptor bytes beyond those we know how to dissect */
if (offset < descriptor_len)
proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA);
return descriptor_len;
}
Commit Message: Make class "type" for USB conversations.
USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match.
Bug: 12356
Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209
Reviewed-on: https://code.wireshark.org/review/15212
Petri-Dish: Michael Mann <[email protected]>
Reviewed-by: Martin Kaiser <[email protected]>
Petri-Dish: Martin Kaiser <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-476
| 0
| 51,829
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: HeadlessDevToolsManagerDelegate::NetworkDisable(
content::DevToolsAgentHost* agent_host,
int session_id,
int command_id,
const base::DictionaryValue* params) {
HeadlessBrowserContextImpl* browser_context =
static_cast<HeadlessBrowserContextImpl*>(
browser_->GetDefaultBrowserContext());
browser_context->SetNetworkConditions(HeadlessNetworkConditions());
return CreateSuccessResponse(command_id, nullptr);
}
Commit Message: Remove some unused includes in headless/
Bug:
Change-Id: Icb5351bb6112fc89e36dab82c15f32887dab9217
Reviewed-on: https://chromium-review.googlesource.com/720594
Reviewed-by: David Vallet <[email protected]>
Commit-Queue: Iris Uy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#509313}
CWE ID: CWE-264
| 0
| 133,165
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void Gfx::popStateGuard() {
while (stackHeight > bottomGuard() && state->hasSaves())
restoreState();
stateGuards.pop_back();
}
Commit Message:
CWE ID: CWE-20
| 0
| 8,177
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void LayerTreeHost::SetElementIdsForTesting() {
LayerTreeHostCommon::CallFunctionForEveryLayer(this, SetElementIdForTesting);
}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
| 0
| 137,159
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: TabManagerTest() : scoped_set_tick_clock_for_testing_(&test_clock_) {
test_clock_.Advance(kShortDelay);
scoped_feature_list_.InitAndEnableFeature(
features::kSiteCharacteristicsDatabase);
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: François Doray <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119
| 0
| 156,480
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int databaseIsUnmoved(Pager *pPager){
int bHasMoved = 0;
int rc;
if( pPager->tempFile ) return SQLITE_OK;
if( pPager->dbSize==0 ) return SQLITE_OK;
assert( pPager->zFilename && pPager->zFilename[0] );
rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
if( rc==SQLITE_NOTFOUND ){
/* If the HAS_MOVED file-control is unimplemented, assume that the file
** has not been moved. That is the historical behavior of SQLite: prior to
** version 3.8.3, it never checked */
rc = SQLITE_OK;
}else if( rc==SQLITE_OK && bHasMoved ){
rc = SQLITE_READONLY_DBMOVED;
}
return rc;
}
Commit Message: sqlite: safely move pointer values through SQL.
This lands https://www.sqlite.org/src/timeline?c=d6a44b35 in
third_party/sqlite/src/ and
third_party/sqlite/patches/0013-Add-new-interfaces-sqlite3_bind_pointer-sqlite3_resu.patch
and re-generates third_party/sqlite/amalgamation/* using the script at
third_party/sqlite/google_generate_amalgamation.sh.
The CL also adds a layout test that verifies the patch works as intended.
BUG=742407
Change-Id: I2e1a457459cd2e975e6241b630e7b79c82545981
Reviewed-on: https://chromium-review.googlesource.com/572976
Reviewed-by: Chris Mumford <[email protected]>
Commit-Queue: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#487275}
CWE ID: CWE-119
| 0
| 136,460
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert3(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
c* (toc(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert3();
return JSValue::encode(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
| 1
| 170,585
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int __net_init fib_net_init(struct net *net)
{
int error;
#ifdef CONFIG_IP_ROUTE_CLASSID
net->ipv4.fib_num_tclassid_users = 0;
#endif
error = ip_fib_net_init(net);
if (error < 0)
goto out;
error = nl_fib_lookup_init(net);
if (error < 0)
goto out_nlfl;
error = fib_proc_init(net);
if (error < 0)
goto out_proc;
out:
return error;
out_proc:
nl_fib_lookup_exit(net);
out_nlfl:
ip_fib_net_exit(net);
goto out;
}
Commit Message: ipv4: Don't do expensive useless work during inetdev destroy.
When an inetdev is destroyed, every address assigned to the interface
is removed. And in this scenerio we do two pointless things which can
be very expensive if the number of assigned interfaces is large:
1) Address promotion. We are deleting all addresses, so there is no
point in doing this.
2) A full nf conntrack table purge for every address. We only need to
do this once, as is already caught by the existing
masq_dev_notifier so masq_inet_event() can skip this.
Reported-by: Solar Designer <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Tested-by: Cyrill Gorcunov <[email protected]>
CWE ID: CWE-399
| 0
| 54,124
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: MagickExport PixelPacket *QueueAuthenticPixelCacheNexus(Image *image,
const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception)
{
CacheInfo
*restrict cache_info;
MagickOffsetType
offset;
MagickSizeType
number_pixels;
PixelPacket
*restrict pixels;
RectangleInfo
region;
/*
Validate pixel cache geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception);
if (cache_info == (Cache) NULL)
return((PixelPacket *) NULL);
assert(cache_info->signature == MagickSignature);
if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) ||
(y < 0) || (x >= (ssize_t) cache_info->columns) ||
(y >= (ssize_t) cache_info->rows))
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"PixelsAreNotAuthentic","`%s'",image->filename);
return((PixelPacket *) NULL);
}
offset=(MagickOffsetType) y*cache_info->columns+x;
if (offset < 0)
return((PixelPacket *) NULL);
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1;
if ((MagickSizeType) offset >= number_pixels)
return((PixelPacket *) NULL);
/*
Return pixel cache.
*/
region.x=x;
region.y=y;
region.width=columns;
region.height=rows;
pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,®ion,
(image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ?
MagickTrue : MagickFalse,nexus_info,exception);
return(pixels);
}
Commit Message:
CWE ID: CWE-189
| 0
| 73,648
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void FrameView::enableAutoSizeMode(const IntSize& minSize, const IntSize& maxSize)
{
if (!m_autoSizeInfo)
m_autoSizeInfo = adoptPtr(new FrameViewAutoSizeInfo(this));
m_autoSizeInfo->configureAutoSizeMode(minSize, maxSize);
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
[email protected]
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416
| 0
| 119,832
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id,
int route_id,
bool alive,
bool did_swap) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id,
route_id,
alive,
did_swap));
return;
}
GpuProcessHost* host = GpuProcessHost::FromID(host_id);
if (host) {
if (alive)
host->Send(new AcceleratedSurfaceMsg_BufferPresented(
route_id, did_swap, 0));
else
host->ForceShutdown();
}
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
| 1
| 171,354
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: LIBOPENMPT_MODPLUG_API void ModPlug_InitMixerCallback(ModPlugFile* file,ModPlugMixerProc proc)
{
if(!file) return;
if(!file->mixerbuf){
file->mixerbuf = malloc(BUFFER_COUNT*sizeof(signed int)*4);
}
file->mixerproc = proc;
}
Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team)
git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27
CWE ID: CWE-120
| 0
| 87,640
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void Browser::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
window()->HandleKeyboardEvent(event);
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
| 0
| 97,242
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: bool JSTestMediaQueryListListenerConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSTestMediaQueryListListenerConstructor, JSDOMWrapper>(exec, &JSTestMediaQueryListListenerConstructorTable, jsCast<JSTestMediaQueryListListenerConstructor*>(cell), propertyName, slot);
}
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
| 0
| 101,164
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
Commit Message: stream: support RST getting lost/ignored
In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'.
However, the target of the RST may not have received it, or may not
have accepted it. Also, the RST may have been injected, so the supposed
sender may not actually be aware of the RST that was sent in it's name.
In this case the previous behavior was to switch the state to CLOSED and
accept no further TCP updates or stream reassembly.
This patch changes this. It still switches the state to CLOSED, as this
is by far the most likely to be correct. However, it will reconsider
the state if the receiver continues to talk.
To do this on each state change the previous state will be recorded in
TcpSession::pstate. If a non-RST packet is received after a RST, this
TcpSession::pstate is used to try to continue the conversation.
If the (supposed) sender of the RST is also continueing the conversation
as normal, it's highly likely it didn't send the RST. In this case
a stream event is generated.
Ticket: #2501
Reported-By: Kirill Shipulin
CWE ID:
| 0
| 79,268
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: __glXContextDestroy(__GLXcontext *context)
{
__glXFlushContextCache();
}
Commit Message:
CWE ID: CWE-20
| 0
| 14,139
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: InputHandler::ScrollStatus LayerTreeHostImpl::TryScroll(
const gfx::PointF& screen_space_point,
InputHandler::ScrollInputType type,
const ScrollTree& scroll_tree,
ScrollNode* scroll_node) const {
InputHandler::ScrollStatus scroll_status;
scroll_status.main_thread_scrolling_reasons =
MainThreadScrollingReason::kNotScrollingOnMain;
if (!!scroll_node->main_thread_scrolling_reasons) {
TRACE_EVENT0("cc", "LayerImpl::TryScroll: Failed ShouldScrollOnMainThread");
scroll_status.thread = InputHandler::SCROLL_ON_MAIN_THREAD;
scroll_status.main_thread_scrolling_reasons =
scroll_node->main_thread_scrolling_reasons;
return scroll_status;
}
gfx::Transform screen_space_transform =
scroll_tree.ScreenSpaceTransform(scroll_node->id);
if (!screen_space_transform.IsInvertible()) {
TRACE_EVENT0("cc", "LayerImpl::TryScroll: Ignored NonInvertibleTransform");
scroll_status.thread = InputHandler::SCROLL_IGNORED;
scroll_status.main_thread_scrolling_reasons =
MainThreadScrollingReason::kNonInvertibleTransform;
return scroll_status;
}
if (!scroll_node->non_fast_scrollable_region.IsEmpty()) {
bool clipped = false;
gfx::Transform inverse_screen_space_transform(
gfx::Transform::kSkipInitialization);
if (!screen_space_transform.GetInverse(&inverse_screen_space_transform)) {
}
gfx::PointF hit_test_point_in_layer_space = MathUtil::ProjectPoint(
inverse_screen_space_transform, screen_space_point, &clipped);
if (!clipped && scroll_node->non_fast_scrollable_region.Contains(
gfx::ToRoundedPoint(hit_test_point_in_layer_space))) {
TRACE_EVENT0("cc",
"LayerImpl::tryScroll: Failed NonFastScrollableRegion");
scroll_status.thread = InputHandler::SCROLL_ON_MAIN_THREAD;
scroll_status.main_thread_scrolling_reasons =
MainThreadScrollingReason::kNonFastScrollableRegion;
return scroll_status;
}
}
if (!scroll_node->scrollable) {
TRACE_EVENT0("cc", "LayerImpl::tryScroll: Ignored not scrollable");
scroll_status.thread = InputHandler::SCROLL_IGNORED;
scroll_status.main_thread_scrolling_reasons =
MainThreadScrollingReason::kNotScrollable;
return scroll_status;
}
gfx::ScrollOffset max_scroll_offset =
scroll_tree.MaxScrollOffset(scroll_node->id);
if (max_scroll_offset.x() <= 0 && max_scroll_offset.y() <= 0) {
TRACE_EVENT0("cc",
"LayerImpl::tryScroll: Ignored. Technically scrollable,"
" but has no affordance in either direction.");
scroll_status.thread = InputHandler::SCROLL_IGNORED;
scroll_status.main_thread_scrolling_reasons =
MainThreadScrollingReason::kNotScrollable;
return scroll_status;
}
scroll_status.thread = InputHandler::SCROLL_ON_IMPL_THREAD;
return scroll_status;
}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
| 0
| 137,390
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void CWebServer::GetJSonDevices(
Json::Value &root,
const std::string &rused,
const std::string &rfilter,
const std::string &order,
const std::string &rowid,
const std::string &planID,
const std::string &floorID,
const bool bDisplayHidden,
const bool bDisplayDisabled,
const bool bFetchFavorites,
const time_t LastUpdate,
const std::string &username,
const std::string &hardwareid)
{
std::vector<std::vector<std::string> > result;
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm tLastUpdate;
localtime_r(&now, &tLastUpdate);
const time_t iLastUpdate = LastUpdate - 1;
int SensorTimeOut = 60;
m_sql.GetPreferencesVar("SensorTimeout", SensorTimeOut);
std::map<int, _tHardwareListInt> _hardwareNames;
result = m_sql.safe_query("SELECT ID, Name, Enabled, Type, Mode1, Mode2 FROM Hardware");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
_tHardwareListInt tlist;
int ID = atoi(sd[0].c_str());
tlist.Name = sd[1];
tlist.Enabled = (atoi(sd[2].c_str()) != 0);
tlist.HardwareTypeVal = atoi(sd[3].c_str());
#ifndef ENABLE_PYTHON
tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal);
#else
if (tlist.HardwareTypeVal != HTYPE_PythonPlugin)
{
tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal);
}
else
{
tlist.HardwareType = PluginHardwareDesc(ID);
}
#endif
tlist.Mode1 = sd[4];
tlist.Mode2 = sd[5];
_hardwareNames[ID] = tlist;
}
}
root["ActTime"] = static_cast<int>(now);
char szTmp[300];
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
strftime(szTmp, 80, "%Y-%m-%d %X", &tm1);
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
char szOrderBy[50];
std::string szQuery;
bool isAlpha = true;
const std::string orderBy = order.c_str();
for (size_t i = 0; i < orderBy.size(); i++) {
if (!isalpha(orderBy[i])) {
isAlpha = false;
}
}
if (order.empty() || (!isAlpha)) {
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
} else {
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
unsigned char tempsign = m_sql.m_tempsign[0];
bool bHaveUser = false;
int iUser = -1;
unsigned int totUserDevices = 0;
bool bShowScenes = true;
bHaveUser = (username != "");
if (bHaveUser)
{
iUser = FindUser(username.c_str());
if (iUser != -1)
{
_eUserRights urights = m_users[iUser].userrights;
if (urights != URIGHTS_ADMIN)
{
result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == %lu)", m_users[iUser].ID);
totUserDevices = (unsigned int)result.size();
bShowScenes = (m_users[iUser].ActiveTabs&(1 << 1)) != 0;
}
}
}
std::set<std::string> _HiddenDevices;
bool bAllowDeviceToBeHidden = false;
int ii = 0;
if (rfilter == "all")
{
if (
(bShowScenes) &&
((rused == "all") || (rused == "true"))
)
{
if (rowid != "")
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A"
" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)"
" WHERE (A.ID=='%q')",
rowid.c_str());
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A, DeviceToPlansMap as B WHERE (B.PlanID=='%q')"
" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==1) ORDER BY B.[Order]",
planID.c_str());
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A, DeviceToPlansMap as B, Plans as C"
" WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID) AND (B.DeviceRowID==a.ID)"
" AND (B.DevSceneType==1) ORDER BY B.[Order]",
floorID.c_str());
else {
szQuery = (
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A"
" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)"
" ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), order.c_str());
}
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
unsigned char favorite = atoi(sd[4].c_str());
if ((bFetchFavorites) && (!favorite))
continue;
std::string sLastUpdate = sd[3];
if (iLastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= iLastUpdate)
continue;
}
int nValue = atoi(sd[2].c_str());
unsigned char scenetype = atoi(sd[5].c_str());
int iProtected = atoi(sd[6].c_str());
std::string sSceneName = sd[1];
if (!bDisplayHidden && sSceneName[0] == '$')
{
continue;
}
if (scenetype == 0)
{
root["result"][ii]["Type"] = "Scene";
root["result"][ii]["TypeImg"] = "scene";
}
else
{
root["result"][ii]["Type"] = "Group";
root["result"][ii]["TypeImg"] = "group";
}
std::string thisIdx = sd[0];
if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) {
std::string typeOfThisOne = root["result"][ii]["Type"].asString();
if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) {
root["result"][ii - 1]["PlanIDs"].append(atoi(sd[9].c_str()));
continue;
}
}
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sSceneName;
root["result"][ii]["Description"] = sd[10];
root["result"][ii]["Favorite"] = favorite;
root["result"][ii]["Protected"] = (iProtected != 0);
root["result"][ii]["LastUpdate"] = sLastUpdate;
root["result"][ii]["PlanID"] = sd[9].c_str();
Json::Value jsonArray;
jsonArray.append(atoi(sd[9].c_str()));
root["result"][ii]["PlanIDs"] = jsonArray;
if (nValue == 0)
root["result"][ii]["Status"] = "Off";
else if (nValue == 1)
root["result"][ii]["Status"] = "On";
else
root["result"][ii]["Status"] = "Mixed";
root["result"][ii]["Data"] = root["result"][ii]["Status"];
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
root["result"][ii]["XOffset"] = atoi(sd[7].c_str());
root["result"][ii]["YOffset"] = atoi(sd[8].c_str());
ii++;
}
}
}
}
char szData[250];
if (totUserDevices == 0)
{
if (rowid != "")
{
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used, A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus A LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) "
"WHERE (A.ID=='%q')",
rowid.c_str());
}
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, B.XOffset, B.YOffset,"
" B.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, DeviceToPlansMap as B "
"WHERE (B.PlanID=='%q') AND (B.DeviceRowID==a.ID)"
" AND (B.DevSceneType==0) ORDER BY B.[Order]",
planID.c_str());
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, B.XOffset, B.YOffset,"
" B.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, DeviceToPlansMap as B,"
" Plans as C "
"WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID)"
" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"ORDER BY B.[Order]",
floorID.c_str());
else {
if (!bDisplayHidden)
{
result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')");
if (!result.empty())
{
std::string pID = result[0][0];
result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)",
pID.c_str());
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator ittP;
for (ittP = result.begin(); ittP != result.end(); ++ittP)
{
_HiddenDevices.insert(ittP[0][0]);
}
}
}
bAllowDeviceToBeHidden = true;
}
if (order.empty() || (!isAlpha))
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
else
{
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
if (hardwareid != "") {
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B "
"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"WHERE (A.HardwareID == %q) "
"ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), hardwareid.c_str(), order.c_str());
}
else {
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B "
"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), order.c_str());
}
}
}
else
{
if (iUser == -1) {
return;
}
if (rowid != "")
{
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, 0 as XOffset,"
" 0 as YOffset, 0 as PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B "
"WHERE (B.DeviceRowID==a.ID)"
" AND (B.SharedUserID==%lu) AND (A.ID=='%q')",
m_users[iUser].ID, rowid.c_str());
}
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, C.XOffset,"
" C.YOffset, C.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B,"
" DeviceToPlansMap as C "
"WHERE (C.PlanID=='%q') AND (C.DeviceRowID==a.ID)"
" AND (B.DeviceRowID==a.ID) "
"AND (B.SharedUserID==%lu) ORDER BY C.[Order]",
planID.c_str(), m_users[iUser].ID);
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, C.XOffset, C.YOffset,"
" C.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B,"
" DeviceToPlansMap as C, Plans as D "
"WHERE (D.FloorplanID=='%q') AND (D.ID==C.PlanID)"
" AND (C.DeviceRowID==a.ID) AND (B.DeviceRowID==a.ID)"
" AND (B.SharedUserID==%lu) ORDER BY C.[Order]",
floorID.c_str(), m_users[iUser].ID);
else {
if (!bDisplayHidden)
{
result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')");
if (!result.empty())
{
std::string pID = result[0][0];
result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)",
pID.c_str());
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator ittP;
for (ittP = result.begin(); ittP != result.end(); ++ittP)
{
_HiddenDevices.insert(ittP[0][0]);
}
}
}
bAllowDeviceToBeHidden = true;
}
if (order.empty() || (!isAlpha))
{
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
}
else
{
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, IFNULL(C.XOffset,0),"
" IFNULL(C.YOffset,0), IFNULL(C.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B "
"LEFT OUTER JOIN DeviceToPlansMap as C ON (C.DeviceRowID==A.ID)"
"WHERE (B.DeviceRowID==A.ID)"
" AND (B.SharedUserID==%lu) ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), m_users[iUser].ID, order.c_str());
}
}
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
unsigned char favorite = atoi(sd[12].c_str());
if ((planID != "") && (planID != "0"))
favorite = 1;
if ((bFetchFavorites) && (!favorite))
continue;
std::string sDeviceName = sd[3];
if (!bDisplayHidden)
{
if (_HiddenDevices.find(sd[0]) != _HiddenDevices.end())
continue;
if (sDeviceName[0] == '$')
{
if (bAllowDeviceToBeHidden)
continue;
if (planID.size() > 0)
sDeviceName = sDeviceName.substr(1);
}
}
int hardwareID = atoi(sd[14].c_str());
std::map<int, _tHardwareListInt>::iterator hItt = _hardwareNames.find(hardwareID);
if (hItt != _hardwareNames.end())
{
if ((!bDisplayDisabled) && (!(*hItt).second.Enabled))
continue;
}
unsigned int dType = atoi(sd[5].c_str());
unsigned int dSubType = atoi(sd[6].c_str());
unsigned int used = atoi(sd[4].c_str());
int nValue = atoi(sd[9].c_str());
std::string sValue = sd[10];
std::string sLastUpdate = sd[11];
if (sLastUpdate.size() > 19)
sLastUpdate = sLastUpdate.substr(0, 19);
if (iLastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= iLastUpdate)
continue;
}
_eSwitchType switchtype = (_eSwitchType)atoi(sd[13].c_str());
_eMeterType metertype = (_eMeterType)switchtype;
double AddjValue = atof(sd[15].c_str());
double AddjMulti = atof(sd[16].c_str());
double AddjValue2 = atof(sd[17].c_str());
double AddjMulti2 = atof(sd[18].c_str());
int LastLevel = atoi(sd[19].c_str());
int CustomImage = atoi(sd[20].c_str());
std::string strParam1 = base64_encode(sd[21]);
std::string strParam2 = base64_encode(sd[22]);
int iProtected = atoi(sd[23].c_str());
std::string Description = sd[27];
std::string sOptions = sd[28];
std::string sColor = sd[29];
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions);
struct tm ntime;
time_t checktime;
ParseSQLdatetime(checktime, ntime, sLastUpdate, tm1.tm_isdst);
bool bHaveTimeout = (now - checktime >= SensorTimeOut * 60);
if (dType == pTypeTEMP_RAIN)
continue; //dont want you for now
if ((rused == "true") && (!used))
continue;
if (
(rused == "false") &&
(used)
)
continue;
if (rfilter != "")
{
if (rfilter == "light")
{
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeChime) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)))
)
continue;
}
else if (rfilter == "temp")
{
if (
(dType != pTypeTEMP) &&
(dType != pTypeHUM) &&
(dType != pTypeTEMP_HUM) &&
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO) &&
(dType != pTypeEvohomeZone) &&
(dType != pTypeEvohomeWater) &&
(!((dType == pTypeWIND) && (dSubType == sTypeWIND4))) &&
(!((dType == pTypeUV) && (dSubType == sTypeUV3))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))) &&
(dType != pTypeThermostat1) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))) &&
(dType != pTypeRego6XXTemp)
)
continue;
}
else if (rfilter == "weather")
{
if (
(dType != pTypeWIND) &&
(dType != pTypeRAIN) &&
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO) &&
(dType != pTypeUV) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeVisibility))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeBaro))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)))
)
continue;
}
else if (rfilter == "utility")
{
if (
(dType != pTypeRFXMeter) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD))) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeVoltage))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCurrent))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeAlert))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypePressure))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypePercentage))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCustom))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeFan))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveClock))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatMode))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatFanMode))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeDistance))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeKwh))) &&
(dType != pTypeCURRENT) &&
(dType != pTypeCURRENTENERGY) &&
(dType != pTypeENERGY) &&
(dType != pTypePOWER) &&
(dType != pTypeP1Power) &&
(dType != pTypeP1Gas) &&
(dType != pTypeYouLess) &&
(dType != pTypeAirQuality) &&
(dType != pTypeLux) &&
(dType != pTypeUsage) &&
(!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))) &&
(!((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))) &&
(dType != pTypeWEIGHT) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwares)))
)
continue;
}
else if (rfilter == "wind")
{
if (
(dType != pTypeWIND)
)
continue;
}
else if (rfilter == "rain")
{
if (
(dType != pTypeRAIN)
)
continue;
}
else if (rfilter == "uv")
{
if (
(dType != pTypeUV)
)
continue;
}
else if (rfilter == "baro")
{
if (
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO)
)
continue;
}
else if (rfilter == "zwavealarms")
{
if (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm)))
continue;
}
}
std::string thisIdx = sd[0];
int devIdx = atoi(thisIdx.c_str());
if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) {
std::string typeOfThisOne = RFX_Type_Desc(dType, 1);
if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) {
root["result"][ii - 1]["PlanIDs"].append(atoi(sd[26].c_str()));
continue;
}
}
root["result"][ii]["HardwareID"] = hardwareID;
if (_hardwareNames.find(hardwareID) == _hardwareNames.end())
{
root["result"][ii]["HardwareName"] = "Unknown?";
root["result"][ii]["HardwareTypeVal"] = 0;
root["result"][ii]["HardwareType"] = "Unknown?";
}
else
{
root["result"][ii]["HardwareName"] = _hardwareNames[hardwareID].Name;
root["result"][ii]["HardwareTypeVal"] = _hardwareNames[hardwareID].HardwareTypeVal;
root["result"][ii]["HardwareType"] = _hardwareNames[hardwareID].HardwareType;
}
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Protected"] = (iProtected != 0);
CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(hardwareID);
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_SolarEdgeAPI)
{
int seSensorTimeOut = 60 * 24 * 60;
bHaveTimeout = (now - checktime >= seSensorTimeOut * 60);
}
else if (pHardware->HwdType == HTYPE_Wunderground)
{
CWunderground *pWHardware = reinterpret_cast<CWunderground *>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_DarkSky)
{
CDarkSky *pWHardware = reinterpret_cast<CDarkSky*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_AccuWeather)
{
CAccuWeather *pWHardware = reinterpret_cast<CAccuWeather*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_OpenWeatherMap)
{
COpenWeatherMap *pWHardware = reinterpret_cast<COpenWeatherMap*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
}
if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_PythonPlugin))
{
root["result"][ii]["ID"] = sd[1];
}
else
{
sprintf(szData, "%04X", (unsigned int)atoi(sd[1].c_str()));
if (
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_BARO) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeBARO) ||
(dType == pTypeHUM) ||
(dType == pTypeWIND) ||
(dType == pTypeRAIN) ||
(dType == pTypeUV) ||
(dType == pTypeCURRENT) ||
(dType == pTypeCURRENTENERGY) ||
(dType == pTypeENERGY) ||
(dType == pTypeRFXMeter) ||
(dType == pTypeAirQuality) ||
(dType == pTypeRFXSensor) ||
(dType == pTypeP1Power) ||
(dType == pTypeP1Gas)
)
{
root["result"][ii]["ID"] = szData;
}
else
{
root["result"][ii]["ID"] = sd[1];
}
}
root["result"][ii]["Unit"] = atoi(sd[2].c_str());
root["result"][ii]["Type"] = RFX_Type_Desc(dType, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(dType, dSubType);
root["result"][ii]["TypeImg"] = RFX_Type_Desc(dType, 2);
root["result"][ii]["Name"] = sDeviceName;
root["result"][ii]["Description"] = Description;
root["result"][ii]["Used"] = used;
root["result"][ii]["Favorite"] = favorite;
int iSignalLevel = atoi(sd[7].c_str());
if (iSignalLevel < 12)
root["result"][ii]["SignalLevel"] = iSignalLevel;
else
root["result"][ii]["SignalLevel"] = "-";
root["result"][ii]["BatteryLevel"] = atoi(sd[8].c_str());
root["result"][ii]["LastUpdate"] = sLastUpdate;
root["result"][ii]["CustomImage"] = CustomImage;
root["result"][ii]["XOffset"] = sd[24].c_str();
root["result"][ii]["YOffset"] = sd[25].c_str();
root["result"][ii]["PlanID"] = sd[26].c_str();
Json::Value jsonArray;
jsonArray.append(atoi(sd[26].c_str()));
root["result"][ii]["PlanIDs"] = jsonArray;
root["result"][ii]["AddjValue"] = AddjValue;
root["result"][ii]["AddjMulti"] = AddjMulti;
root["result"][ii]["AddjValue2"] = AddjValue2;
root["result"][ii]["AddjMulti2"] = AddjMulti2;
std::stringstream s_data;
s_data << int(nValue) << ", " << sValue;
root["result"][ii]["Data"] = s_data.str();
root["result"][ii]["Notifications"] = (m_notifications.HasNotifications(sd[0]) == true) ? "true" : "false";
root["result"][ii]["ShowNotifications"] = true;
bool bHasTimers = false;
if (
(dType == pTypeLighting1) ||
(dType == pTypeLighting2) ||
(dType == pTypeLighting3) ||
(dType == pTypeLighting4) ||
(dType == pTypeLighting5) ||
(dType == pTypeLighting6) ||
(dType == pTypeFan) ||
(dType == pTypeColorSwitch) ||
(dType == pTypeCurtain) ||
(dType == pTypeBlinds) ||
(dType == pTypeRFY) ||
(dType == pTypeChime) ||
(dType == pTypeThermostat2) ||
(dType == pTypeThermostat3) ||
(dType == pTypeThermostat4) ||
(dType == pTypeRemote) ||
(dType == pTypeGeneralSwitch) ||
(dType == pTypeHomeConfort) ||
(dType == pTypeFS20) ||
((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)) ||
((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))
)
{
bHasTimers = m_sql.HasTimers(sd[0]);
bHaveTimeout = false;
#ifdef WITH_OPENZWAVE
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
int nodeID = (ID & 0x0000FF00) >> 8;
bHaveTimeout = pZWave->HasNodeFailed(nodeID);
}
}
#endif
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
std::string IconFile = "Light";
std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage);
if (ittIcon != m_custom_light_icons_lookup.end())
{
IconFile = m_custom_light_icons[ittIcon->second].RootFile;
}
root["result"][ii]["Image"] = IconFile;
if (switchtype == STYPE_Dimmer)
{
root["result"][ii]["Level"] = LastLevel;
int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel);
root["result"][ii]["LevelInt"] = iLevel;
if ((dType == pTypeColorSwitch) ||
(dType == pTypeLighting5 && dSubType == sTypeTRC02) ||
(dType == pTypeLighting5 && dSubType == sTypeTRC02_2) ||
(dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02) ||
(dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02_2))
{
_tColor color(sColor);
std::string jsonColor = color.toJSONString();
root["result"][ii]["Color"] = jsonColor;
llevel = LastLevel;
if (lstatus == "Set Level" || lstatus == "Set Color")
{
sprintf(szTmp, "Set Level: %d %%", LastLevel);
root["result"][ii]["Status"] = szTmp;
}
}
}
else
{
root["result"][ii]["Level"] = llevel;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
}
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
std::string DimmerType = "none";
if (switchtype == STYPE_Dimmer)
{
DimmerType = "abs";
if (_hardwareNames.find(hardwareID) != _hardwareNames.end())
{
if (_hardwareNames[hardwareID].HardwareTypeVal == HTYPE_LimitlessLights &&
atoi(_hardwareNames[hardwareID].Mode2.c_str()) != CLimitLess::LBTYPE_V6 &&
(atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_RGB ||
atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_White ||
atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_CW_WW))
{
DimmerType = "rel";
}
}
}
root["result"][ii]["DimmerType"] = DimmerType;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(switchtype);
root["result"][ii]["SwitchTypeVal"] = switchtype;
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
bool bIsSubDevice = false;
std::vector<std::vector<std::string> > resultSD;
resultSD = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')",
sd[0].c_str());
bIsSubDevice = (resultSD.size() > 0);
root["result"][ii]["IsSubDevice"] = bIsSubDevice;
if (switchtype == STYPE_Doorbell)
{
root["result"][ii]["TypeImg"] = "doorbell";
root["result"][ii]["Status"] = "";//"Pressed";
}
else if (switchtype == STYPE_DoorContact)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Open" : "Closed";
if (bIsOn) {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_DoorLock)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Locked" : "Unlocked";
if (bIsOn) {
lstatus = "Locked";
}
else {
lstatus = "Unlocked";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_DoorLockInverted)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Unlocked" : "Locked";
if (bIsOn) {
lstatus = "Unlocked";
}
else {
lstatus = "Locked";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_PushOn)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Push";
}
root["result"][ii]["TypeImg"] = "push";
root["result"][ii]["Status"] = "";
root["result"][ii]["InternalState"] = (IsLightSwitchOn(lstatus) == true) ? "On" : "Off";
}
else if (switchtype == STYPE_PushOff)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Push";
}
root["result"][ii]["TypeImg"] = "push";
root["result"][ii]["Status"] = "";
root["result"][ii]["TypeImg"] = "pushoff";
}
else if (switchtype == STYPE_X10Siren)
root["result"][ii]["TypeImg"] = "siren";
else if (switchtype == STYPE_SMOKEDETECTOR)
{
root["result"][ii]["TypeImg"] = "smoke";
root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR);
}
else if (switchtype == STYPE_Contact)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Contact";
}
root["result"][ii]["TypeImg"] = "contact";
bool bIsOn = IsLightSwitchOn(lstatus);
if (bIsOn) {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_Media)
{
if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_LogitechMediaServer))
root["result"][ii]["TypeImg"] = "LogitechMediaServer";
else
root["result"][ii]["TypeImg"] = "Media";
root["result"][ii]["Status"] = Media_Player_States((_eMediaStatus)nValue);
lstatus = sValue;
}
else if (
(switchtype == STYPE_Blinds) ||
(switchtype == STYPE_VenetianBlindsUS) ||
(switchtype == STYPE_VenetianBlindsEU)
)
{
root["result"][ii]["TypeImg"] = "blinds";
if ((lstatus == "On") || (lstatus == "Close inline relay")) {
lstatus = "Closed";
}
else if ((lstatus == "Stop") || (lstatus == "Stop inline relay")) {
lstatus = "Stopped";
}
else {
lstatus = "Open";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_BlindsInverted)
{
root["result"][ii]["TypeImg"] = "blinds";
if (lstatus == "On") {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if ((switchtype == STYPE_BlindsPercentage) || (switchtype == STYPE_BlindsPercentageInverted))
{
root["result"][ii]["TypeImg"] = "blinds";
root["result"][ii]["Level"] = LastLevel;
int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel);
root["result"][ii]["LevelInt"] = iLevel;
if (lstatus == "On") {
lstatus = (switchtype == STYPE_BlindsPercentage) ? "Closed" : "Open";
}
else if (lstatus == "Off") {
lstatus = (switchtype == STYPE_BlindsPercentage) ? "Open" : "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_Dimmer)
{
root["result"][ii]["TypeImg"] = "dimmer";
}
else if (switchtype == STYPE_Motion)
{
root["result"][ii]["TypeImg"] = "motion";
}
else if (switchtype == STYPE_Selector)
{
std::string selectorStyle = options["SelectorStyle"];
std::string levelOffHidden = options["LevelOffHidden"];
std::string levelNames = options["LevelNames"];
std::string levelActions = options["LevelActions"];
if (selectorStyle.empty()) {
selectorStyle.assign("0"); // default is 'button set'
}
if (levelOffHidden.empty()) {
levelOffHidden.assign("false"); // default is 'not hidden'
}
if (levelNames.empty()) {
levelNames.assign("Off"); // default is Off only
}
root["result"][ii]["TypeImg"] = "Light";
root["result"][ii]["SelectorStyle"] = atoi(selectorStyle.c_str());
root["result"][ii]["LevelOffHidden"] = (levelOffHidden == "true");
root["result"][ii]["LevelNames"] = base64_encode(levelNames);
root["result"][ii]["LevelActions"] = base64_encode(levelActions);
}
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
}
else if (dType == pTypeSecurity1)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "Security";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "security";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
if ((dSubType == sTypeKD101) || (dSubType == sTypeSA30) || (switchtype == STYPE_SMOKEDETECTOR))
{
root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR;
root["result"][ii]["TypeImg"] = "smoke";
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR);
}
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeSecurity2)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "Security";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "security";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeEvohome || dType == pTypeEvohomeRelay)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "evohome";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "override_mini";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
if (dType == pTypeEvohomeRelay)
{
root["result"][ii]["SwitchType"] = "TPI";
root["result"][ii]["Level"] = llevel;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
if (root["result"][ii]["Unit"].asInt() > 100)
root["result"][ii]["Protected"] = true;
sprintf(szData, "%s: %d", lstatus.c_str(), atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
}
}
else if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "override_mini";
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() >= 3)
{
int i = 0;
double tempCelcius = atof(strarray[i++].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
double tempSetPoint;
root["result"][ii]["Temp"] = temp;
if (dType == pTypeEvohomeZone)
{
tempCelcius = atof(strarray[i++].c_str());
tempSetPoint = ConvertTemperature(tempCelcius, tempsign);
root["result"][ii]["SetPoint"] = tempSetPoint;
}
else
root["result"][ii]["State"] = strarray[i++];
std::string strstatus = strarray[i++];
root["result"][ii]["Status"] = strstatus;
if ((dType == pTypeEvohomeZone || dType == pTypeEvohomeWater) && strarray.size() >= 4)
{
root["result"][ii]["Until"] = strarray[i++];
}
if (dType == pTypeEvohomeZone)
{
if (tempCelcius == 325.1)
sprintf(szTmp, "Off");
else
sprintf(szTmp, "%.1f %c", tempSetPoint, tempsign);
if (strarray.size() >= 4)
sprintf(szData, "%.1f %c, (%s), %s until %s", temp, tempsign, szTmp, strstatus.c_str(), strarray[3].c_str());
else
sprintf(szData, "%.1f %c, (%s), %s", temp, tempsign, szTmp, strstatus.c_str());
}
else
if (strarray.size() >= 4)
sprintf(szData, "%.1f %c, %s, %s until %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str(), strarray[3].c_str());
else
sprintf(szData, "%.1f %c, %s, %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if ((dType == pTypeTEMP) || (dType == pTypeRego6XXTemp))
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dType == pTypeThermostat1)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 4)
{
double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if ((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "temperature";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dType == pTypeHUM)
{
root["result"][ii]["Humidity"] = nValue;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(sValue.c_str()));
sprintf(szData, "Humidity %d %%", nValue);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeTEMP_HUM)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 3)
{
double tempCelcius = atof(strarray[0].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
int humidity = atoi(strarray[1].c_str());
root["result"][ii]["Temp"] = temp;
root["result"][ii]["Humidity"] = humidity;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str()));
sprintf(szData, "%.1f %c, %d %%", temp, tempsign, atoi(strarray[1].c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign));
root["result"][ii]["DewPoint"] = szTmp;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeTEMP_HUM_BARO)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 5)
{
double tempCelcius = atof(strarray[0].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
int humidity = atoi(strarray[1].c_str());
root["result"][ii]["Temp"] = temp;
root["result"][ii]["Humidity"] = humidity;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str()));
root["result"][ii]["Forecast"] = atoi(strarray[4].c_str());
sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign));
root["result"][ii]["DewPoint"] = szTmp;
if (dSubType == sTypeTHBFloat)
{
root["result"][ii]["Barometer"] = atof(strarray[3].c_str());
root["result"][ii]["ForecastStr"] = RFX_WSForecast_Desc(atoi(strarray[4].c_str()));
}
else
{
root["result"][ii]["Barometer"] = atoi(strarray[3].c_str());
root["result"][ii]["ForecastStr"] = RFX_Forecast_Desc(atoi(strarray[4].c_str()));
}
if (dSubType == sTypeTHBFloat)
{
sprintf(szData, "%.1f %c, %d %%, %.1f hPa",
temp,
tempsign,
atoi(strarray[1].c_str()),
atof(strarray[3].c_str())
);
}
else
{
sprintf(szData, "%.1f %c, %d %%, %d hPa",
temp,
tempsign,
atoi(strarray[1].c_str()),
atoi(strarray[3].c_str())
);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeTEMP_BARO)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() >= 3)
{
double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
int forecast = atoi(strarray[2].c_str());
root["result"][ii]["Forecast"] = forecast;
root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast);
root["result"][ii]["Barometer"] = atof(strarray[1].c_str());
sprintf(szData, "%.1f %c, %.1f hPa",
tvalue,
tempsign,
atof(strarray[1].c_str())
);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeUV)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
float UVI = static_cast<float>(atof(strarray[0].c_str()));
root["result"][ii]["UVI"] = strarray[0];
if (dSubType == sTypeUV3)
{
double tvalue = ConvertTemperature(atof(strarray[1].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f UVI, %.1f° %c", UVI, tvalue, tempsign);
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else
{
sprintf(szData, "%.1f UVI", UVI);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeWIND)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 6)
{
root["result"][ii]["Direction"] = atof(strarray[0].c_str());
root["result"][ii]["DirectionStr"] = strarray[1];
if (dSubType != sTypeWIND5)
{
int intSpeed = atoi(strarray[2].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
}
else
{
float windms = float(intSpeed) * 0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windms));
}
root["result"][ii]["Speed"] = szTmp;
}
{
int intGust = atoi(strarray[3].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intGust) *m_sql.m_windscale);
}
else
{
float gustms = float(intGust) * 0.1f;
sprintf(szTmp, "%d", MStoBeaufort(gustms));
}
root["result"][ii]["Gust"] = szTmp;
}
if ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp))
{
if (dSubType == sTypeWIND4)
{
double tvalue = ConvertTemperature(atof(strarray[4].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
}
double tvalue = ConvertTemperature(atof(strarray[5].c_str()), tempsign);
root["result"][ii]["Chill"] = tvalue;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeRAIN)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
if (dSubType != sTypeRAINWU)
{
result2 = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total) FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
}
else
{
result2 = m_sql.safe_query(
"SELECT Total, Total FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q') ORDER BY ROWID DESC LIMIT 1", sd[0].c_str(), szDate);
}
if (!result2.empty())
{
double total_real = 0;
float rate = 0;
std::vector<std::string> sd2 = result2[0];
if (dSubType != sTypeRAINWU)
{
double total_min = atof(sd2[0].c_str());
double total_max = atof(strarray[1].c_str());
total_real = total_max - total_min;
}
else
{
total_real = atof(sd2[1].c_str());
}
total_real *= AddjMulti;
rate = (static_cast<float>(atof(strarray[0].c_str())) / 100.0f)*float(AddjMulti);
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["Rain"] = szTmp;
sprintf(szTmp, "%g", rate);
root["result"][ii]["RainRate"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else
{
root["result"][ii]["Rain"] = "0";
root["result"][ii]["RainRate"] = "0";
root["result"][ii]["Data"] = "0";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
}
else if (dType == pTypeRFXMeter)
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min = std::stoull(sd2[0]);
uint64_t total_max = std::stoull(sValue);
uint64_t total_real = total_max - total_min;
sprintf(szTmp, "%" PRIu64, total_real);
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
float musage = 0.0f;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / (divider / 1000.0f);
sprintf(szTmp, "%d Liter", round(musage));
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64, total_real);
if (!ValueUnits.empty())
{
strcat(szTmp, " ");
strcat(szTmp, ValueUnits.c_str());
}
break;
default:
strcpy(szTmp, "?");
break;
}
}
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
double meteroffset = AddjValue;
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
double dvalue = static_cast<double>(atof(sValue.c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min = std::stoull(sd2[0]);
uint64_t total_max = std::stoull(sValue);
uint64_t total_real = total_max - total_min;
sprintf(szTmp, "%" PRIu64, total_real);
float musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64, total_real);
if (!ValueUnits.empty())
{
strcat(szTmp, " ");
strcat(szTmp, ValueUnits.c_str());
}
break;
default:
strcpy(szTmp, "0");
break;
}
}
root["result"][ii]["Counter"] = sValue;
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "counter";
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
double dvalue = static_cast<double>(atof(sValue.c_str()));
double meteroffset = AddjValue;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64 " %s", static_cast<uint64_t>(meteroffset + dvalue), ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
double dvalue;
if (splitresults.size() < 2) {
dvalue = static_cast<double>(atof(sValue.c_str()));
}
else {
dvalue = static_cast<double>(atof(splitresults[1].c_str()));
if (dvalue < 0.0) {
dvalue = static_cast<double>(atof(splitresults[0].c_str()));
}
}
root["result"][ii]["Data"] = root["result"][ii]["Counter"];
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "counter";
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
root["result"][ii]["ShowNotifications"] = false;
double meteroffset = AddjValue;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if (dType == pTypeYouLess)
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
float musage = 0;
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu %s", total_real, ValueUnits.c_str());
break;
default:
strcpy(szTmp, "0");
break;
}
}
root["result"][ii]["CounterToday"] = szTmp;
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() < 2)
continue;
unsigned long long total_actual = std::strtoull(splitresults[0].c_str(), nullptr, 10);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_actual) / divider;
sprintf(szTmp, "%.03f", musage);
break;
case MTYPE_GAS:
case MTYPE_WATER:
musage = float(total_actual) / divider;
sprintf(szTmp, "%.03f", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu", total_actual);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
unsigned long long acounter = std::strtoull(sValue.c_str(), nullptr, 10);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f kWh %s Watt", musage, splitresults[1].c_str());
break;
case MTYPE_GAS:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu %s", acounter, ValueUnits.c_str());
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%s Watt", splitresults[1].c_str());
break;
case MTYPE_GAS:
sprintf(szTmp, "%s m3", splitresults[1].c_str());
break;
case MTYPE_WATER:
sprintf(szTmp, "%s m3", splitresults[1].c_str());
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%s", splitresults[1].c_str());
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Usage"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeP1Power)
{
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() != 6)
{
root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY;
root["result"][ii]["Counter"] = "0";
root["result"][ii]["CounterDeliv"] = "0";
root["result"][ii]["Usage"] = "Invalid";
root["result"][ii]["UsageDeliv"] = "Invalid";
root["result"][ii]["Data"] = "Invalid!: " + sValue;
root["result"][ii]["HaveTimeout"] = true;
root["result"][ii]["CounterToday"] = "Invalid";
root["result"][ii]["CounterDelivToday"] = "Invalid";
}
else
{
float EnergyDivider = 1000.0f;
int tValue;
if (m_sql.GetPreferencesVar("MeterDividerEnergy", tValue))
{
EnergyDivider = float(tValue);
}
unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10);
unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10);
unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10);
unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10);
unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10);
unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10);
powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1;
powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2;
unsigned long long powerusage = powerusage1 + powerusage2;
unsigned long long powerdeliv = powerdeliv1 + powerdeliv2;
if (powerdeliv < 2)
powerdeliv = 0;
double musage = 0;
root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY;
musage = double(powerusage) / EnergyDivider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["Counter"] = szTmp;
musage = double(powerdeliv) / EnergyDivider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["CounterDeliv"] = szTmp;
if (bHaveTimeout)
{
usagecurrent = 0;
delivcurrent = 0;
}
sprintf(szTmp, "%llu Watt", usagecurrent);
root["result"][ii]["Usage"] = szTmp;
sprintf(szTmp, "%llu Watt", delivcurrent);
root["result"][ii]["UsageDeliv"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value1), MIN(Value2), MIN(Value5), MIN(Value6) FROM MultiMeter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min_usage_1 = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_min_deliv_1 = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd2[2].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd2[3].c_str(), nullptr, 10);
unsigned long long total_real_usage, total_real_deliv;
total_real_usage = powerusage - (total_min_usage_1 + total_min_usage_2);
total_real_deliv = powerdeliv - (total_min_deliv_1 + total_min_deliv_2);
musage = double(total_real_usage) / EnergyDivider;
sprintf(szTmp, "%.3f kWh", musage);
root["result"][ii]["CounterToday"] = szTmp;
musage = double(total_real_deliv) / EnergyDivider;
sprintf(szTmp, "%.3f kWh", musage);
root["result"][ii]["CounterDelivToday"] = szTmp;
}
else
{
sprintf(szTmp, "%.3f kWh", 0.0f);
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["CounterDelivToday"] = szTmp;
}
}
}
else if (dType == pTypeP1Gas)
{
root["result"][ii]["SwitchTypeVal"] = MTYPE_GAS;
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min_gas = std::stoull(sd2[0]);
uint64_t gasactual = std::stoull(sValue);
uint64_t total_real_gas = gasactual - total_min_gas;
double musage = double(gasactual) / divider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["Counter"] = szTmp;
musage = double(total_real_gas) / divider;
sprintf(szTmp, "%.03f m3", musage);
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider);
root["result"][ii]["Data"] = szTmp;
}
else
{
sprintf(szTmp, "%.03f", 0.0f);
root["result"][ii]["Counter"] = szTmp;
sprintf(szTmp, "%.03f m3", 0.0f);
root["result"][ii]["CounterToday"] = szTmp;
sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeCURRENT)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 3)
{
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
double val1 = atof(strarray[0].c_str());
double val2 = atof(strarray[1].c_str());
double val3 = atof(strarray[2].c_str());
if (displaytype == 0)
{
if ((val2 == 0) && (val3 == 0))
sprintf(szData, "%.1f A", val1);
else
sprintf(szData, "%.1f A, %.1f A, %.1f A", val1, val2, val3);
}
else
{
if ((val2 == 0) && (val3 == 0))
sprintf(szData, "%d Watt", int(val1*voltage));
else
sprintf(szData, "%d Watt, %d Watt, %d Watt", int(val1*voltage), int(val2*voltage), int(val3*voltage));
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["displaytype"] = displaytype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeCURRENTENERGY)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 4)
{
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
double total = atof(strarray[3].c_str());
if (displaytype == 0)
{
sprintf(szData, "%.1f A, %.1f A, %.1f A", atof(strarray[0].c_str()), atof(strarray[1].c_str()), atof(strarray[2].c_str()));
}
else
{
sprintf(szData, "%d Watt, %d Watt, %d Watt", int(atof(strarray[0].c_str())*voltage), int(atof(strarray[1].c_str())*voltage), int(atof(strarray[2].c_str())*voltage));
}
if (total > 0)
{
sprintf(szTmp, ", Total: %.3f kWh", total / 1000.0f);
strcat(szData, szTmp);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["displaytype"] = displaytype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (
((dType == pTypeENERGY) || (dType == pTypePOWER)) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
double total = atof(strarray[1].c_str()) / 1000;
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::vector<std::string> sd2 = result2[0];
double minimum = atof(sd2[0].c_str()) / divider;
sprintf(szData, "%.3f kWh", total);
root["result"][ii]["Data"] = szData;
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
{
sprintf(szData, "%ld Watt", atol(strarray[0].c_str()));
}
else
{
sprintf(szData, "%g Watt", atof(strarray[0].c_str()));
}
root["result"][ii]["Usage"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.3f kWh", total - minimum);
root["result"][ii]["CounterToday"] = szTmp;
}
else
{
sprintf(szData, "%.3f kWh", total);
root["result"][ii]["Data"] = szData;
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
{
sprintf(szData, "%ld Watt", atol(strarray[0].c_str()));
}
else
{
sprintf(szData, "%g Watt", atof(strarray[0].c_str()));
}
root["result"][ii]["Usage"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%d kWh", 0);
root["result"][ii]["CounterToday"] = szTmp;
}
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["SwitchTypeVal"] = switchtype; //MTYPE_ENERGY
root["result"][ii]["EnergyMeterMode"] = options["EnergyMeterMode"]; //for alternate Energy Reading
}
}
else if (dType == pTypeAirQuality)
{
if (bHaveTimeout)
nValue = 0;
sprintf(szTmp, "%d ppm", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
int airquality = nValue;
if (airquality < 700)
root["result"][ii]["Quality"] = "Excellent";
else if (airquality < 900)
root["result"][ii]["Quality"] = "Good";
else if (airquality < 1100)
root["result"][ii]["Quality"] = "Fair";
else if (airquality < 1600)
root["result"][ii]["Quality"] = "Mediocre";
else
root["result"][ii]["Quality"] = "Bad";
}
else if (dType == pTypeThermostat)
{
if (dSubType == sTypeThermSetpoint)
{
bHasTimers = m_sql.HasTimers(sd[0]);
double tempCelcius = atof(sValue.c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
sprintf(szTmp, "%.1f", temp);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["SetPoint"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "override_mini";
}
}
else if (dType == pTypeRadiator1)
{
if (dSubType == sTypeSmartwares)
{
bHasTimers = m_sql.HasTimers(sd[0]);
double tempCelcius = atof(sValue.c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
sprintf(szTmp, "%.1f", temp);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["SetPoint"] = szTmp;
root["result"][ii]["HaveTimeout"] = false; //this device does not provide feedback, so no timeout!
root["result"][ii]["TypeImg"] = "override_mini";
}
}
else if (dType == pTypeGeneral)
{
if (dSubType == sTypeVisibility)
{
float vis = static_cast<float>(atof(sValue.c_str()));
if (metertype == 0)
{
sprintf(szTmp, "%.1f km", vis);
}
else
{
sprintf(szTmp, "%.1f mi", vis*0.6214f);
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Visibility"] = atof(sValue.c_str());
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "visibility";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeDistance)
{
float vis = static_cast<float>(atof(sValue.c_str()));
if (metertype == 0)
{
sprintf(szTmp, "%.1f cm", vis);
}
else
{
sprintf(szTmp, "%.1f in", vis*0.6214f);
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "visibility";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSolarRadiation)
{
float radiation = static_cast<float>(atof(sValue.c_str()));
sprintf(szTmp, "%.1f Watt/m2", radiation);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Radiation"] = atof(sValue.c_str());
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "radiation";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSoilMoisture)
{
sprintf(szTmp, "%d cb", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Desc"] = Get_Moisture_Desc(nValue);
root["result"][ii]["TypeImg"] = "moisture";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeLeafWetness)
{
sprintf(szTmp, "%d", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["TypeImg"] = "leaf";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSystemTemp)
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Computer";
root["result"][ii]["TypeImg"] = "temperature";
root["result"][ii]["Type"] = "temperature";
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dSubType == sTypePercentage)
{
sprintf(szData, "%g%%", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Computer";
root["result"][ii]["TypeImg"] = "hardware";
}
else if (dSubType == sTypeWaterflow)
{
sprintf(szData, "%g l/min", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Moisture";
root["result"][ii]["TypeImg"] = "moisture";
}
else if (dSubType == sTypeCustom)
{
std::string szAxesLabel = "";
int SensorType = 1;
std::vector<std::string> sResults;
StringSplit(sOptions, ";", sResults);
if (sResults.size() == 2)
{
SensorType = atoi(sResults[0].c_str());
szAxesLabel = sResults[1];
}
sprintf(szData, "%g %s", atof(sValue.c_str()), szAxesLabel.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["SensorType"] = SensorType;
root["result"][ii]["SensorUnit"] = szAxesLabel;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string IconFile = "Custom";
if (CustomImage != 0)
{
std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage);
if (ittIcon != m_custom_light_icons_lookup.end())
{
IconFile = m_custom_light_icons[ittIcon->second].RootFile;
}
}
root["result"][ii]["Image"] = IconFile;
root["result"][ii]["TypeImg"] = IconFile;
}
else if (dSubType == sTypeFan)
{
sprintf(szData, "%d RPM", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Fan";
root["result"][ii]["TypeImg"] = "Fan";
}
else if (dSubType == sTypeSoundLevel)
{
sprintf(szData, "%d dB", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "Speaker";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dSubType == sTypeVoltage)
{
sprintf(szData, "%g V", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Voltage"] = atof(sValue.c_str());
}
else if (dSubType == sTypeCurrent)
{
sprintf(szData, "%g A", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Current"] = atof(sValue.c_str());
}
else if (dSubType == sTypeTextStatus)
{
root["result"][ii]["Data"] = sValue;
root["result"][ii]["TypeImg"] = "text";
root["result"][ii]["HaveTimeout"] = false;
root["result"][ii]["ShowNotifications"] = false;
}
else if (dSubType == sTypeAlert)
{
if (nValue > 4)
nValue = 4;
sprintf(szData, "Level: %d", nValue);
root["result"][ii]["Data"] = szData;
if (!sValue.empty())
root["result"][ii]["Data"] = sValue;
else
root["result"][ii]["Data"] = Get_Alert_Desc(nValue);
root["result"][ii]["TypeImg"] = "Alert";
root["result"][ii]["Level"] = nValue;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dSubType == sTypePressure)
{
sprintf(szData, "%.1f Bar", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "gauge";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Pressure"] = atof(sValue.c_str());
}
else if (dSubType == sTypeBaro)
{
std::vector<std::string> tstrarray;
StringSplit(sValue, ";", tstrarray);
if (tstrarray.empty())
continue;
sprintf(szData, "%g hPa", atof(tstrarray[0].c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "gauge";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
if (tstrarray.size() > 1)
{
root["result"][ii]["Barometer"] = atof(tstrarray[0].c_str());
int forecast = atoi(tstrarray[1].c_str());
root["result"][ii]["Forecast"] = forecast;
root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast);
}
}
else if (dSubType == sTypeZWaveClock)
{
std::vector<std::string> tstrarray;
StringSplit(sValue, ";", tstrarray);
int day = 0;
int hour = 0;
int minute = 0;
if (tstrarray.size() == 3)
{
day = atoi(tstrarray[0].c_str());
hour = atoi(tstrarray[1].c_str());
minute = atoi(tstrarray[2].c_str());
}
sprintf(szData, "%s %02d:%02d", ZWave_Clock_Days(day), hour, minute);
root["result"][ii]["DayTime"] = sValue;
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "clock";
}
else if (dSubType == sTypeZWaveThermostatMode)
{
strcpy(szData, "");
root["result"][ii]["Mode"] = nValue;
root["result"][ii]["TypeImg"] = "mode";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string modes = "";
#ifdef WITH_OPENZWAVE
if (pHardware)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
std::vector<std::string> vmodes = pZWave->GetSupportedThermostatModes(ID);
int smode = 0;
char szTmp[200];
for (const auto & itt : vmodes)
{
sprintf(szTmp, "%d;%s;", smode, itt.c_str());
modes += szTmp;
smode++;
}
if (!vmodes.empty())
{
if (nValue < (int)vmodes.size())
{
sprintf(szData, "%s", vmodes[nValue].c_str());
}
}
}
}
#endif
root["result"][ii]["Data"] = szData;
root["result"][ii]["Modes"] = modes;
}
else if (dSubType == sTypeZWaveThermostatFanMode)
{
sprintf(szData, "%s", ZWave_Thermostat_Fan_Modes[nValue]);
root["result"][ii]["Data"] = szData;
root["result"][ii]["Mode"] = nValue;
root["result"][ii]["TypeImg"] = "mode";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
bool bAddedSupportedModes = false;
std::string modes = "";
#ifdef WITH_OPENZWAVE
if (pHardware)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
modes = pZWave->GetSupportedThermostatFanModes(ID);
bAddedSupportedModes = !modes.empty();
}
}
#endif
if (!bAddedSupportedModes)
{
int smode = 0;
while (ZWave_Thermostat_Fan_Modes[smode] != NULL)
{
sprintf(szTmp, "%d;%s;", smode, ZWave_Thermostat_Fan_Modes[smode]);
modes += szTmp;
smode++;
}
}
root["result"][ii]["Modes"] = modes;
}
else if (dSubType == sTypeZWaveAlarm)
{
sprintf(szData, "Event: 0x%02X (%d)", nValue, nValue);
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "Alert";
root["result"][ii]["Level"] = nValue;
root["result"][ii]["HaveTimeout"] = false;
}
}
else if (dType == pTypeLux)
{
sprintf(szTmp, "%.0f Lux", atof(sValue.c_str()));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeWEIGHT)
{
sprintf(szTmp, "%g %s", m_sql.m_weightscale * atof(sValue.c_str()), m_sql.m_weightsign.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeUsage)
{
if (dSubType == sTypeElectric)
{
sprintf(szData, "%g Watt", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
}
else
{
root["result"][ii]["Data"] = sValue;
}
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeRFXSensor)
{
switch (dSubType)
{
case sTypeRFXSensorAD:
sprintf(szData, "%d mV", atoi(sValue.c_str()));
root["result"][ii]["TypeImg"] = "current";
break;
case sTypeRFXSensorVolt:
sprintf(szData, "%d mV", atoi(sValue.c_str()));
root["result"][ii]["TypeImg"] = "current";
break;
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeRego6XXValue)
{
switch (dSubType)
{
case sTypeRego6XXStatus:
{
std::string lstatus = "On";
if (atoi(sValue.c_str()) == 0)
{
lstatus = "Off";
}
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = false;
root["result"][ii]["MaxDimLevel"] = 0;
root["result"][ii]["HaveGroupCmd"] = false;
root["result"][ii]["TypeImg"] = "utility";
root["result"][ii]["SwitchTypeVal"] = STYPE_OnOff;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_OnOff);
sprintf(szData, "%d", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
if (CustomImage < static_cast<int>(m_custom_light_icons.size()))
root["result"][ii]["Image"] = m_custom_light_icons[CustomImage].RootFile;
else
root["result"][ii]["Image"] = "Light";
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
root["result"][ii]["Level"] = 0;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
}
break;
case sTypeRego6XXCounter:
{
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
}
root["result"][ii]["SwitchTypeVal"] = MTYPE_COUNTER;
root["result"][ii]["Counter"] = sValue;
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
break;
}
}
#ifdef ENABLE_PYTHON
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_PythonPlugin)
{
Plugins::CPlugin *pPlugin = (Plugins::CPlugin*)pHardware;
bHaveTimeout = pPlugin->HasNodeFailed(atoi(sd[2].c_str()));
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
#endif
root["result"][ii]["Timers"] = (bHasTimers == true) ? "true" : "false";
ii++;
}
}
}
Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
CWE ID: CWE-89
| 0
| 91,037
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void clear_huge_page(struct page *page,
unsigned long addr, unsigned int pages_per_huge_page)
{
int i;
if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
clear_gigantic_page(page, addr, pages_per_huge_page);
return;
}
might_sleep();
for (i = 0; i < pages_per_huge_page; i++) {
cond_resched();
clear_user_highpage(page + i, addr + i * PAGE_SIZE);
}
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
| 0
| 21,210
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: dump_extra(Buffer *buf)
{
printf("W3m-current-url: %s\n", parsedURL2Str(&buf->currentURL)->ptr);
if (buf->baseURL)
printf("W3m-base-url: %s\n", parsedURL2Str(buf->baseURL)->ptr);
#ifdef USE_M17N
printf("W3m-document-charset: %s\n",
wc_ces_to_charset(buf->document_charset));
#endif
#ifdef USE_SSL
if (buf->ssl_certificate) {
Str tmp = Strnew();
char *p;
for (p = buf->ssl_certificate; *p; p++) {
Strcat_char(tmp, *p);
if (*p == '\n') {
for (; *(p + 1) == '\n'; p++) ;
if (*(p + 1))
Strcat_char(tmp, '\t');
}
}
if (Strlastchar(tmp) != '\n')
Strcat_char(tmp, '\n');
printf("W3m-ssl-certificate: %s", tmp->ptr);
}
#endif
}
Commit Message: Make temporary directory safely when ~/.w3m is unwritable
CWE ID: CWE-59
| 0
| 84,490
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static asmlinkage void do_default_vi(void)
{
show_regs(get_irq_regs());
panic("Caught unexpected vectored interrupt.");
}
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
| 0
| 25,394
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: get_ticket_flags(krb5_flags reqflags, krb5_db_entry *client,
krb5_db_entry *server, krb5_enc_tkt_part *header_enc)
{
krb5_flags flags;
/* Indicate support for encrypted padata (RFC 6806), and set flags based on
* request options and the header ticket. */
flags = OPTS2FLAGS(reqflags) | TKT_FLG_ENC_PA_REP;
if (reqflags & KDC_OPT_POSTDATED)
flags |= TKT_FLG_INVALID;
if (header_enc != NULL)
flags |= COPY_TKT_FLAGS(header_enc->flags);
if (header_enc == NULL)
flags |= TKT_FLG_INITIAL;
/* For TGS requests, indicate if the service is marked ok-as-delegate. */
if (header_enc != NULL && (server->attributes & KRB5_KDB_OK_AS_DELEGATE))
flags |= TKT_FLG_OK_AS_DELEGATE;
/* Unset PROXIABLE if it is disallowed. */
if (client != NULL && (client->attributes & KRB5_KDB_DISALLOW_PROXIABLE))
flags &= ~TKT_FLG_PROXIABLE;
if (server->attributes & KRB5_KDB_DISALLOW_PROXIABLE)
flags &= ~TKT_FLG_PROXIABLE;
if (header_enc != NULL && !(header_enc->flags & TKT_FLG_PROXIABLE))
flags &= ~TKT_FLG_PROXIABLE;
/* Unset FORWARDABLE if it is disallowed. */
if (client != NULL && (client->attributes & KRB5_KDB_DISALLOW_FORWARDABLE))
flags &= ~TKT_FLG_FORWARDABLE;
if (server->attributes & KRB5_KDB_DISALLOW_FORWARDABLE)
flags &= ~TKT_FLG_FORWARDABLE;
if (header_enc != NULL && !(header_enc->flags & TKT_FLG_FORWARDABLE))
flags &= ~TKT_FLG_FORWARDABLE;
/* We don't currently handle issuing anonymous tickets based on
* non-anonymous ones. */
if (header_enc != NULL && !(header_enc->flags & TKT_FLG_ANONYMOUS))
flags &= ~TKT_FLG_ANONYMOUS;
return flags;
}
Commit Message: Ignore password attributes for S4U2Self requests
For consistency with Windows KDCs, allow protocol transition to work
even if the password has expired or needs changing.
Also, when looking up an enterprise principal with an AS request,
treat ERR_KEY_EXP as confirmation that the client is present in the
realm.
[[email protected]: added comment in kdc_process_s4u2self_req(); edited
commit message]
ticket: 8763 (new)
tags: pullup
target_version: 1.17
CWE ID: CWE-617
| 0
| 75,474
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void RenderProcessHostImpl::OnProcessLaunched() {
if (deleting_soon_)
return;
if (child_process_launcher_.get()) {
if (!child_process_launcher_->GetHandle()) {
OnChannelError();
return;
}
child_process_launcher_->SetProcessBackgrounded(backgrounded_);
}
NotificationService::current()->Notify(
NOTIFICATION_RENDERER_PROCESS_CREATED,
Source<RenderProcessHost>(this),
NotificationService::NoDetails());
while (!queued_messages_.empty()) {
Send(queued_messages_.front());
queued_messages_.pop();
}
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
| 0
| 114,546
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: bool OmniboxViewViews::MaybeUnfocusTabButton() {
if (SelectedSuggestionHasTabMatch() &&
model()->popup_model()->selected_line_state() ==
OmniboxPopupModel::BUTTON_FOCUSED) {
model()->popup_model()->SetSelectedLineState(OmniboxPopupModel::NORMAL);
return true;
}
return false;
}
Commit Message: omnibox: experiment with restoring placeholder when caret shows
Shows the "Search Google or type a URL" omnibox placeholder even when
the caret (text edit cursor) is showing / when focused. views::Textfield
works this way, as does <input placeholder="">. Omnibox and the NTP's
"fakebox" are exceptions in this regard and this experiment makes this
more consistent.
[email protected]
BUG=955585
Change-Id: I23c299c0973f2feb43f7a2be3bd3425a80b06c2d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1582315
Commit-Queue: Dan Beam <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654279}
CWE ID: CWE-200
| 0
| 142,436
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void UpdateSuddenTerminationStatus(
LocalDOMWindow* dom_window,
bool added_listener,
WebSuddenTerminationDisablerType disabler_type) {
Platform::Current()->SuddenTerminationChanged(!added_listener);
if (dom_window->GetFrame() && dom_window->GetFrame()->Client())
dom_window->GetFrame()->Client()->SuddenTerminationDisablerChanged(
added_listener, disabler_type);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
| 0
| 125,921
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void assertLayoutTreeUpdated(Node& root)
{
for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) {
if (!node.isElementNode()
&& !node.isTextNode()
&& !node.isShadowRoot()
&& !node.isDocumentNode())
continue;
ASSERT(!node.needsStyleRecalc());
ASSERT(!node.childNeedsStyleRecalc());
ASSERT(!node.childNeedsDistributionRecalc());
ASSERT(!node.needsStyleInvalidation());
ASSERT(!node.childNeedsStyleInvalidation());
for (ShadowRoot* shadowRoot = node.youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
assertLayoutTreeUpdated(*shadowRoot);
}
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
| 0
| 124,276
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: void UsbChooserContext::GetDevice(
const std::string& guid,
device::mojom::UsbDeviceRequest device_request,
device::mojom::UsbDeviceClientPtr device_client) {
EnsureConnectionWithDeviceManager();
device_manager_->GetDevice(guid, std::move(device_request),
std::move(device_client));
}
Commit Message: Enforce the WebUsbAllowDevicesForUrls policy
This change modifies UsbChooserContext to use the UsbAllowDevicesForUrls
class to consider devices allowed by the WebUsbAllowDevicesForUrls
policy. The WebUsbAllowDevicesForUrls policy overrides the other WebUSB
policies. Unit tests are also added to ensure that the policy is being
enforced correctly.
The design document for this feature is found at:
https://docs.google.com/document/d/1MPvsrWiVD_jAC8ELyk8njFpy6j1thfVU5aWT3TCWE8w
Bug: 854329
Change-Id: I5f82e662ca9dc544da5918eae766b5535a31296b
Reviewed-on: https://chromium-review.googlesource.com/c/1259289
Commit-Queue: Ovidio Henriquez <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Julian Pastarmov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597926}
CWE ID: CWE-119
| 0
| 157,132
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
/* Negative exptimes can underflow and end up immortal. realtime() will
immediately expire values that are greater than REALTIME_MAXDELTA, but less
than process_started, so lets aim for that. */
if (exptime < 0)
exptime = REALTIME_MAXDELTA + 1;
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
if (vlen < 0 || vlen > (INT_MAX - 2)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
vlen += 2;
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, flags, vlen)) {
out_string(c, "SERVER_ERROR object too large for cache");
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR out of memory storing object");
status = NO_MEMORY;
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, comm, key, nkey, 0, 0);
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
Commit Message: Don't overflow item refcount on get
Counts as a miss if the refcount is too high. ASCII multigets are the only
time refcounts can be held for so long.
doing a dirty read of refcount. is aligned.
trying to avoid adding an extra refcount branch for all calls of item_get due
to performance. might be able to move it in there after logging refactoring
simplifies some of the branches.
CWE ID: CWE-190
| 0
| 75,203
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static int dvb_usbv2_exit(struct dvb_usb_device *d)
{
dev_dbg(&d->udev->dev, "%s:\n", __func__);
dvb_usbv2_remote_exit(d);
dvb_usbv2_adapter_exit(d);
dvb_usbv2_i2c_exit(d);
kfree(d->priv);
kfree(d);
return 0;
}
Commit Message: [media] dvb-usb-v2: avoid use-after-free
I ran into a stack frame size warning because of the on-stack copy of
the USB device structure:
drivers/media/usb/dvb-usb-v2/dvb_usb_core.c: In function 'dvb_usbv2_disconnect':
drivers/media/usb/dvb-usb-v2/dvb_usb_core.c:1029:1: error: the frame size of 1104 bytes is larger than 1024 bytes [-Werror=frame-larger-than=]
Copying a device structure like this is wrong for a number of other reasons
too aside from the possible stack overflow. One of them is that the
dev_info() call will print the name of the device later, but AFAICT
we have only copied a pointer to the name earlier and the actual name
has been freed by the time it gets printed.
This removes the on-stack copy of the device and instead copies the
device name using kstrdup(). I'm ignoring the possible failure here
as both printk() and kfree() are able to deal with NULL pointers.
Signed-off-by: Arnd Bergmann <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
| 0
| 66,690
|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0', No explanation.
|
Code: static const char* inet_satop(struct sockaddr* sa, char* buf, size_t buf_len)
{
if (sa->sa_family == AF_INET) {
return inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), buf, buf_len);
} else {
return inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), buf, buf_len);
}
}
Commit Message: pcpserver.c: copyIPv6IfDifferent() check for NULL src argument
CWE ID: CWE-476
| 0
| 89,815
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.