instruction
stringclasses 1
value | input
stringlengths 64
129k
| output
int64 0
1
| __index_level_0__
int64 0
30k
|
|---|---|---|---|
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'.
|
Code: static int em_fxsave(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
size_t size;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->ops->get_fpu(ctxt);
rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
ctxt->ops->put_fpu(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)
size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]);
else
size = offsetof(struct fxregs_state, xmm_space[0]);
return segmented_write_std(ctxt, ctxt->memop.addr.mem, &fx_state, size);
}
Commit Message: KVM: x86: fix emulation of "MOV SS, null selector"
This is CVE-2017-2583. On Intel this causes a failed vmentry because
SS's type is neither 3 nor 7 (even though the manual says this check is
only done for usable SS, and the dmesg splat says that SS is unusable!).
On AMD it's worse: svm.c is confused and sets CPL to 0 in the vmcb.
The fix fabricates a data segment descriptor when SS is set to a null
selector, so that CPL and SS.DPL are set correctly in the VMCS/vmcb.
Furthermore, only allow setting SS to a NULL selector if SS.RPL < 3;
this in turn ensures CPL < 3 because RPL must be equal to CPL.
Thanks to Andy Lutomirski and Willy Tarreau for help in analyzing
the bug and deciphering the manuals.
Reported-by: Xiaohan Zhang <zhangxiaohan1@huawei.com>
Fixes: 79d5b4c3cd809c770d4bf9812635647016c56011
Cc: stable@nongnu.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
CWE ID:
| 0
| 5,634
|
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'.
|
Code: int tls_construct_new_session_ticket(SSL *s)
{
unsigned char *senc = NULL;
EVP_CIPHER_CTX *ctx;
HMAC_CTX *hctx = NULL;
unsigned char *p, *macstart;
const unsigned char *const_p;
int len, slen_full, slen;
SSL_SESSION *sess;
unsigned int hlen;
SSL_CTX *tctx = s->initial_ctx;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
int iv_len;
/* get session encoding length */
slen_full = i2d_SSL_SESSION(s->session, NULL);
/*
* Some length values are 16 bits, so forget it if session is too
* long
*/
if (slen_full == 0 || slen_full > 0xFF00) {
ossl_statem_set_error(s);
return 0;
}
senc = OPENSSL_malloc(slen_full);
if (senc == NULL) {
ossl_statem_set_error(s);
return 0;
}
ctx = EVP_CIPHER_CTX_new();
hctx = HMAC_CTX_new();
p = senc;
if (!i2d_SSL_SESSION(s->session, &p))
goto err;
/*
* create a fresh copy (not shared with other threads) to clean up
*/
const_p = senc;
sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
if (sess == NULL)
goto err;
sess->session_id_length = 0; /* ID is irrelevant for the ticket */
slen = i2d_SSL_SESSION(sess, NULL);
if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
SSL_SESSION_free(sess);
goto err;
}
p = senc;
if (!i2d_SSL_SESSION(sess, &p)) {
SSL_SESSION_free(sess);
goto err;
}
SSL_SESSION_free(sess);
/*-
* Grow buffer if need be: the length calculation is as
* follows handshake_header_length +
* 4 (ticket lifetime hint) + 2 (ticket length) +
* sizeof(keyname) + max_iv_len (iv length) +
* max_enc_block_size (max encrypted session * length) +
* max_md_size (HMAC) + session_length.
*/
if (!BUF_MEM_grow(s->init_buf,
SSL_HM_HEADER_LENGTH(s) + 6 + sizeof(key_name) +
EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
EVP_MAX_MD_SIZE + slen))
goto err;
p = ssl_handshake_start(s);
/*
* Initialize HMAC and cipher contexts. If callback present it does
* all the work otherwise use generated values from parent ctx.
*/
if (tctx->tlsext_ticket_key_cb) {
/* if 0 is returned, write an empty ticket */
int ret = tctx->tlsext_ticket_key_cb(s, key_name, iv, ctx,
hctx, 1);
if (ret == 0) {
l2n(0, p); /* timeout */
s2n(0, p); /* length */
if (!ssl_set_handshake_header
(s, SSL3_MT_NEWSESSION_TICKET, p - ssl_handshake_start(s)))
goto err;
OPENSSL_free(senc);
EVP_CIPHER_CTX_free(ctx);
HMAC_CTX_free(hctx);
return 1;
}
if (ret < 0)
goto err;
iv_len = EVP_CIPHER_CTX_iv_length(ctx);
} else {
const EVP_CIPHER *cipher = EVP_aes_256_cbc();
iv_len = EVP_CIPHER_iv_length(cipher);
if (RAND_bytes(iv, iv_len) <= 0)
goto err;
if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
tctx->tlsext_tick_aes_key, iv))
goto err;
if (!HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
sizeof(tctx->tlsext_tick_hmac_key),
EVP_sha256(), NULL))
goto err;
memcpy(key_name, tctx->tlsext_tick_key_name,
sizeof(tctx->tlsext_tick_key_name));
}
/*
* Ticket lifetime hint (advisory only): We leave this unspecified
* for resumed session (for simplicity), and guess that tickets for
* new sessions will live as long as their sessions.
*/
l2n(s->hit ? 0 : s->session->timeout, p);
/* Skip ticket length for now */
p += 2;
/* Output key name */
macstart = p;
memcpy(p, key_name, sizeof(key_name));
p += sizeof(key_name);
/* output IV */
memcpy(p, iv, iv_len);
p += iv_len;
/* Encrypt session data */
if (!EVP_EncryptUpdate(ctx, p, &len, senc, slen))
goto err;
p += len;
if (!EVP_EncryptFinal(ctx, p, &len))
goto err;
p += len;
if (!HMAC_Update(hctx, macstart, p - macstart))
goto err;
if (!HMAC_Final(hctx, p, &hlen))
goto err;
EVP_CIPHER_CTX_free(ctx);
HMAC_CTX_free(hctx);
ctx = NULL;
hctx = NULL;
p += hlen;
/* Now write out lengths: p points to end of data written */
/* Total length */
len = p - ssl_handshake_start(s);
/* Skip ticket lifetime hint */
p = ssl_handshake_start(s) + 4;
s2n(len - 6, p);
if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
goto err;
OPENSSL_free(senc);
return 1;
err:
OPENSSL_free(senc);
EVP_CIPHER_CTX_free(ctx);
HMAC_CTX_free(hctx);
ossl_statem_set_error(s);
return 0;
}
Commit Message:
CWE ID: CWE-399
| 0
| 25,647
|
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'.
|
Code: getu32(int swap, uint32_t value)
{
union {
uint32_t ui;
char c[4];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[3];
retval.c[1] = tmpval.c[2];
retval.c[2] = tmpval.c[1];
retval.c[3] = tmpval.c[0];
return retval.ui;
} else
return value;
}
Commit Message: Stop reporting bad capabilities after the first few.
CWE ID: CWE-399
| 0
| 24,837
|
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'.
|
Code: static bool ExecuteSelectWord(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
return ExpandSelectionToGranularity(frame, TextGranularity::kWord);
}
Commit Message: Move Editor::Transpose() out of Editor class
This patch moves |Editor::Transpose()| out of |Editor| class as preparation of
expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor|
class simpler for improving code health.
Following patch will expand |Transpose()| into |ExecutTranspose()|.
Bug: 672405
Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6
Reviewed-on: https://chromium-review.googlesource.com/583880
Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org>
Commit-Queue: Yoshifumi Inoue <yosin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#489518}
CWE ID:
| 0
| 3,753
|
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'.
|
Code: GF_Err rssr_Read(GF_Box *s, GF_BitStream *bs)
{
GF_ReceivedSsrcBox *ptr = (GF_ReceivedSsrcBox *)s;
ptr->ssrc = gf_bs_read_u32(bs);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
| 0
| 28,606
|
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'.
|
Code: static long unix_stream_data_wait(struct sock *sk, long timeo,
struct sk_buff *last, unsigned int last_len)
{
struct sk_buff *tail;
DEFINE_WAIT(wait);
unix_state_lock(sk);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
tail = skb_peek_tail(&sk->sk_receive_queue);
if (tail != last ||
(tail && tail->len != last_len) ||
sk->sk_err ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current) ||
!timeo)
break;
sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
unix_state_unlock(sk);
timeo = freezable_schedule_timeout(timeo);
unix_state_lock(sk);
if (sock_flag(sk, SOCK_DEAD))
break;
sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
}
finish_wait(sk_sleep(sk), &wait);
unix_state_unlock(sk);
return timeo;
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <dh.herrmann@gmail.com>
Cc: David Herrmann <dh.herrmann@gmail.com>
Cc: Willy Tarreau <w@1wt.eu>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-399
| 0
| 16,677
|
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'.
|
Code: static void VoidMethodDefaultUndefinedLongArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodDefaultUndefinedLongArg");
TestObject* impl = V8TestObject::ToImpl(info.Holder());
int32_t default_undefined_long_arg;
default_undefined_long_arg = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), info[0], exception_state);
if (exception_state.HadException())
return;
impl->voidMethodDefaultUndefinedLongArg(default_undefined_long_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 <peria@chromium.org>
Commit-Queue: Yuki Shiino <yukishiino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
| 0
| 1,413
|
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'.
|
Code: void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
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
| 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'.
|
Code: aspath_cmp_left (const struct aspath *aspath1, const struct aspath *aspath2)
{
const struct assegment *seg1;
const struct assegment *seg2;
if (!(aspath1 && aspath2))
return 0;
seg1 = aspath1->segments;
seg2 = aspath2->segments;
/* If both paths are originated in this AS then we do want to compare MED */
if (!seg1 && !seg2)
return 1;
/* find first non-confed segments for each */
while (seg1 && ((seg1->type == AS_CONFED_SEQUENCE)
|| (seg1->type == AS_CONFED_SET)))
seg1 = seg1->next;
while (seg2 && ((seg2->type == AS_CONFED_SEQUENCE)
|| (seg2->type == AS_CONFED_SET)))
seg2 = seg2->next;
/* Check as1's */
if (!(seg1 && seg2
&& (seg1->type == AS_SEQUENCE) && (seg2->type == AS_SEQUENCE)))
return 0;
if (seg1->as[0] == seg2->as[0])
return 1;
return 0;
}
Commit Message:
CWE ID: CWE-20
| 0
| 25,222
|
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'.
|
Code: status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
{
Mutex::Autolock lock(mLock);
if (mTrack == 0) return NO_INIT;
return mTrack->getPosition(position);
}
Commit Message: MediaPlayerService: avoid invalid static cast
Bug: 30204103
Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028
(cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d)
CWE ID: CWE-264
| 0
| 7,216
|
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'.
|
Code: VirtualAuthenticator::VirtualAuthenticator(
::device::FidoTransportProtocol transport)
: transport_(transport),
unique_id_(base::GenerateGUID()),
state_(base::MakeRefCounted<::device::VirtualFidoDevice::State>()) {}
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <rsleevi@chromium.org>
Reviewed-by: Balazs Engedy <engedy@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Commit-Queue: Jan Wilken Dörrie <jdoerrie@chromium.org>
Cr-Commit-Position: refs/heads/master@{#586657}
CWE ID: CWE-22
| 0
| 29,458
|
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'.
|
Code: bool P2PQuicTransportImpl::IsClosed() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
return !connection_->connected();
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <shampson@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
| 0
| 9,931
|
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'.
|
Code: void ChromeClientImpl::ShowUnhandledTapUIIfNeeded(WebTappedInfo& tapped_info) {
if (web_view_->Client()) {
web_view_->Client()->ShowUnhandledTapUIIfNeeded(tapped_info);
}
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
| 0
| 7,335
|
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'.
|
Code: static void __exit serpent_exit(void)
{
crypto_unregister_algs(serpent_algs, ARRAY_SIZE(serpent_algs));
}
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 <keescook@chromium.org>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
CWE ID: CWE-264
| 0
| 19,023
|
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'.
|
Code: static unsigned long mmap_base(void)
{
unsigned long gap = rlimit(RLIMIT_STACK);
if (gap < MIN_GAP)
gap = MIN_GAP;
else if (gap > MAX_GAP)
gap = MAX_GAP;
return PAGE_ALIGN(TASK_SIZE - gap - mmap_rnd());
}
Commit Message: x86, mm/ASLR: Fix stack randomization on 64-bit systems
The issue is that the stack for processes is not properly randomized on
64 bit architectures due to an integer overflow.
The affected function is randomize_stack_top() in file
"fs/binfmt_elf.c":
static unsigned long randomize_stack_top(unsigned long stack_top)
{
unsigned int random_variable = 0;
if ((current->flags & PF_RANDOMIZE) &&
!(current->personality & ADDR_NO_RANDOMIZE)) {
random_variable = get_random_int() & STACK_RND_MASK;
random_variable <<= PAGE_SHIFT;
}
return PAGE_ALIGN(stack_top) + random_variable;
return PAGE_ALIGN(stack_top) - random_variable;
}
Note that, it declares the "random_variable" variable as "unsigned int".
Since the result of the shifting operation between STACK_RND_MASK (which
is 0x3fffff on x86_64, 22 bits) and PAGE_SHIFT (which is 12 on x86_64):
random_variable <<= PAGE_SHIFT;
then the two leftmost bits are dropped when storing the result in the
"random_variable". This variable shall be at least 34 bits long to hold
the (22+12) result.
These two dropped bits have an impact on the entropy of process stack.
Concretely, the total stack entropy is reduced by four: from 2^28 to
2^30 (One fourth of expected entropy).
This patch restores back the entropy by correcting the types involved
in the operations in the functions randomize_stack_top() and
stack_maxrandom_size().
The successful fix can be tested with:
$ for i in `seq 1 10`; do cat /proc/self/maps | grep stack; done
7ffeda566000-7ffeda587000 rw-p 00000000 00:00 0 [stack]
7fff5a332000-7fff5a353000 rw-p 00000000 00:00 0 [stack]
7ffcdb7a1000-7ffcdb7c2000 rw-p 00000000 00:00 0 [stack]
7ffd5e2c4000-7ffd5e2e5000 rw-p 00000000 00:00 0 [stack]
...
Once corrected, the leading bytes should be between 7ffc and 7fff,
rather than always being 7fff.
Signed-off-by: Hector Marco-Gisbert <hecmargi@upv.es>
Signed-off-by: Ismael Ripoll <iripoll@upv.es>
[ Rebased, fixed 80 char bugs, cleaned up commit message, added test example and CVE ]
Signed-off-by: Kees Cook <keescook@chromium.org>
Cc: <stable@vger.kernel.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Fixes: CVE-2015-1593
Link: http://lkml.kernel.org/r/20150214173350.GA18393@www.outflux.net
Signed-off-by: Borislav Petkov <bp@suse.de>
CWE ID: CWE-264
| 0
| 10,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'.
|
Code: static int ipgre_tunnel_bind_dev(struct net_device *dev)
{
struct net_device *tdev = NULL;
struct ip_tunnel *tunnel;
struct iphdr *iph;
int hlen = LL_MAX_HEADER;
int mtu = ETH_DATA_LEN;
int addend = sizeof(struct iphdr) + 4;
tunnel = netdev_priv(dev);
iph = &tunnel->parms.iph;
/* Guess output device to choose reasonable mtu and needed_headroom */
if (iph->daddr) {
struct flowi fl = { .oif = tunnel->parms.link,
.nl_u = { .ip4_u =
{ .daddr = iph->daddr,
.saddr = iph->saddr,
.tos = RT_TOS(iph->tos) } },
.proto = IPPROTO_GRE };
struct rtable *rt;
if (!ip_route_output_key(dev_net(dev), &rt, &fl)) {
tdev = rt->u.dst.dev;
ip_rt_put(rt);
}
if (dev->type != ARPHRD_ETHER)
dev->flags |= IFF_POINTOPOINT;
}
if (!tdev && tunnel->parms.link)
tdev = __dev_get_by_index(dev_net(dev), tunnel->parms.link);
if (tdev) {
hlen = tdev->hard_header_len + tdev->needed_headroom;
mtu = tdev->mtu;
}
dev->iflink = tunnel->parms.link;
/* Precalculate GRE options length */
if (tunnel->parms.o_flags&(GRE_CSUM|GRE_KEY|GRE_SEQ)) {
if (tunnel->parms.o_flags&GRE_CSUM)
addend += 4;
if (tunnel->parms.o_flags&GRE_KEY)
addend += 4;
if (tunnel->parms.o_flags&GRE_SEQ)
addend += 4;
}
dev->needed_headroom = addend + hlen;
mtu -= dev->hard_header_len + addend;
if (mtu < 68)
mtu = 68;
tunnel->hlen = addend;
return mtu;
}
Commit Message: gre: fix netns vs proto registration ordering
GRE protocol receive hook can be called right after protocol addition is done.
If netns stuff is not yet initialized, we're going to oops in
net_generic().
This is remotely oopsable if ip_gre is compiled as module and packet
comes at unfortunate moment of module loading.
Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
| 0
| 3,919
|
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'.
|
Code: void GLES2DecoderImpl::DoGetFramebufferAttachmentParameteriv(
GLenum target,
GLenum attachment,
GLenum pname,
GLint* params,
GLsizei params_size) {
const char kFunctionName[] = "glGetFramebufferAttachmentParameteriv";
Framebuffer* framebuffer = GetFramebufferInfoForTarget(target);
if (!framebuffer) {
if (!feature_info_->IsWebGL2OrES3Context()) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, kFunctionName,
"no framebuffer bound");
return;
}
if (!validators_->backbuffer_attachment.IsValid(attachment)) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, kFunctionName,
"invalid attachment for backbuffer");
return;
}
switch (pname) {
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
*params = static_cast<GLint>(GL_FRAMEBUFFER_DEFAULT);
return;
case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:
case GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:
case GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:
break;
default:
LOCAL_SET_GL_ERROR(GL_INVALID_ENUM, kFunctionName,
"invalid pname for backbuffer");
return;
}
if (GetBackbufferServiceId() != 0) { // Emulated backbuffer.
switch (attachment) {
case GL_BACK:
attachment = GL_COLOR_ATTACHMENT0;
break;
case GL_DEPTH:
attachment = GL_DEPTH_ATTACHMENT;
break;
case GL_STENCIL:
attachment = GL_STENCIL_ATTACHMENT;
break;
default:
NOTREACHED();
break;
}
}
} else {
if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) {
const Framebuffer::Attachment* depth =
framebuffer->GetAttachment(GL_DEPTH_ATTACHMENT);
const Framebuffer::Attachment* stencil =
framebuffer->GetAttachment(GL_STENCIL_ATTACHMENT);
if ((!depth && !stencil) ||
(depth && stencil && depth->IsSameAttachment(stencil))) {
attachment = GL_DEPTH_ATTACHMENT;
} else {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, kFunctionName,
"depth and stencil attachment mismatch");
return;
}
}
}
if (pname == GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT &&
features().use_img_for_multisampled_render_to_texture) {
pname = GL_TEXTURE_SAMPLES_IMG;
}
if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME) {
DCHECK(framebuffer);
const Framebuffer::Attachment* attachment_object =
framebuffer->GetAttachment(attachment);
*params = attachment_object ? attachment_object->object_name() : 0;
return;
}
api()->glGetFramebufferAttachmentParameterivEXTFn(target, attachment, pname,
params);
LOCAL_PEEK_GL_ERROR(kFunctionName);
}
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 <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
| 0
| 9,665
|
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'.
|
Code: bool ScriptController::processingUserGesture()
{
return UserGestureIndicator::processingUserGesture();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
| 0
| 6,928
|
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'.
|
Code: void GLES2DecoderImpl::DoGetVertexAttribIuiv(GLuint index,
GLenum pname,
GLuint* params,
GLsizei params_size) {
DoGetVertexAttribImpl<GLuint>(index, pname, params);
}
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 <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
| 0
| 7,281
|
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'.
|
Code: parse_GROUP(char *arg, struct ofpbuf *ofpacts,
enum ofputil_protocol *usable_protocols OVS_UNUSED)
{
return str_to_u32(arg, &ofpact_put_GROUP(ofpacts)->group_id);
}
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 <blp@ovn.org>
Acked-by: Justin Pettit <jpettit@ovn.org>
CWE ID:
| 0
| 28,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'.
|
Code: static void btsnoop_write(const void *data, size_t length) {
if (logfile_fd != INVALID_FD)
write(logfile_fd, data, length);
btsnoop_net_write(data, length);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
| 1
| 1,095
|
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'.
|
Code: static int bond_ioctl(struct net *net, unsigned int cmd,
struct compat_ifreq __user *ifr32)
{
struct ifreq kifr;
struct ifreq __user *uifr;
mm_segment_t old_fs;
int err;
u32 data;
void __user *datap;
switch (cmd) {
case SIOCBONDENSLAVE:
case SIOCBONDRELEASE:
case SIOCBONDSETHWADDR:
case SIOCBONDCHANGEACTIVE:
if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq)))
return -EFAULT;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = dev_ioctl(net, cmd,
(struct ifreq __user __force *) &kifr);
set_fs(old_fs);
return err;
case SIOCBONDSLAVEINFOQUERY:
case SIOCBONDINFOQUERY:
uifr = compat_alloc_user_space(sizeof(*uifr));
if (copy_in_user(&uifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ))
return -EFAULT;
if (get_user(data, &ifr32->ifr_ifru.ifru_data))
return -EFAULT;
datap = compat_ptr(data);
if (put_user(datap, &uifr->ifr_ifru.ifru_data))
return -EFAULT;
return dev_ioctl(net, cmd, uifr);
default:
return -ENOIOCTLCMD;
}
}
Commit Message: Fix order of arguments to compat_put_time[spec|val]
Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in
net/socket.c") introduced a bug where the helper functions to take
either a 64-bit or compat time[spec|val] got the arguments in the wrong
order, passing the kernel stack pointer off as a user pointer (and vice
versa).
Because of the user address range check, that in turn then causes an
EFAULT due to the user pointer range checking failing for the kernel
address. Incorrectly resuling in a failed system call for 32-bit
processes with a 64-bit kernel.
On odder architectures like HP-PA (with separate user/kernel address
spaces), it can be used read kernel memory.
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-399
| 0
| 4,424
|
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'.
|
Code: evdns_request_remove(struct request *req, struct request **head)
{
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
#if 0
{
struct request *ptr;
int found = 0;
EVUTIL_ASSERT(*head != NULL);
ptr = *head;
do {
if (ptr == req) {
found = 1;
break;
}
ptr = ptr->next;
} while (ptr != *head);
EVUTIL_ASSERT(found);
EVUTIL_ASSERT(req->next);
}
#endif
if (req->next == req) {
/* only item in the list */
*head = NULL;
} else {
req->next->prev = req->prev;
req->prev->next = req->next;
if (*head == req) *head = req->next;
}
req->next = req->prev = NULL;
}
Commit Message: evdns: fix searching empty hostnames
From #332:
Here follows a bug report by **Guido Vranken** via the _Tor bug bounty program_. Please credit Guido accordingly.
## Bug report
The DNS code of Libevent contains this rather obvious OOB read:
```c
static char *
search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
```
If the length of ```base_name``` is 0, then line 3125 reads 1 byte before the buffer. This will trigger a crash on ASAN-protected builds.
To reproduce:
Build libevent with ASAN:
```
$ CFLAGS='-fomit-frame-pointer -fsanitize=address' ./configure && make -j4
```
Put the attached ```resolv.conf``` and ```poc.c``` in the source directory and then do:
```
$ gcc -fsanitize=address -fomit-frame-pointer poc.c .libs/libevent.a
$ ./a.out
=================================================================
==22201== ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60060000efdf at pc 0x4429da bp 0x7ffe1ed47300 sp 0x7ffe1ed472f8
READ of size 1 at 0x60060000efdf thread T0
```
P.S. we can add a check earlier, but since this is very uncommon, I didn't add it.
Fixes: #332
CWE ID: CWE-125
| 0
| 12,535
|
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'.
|
Code: void SyncBackendHost::GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
base::AutoLock lock(registrar_lock_);
ModelSafeRoutingInfo copy(registrar_.routing_info);
out->swap(copy);
}
Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed.
BUG=69561
TEST=Run sync manually and run integration tests, sync should not crash.
Review URL: http://codereview.chromium.org/7016007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
| 0
| 9,127
|
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'.
|
Code: bool BrowserWindowGtk::IsMaximized() const {
return (state_ & GDK_WINDOW_STATE_MAXIMIZED);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
| 0
| 13,462
|
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'.
|
Code: void ChromeClientImpl::ContentsSizeChanged(LocalFrame* frame,
const IntSize& size) const {
web_view_->DidChangeContentsSize();
WebLocalFrameImpl* webframe = WebLocalFrameImpl::FromFrame(frame);
webframe->DidChangeContentsSize(size);
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
| 0
| 8,724
|
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'.
|
Code: SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
{
if (force_o_largefile())
flags |= O_LARGEFILE;
return do_sys_open(AT_FDCWD, filename, flags, mode);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-17
| 0
| 12,568
|
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'.
|
Code: struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = __sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_tx_queue_clear(sk);
RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
dst_release(dst);
return NULL;
}
return dst;
}
Commit Message: net: sock: validate data_len before allocating skb in sock_alloc_send_pskb()
We need to validate the number of pages consumed by data_len, otherwise frags
array could be overflowed by userspace. So this patch validate data_len and
return -EMSGSIZE when data_len may occupies more frags than MAX_SKB_FRAGS.
Signed-off-by: Jason Wang <jasowang@redhat.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20
| 0
| 19,566
|
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'.
|
Code: static ssize_t o2nm_cluster_idle_timeout_ms_store(struct config_item *item,
const char *page, size_t count)
{
struct o2nm_cluster *cluster = to_o2nm_cluster(item);
ssize_t ret;
unsigned int val;
ret = o2nm_cluster_attr_write(page, count, &val);
if (ret > 0) {
if (cluster->cl_idle_timeout_ms != val
&& o2net_num_connected_peers()) {
mlog(ML_NOTICE,
"o2net: cannot change idle timeout after "
"the first peer has agreed to it."
" %d connected peers\n",
o2net_num_connected_peers());
ret = -EINVAL;
} else if (val <= cluster->cl_keepalive_delay_ms) {
mlog(ML_NOTICE, "o2net: idle timeout must be larger "
"than keepalive delay\n");
ret = -EINVAL;
} else {
cluster->cl_idle_timeout_ms = val;
}
}
return ret;
}
Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent
The subsystem.su_mutex is required while accessing the item->ci_parent,
otherwise, NULL pointer dereference to the item->ci_parent will be
triggered in the following situation:
add node delete node
sys_write
vfs_write
configfs_write_file
o2nm_node_store
o2nm_node_local_write
do_rmdir
vfs_rmdir
configfs_rmdir
mutex_lock(&subsys->su_mutex);
unlink_obj
item->ci_group = NULL;
item->ci_parent = NULL;
to_o2nm_cluster_from_node
node->nd_item.ci_parent->ci_parent
BUG since of NULL pointer dereference to nd_item.ci_parent
Moreover, the o2nm_cluster also should be protected by the
subsystem.su_mutex.
[alex.chen@huawei.com: v2]
Link: http://lkml.kernel.org/r/59EEAA69.9080703@huawei.com
Link: http://lkml.kernel.org/r/59E9B36A.10700@huawei.com
Signed-off-by: Alex Chen <alex.chen@huawei.com>
Reviewed-by: Jun Piao <piaojun@huawei.com>
Reviewed-by: Joseph Qi <jiangqi903@gmail.com>
Cc: Mark Fasheh <mfasheh@versity.com>
Cc: Joel Becker <jlbec@evilplan.org>
Cc: Junxiao Bi <junxiao.bi@oracle.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-476
| 0
| 11,157
|
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'.
|
Code: PHP_FUNCTION(get_headers)
{
char *url;
int url_len;
php_stream_context *context;
php_stream *stream;
zval **prev_val, **hdr = NULL, **h;
HashPosition pos;
HashTable *hashT;
long format = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) {
return;
}
context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C));
if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) {
RETURN_FALSE;
}
if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) {
php_stream_close(stream);
RETURN_FALSE;
}
array_init(return_value);
/* check for curl-wrappers that provide headers via a special "headers" element */
if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) {
/* curl-wrappers don't load data until the 1st read */
if (!Z_ARRVAL_PP(h)->nNumOfElements) {
php_stream_getc(stream);
}
zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h);
hashT = Z_ARRVAL_PP(h);
} else {
hashT = HASH_OF(stream->wrapperdata);
}
zend_hash_internal_pointer_reset_ex(hashT, &pos);
while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) {
if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) {
zend_hash_move_forward_ex(hashT, &pos);
continue;
}
if (!format) {
no_name_header:
add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1);
} else {
char c;
char *s, *p;
if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) {
c = *p;
*p = '\0';
s = p + 1;
while (isspace((int)*(unsigned char *)s)) {
s++;
}
if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) {
add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1);
} else { /* some headers may occur more then once, therefor we need to remake the string into an array */
convert_to_array(*prev_val);
add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1);
}
*p = c;
} else {
goto no_name_header;
}
}
zend_hash_move_forward_ex(hashT, &pos);
}
php_stream_close(stream);
}
Commit Message:
CWE ID: CWE-20
| 0
| 23,494
|
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'.
|
Code: bool GLES2DecoderImpl::CheckBoundFramebuffersValid(const char* func_name) {
if (!feature_info_->feature_flags().chromium_framebuffer_multisample) {
return CheckFramebufferValid(
bound_draw_framebuffer_, GL_FRAMEBUFFER_EXT, func_name);
}
return CheckFramebufferValid(
bound_draw_framebuffer_, GL_DRAW_FRAMEBUFFER_EXT, func_name) &&
CheckFramebufferValid(
bound_read_framebuffer_, GL_READ_FRAMEBUFFER_EXT, func_name);
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
| 0
| 15,327
|
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'.
|
Code: void DocumentLoader::stopLoading()
{
RefPtr<Frame> protectFrame(m_frame);
RefPtr<DocumentLoader> protectLoader(this);
bool loading = isLoading();
if (m_committed) {
Document* doc = m_frame->document();
if (loading || doc->parsing())
m_frame->loader()->stopLoading(UnloadEventPolicyNone);
}
cancelAll(m_multipartSubresourceLoaders);
m_applicationCacheHost->stopLoadingInFrame(m_frame);
#if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
clearArchiveResources();
#endif
if (!loading) {
ASSERT(!isLoading());
return;
}
if (m_isStopping)
return;
m_isStopping = true;
FrameLoader* frameLoader = DocumentLoader::frameLoader();
if (isLoadingMainResource())
cancelMainResourceLoad(frameLoader->cancelledError(m_request));
else if (!m_subresourceLoaders.isEmpty())
setMainDocumentError(frameLoader->cancelledError(m_request));
else
mainReceivedError(frameLoader->cancelledError(m_request));
stopLoadingSubresources();
stopLoadingPlugIns();
m_isStopping = false;
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
| 0
| 8,591
|
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'.
|
Code: error::Error GLES2DecoderPassthroughImpl::DoRenderbufferStorage(
GLenum target,
GLenum internalformat,
GLsizei width,
GLsizei height) {
api()->glRenderbufferStorageEXTFn(target, internalformat, width, height);
return error::kNoError;
}
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 <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
| 0
| 4,674
|
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'.
|
Code: void MSG_WriteDeltaKeyFloat( msg_t *msg, int key, float oldV, float newV ) {
floatint_t fi;
if ( oldV == newV ) {
MSG_WriteBits( msg, 0, 1 );
return;
}
fi.f = newV;
MSG_WriteBits( msg, 1, 1 );
MSG_WriteBits( msg, fi.i ^ key, 32 );
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
CWE ID: CWE-119
| 0
| 19,450
|
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'.
|
Code: static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
int *insn_idx)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_func_state *caller, *callee;
int i, err, subprog, target_insn;
if (state->curframe + 1 >= MAX_CALL_FRAMES) {
verbose(env, "the call stack of %d frames is too deep\n",
state->curframe + 2);
return -E2BIG;
}
target_insn = *insn_idx + insn->imm;
subprog = find_subprog(env, target_insn + 1);
if (subprog < 0) {
verbose(env, "verifier bug. No program starts at insn %d\n",
target_insn + 1);
return -EFAULT;
}
caller = state->frame[state->curframe];
if (state->frame[state->curframe + 1]) {
verbose(env, "verifier bug. Frame %d already allocated\n",
state->curframe + 1);
return -EFAULT;
}
callee = kzalloc(sizeof(*callee), GFP_KERNEL);
if (!callee)
return -ENOMEM;
state->frame[state->curframe + 1] = callee;
/* callee cannot access r0, r6 - r9 for reading and has to write
* into its own stack before reading from it.
* callee can read/write into caller's stack
*/
init_func_state(env, callee,
/* remember the callsite, it will be used by bpf_exit */
*insn_idx /* callsite */,
state->curframe + 1 /* frameno within this callchain */,
subprog /* subprog number within this prog */);
/* Transfer references to the callee */
err = transfer_reference_state(callee, caller);
if (err)
return err;
/* copy r1 - r5 args that callee can access. The copy includes parent
* pointers, which connects us up to the liveness chain
*/
for (i = BPF_REG_1; i <= BPF_REG_5; i++)
callee->regs[i] = caller->regs[i];
/* after the call registers r0 - r5 were scratched */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, caller->regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* only increment it after check_reg_arg() finished */
state->curframe++;
/* and go analyze first insn of the callee */
*insn_idx = target_insn;
if (env->log.level) {
verbose(env, "caller:\n");
print_verifier_state(env, caller);
verbose(env, "callee:\n");
print_verifier_state(env, callee);
}
return 0;
}
Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths
While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer
arithmetic") took care of rejecting alu op on pointer when e.g. pointer
came from two different map values with different map properties such as
value size, Jann reported that a case was not covered yet when a given
alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from
different branches where we would incorrectly try to sanitize based
on the pointer's limit. Catch this corner case and reject the program
instead.
Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
CWE ID: CWE-189
| 0
| 19,671
|
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'.
|
Code: void InspectorPageAgent::Restore() {
if (state_->booleanProperty(PageAgentState::kPageAgentEnabled, false))
enable();
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
| 0
| 675
|
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'.
|
Code: void WebRuntimeFeatures::enableOverlayScrollbars(bool enable)
{
RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94
| 0
| 11,298
|
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'.
|
Code: pp::Var Plugin::GetInstanceObject() {
PLUGIN_PRINTF(("Plugin::GetInstanceObject (this=%p)\n",
static_cast<void*>(this)));
ScriptablePlugin* handle =
static_cast<ScriptablePlugin*>(scriptable_plugin()->AddRef());
pp::Var* handle_var = handle->var();
PLUGIN_PRINTF(("Plugin::GetInstanceObject (handle=%p, handle_var=%p)\n",
static_cast<void*>(handle), static_cast<void*>(handle_var)));
return *handle_var; // make a copy
}
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
TBR=bbudge@chromium.org
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
| 3,966
|
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'.
|
Code: static MenuCache* menu_cache_new( const char* cache_file )
{
MenuCache* cache;
cache = g_slice_new0( MenuCache );
cache->cache_file = g_strdup( cache_file );
cache->n_ref = 1;
return cache;
}
Commit Message:
CWE ID: CWE-20
| 0
| 7,219
|
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'.
|
Code: int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
{
unsigned char *sigalgs, *sptr;
int rhash, rsign;
size_t i;
if (salglen & 1)
return 0;
sigalgs = OPENSSL_malloc(salglen);
if (sigalgs == NULL)
return 0;
for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
rhash = tls12_find_id(*psig_nids++, tls12_md, OSSL_NELEM(tls12_md));
rsign = tls12_find_id(*psig_nids++, tls12_sig, OSSL_NELEM(tls12_sig));
if (rhash == -1 || rsign == -1)
goto err;
*sptr++ = rhash;
*sptr++ = rsign;
}
if (client) {
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen;
} else {
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen;
}
return 1;
err:
OPENSSL_free(sigalgs);
return 0;
}
Commit Message:
CWE ID: CWE-20
| 0
| 2,803
|
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'.
|
Code: static void reflectedTreatNullAsNullStringTreatUndefinedAsNullStringCustomURLAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
TestObjectV8Internal::reflectedTreatNullAsNullStringTreatUndefinedAsNullStringCustomURLAttrAttributeSetter(jsValue, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
Commit Message: document.location bindings fix
BUG=352374
R=jochen@chromium.org
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
| 0
| 29,162
|
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'.
|
Code: horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint16 *wp = (uint16*) cp0;
tmsize_t wc = cc/2;
if((cc%(2*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff8",
"%s", "(cc%(2*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in
previous commit (fix for MSVR 35105)
CWE ID: CWE-119
| 0
| 22,851
|
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'.
|
Code: static void ImportTIFF_PhotographicSensitivity ( const TIFF_Manager & exif, SXMPMeta * xmp ) {
try {
bool found;
TIFF_Manager::TagInfo tagInfo;
bool haveOldExif = true; // Default to old Exif if no version tag.
bool haveTag34855 = false;
bool haveLowISO = false; // Set for real if haveTag34855 is true.
XMP_Uns32 valueTag34855; // ! Only care about the first value if more than 1.
found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_ExifVersion, &tagInfo );
if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) {
haveOldExif = (strncmp ( (char*)tagInfo.dataPtr, "0230", 4 ) < 0);
}
haveTag34855 = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, &valueTag34855 );
if ( haveTag34855 ) haveLowISO = (valueTag34855 < 65535);
if ( haveOldExif ) { // Exif version is before 2.3, use just the old tag and property.
if ( haveTag34855 ) {
if ( haveLowISO || (! xmp->DoesPropertyExist ( kXMP_NS_EXIF, "ISOSpeedRatings" )) ) {
xmp->DeleteProperty ( kXMP_NS_EXIF, "ISOSpeedRatings" );
xmp->AppendArrayItem ( kXMP_NS_EXIF, "ISOSpeedRatings", kXMP_PropArrayIsOrdered, "" );
xmp->SetProperty_Int ( kXMP_NS_EXIF, "ISOSpeedRatings[1]", valueTag34855 );
}
}
} else { // Exif version is 2.3 or newer, use the Exif 2.3 tags and properties.
XMP_Uns16 whichLongTag = 0;
XMP_Uns32 sensitivityType, tagValue;
bool haveSensitivityType = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_SensitivityType, &sensitivityType );
if ( haveSensitivityType ) {
xmp->SetProperty_Int ( kXMP_NS_ExifEX, "SensitivityType", sensitivityType );
switch ( sensitivityType ) {
case 1 : // Use StandardOutputSensitivity for both 1 and 4.
case 4 : whichLongTag = kTIFF_StandardOutputSensitivity; break;
case 2 : whichLongTag = kTIFF_RecommendedExposureIndex; break;
case 3 : // Use ISOSpeed for all of 3, 5, 6, and 7.
case 5 :
case 6 :
case 7 : whichLongTag = kTIFF_ISOSpeed; break;
}
}
found = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_StandardOutputSensitivity, &tagValue );
if ( found ) {
xmp->SetProperty_Int64 ( kXMP_NS_ExifEX, "StandardOutputSensitivity", tagValue );
}
found = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_RecommendedExposureIndex, &tagValue );
if ( found ) {
xmp->SetProperty_Int64 ( kXMP_NS_ExifEX, "RecommendedExposureIndex", tagValue );
}
found = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_ISOSpeed, &tagValue );
if ( found ) {
xmp->SetProperty_Int64 ( kXMP_NS_ExifEX, "ISOSpeed", tagValue );
}
found = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_ISOSpeedLatitudeyyy, &tagValue );
if ( found ) {
xmp->SetProperty_Int64 ( kXMP_NS_ExifEX, "ISOSpeedLatitudeyyy", tagValue );
}
found = exif.GetTag_Integer ( kTIFF_ExifIFD, kTIFF_ISOSpeedLatitudezzz, &tagValue );
if ( found ) {
xmp->SetProperty_Int64 ( kXMP_NS_ExifEX, "ISOSpeedLatitudezzz", tagValue );
}
if ( haveTag34855 & haveLowISO ) { // The easier low ISO case.
xmp->DeleteProperty ( kXMP_NS_EXIF, "ISOSpeedRatings" );
xmp->AppendArrayItem ( kXMP_NS_EXIF, "ISOSpeedRatings", kXMP_PropArrayIsOrdered, "" );
xmp->SetProperty_Int ( kXMP_NS_EXIF, "ISOSpeedRatings[1]", valueTag34855 );
xmp->SetProperty_Int ( kXMP_NS_ExifEX, "PhotographicSensitivity", valueTag34855 );
} else { // The more complex high ISO case, or no PhotographicSensitivity tag.
if ( haveTag34855 ) {
XMP_Assert ( valueTag34855 == 65535 );
xmp->SetProperty_Int ( kXMP_NS_ExifEX, "PhotographicSensitivity", valueTag34855 );
}
if ( whichLongTag != 0 ) {
found = exif.GetTag ( kTIFF_ExifIFD, whichLongTag, &tagInfo );
if ( found && (tagInfo.type == kTIFF_LongType) && (tagInfo.count == 1) ){
xmp->DeleteProperty ( kXMP_NS_EXIF, "ISOSpeedRatings" );
xmp->AppendArrayItem ( kXMP_NS_EXIF, "ISOSpeedRatings", kXMP_PropArrayIsOrdered, "" );
xmp->SetProperty_Int ( kXMP_NS_EXIF, "ISOSpeedRatings[1]", exif.GetUns32 ( tagInfo.dataPtr ) );
}
}
}
}
} catch ( ... ) {
}
} // ImportTIFF_PhotographicSensitivity
Commit Message:
CWE ID: CWE-416
| 0
| 9,891
|
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'.
|
Code: static int __perf_event_overflow(struct perf_event *event,
int throttle, struct perf_sample_data *data,
struct pt_regs *regs)
{
int events = atomic_read(&event->event_limit);
struct hw_perf_event *hwc = &event->hw;
u64 seq;
int ret = 0;
/*
* Non-sampling counters might still use the PMI to fold short
* hardware counters, ignore those.
*/
if (unlikely(!is_sampling_event(event)))
return 0;
seq = __this_cpu_read(perf_throttled_seq);
if (seq != hwc->interrupts_seq) {
hwc->interrupts_seq = seq;
hwc->interrupts = 1;
} else {
hwc->interrupts++;
if (unlikely(throttle
&& hwc->interrupts >= max_samples_per_tick)) {
__this_cpu_inc(perf_throttled_count);
tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
hwc->interrupts = MAX_INTERRUPTS;
perf_log_throttle(event, 0);
ret = 1;
}
}
if (event->attr.freq) {
u64 now = perf_clock();
s64 delta = now - hwc->freq_time_stamp;
hwc->freq_time_stamp = now;
if (delta > 0 && delta < 2*TICK_NSEC)
perf_adjust_period(event, delta, hwc->last_period, true);
}
/*
* XXX event_limit might not quite work as expected on inherited
* events
*/
event->pending_kill = POLL_IN;
if (events && atomic_dec_and_test(&event->event_limit)) {
ret = 1;
event->pending_kill = POLL_HUP;
perf_event_disable_inatomic(event);
}
READ_ONCE(event->overflow_handler)(event, data, regs);
if (*perf_event_fasync(event) && event->pending_kill) {
event->pending_wakeup = 1;
irq_work_queue(&event->pending);
}
return ret;
}
Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race
Di Shen reported a race between two concurrent sys_perf_event_open()
calls where both try and move the same pre-existing software group
into a hardware context.
The problem is exactly that described in commit:
f63a8daa5812 ("perf: Fix event->ctx locking")
... where, while we wait for a ctx->mutex acquisition, the event->ctx
relation can have changed under us.
That very same commit failed to recognise sys_perf_event_context() as an
external access vector to the events and thereby didn't apply the
established locking rules correctly.
So while one sys_perf_event_open() call is stuck waiting on
mutex_lock_double(), the other (which owns said locks) moves the group
about. So by the time the former sys_perf_event_open() acquires the
locks, the context we've acquired is stale (and possibly dead).
Apply the established locking rules as per perf_event_ctx_lock_nested()
to the mutex_lock_double() for the 'move_group' case. This obviously means
we need to validate state after we acquire the locks.
Reported-by: Di Shen (Keen Lab)
Tested-by: John Dias <joaodias@google.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com>
Cc: Arnaldo Carvalho de Melo <acme@kernel.org>
Cc: Arnaldo Carvalho de Melo <acme@redhat.com>
Cc: Jiri Olsa <jolsa@redhat.com>
Cc: Kees Cook <keescook@chromium.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Min Chong <mchong@google.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Stephane Eranian <eranian@google.com>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Vince Weaver <vincent.weaver@maine.edu>
Fixes: f63a8daa5812 ("perf: Fix event->ctx locking")
Link: http://lkml.kernel.org/r/20170106131444.GZ3174@twins.programming.kicks-ass.net
Signed-off-by: Ingo Molnar <mingo@kernel.org>
CWE ID: CWE-362
| 0
| 26,307
|
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'.
|
Code: void set_current_blocked(sigset_t *newset)
{
sigdelsetmask(newset, sigmask(SIGKILL) | sigmask(SIGSTOP));
__set_current_blocked(newset);
}
Commit Message: kernel/signal.c: stop info leak via the tkill and the tgkill syscalls
This fixes a kernel memory contents leak via the tkill and tgkill syscalls
for compat processes.
This is visible in the siginfo_t->_sifields._rt.si_sigval.sival_ptr field
when handling signals delivered from tkill.
The place of the infoleak:
int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from)
{
...
put_user_ex(ptr_to_compat(from->si_ptr), &to->si_ptr);
...
}
Signed-off-by: Emese Revfy <re.emese@gmail.com>
Reviewed-by: PaX Team <pageexec@freemail.hu>
Signed-off-by: Kees Cook <keescook@chromium.org>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: "Eric W. Biederman" <ebiederm@xmission.com>
Cc: Serge Hallyn <serge.hallyn@canonical.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-399
| 0
| 24,538
|
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'.
|
Code: struct net_device *rtnl_create_link(struct net *net,
const char *ifname, unsigned char name_assign_type,
const struct rtnl_link_ops *ops, struct nlattr *tb[])
{
int err;
struct net_device *dev;
unsigned int num_tx_queues = 1;
unsigned int num_rx_queues = 1;
if (tb[IFLA_NUM_TX_QUEUES])
num_tx_queues = nla_get_u32(tb[IFLA_NUM_TX_QUEUES]);
else if (ops->get_num_tx_queues)
num_tx_queues = ops->get_num_tx_queues();
if (tb[IFLA_NUM_RX_QUEUES])
num_rx_queues = nla_get_u32(tb[IFLA_NUM_RX_QUEUES]);
else if (ops->get_num_rx_queues)
num_rx_queues = ops->get_num_rx_queues();
err = -ENOMEM;
dev = alloc_netdev_mqs(ops->priv_size, ifname, name_assign_type,
ops->setup, num_tx_queues, num_rx_queues);
if (!dev)
goto err;
dev_net_set(dev, net);
dev->rtnl_link_ops = ops;
dev->rtnl_link_state = RTNL_LINK_INITIALIZING;
if (tb[IFLA_MTU])
dev->mtu = nla_get_u32(tb[IFLA_MTU]);
if (tb[IFLA_ADDRESS]) {
memcpy(dev->dev_addr, nla_data(tb[IFLA_ADDRESS]),
nla_len(tb[IFLA_ADDRESS]));
dev->addr_assign_type = NET_ADDR_SET;
}
if (tb[IFLA_BROADCAST])
memcpy(dev->broadcast, nla_data(tb[IFLA_BROADCAST]),
nla_len(tb[IFLA_BROADCAST]));
if (tb[IFLA_TXQLEN])
dev->tx_queue_len = nla_get_u32(tb[IFLA_TXQLEN]);
if (tb[IFLA_OPERSTATE])
set_operstate(dev, nla_get_u8(tb[IFLA_OPERSTATE]));
if (tb[IFLA_LINKMODE])
dev->link_mode = nla_get_u8(tb[IFLA_LINKMODE]);
if (tb[IFLA_GROUP])
dev_set_group(dev, nla_get_u32(tb[IFLA_GROUP]));
return dev;
err:
return ERR_PTR(err);
}
Commit Message: net: fix infoleak in rtnetlink
The stack object “map” has a total size of 32 bytes. Its last 4
bytes are padding generated by compiler. These padding bytes are
not initialized and sent out via “nla_put”.
Signed-off-by: Kangjie Lu <kjlu@gatech.edu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
| 0
| 26,098
|
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'.
|
Code: void OnInit(const PluginMsg_Init_Params& params, IPC::Message* reply_msg) {
base::AutoLock auto_lock(modal_dialog_event_map_lock_);
if (modal_dialog_event_map_.count(params.containing_window)) {
modal_dialog_event_map_[params.containing_window].refcount++;
return;
}
WaitableEventWrapper wrapper;
wrapper.event = new base::WaitableEvent(true, false);
wrapper.refcount = 1;
modal_dialog_event_map_[params.containing_window] = wrapper;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
| 0
| 4,523
|
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'.
|
Code: void WT_UpdateLFO (S_LFO_CONTROL *pLFO, EAS_I16 phaseInc)
{
/* To save memory, if m_nPhaseValue is negative, we are in the
* delay phase, and m_nPhaseValue represents the time left
* in the delay.
*/
if (pLFO->lfoPhase < 0)
{
pLFO->lfoPhase++;
return;
}
/* calculate LFO output from phase value */
/*lint -e{701} Use shift for performance */
pLFO->lfoValue = (EAS_I16) (pLFO->lfoPhase << 2);
/*lint -e{502} <shortcut to turn sawtooth into triangle wave> */
if ((pLFO->lfoPhase > 0x1fff) && (pLFO->lfoPhase < 0x6000))
pLFO->lfoValue = ~pLFO->lfoValue;
/* update LFO phase */
pLFO->lfoPhase = (pLFO->lfoPhase + phaseInc) & 0x7fff;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
| 0
| 4,293
|
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'.
|
Code: void RenderFrameHostImpl::AccessibilityFatalError() {
browser_accessibility_manager_.reset(nullptr);
if (accessibility_reset_token_)
return;
accessibility_reset_count_++;
if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
Send(new AccessibilityMsg_FatalError(routing_id_));
} else {
accessibility_reset_token_ = g_next_accessibility_reset_token++;
Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
}
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <lowell@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Camille Lamy <clamy@chromium.org>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
| 0
| 22,755
|
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'.
|
Code: int AutofillManager::BackendIDToInt(const std::string& backend_id) const {
if (!base::IsValidGUID(backend_id))
return 0;
const auto found = backend_to_int_map_.find(backend_id);
if (found == backend_to_int_map_.end()) {
int int_id = backend_to_int_map_.size() + 1;
backend_to_int_map_[backend_id] = int_id;
int_to_backend_map_[int_id] = backend_id;
return int_id;
}
return found->second;
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <rogerm@chromium.org>
Commit-Queue: Sebastien Seguin-Gagnon <sebsg@chromium.org>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID:
| 0
| 22,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'.
|
Code: isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
Commit Message: CVE-2017-13026/IS-IS: Clean up processing of subTLVs.
Add bounds checks, do a common check to make sure we captured the entire
subTLV, add checks to make sure the subTLV fits within the TLV.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add tests using the capture files supplied by the reporter(s), modified
so the capture files won't be rejected as an invalid capture.
Update existing tests for changes to IS-IS dissector.
CWE ID: CWE-125
| 1
| 8,649
|
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'.
|
Code: void CWebServer::RType_HandleGraph(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
char szTmp[300];
std::string sensor = request::findValue(&req, "sensor");
if (sensor == "")
return;
std::string srange = request::findValue(&req, "range");
if (srange == "")
return;
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
result = m_sql.safe_query("SELECT Type, SubType, SwitchType, AddjValue, AddjMulti, AddjValue2, Options FROM DeviceStatus WHERE (ID == %" PRIu64 ")",
idx);
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
_eMeterType metertype = (_eMeterType)atoi(result[0][2].c_str());
if (
(dType == pTypeP1Power) ||
(dType == pTypeENERGY) ||
(dType == pTypePOWER) ||
(dType == pTypeCURRENTENERGY) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
metertype = MTYPE_ENERGY;
}
else if (dType == pTypeP1Gas)
metertype = MTYPE_GAS;
else if ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))
metertype = MTYPE_COUNTER;
bool bIsManagedCounter = (dType == pTypeGeneral) && (dSubType == sTypeManagedCounter);
double AddjValue = atof(result[0][3].c_str());
double AddjMulti = atof(result[0][4].c_str());
double AddjValue2 = atof(result[0][5].c_str());
std::string sOptions = result[0][6].c_str();
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions);
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::string dbasetable = "";
if (srange == "day") {
if (sensor == "temp")
dbasetable = "Temperature";
else if (sensor == "rain")
dbasetable = "Rain";
else if (sensor == "Percentage")
dbasetable = "Percentage";
else if (sensor == "fan")
dbasetable = "Fan";
else if (sensor == "counter")
{
if ((dType == pTypeP1Power) || (dType == pTypeCURRENT) || (dType == pTypeCURRENTENERGY))
{
dbasetable = "MultiMeter";
}
else
{
dbasetable = "Meter";
}
}
else if ((sensor == "wind") || (sensor == "winddir"))
dbasetable = "Wind";
else if (sensor == "uv")
dbasetable = "UV";
else
return;
}
else
{
if (sensor == "temp")
dbasetable = "Temperature_Calendar";
else if (sensor == "rain")
dbasetable = "Rain_Calendar";
else if (sensor == "Percentage")
dbasetable = "Percentage_Calendar";
else if (sensor == "fan")
dbasetable = "Fan_Calendar";
else if (sensor == "counter")
{
if (
(dType == pTypeP1Power) ||
(dType == pTypeCURRENT) ||
(dType == pTypeCURRENTENERGY) ||
(dType == pTypeAirQuality) ||
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture)) ||
((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel)) ||
(dType == pTypeLux) ||
(dType == pTypeWEIGHT) ||
(dType == pTypeUsage)
)
dbasetable = "MultiMeter_Calendar";
else
dbasetable = "Meter_Calendar";
}
else if ((sensor == "wind") || (sensor == "winddir"))
dbasetable = "Wind_Calendar";
else if (sensor == "uv")
dbasetable = "UV_Calendar";
else
return;
}
unsigned char tempsign = m_sql.m_tempsign[0];
int iPrev;
if (srange == "day")
{
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Temperature, Chill, Humidity, Barometer, Date, SetPoint FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) ||
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
(dType == pTypeThermostat1) ||
(dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) ||
(dType == pTypeEvohomeWater)
)
{
double tvalue = ConvertTemperature(atof(sd[0].c_str()), tempsign);
root["result"][ii]["te"] = tvalue;
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double tvalue = ConvertTemperature(atof(sd[1].c_str()), tempsign);
root["result"][ii]["ch"] = tvalue;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[2];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[3];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double se = ConvertTemperature(atof(sd[5].c_str()), tempsign);
root["result"][ii]["se"] = se;
}
ii++;
}
}
}
else if (sensor == "Percentage") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Percentage, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (sensor == "fan") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Speed, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (sensor == "counter")
{
if (dType == pTypeP1Power)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Value4, Value5, Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveDeliverd = false;
bool bHaveFirstValue = false;
long long lastUsage1, lastUsage2, lastDeliv1, lastDeliv2;
time_t lastTime = 0;
long long firstUsage1, firstUsage2, firstDeliv1, firstDeliv2;
int nMeterType = 0;
m_sql.GetPreferencesVar("SmartMeterType", nMeterType);
int lastDay = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
if (nMeterType == 0)
{
long long actUsage1 = std::strtoll(sd[0].c_str(), nullptr, 10);
long long actUsage2 = std::strtoll(sd[4].c_str(), nullptr, 10);
long long actDeliv1 = std::strtoll(sd[1].c_str(), nullptr, 10);
long long actDeliv2 = std::strtoll(sd[5].c_str(), nullptr, 10);
actDeliv1 = (actDeliv1 < 10) ? 0 : actDeliv1;
actDeliv2 = (actDeliv2 < 10) ? 0 : actDeliv2;
std::string stime = sd[6];
struct tm ntime;
time_t atime;
ParseSQLdatetime(atime, ntime, stime, -1);
if (lastDay != ntime.tm_mday)
{
lastDay = ntime.tm_mday;
firstUsage1 = actUsage1;
firstUsage2 = actUsage2;
firstDeliv1 = actDeliv1;
firstDeliv2 = actDeliv2;
}
if (bHaveFirstValue)
{
long curUsage1 = (long)(actUsage1 - lastUsage1);
long curUsage2 = (long)(actUsage2 - lastUsage2);
long curDeliv1 = (long)(actDeliv1 - lastDeliv1);
long curDeliv2 = (long)(actDeliv2 - lastDeliv2);
if ((curUsage1 < 0) || (curUsage1 > 100000))
curUsage1 = 0;
if ((curUsage2 < 0) || (curUsage2 > 100000))
curUsage2 = 0;
if ((curDeliv1 < 0) || (curDeliv1 > 100000))
curDeliv1 = 0;
if ((curDeliv2 < 0) || (curDeliv2 > 100000))
curDeliv2 = 0;
float tdiff = static_cast<float>(difftime(atime, lastTime));
if (tdiff == 0)
tdiff = 1;
float tlaps = 3600.0f / tdiff;
curUsage1 *= int(tlaps);
curUsage2 *= int(tlaps);
curDeliv1 *= int(tlaps);
curDeliv2 *= int(tlaps);
root["result"][ii]["d"] = sd[6].substr(0, 16);
if ((curDeliv1 != 0) || (curDeliv2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%ld", curUsage1);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%ld", curUsage2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%ld", curDeliv1);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%ld", curDeliv2);
root["result"][ii]["r2"] = szTmp;
long pUsage1 = (long)(actUsage1 - firstUsage1);
long pUsage2 = (long)(actUsage2 - firstUsage2);
sprintf(szTmp, "%ld", pUsage1 + pUsage2);
root["result"][ii]["eu"] = szTmp;
if (bHaveDeliverd)
{
long pDeliv1 = (long)(actDeliv1 - firstDeliv1);
long pDeliv2 = (long)(actDeliv2 - firstDeliv2);
sprintf(szTmp, "%ld", pDeliv1 + pDeliv2);
root["result"][ii]["eg"] = szTmp;
}
ii++;
}
else
{
bHaveFirstValue = true;
if ((ntime.tm_hour != 0) && (ntime.tm_min != 0))
{
struct tm ltime;
localtime_r(&atime, &tm1);
getNoon(atime, ltime, ntime.tm_year + 1900, ntime.tm_mon + 1, ntime.tm_mday - 1); // We're only interested in finding the date
int year = ltime.tm_year + 1900;
int mon = ltime.tm_mon + 1;
int day = ltime.tm_mday;
sprintf(szTmp, "%04d-%02d-%02d", year, mon, day);
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query(
"SELECT Counter1, Counter2, Counter3, Counter4 FROM Multimeter_Calendar WHERE (DeviceRowID==%" PRIu64 ") AND (Date=='%q')",
idx, szTmp);
if (!result2.empty())
{
std::vector<std::string> sd = result2[0];
firstUsage1 = std::strtoll(sd[0].c_str(), nullptr, 10);
firstDeliv1 = std::strtoll(sd[1].c_str(), nullptr, 10);
firstUsage2 = std::strtoll(sd[2].c_str(), nullptr, 10);
firstDeliv2 = std::strtoll(sd[3].c_str(), nullptr, 10);
lastDay = ntime.tm_mday;
}
}
}
lastUsage1 = actUsage1;
lastUsage2 = actUsage2;
lastDeliv1 = actDeliv1;
lastDeliv2 = actDeliv2;
lastTime = atime;
}
else
{
root["result"][ii]["d"] = sd[6].substr(0, 16);
if (sd[3] != "0")
bHaveDeliverd = true;
root["result"][ii]["v"] = sd[2];
root["result"][ii]["r1"] = sd[3];
ii++;
}
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (dType == pTypeAirQuality)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["co2"] = sd[0];
ii++;
}
}
}
else if ((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness)))
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
float fValue = float(atof(sd[0].c_str())) / vdiv;
if (metertype == 1)
fValue *= 0.6214f;
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue);
else
sprintf(szTmp, "%.1f", fValue);
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
else if ((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (dType == pTypeLux)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["lux"] = sd[0];
ii++;
}
}
}
else if (dType == pTypeWEIGHT)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[0].c_str()) / 10.0f);
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
else if (dType == pTypeUsage)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["u"] = atof(sd[0].c_str()) / 10.0f;
ii++;
}
}
}
else if (dType == pTypeCURRENT)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
if (fval1 != 0)
bHaveL1 = true;
if (fval2 != 0)
bHaveL2 = true;
if (fval3 != 0)
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if (dType == pTypeCURRENTENERGY)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
if (fval1 != 0)
bHaveL1 = true;
if (fval2 != 0)
bHaveL2 = true;
if (fval3 != 0)
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if ((dType == pTypeENERGY) || (dType == pTypePOWER) || (dType == pTypeYouLess) || ((dType == pTypeGeneral) && (dSubType == sTypeKwh)))
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
bool bHaveUsage = true;
result = m_sql.safe_query("SELECT MIN([Usage]), MAX([Usage]) FROM %s WHERE (DeviceRowID==%" PRIu64 ")", dbasetable.c_str(), idx);
if (!result.empty())
{
long long minValue = std::strtoll(result[0][0].c_str(), nullptr, 10);
long long maxValue = std::strtoll(result[0][1].c_str(), nullptr, 10);
if ((minValue == 0) && (maxValue == 0))
{
bHaveUsage = false;
}
}
int ii = 0;
result = m_sql.safe_query("SELECT Value,[Usage], Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
int method = 0;
std::string sMethod = request::findValue(&req, "method");
if (sMethod.size() > 0)
method = atoi(sMethod.c_str());
if (bHaveUsage == false)
method = 0;
if ((dType == pTypeYouLess) && ((metertype == MTYPE_ENERGY) || (metertype == MTYPE_ENERGY_GENERATED)))
method = 1;
if (method != 0)
{
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
divider /= 100.0f;
}
root["method"] = method;
bool bHaveFirstValue = false;
bool bHaveFirstRealValue = false;
float FirstValue = 0;
long long ulFirstRealValue = 0;
long long ulFirstValue = 0;
long long ulLastValue = 0;
std::string LastDateTime = "";
time_t lastTime = 0;
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator itt;
for (itt = result.begin(); itt!=result.end(); ++itt)
{
std::vector<std::string> sd = *itt;
{
std::string actDateTimeHour = sd[2].substr(0, 13);
long long actValue = std::strtoll(sd[0].c_str(), nullptr, 10);
if (actValue >= ulLastValue)
ulLastValue = actValue;
if (actDateTimeHour != LastDateTime || ((method == 1) && (itt + 1 == result.end())))
{
if (bHaveFirstValue)
{
root["result"][ii]["d"] = LastDateTime + ":00";
long long ulTotalValue = ulLastValue - ulFirstValue;
if (ulTotalValue == 0)
{
ulTotalValue = ulLastValue - ulFirstRealValue;
}
ulFirstRealValue = ulLastValue;
float TotalValue = float(ulTotalValue);
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii][method == 1 ? "eu" : "v"] = szTmp;
ii++;
}
LastDateTime = actDateTimeHour;
bHaveFirstValue = false;
}
if (!bHaveFirstValue)
{
ulFirstValue = ulLastValue;
bHaveFirstValue = true;
}
if (!bHaveFirstRealValue)
{
bHaveFirstRealValue = true;
ulFirstRealValue = ulLastValue;
}
}
if (method == 1)
{
long long actValue = std::strtoll(sd[1].c_str(), nullptr, 10);
root["result"][ii]["d"] = sd[2].substr(0, 16);
float TotalValue = float(actValue);
if ((dType == pTypeGeneral) && (dSubType == sTypeKwh))
TotalValue /= 10.0f;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
}
else
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int ii = 0;
bool bHaveFirstValue = false;
bool bHaveFirstRealValue = false;
float FirstValue = 0;
unsigned long long ulFirstRealValue = 0;
unsigned long long ulFirstValue = 0;
unsigned long long ulLastValue = 0;
std::string LastDateTime = "";
time_t lastTime = 0;
if (bIsManagedCounter) {
result = m_sql.safe_query("SELECT Usage, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
bHaveFirstValue = true;
bHaveFirstRealValue = true;
}
else {
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
}
int method = 0;
std::string sMethod = request::findValue(&req, "method");
if (sMethod.size() > 0)
method = atoi(sMethod.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
if (method == 0)
{
unsigned long long actValue = std::strtoull(sd[0].c_str(), nullptr, 10);
std::string actDateTimeHour = sd[1].substr(0, 13);
if (actDateTimeHour != LastDateTime)
{
if (bHaveFirstValue)
{
struct tm ntime;
time_t atime;
if (actDateTimeHour.size() == 10)
actDateTimeHour += " 00";
constructTime(atime, ntime,
atoi(actDateTimeHour.substr(0, 4).c_str()),
atoi(actDateTimeHour.substr(5, 2).c_str()),
atoi(actDateTimeHour.substr(8, 2).c_str()),
atoi(actDateTimeHour.substr(11, 2).c_str()) - 1,
0, 0, -1);
char szTime[50];
sprintf(szTime, "%04d-%02d-%02d %02d:00", ntime.tm_year + 1900, ntime.tm_mon + 1, ntime.tm_mday, ntime.tm_hour);
root["result"][ii]["d"] = szTime;
float TotalValue = (actValue >= ulFirstValue) ? float(actValue - ulFirstValue) : actValue;
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
if (!bIsManagedCounter) {
ulFirstValue = actValue;
}
LastDateTime = actDateTimeHour;
}
if (!bHaveFirstValue)
{
ulFirstValue = actValue;
bHaveFirstValue = true;
}
ulLastValue = actValue;
}
else
{
unsigned long long actValue = std::strtoull(sd[0].c_str(), nullptr, 10);
std::string stime = sd[1];
struct tm ntime;
time_t atime;
ParseSQLdatetime(atime, ntime, stime, -1);
if (bHaveFirstRealValue)
{
long long curValue = actValue - ulLastValue;
float tdiff = static_cast<float>(difftime(atime, lastTime));
if (tdiff == 0)
tdiff = 1;
float tlaps = 3600.0f / tdiff;
curValue *= int(tlaps);
root["result"][ii]["d"] = sd[1].substr(0, 16);
float TotalValue = float(curValue);
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
else
bHaveFirstRealValue = true;
if (!bIsManagedCounter) {
ulLastValue = actValue;
}
lastTime = atime;
}
}
}
if ((!bIsManagedCounter) && (bHaveFirstValue) && (method == 0))
{
root["result"][ii]["d"] = LastDateTime + ":00";
unsigned long long ulTotalValue = ulLastValue - ulFirstValue;
float TotalValue = float(ulTotalValue);
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int LastHour = -1;
float LastTotalPreviousHour = -1;
float LastValue = -1;
std::string LastDate = "";
result = m_sql.safe_query("SELECT Total, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float ActTotal = static_cast<float>(atof(sd[0].c_str()));
int Hour = atoi(sd[1].substr(11, 2).c_str());
if (Hour != LastHour)
{
if (LastHour != -1)
{
int NextCalculatedHour = (LastHour + 1) % 24;
if (Hour != NextCalculatedHour)
{
root["result"][ii]["d"] = LastDate;
double mmval = ActTotal - LastValue;
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
else
{
root["result"][ii]["d"] = sd[1].substr(0, 16);
double mmval = ActTotal - LastTotalPreviousHour;
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
LastHour = Hour;
LastTotalPreviousHour = ActTotal;
}
LastValue = ActTotal;
LastDate = sd[1];
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Direction, Speed, Gust, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[1].c_str());
int intGust = atoi(sd[2].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
}
else if (sensor == "winddir") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Direction, Speed, Gust FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
std::map<int, int> _directions;
int wdirtabletemp[17][8];
std::string szLegendLabels[7];
int ii = 0;
int totalvalues = 0;
int idir;
for (idir = 0; idir < 360 + 1; idir++)
_directions[idir] = 0;
for (ii = 0; ii < 17; ii++)
{
for (int jj = 0; jj < 8; jj++)
{
wdirtabletemp[ii][jj] = 0;
}
}
if (m_sql.m_windunit == WINDUNIT_MS)
{
szLegendLabels[0] = "< 0.5 " + m_sql.m_windsign;
szLegendLabels[1] = "0.5-2 " + m_sql.m_windsign;
szLegendLabels[2] = "2-4 " + m_sql.m_windsign;
szLegendLabels[3] = "4-6 " + m_sql.m_windsign;
szLegendLabels[4] = "6-8 " + m_sql.m_windsign;
szLegendLabels[5] = "8-10 " + m_sql.m_windsign;
szLegendLabels[6] = "> 10" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_KMH)
{
szLegendLabels[0] = "< 2 " + m_sql.m_windsign;
szLegendLabels[1] = "2-4 " + m_sql.m_windsign;
szLegendLabels[2] = "4-6 " + m_sql.m_windsign;
szLegendLabels[3] = "6-10 " + m_sql.m_windsign;
szLegendLabels[4] = "10-20 " + m_sql.m_windsign;
szLegendLabels[5] = "20-36 " + m_sql.m_windsign;
szLegendLabels[6] = "> 36" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_MPH)
{
szLegendLabels[0] = "< 3 " + m_sql.m_windsign;
szLegendLabels[1] = "3-7 " + m_sql.m_windsign;
szLegendLabels[2] = "7-12 " + m_sql.m_windsign;
szLegendLabels[3] = "12-18 " + m_sql.m_windsign;
szLegendLabels[4] = "18-24 " + m_sql.m_windsign;
szLegendLabels[5] = "24-46 " + m_sql.m_windsign;
szLegendLabels[6] = "> 46" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_Knots)
{
szLegendLabels[0] = "< 3 " + m_sql.m_windsign;
szLegendLabels[1] = "3-7 " + m_sql.m_windsign;
szLegendLabels[2] = "7-17 " + m_sql.m_windsign;
szLegendLabels[3] = "17-27 " + m_sql.m_windsign;
szLegendLabels[4] = "27-34 " + m_sql.m_windsign;
szLegendLabels[5] = "34-41 " + m_sql.m_windsign;
szLegendLabels[6] = "> 41" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_Beaufort)
{
szLegendLabels[0] = "< 2 " + m_sql.m_windsign;
szLegendLabels[1] = "2-4 " + m_sql.m_windsign;
szLegendLabels[2] = "4-6 " + m_sql.m_windsign;
szLegendLabels[3] = "6-8 " + m_sql.m_windsign;
szLegendLabels[4] = "8-10 " + m_sql.m_windsign;
szLegendLabels[5] = "10-12 " + m_sql.m_windsign;
szLegendLabels[6] = "> 12" + m_sql.m_windsign;
}
else {
szLegendLabels[0] = "< 0.5 " + m_sql.m_windsign;
szLegendLabels[1] = "0.5-2 " + m_sql.m_windsign;
szLegendLabels[2] = "2-4 " + m_sql.m_windsign;
szLegendLabels[3] = "4-6 " + m_sql.m_windsign;
szLegendLabels[4] = "6-8 " + m_sql.m_windsign;
szLegendLabels[5] = "8-10 " + m_sql.m_windsign;
szLegendLabels[6] = "> 10" + m_sql.m_windsign;
}
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float fdirection = static_cast<float>(atof(sd[0].c_str()));
if (fdirection >= 360)
fdirection = 0;
int direction = int(fdirection);
float speedOrg = static_cast<float>(atof(sd[1].c_str()));
float gustOrg = static_cast<float>(atof(sd[2].c_str()));
if ((gustOrg == 0) && (speedOrg != 0))
gustOrg = speedOrg;
if (gustOrg == 0)
continue; //no direction if wind is still
float speed = speedOrg * m_sql.m_windscale;
float gust = gustOrg * m_sql.m_windscale;
int bucket = int(fdirection / 22.5f);
int speedpos = 0;
if (m_sql.m_windunit == WINDUNIT_MS)
{
if (gust < 0.5f) speedpos = 0;
else if (gust < 2.0f) speedpos = 1;
else if (gust < 4.0f) speedpos = 2;
else if (gust < 6.0f) speedpos = 3;
else if (gust < 8.0f) speedpos = 4;
else if (gust < 10.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_KMH)
{
if (gust < 2.0f) speedpos = 0;
else if (gust < 4.0f) speedpos = 1;
else if (gust < 6.0f) speedpos = 2;
else if (gust < 10.0f) speedpos = 3;
else if (gust < 20.0f) speedpos = 4;
else if (gust < 36.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_MPH)
{
if (gust < 3.0f) speedpos = 0;
else if (gust < 7.0f) speedpos = 1;
else if (gust < 12.0f) speedpos = 2;
else if (gust < 18.0f) speedpos = 3;
else if (gust < 24.0f) speedpos = 4;
else if (gust < 46.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_Knots)
{
if (gust < 3.0f) speedpos = 0;
else if (gust < 7.0f) speedpos = 1;
else if (gust < 17.0f) speedpos = 2;
else if (gust < 27.0f) speedpos = 3;
else if (gust < 34.0f) speedpos = 4;
else if (gust < 41.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_Beaufort)
{
float gustms = gustOrg * 0.1f;
int iBeaufort = MStoBeaufort(gustms);
if (iBeaufort < 2) speedpos = 0;
else if (iBeaufort < 4) speedpos = 1;
else if (iBeaufort < 6) speedpos = 2;
else if (iBeaufort < 8) speedpos = 3;
else if (iBeaufort < 10) speedpos = 4;
else if (iBeaufort < 12) speedpos = 5;
else speedpos = 6;
}
else
{
if (gust < 0.5f) speedpos = 0;
else if (gust < 2.0f) speedpos = 1;
else if (gust < 4.0f) speedpos = 2;
else if (gust < 6.0f) speedpos = 3;
else if (gust < 8.0f) speedpos = 4;
else if (gust < 10.0f) speedpos = 5;
else speedpos = 6;
}
wdirtabletemp[bucket][speedpos]++;
_directions[direction]++;
totalvalues++;
}
for (int jj = 0; jj < 7; jj++)
{
root["result_speed"][jj]["label"] = szLegendLabels[jj];
for (ii = 0; ii < 16; ii++)
{
float svalue = 0;
if (totalvalues > 0)
{
svalue = (100.0f / totalvalues)*wdirtabletemp[ii][jj];
}
sprintf(szTmp, "%.2f", svalue);
root["result_speed"][jj]["sp"][ii] = szTmp;
}
}
ii = 0;
for (idir = 0; idir < 360 + 1; idir++)
{
if (_directions[idir] != 0)
{
root["result"][ii]["dig"] = idir;
float percentage = 0;
if (totalvalues > 0)
{
percentage = (float(100.0 / float(totalvalues))*float(_directions[idir]));
}
sprintf(szTmp, "%.2f", percentage);
root["result"][ii]["div"] = szTmp;
ii++;
}
}
}
}
}//day
else if (srange == "week")
{
if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
char szDateStart[40];
char szDateEnd[40];
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
time_t weekbefore;
struct tm tm2;
getNoon(weekbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday - 7); // We only want the date
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
result = m_sql.safe_query("SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd);
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
double total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
total_real *= AddjMulti;
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
else if (sensor == "counter")
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
char szDateStart[40];
char szDateEnd[40];
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
time_t weekbefore;
struct tm tm2;
getNoon(weekbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday - 7); // We only want the date
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
int ii = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value5,Value6,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
std::string szValueUsage1 = sd[0];
std::string szValueDeliv1 = sd[1];
std::string szValueUsage2 = sd[2];
std::string szValueDeliv2 = sd[3];
float fUsage1 = (float)(atof(szValueUsage1.c_str()));
float fUsage2 = (float)(atof(szValueUsage2.c_str()));
float fDeliv1 = (float)(atof(szValueDeliv1.c_str()));
float fDeliv2 = (float)(atof(szValueDeliv2.c_str()));
fDeliv1 = (fDeliv1 < 10) ? 0 : fDeliv1;
fDeliv2 = (fDeliv2 < 10) ? 0 : fDeliv2;
if ((fDeliv1 != 0) || (fDeliv2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage1 / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage2 / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv1 / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv2 / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else
{
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_COUNTER:
break;
default:
szValue = "0";
break;
}
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2), MAX(Value2),MIN(Value5), MAX(Value5), MIN(Value6), MAX(Value6) FROM MultiMeter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage_1, total_real_usage_2;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv_1, total_real_deliv_2;
bool bHaveDeliverd = false;
total_real_usage_1 = total_max_usage_1 - total_min_usage_1;
total_real_usage_2 = total_max_usage_2 - total_min_usage_2;
total_real_deliv_1 = total_max_deliv_1 - total_min_deliv_1;
total_real_deliv_2 = total_max_deliv_2 - total_min_deliv_2;
if ((total_real_deliv_1 != 0) || (total_real_deliv_2 != 0))
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%llu", total_real_usage_1);
std::string szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_usage_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_COUNTER:
break;
default:
szValue = "0";
break;
}
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
}//week
else if ((srange == "month") || (srange == "year"))
{
char szDateStart[40];
char szDateEnd[40];
char szDateStartPrev[40];
char szDateEndPrev[40];
std::string sactmonth = request::findValue(&req, "actmonth");
std::string sactyear = request::findValue(&req, "actyear");
int actMonth = atoi(sactmonth.c_str());
int actYear = atoi(sactyear.c_str());
if ((sactmonth != "") && (sactyear != ""))
{
sprintf(szDateStart, "%04d-%02d-%02d", actYear, actMonth, 1);
sprintf(szDateStartPrev, "%04d-%02d-%02d", actYear - 1, actMonth, 1);
actMonth++;
if (actMonth == 13)
{
actMonth = 1;
actYear++;
}
sprintf(szDateEnd, "%04d-%02d-%02d", actYear, actMonth, 1);
sprintf(szDateEndPrev, "%04d-%02d-%02d", actYear - 1, actMonth, 1);
}
else if (sactyear != "")
{
sprintf(szDateStart, "%04d-%02d-%02d", actYear, 1, 1);
sprintf(szDateStartPrev, "%04d-%02d-%02d", actYear - 1, 1, 1);
actYear++;
sprintf(szDateEnd, "%04d-%02d-%02d", actYear, 1, 1);
sprintf(szDateEndPrev, "%04d-%02d-%02d", actYear - 1, 1, 1);
}
else
{
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
sprintf(szDateEndPrev, "%04d-%02d-%02d", tm1.tm_year + 1900 - 1, tm1.tm_mon + 1, tm1.tm_mday);
struct tm tm2;
if (srange == "month")
{
time_t monthbefore;
getNoon(monthbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon, tm1.tm_mday);
}
else
{
time_t yearbefore;
getNoon(yearbefore, tm2, tm1.tm_year + 1900 - 1, tm1.tm_mon + 1, tm1.tm_mday);
}
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
sprintf(szDateStartPrev, "%04d-%02d-%02d", tm2.tm_year + 1900 - 1, tm2.tm_mon + 1, tm2.tm_mday);
}
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Temp_Avg, Date, SetPoint_Min,"
" SetPoint_Max, SetPoint_Avg "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[7].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
bool bOK = true;
if (dType == pTypeWIND)
{
bOK = ((dSubType != sTypeWINDNoTemp) && (dSubType != sTypeWINDNoTempNoChill));
}
if (bOK)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sm = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[10].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
}
ii++;
}
}
result = m_sql.safe_query(
"SELECT MIN(Temperature), MAX(Temperature),"
" MIN(Chill), MAX(Chill), AVG(Humidity),"
" AVG(Barometer), AVG(Temperature), MIN(SetPoint),"
" MAX(SetPoint), AVG(SetPoint) "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
if (
((dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sx = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sm = ConvertTemperature(atof(sd[7].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[9].c_str()), tempsign);
root["result"][ii]["se"] = se;
root["result"][ii]["sm"] = sm;
root["result"][ii]["sx"] = sx;
}
ii++;
}
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Temp_Avg, Date, SetPoint_Min,"
" SetPoint_Max, SetPoint_Avg "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[7].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
{
bool bOK = true;
if (dType == pTypeWIND)
{
bOK = ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp));
}
if (bOK)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["resultprev"][iPrev]["te"] = te;
root["resultprev"][iPrev]["tm"] = tm;
root["resultprev"][iPrev]["ta"] = ta;
}
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["resultprev"][iPrev]["ch"] = ch;
root["resultprev"][iPrev]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["resultprev"][iPrev]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
else
root["resultprev"][iPrev]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sx = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sm = ConvertTemperature(atof(sd[7].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[9].c_str()), tempsign);
root["resultprev"][iPrev]["se"] = se;
root["resultprev"][iPrev]["sm"] = sm;
root["resultprev"][iPrev]["sx"] = sx;
}
iPrev++;
}
}
}
else if (sensor == "Percentage") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Percentage_Min, Percentage_Max, Percentage_Avg, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_avg"] = sd[2];
ii++;
}
}
result = m_sql.safe_query(
"SELECT MIN(Percentage), MAX(Percentage), AVG(Percentage) FROM Percentage WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_avg"] = sd[2];
ii++;
}
}
else if (sensor == "fan") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Speed_Min, Speed_Max, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_min"] = sd[0];
ii++;
}
}
result = m_sql.safe_query("SELECT MIN(Speed), MAX(Speed) FROM Fan WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_min"] = sd[0];
ii++;
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
result = m_sql.safe_query(
"SELECT MAX(Level) FROM UV WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["uvi"] = sd[0];
ii++;
}
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
root["resultprev"][iPrev]["uvi"] = sd[0];
iPrev++;
}
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd);
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
double total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
total_real *= AddjMulti;
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
result = m_sql.safe_query(
"SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["resultprev"][iPrev]["mm"] = szTmp;
iPrev++;
}
}
}
else if (sensor == "counter") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int nValue = 0;
std::string sValue = "";
result = m_sql.safe_query("SELECT nValue, sValue FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
idx);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
nValue = atoi(sd[0].c_str());
sValue = sd[1];
}
int ii = 0;
iPrev = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date,"
" Counter1, Counter2, Counter3, Counter4 "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
double counter_1 = atof(sd[5].c_str());
double counter_2 = atof(sd[6].c_str());
double counter_3 = atof(sd[7].c_str());
double counter_4 = atof(sd[8].c_str());
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage_1 = static_cast<float>(atof(szUsage1.c_str()));
float fUsage_2 = static_cast<float>(atof(szUsage2.c_str()));
float fDeliv_1 = static_cast<float>(atof(szDeliv1.c_str()));
float fDeliv_2 = static_cast<float>(atof(szDeliv2.c_str()));
fDeliv_1 = (fDeliv_1 < 10) ? 0 : fDeliv_1;
fDeliv_2 = (fDeliv_2 < 10) ? 0 : fDeliv_2;
if ((fDeliv_1 != 0) || (fDeliv_2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage_1 / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage_2 / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_1 / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_2 / divider);
root["result"][ii]["r2"] = szTmp;
if (counter_1 != 0)
{
sprintf(szTmp, "%.3f", (counter_1 - fUsage_1) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c1"] = szTmp;
if (counter_2 != 0)
{
sprintf(szTmp, "%.3f", (counter_2 - fDeliv_1) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c2"] = szTmp;
if (counter_3 != 0)
{
sprintf(szTmp, "%.3f", (counter_3 - fUsage_2) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c3"] = szTmp;
if (counter_4 != 0)
{
sprintf(szTmp, "%.3f", (counter_4 - fDeliv_2) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c4"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
bool bHaveDeliverd = false;
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[4].substr(0, 16);
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage_1 = static_cast<float>(atof(szUsage1.c_str()));
float fUsage_2 = static_cast<float>(atof(szUsage2.c_str()));
float fDeliv_1 = static_cast<float>(atof(szDeliv1.c_str()));
float fDeliv_2 = static_cast<float>(atof(szDeliv2.c_str()));
if ((fDeliv_1 != 0) || (fDeliv_2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage_1 / divider);
root["resultprev"][iPrev]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage_2 / divider);
root["resultprev"][iPrev]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_1 / divider);
root["resultprev"][iPrev]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_2 / divider);
root["resultprev"][iPrev]["r2"] = szTmp;
iPrev++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (dType == pTypeAirQuality)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["co2_min"] = sd[0];
root["result"][ii]["co2_max"] = sd[1];
root["result"][ii]["co2_avg"] = sd[2];
ii++;
}
}
result = m_sql.safe_query("SELECT Value2,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
root["resultprev"][iPrev]["co2_max"] = sd[0];
iPrev++;
}
}
}
else if (
((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness))) ||
((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
ii++;
}
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float fValue1 = float(atof(sd[0].c_str())) / vdiv;
float fValue2 = float(atof(sd[1].c_str())) / vdiv;
float fValue3 = float(atof(sd[2].c_str())) / vdiv;
root["result"][ii]["d"] = sd[3].substr(0, 16);
if (metertype == 1)
{
fValue1 *= 0.6214f;
fValue2 *= 0.6214f;
}
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
sprintf(szTmp, "%.3f", fValue1);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.3f", fValue2);
root["result"][ii]["v_max"] = szTmp;
if (fValue3 != 0)
{
sprintf(szTmp, "%.3f", fValue3);
root["result"][ii]["v_avg"] = szTmp;
}
}
else
{
sprintf(szTmp, "%.1f", fValue1);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", fValue2);
root["result"][ii]["v_max"] = szTmp;
if (fValue3 != 0)
{
sprintf(szTmp, "%.1f", fValue3);
root["result"][ii]["v_avg"] = szTmp;
}
}
ii++;
}
}
}
else if (dType == pTypeLux)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2,Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["lux_min"] = sd[0];
root["result"][ii]["lux_max"] = sd[1];
root["result"][ii]["lux_avg"] = sd[2];
ii++;
}
}
}
else if (dType == pTypeWEIGHT)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[0].c_str()) / 10.0f);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[1].c_str()) / 10.0f);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
}
else if (dType == pTypeUsage)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["u_min"] = atof(sd[0].c_str()) / 10.0f;
root["result"][ii]["u_max"] = atof(sd[1].c_str()) / 10.0f;
ii++;
}
}
}
else if (dType == pTypeCURRENT)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Value4,Value5,Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
float fval4 = static_cast<float>(atof(sd[3].c_str()) / 10.0f);
float fval5 = static_cast<float>(atof(sd[4].c_str()) / 10.0f);
float fval6 = static_cast<float>(atof(sd[5].c_str()) / 10.0f);
if ((fval1 != 0) || (fval2 != 0))
bHaveL1 = true;
if ((fval3 != 0) || (fval4 != 0))
bHaveL2 = true;
if ((fval5 != 0) || (fval6 != 0))
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%.1f", fval4);
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%.1f", fval5);
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%.1f", fval6);
root["result"][ii]["v6"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%d", int(fval4*voltage));
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%d", int(fval5*voltage));
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%d", int(fval6*voltage));
root["result"][ii]["v6"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if (dType == pTypeCURRENTENERGY)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Value4,Value5,Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
float fval4 = static_cast<float>(atof(sd[3].c_str()) / 10.0f);
float fval5 = static_cast<float>(atof(sd[4].c_str()) / 10.0f);
float fval6 = static_cast<float>(atof(sd[5].c_str()) / 10.0f);
if ((fval1 != 0) || (fval2 != 0))
bHaveL1 = true;
if ((fval3 != 0) || (fval4 != 0))
bHaveL2 = true;
if ((fval5 != 0) || (fval6 != 0))
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%.1f", fval4);
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%.1f", fval5);
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%.1f", fval6);
root["result"][ii]["v6"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%d", int(fval4*voltage));
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%d", int(fval5*voltage));
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%d", int(fval6*voltage));
root["result"][ii]["v6"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else
{
if (dType == pTypeP1Gas)
{
sprintf(szTmp, "%.3f", atof(sValue.c_str()) / 1000.0);
root["counter"] = szTmp;
}
else if (dType == pTypeENERGY)
{
size_t spos = sValue.find(";");
if (spos != std::string::npos)
{
float fvalue = static_cast<float>(atof(sValue.substr(spos + 1).c_str()));
sprintf(szTmp, "%.3f", fvalue / (divider / 100.0f));
root["counter"] = szTmp;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeKwh))
{
size_t spos = sValue.find(";");
if (spos != std::string::npos)
{
float fvalue = static_cast<float>(atof(sValue.substr(spos + 1).c_str()));
sprintf(szTmp, "%.3f", fvalue / divider);
root["counter"] = szTmp;
}
}
else if (dType == pTypeRFXMeter)
{
float fvalue = static_cast<float>(atof(sValue.c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", AddjValue + (fvalue / divider));
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", AddjValue + (fvalue / divider));
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", AddjValue + (fvalue / divider));
break;
default:
strcpy(szTmp, "");
break;
}
root["counter"] = szTmp;
}
else if (dType == pTypeYouLess)
{
std::vector<std::string> results;
StringSplit(sValue, ";", results);
if (results.size() == 2)
{
float fvalue = static_cast<float>(atof(results[0].c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", fvalue / divider);
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", fvalue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", fvalue / divider);
break;
default:
strcpy(szTmp, "");
break;
}
root["counter"] = szTmp;
}
}
else if (!bIsManagedCounter)
{
sprintf(szTmp, "%d", atoi(sValue.c_str()));
root["counter"] = szTmp;
}
else
{
root["counter"] = "0";
}
result = m_sql.safe_query("SELECT Value, Date, Counter FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
double fcounter = atof(sd[2].c_str());
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.3f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.2f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.3f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.0f", AddjValue + ((fcounter - atof(szValue.c_str()))));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
}
ii++;
}
}
result = m_sql.safe_query("SELECT Value, Date, Counter FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["resultprev"][iPrev]["v"] = szTmp;
break;
}
iPrev++;
}
}
}
if ((sactmonth != "") || (sactyear != ""))
{
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
if ((sactmonth != "") && (sactyear != ""))
{
bool bIsThisMonth = (atoi(sactyear.c_str()) == loctime.tm_year + 1900) && (atoi(sactmonth.c_str()) == loctime.tm_mon + 1);
if (bIsThisMonth)
{
sprintf(szDateEnd, "%04d-%02d-%02d", loctime.tm_year + 1900, loctime.tm_mon + 1, loctime.tm_mday);
}
}
else if (sactyear != "")
{
bool bIsThisYear = (atoi(sactyear.c_str()) == loctime.tm_year + 1900);
if (bIsThisYear)
{
sprintf(szDateEnd, "%04d-%02d-%02d", loctime.tm_year + 1900, loctime.tm_mon + 1, loctime.tm_mday);
}
}
}
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2),"
" MAX(Value2), MIN(Value5), MAX(Value5),"
" MIN(Value6), MAX(Value6) "
"FROM MultiMeter WHERE (DeviceRowID=%" PRIu64 ""
" AND Date>='%q')",
idx, szDateEnd);
bool bHaveDeliverd = false;
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage_1, total_real_usage_2;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv_1, total_real_deliv_2;
total_real_usage_1 = total_max_usage_1 - total_min_usage_1;
total_real_usage_2 = total_max_usage_2 - total_min_usage_2;
total_real_deliv_1 = total_max_deliv_1 - total_min_deliv_1;
total_real_deliv_2 = total_max_deliv_2 - total_min_deliv_2;
if ((total_real_deliv_1 != 0) || (total_real_deliv_2 != 0))
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
std::string szValue;
sprintf(szTmp, "%llu", total_real_usage_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_usage_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
else if (dType == pTypeAirQuality)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value), AVG(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["co2_min"] = result[0][0];
root["result"][ii]["co2_max"] = result[0][1];
root["result"][ii]["co2_avg"] = result[0][2];
ii++;
}
}
else if (
((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness))) ||
((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_min"] = result[0][0];
root["result"][ii]["v_max"] = result[0][1];
ii++;
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
float fValue1 = float(atof(result[0][0].c_str())) / vdiv;
float fValue2 = float(atof(result[0][1].c_str())) / vdiv;
if (metertype == 1)
{
fValue1 *= 0.6214f;
fValue2 *= 0.6214f;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue1);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue1);
else
sprintf(szTmp, "%.1f", fValue1);
root["result"][ii]["v_min"] = szTmp;
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue2);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue2);
else
sprintf(szTmp, "%.1f", fValue2);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
else if (dType == pTypeLux)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value), AVG(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["lux_min"] = result[0][0];
root["result"][ii]["lux_max"] = result[0][1];
root["result"][ii]["lux_avg"] = result[0][2];
ii++;
}
}
else if (dType == pTypeWEIGHT)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%.1f", m_sql.m_weightscale* atof(result[0][0].c_str()) / 10.0f);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(result[0][1].c_str()) / 10.0f);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
else if (dType == pTypeUsage)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["u_min"] = atof(result[0][0].c_str()) / 10.0f;
root["result"][ii]["u_max"] = atof(result[0][1].c_str()) / 10.0f;
ii++;
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
root["result"][ii]["d"] = szDateEnd;
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
{
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
std::vector<std::string> mresults;
StringSplit(sValue, ";", mresults);
if (mresults.size() == 2)
{
sValue = mresults[1];
}
if (dType == pTypeENERGY)
sprintf(szTmp, "%.3f", AddjValue + (((atof(sValue.c_str())*100.0f) - atof(szValue.c_str())) / divider));
else
sprintf(szTmp, "%.3f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
}
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.2f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.0f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str()))));
root["result"][ii]["c"] = szTmp;
break;
}
ii++;
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int ii = 0;
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[5].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
result = m_sql.safe_query(
"SELECT AVG(Direction), MIN(Speed), MAX(Speed),"
" MIN(Gust), MAX(Gust) "
"FROM Wind WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY Date ASC",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[5].substr(0, 16);
root["resultprev"][iPrev]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["resultprev"][iPrev]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["resultprev"][iPrev]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["resultprev"][iPrev]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["resultprev"][iPrev]["gu"] = szTmp;
}
iPrev++;
}
}
}
}//month or year
else if ((srange.substr(0, 1) == "2") && (srange.substr(10, 1) == "T") && (srange.substr(11, 1) == "2")) // custom range 2013-01-01T2013-12-31
{
std::string szDateStart = srange.substr(0, 10);
std::string szDateEnd = srange.substr(11, 10);
std::string sgraphtype = request::findValue(&req, "graphtype");
std::string sgraphTemp = request::findValue(&req, "graphTemp");
std::string sgraphChill = request::findValue(&req, "graphChill");
std::string sgraphHum = request::findValue(&req, "graphHum");
std::string sgraphBaro = request::findValue(&req, "graphBaro");
std::string sgraphDew = request::findValue(&req, "graphDew");
std::string sgraphSet = request::findValue(&req, "graphSet");
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
bool sendTemp = false;
bool sendChill = false;
bool sendHum = false;
bool sendBaro = false;
bool sendDew = false;
bool sendSet = false;
if ((sgraphTemp == "true") &&
((dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
)
{
sendTemp = true;
}
if ((sgraphSet == "true") &&
((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))) //FIXME cheat for water setpoint is just on or off
{
sendSet = true;
}
if ((sgraphChill == "true") &&
(((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp)))
)
{
sendChill = true;
}
if ((sgraphHum == "true") &&
((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
)
{
sendHum = true;
}
if ((sgraphBaro == "true") && (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
))
{
sendBaro = true;
}
if ((sgraphDew == "true") && ((dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO)))
{
sendDew = true;
}
if (sgraphtype == "1")
{
result = m_sql.safe_query(
"SELECT Temperature, Chill, Humidity, Barometer,"
" Date, DewPoint, SetPoint "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q' AND Date<='%q 23:59:59') ORDER BY Date ASC",
idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4];//.substr(0,16);
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[1].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[2];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[3];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[5].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double se = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["se"] = se;
}
ii++;
}
}
}
else
{
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Date, DewPoint, Temp_Avg,"
" SetPoint_Min, SetPoint_Max, SetPoint_Avg "
"FROM Temperature_Calendar "
"WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[8].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[4];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[7].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double sm = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[10].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[11].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
char szTmp[1024];
sprintf(szTmp, "%.1f %.1f %.1f", sm, se, sx);
_log.Log(LOG_STATUS, "%s", szTmp);
}
ii++;
}
}
result = m_sql.safe_query(
"SELECT MIN(Temperature), MAX(Temperature),"
" MIN(Chill), MAX(Chill), AVG(Humidity),"
" AVG(Barometer), MIN(DewPoint), AVG(Temperature),"
" MIN(SetPoint), MAX(SetPoint), AVG(SetPoint) "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[7].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[4];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double sm = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[10].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
}
ii++;
}
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
result = m_sql.safe_query(
"SELECT MAX(Level) FROM UV WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Total, Rate, Date FROM %s "
"WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["mm"] = sd[0];
ii++;
}
}
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd.c_str());
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
float total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
else if (sensor == "counter") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int ii = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage = (float)(atof(szUsage1.c_str()) + atof(szUsage2.c_str()));
float fDeliv = (float)(atof(szDeliv1.c_str()) + atof(szDeliv2.c_str()));
if (fDeliv != 0)
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv / divider);
root["result"][ii]["v2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else
{
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
}
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2),"
" MAX(Value2),MIN(Value5), MAX(Value5),"
" MIN(Value6), MAX(Value6) "
"FROM MultiMeter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
bool bHaveDeliverd = false;
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv;
total_real_usage = (total_max_usage_1 + total_max_usage_2) - (total_min_usage_1 + total_min_usage_2);
total_real_deliv = (total_max_deliv_1 + total_max_deliv_2) - (total_min_deliv_1 + total_min_deliv_2);
if (total_real_deliv != 0)
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%llu", total_real_usage);
std::string szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
ii++;
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
}
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int ii = 0;
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[5].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
result = m_sql.safe_query(
"SELECT AVG(Direction), MIN(Speed), MAX(Speed), MIN(Gust), MAX(Gust) FROM Wind WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY Date ASC",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
}//custom range
}
Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
CWE ID: CWE-89
| 0
| 17,535
|
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'.
|
Code: static void authenc_verify_ahash_done(struct crypto_async_request *areq,
int err)
{
u8 *ihash;
unsigned int authsize;
struct ablkcipher_request *abreq;
struct aead_request *req = areq->data;
struct crypto_aead *authenc = crypto_aead_reqtfm(req);
struct crypto_authenc_ctx *ctx = crypto_aead_ctx(authenc);
struct authenc_request_ctx *areq_ctx = aead_request_ctx(req);
struct ahash_request *ahreq = (void *)(areq_ctx->tail + ctx->reqoff);
unsigned int cryptlen = req->cryptlen;
if (err)
goto out;
authsize = crypto_aead_authsize(authenc);
cryptlen -= authsize;
ihash = ahreq->result + authsize;
scatterwalk_map_and_copy(ihash, areq_ctx->sg, areq_ctx->cryptlen,
authsize, 0);
err = crypto_memneq(ihash, ahreq->result, authsize) ? -EBADMSG : 0;
if (err)
goto out;
abreq = aead_request_ctx(req);
ablkcipher_request_set_tfm(abreq, ctx->enc);
ablkcipher_request_set_callback(abreq, aead_request_flags(req),
req->base.complete, req->base.data);
ablkcipher_request_set_crypt(abreq, req->src, req->dst,
cryptlen, req->iv);
err = crypto_ablkcipher_decrypt(abreq);
out:
authenc_request_complete(req, err);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: Kees Cook <keescook@chromium.org>
Acked-by: Mathias Krause <minipli@googlemail.com>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
CWE ID: CWE-264
| 0
| 19,207
|
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'.
|
Code: check_uuid(const char *uuid)
{
const char *p;
for (p = uuid; p[0]; p++)
if ((!isalnum(*p)) && (*p != '-')) return EINA_FALSE;
return EINA_TRUE;
}
Commit Message:
CWE ID: CWE-264
| 0
| 4,753
|
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'.
|
Code: const gfx::Point& tap_location() const {
return tap_location_;
}
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
| 12,072
|
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'.
|
Code: void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
DCHECK(!frame_);
std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
std::make_pair(web_frame, this));
CHECK(result.second) << "Inserting a duplicate item.";
frame_ = web_frame;
}
Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame.
BUG=369553
R=creis@chromium.org
Review URL: https://codereview.chromium.org/263833020
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
| 0
| 25,426
|
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'.
|
Code: bool Textfield::GetWordLookupDataAtPoint(const gfx::Point& point,
gfx::DecoratedText* decorated_word,
gfx::Point* baseline_point) {
return GetRenderText()->GetWordLookupDataAtPoint(point, decorated_word,
baseline_point);
}
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 <mblsha@yandex-team.ru>
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Avi Drissman <avi@chromium.org>
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
| 0
| 3,070
|
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'.
|
Code: void DesktopWindowTreeHostX11::ShowImpl() {
Show(ui::SHOW_STATE_NORMAL, gfx::Rect());
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <sky@chromium.org>
Commit-Queue: enne <enne@chromium.org>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284
| 0
| 5,822
|
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'.
|
Code: static int ext3_show_options(struct seq_file *seq, struct dentry *root)
{
struct super_block *sb = root->d_sb;
struct ext3_sb_info *sbi = EXT3_SB(sb);
struct ext3_super_block *es = sbi->s_es;
unsigned long def_mount_opts;
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
if (sbi->s_sb_block != 1)
seq_printf(seq, ",sb=%lu", sbi->s_sb_block);
if (test_opt(sb, MINIX_DF))
seq_puts(seq, ",minixdf");
if (test_opt(sb, GRPID))
seq_puts(seq, ",grpid");
if (!test_opt(sb, GRPID) && (def_mount_opts & EXT3_DEFM_BSDGROUPS))
seq_puts(seq, ",nogrpid");
if (!uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT3_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT3_DEF_RESUID) {
seq_printf(seq, ",resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
}
if (!gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT3_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT3_DEF_RESGID) {
seq_printf(seq, ",resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
}
if (test_opt(sb, ERRORS_RO)) {
int def_errors = le16_to_cpu(es->s_errors);
if (def_errors == EXT3_ERRORS_PANIC ||
def_errors == EXT3_ERRORS_CONTINUE) {
seq_puts(seq, ",errors=remount-ro");
}
}
if (test_opt(sb, ERRORS_CONT))
seq_puts(seq, ",errors=continue");
if (test_opt(sb, ERRORS_PANIC))
seq_puts(seq, ",errors=panic");
if (test_opt(sb, NO_UID32))
seq_puts(seq, ",nouid32");
if (test_opt(sb, DEBUG))
seq_puts(seq, ",debug");
#ifdef CONFIG_EXT3_FS_XATTR
if (test_opt(sb, XATTR_USER))
seq_puts(seq, ",user_xattr");
if (!test_opt(sb, XATTR_USER) &&
(def_mount_opts & EXT3_DEFM_XATTR_USER)) {
seq_puts(seq, ",nouser_xattr");
}
#endif
#ifdef CONFIG_EXT3_FS_POSIX_ACL
if (test_opt(sb, POSIX_ACL))
seq_puts(seq, ",acl");
if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT3_DEFM_ACL))
seq_puts(seq, ",noacl");
#endif
if (!test_opt(sb, RESERVATION))
seq_puts(seq, ",noreservation");
if (sbi->s_commit_interval) {
seq_printf(seq, ",commit=%u",
(unsigned) (sbi->s_commit_interval / HZ));
}
/*
* Always display barrier state so it's clear what the status is.
*/
seq_puts(seq, ",barrier=");
seq_puts(seq, test_opt(sb, BARRIER) ? "1" : "0");
seq_printf(seq, ",data=%s", data_mode_string(test_opt(sb, DATA_FLAGS)));
if (test_opt(sb, DATA_ERR_ABORT))
seq_puts(seq, ",data_err=abort");
if (test_opt(sb, NOLOAD))
seq_puts(seq, ",norecovery");
ext3_show_quota_options(seq, sb);
return 0;
}
Commit Message: ext3: Fix format string issues
ext3_msg() takes the printk prefix as the second parameter and the
format string as the third parameter. Two callers of ext3_msg omit the
prefix and pass the format string as the second parameter and the first
parameter to the format string as the third parameter. In both cases
this string comes from an arbitrary source. Which means the string may
contain format string characters, which will
lead to undefined and potentially harmful behavior.
The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages
in ext3") and is fixed by this patch.
CC: stable@vger.kernel.org
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Jan Kara <jack@suse.cz>
CWE ID: CWE-20
| 0
| 19,059
|
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'.
|
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 <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
| 0
| 2,383
|
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'.
|
Code: static int nfs4_recover_expired_lease(struct nfs_server *server)
{
struct nfs_client *clp = server->nfs_client;
int ret;
for (;;) {
ret = nfs4_wait_clnt_recover(clp);
if (ret != 0)
return ret;
if (!test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state) &&
!test_bit(NFS4CLNT_CHECK_LEASE,&clp->cl_state))
break;
nfs4_schedule_state_recovery(clp);
}
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
| 0
| 16,256
|
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'.
|
Code: static void digi_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct usb_serial *serial;
struct digi_port *priv;
struct digi_serial *serial_priv;
int ret = 0;
int status = urb->status;
/* port and serial sanity check */
if (port == NULL || (priv = usb_get_serial_port_data(port)) == NULL) {
pr_err("%s: port or port->private is NULL, status=%d\n",
__func__, status);
return;
}
serial = port->serial;
if (serial == NULL || (serial_priv = usb_get_serial_data(serial)) == NULL) {
dev_err(&port->dev,
"%s: serial or serial->private is NULL, status=%d\n",
__func__, status);
return;
}
/* handle oob callback */
if (priv->dp_port_num == serial_priv->ds_oob_port_num) {
dev_dbg(&port->dev, "digi_write_bulk_callback: oob callback\n");
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
wake_up_interruptible(&port->write_wait);
spin_unlock(&priv->dp_port_lock);
return;
}
/* try to send any buffered data on this port */
spin_lock(&priv->dp_port_lock);
priv->dp_write_urb_in_use = 0;
if (priv->dp_out_buf_len > 0) {
*((unsigned char *)(port->write_urb->transfer_buffer))
= (unsigned char)DIGI_CMD_SEND_DATA;
*((unsigned char *)(port->write_urb->transfer_buffer) + 1)
= (unsigned char)priv->dp_out_buf_len;
port->write_urb->transfer_buffer_length =
priv->dp_out_buf_len + 2;
memcpy(port->write_urb->transfer_buffer + 2, priv->dp_out_buf,
priv->dp_out_buf_len);
ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (ret == 0) {
priv->dp_write_urb_in_use = 1;
priv->dp_out_buf_len = 0;
}
}
/* wake up processes sleeping on writes immediately */
tty_port_tty_wakeup(&port->port);
/* also queue up a wakeup at scheduler time, in case we */
/* lost the race in write_chan(). */
schedule_work(&priv->dp_wakeup_work);
spin_unlock(&priv->dp_port_lock);
if (ret && ret != -EPERM)
dev_err_console(port,
"%s: usb_submit_urb failed, ret=%d, port=%d\n",
__func__, ret, priv->dp_port_num);
}
Commit Message: USB: digi_acceleport: do sanity checking for the number of ports
The driver can be crashed with devices that expose crafted descriptors
with too few endpoints.
See: http://seclists.org/bugtraq/2016/Mar/61
Signed-off-by: Oliver Neukum <ONeukum@suse.com>
[johan: fix OOB endpoint check and add error messages ]
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID:
| 0
| 7,008
|
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'.
|
Code: static inline void loop_update_dio(struct loop_device *lo)
{
__loop_update_dio(lo, io_is_direct(lo->lo_backing_file) |
lo->use_dio);
}
Commit Message: loop: fix concurrent lo_open/lo_release
范龙飞 reports that KASAN can report a use-after-free in __lock_acquire.
The reason is due to insufficient serialization in lo_release(), which
will continue to use the loop device even after it has decremented the
lo_refcnt to zero.
In the meantime, another process can come in, open the loop device
again as it is being shut down. Confusion ensues.
Reported-by: 范龙飞 <long7573@126.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
CWE ID: CWE-416
| 0
| 22,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'.
|
Code: wkbReadDouble(wkbObj *w)
{
double d;
memcpy(&d, w->ptr, sizeof(double));
w->ptr += sizeof(double);
return d;
}
Commit Message: Fix potential SQL Injection with postgis TIME filters (#4834)
CWE ID: CWE-89
| 0
| 22,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'.
|
Code: static void ncq_err(NCQTransferState *ncq_tfs)
{
IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
ide_state->error = ABRT_ERR;
ide_state->status = READY_STAT | ERR_STAT;
ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
}
Commit Message:
CWE ID:
| 1
| 26,050
|
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'.
|
Code: static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
{
#ifdef CONFIG_SMP
atomic_inc(&hb->waiters);
/*
* Full barrier (A), see the ordering comment above.
*/
smp_mb__after_atomic();
#endif
}
Commit Message: futex: Prevent overflow by strengthen input validation
UBSAN reports signed integer overflow in kernel/futex.c:
UBSAN: Undefined behaviour in kernel/futex.c:2041:18
signed integer overflow:
0 - -2147483648 cannot be represented in type 'int'
Add a sanity check to catch negative values of nr_wake and nr_requeue.
Signed-off-by: Li Jinyue <lijinyue@huawei.com>
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Cc: peterz@infradead.org
Cc: dvhart@infradead.org
Cc: stable@vger.kernel.org
Link: https://lkml.kernel.org/r/1513242294-31786-1-git-send-email-lijinyue@huawei.com
CWE ID: CWE-190
| 0
| 11,045
|
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'.
|
Code: modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st)
{
while (st > 0)
{
size_t cb;
png_uint_32 len, chunk;
png_modification *mod;
if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
{
static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
case modifier_start:
store_read_imp(&pm->this, pm->buffer, 8); /* size of signature. */
pm->buffer_count = 8;
pm->buffer_position = 0;
if (memcmp(pm->buffer, sign, 8) != 0)
png_error(pm->this.pread, "invalid PNG file signature");
pm->state = modifier_signature;
break;
case modifier_signature:
store_read_imp(&pm->this, pm->buffer, 13+12); /* size of IHDR */
pm->buffer_count = 13+12;
pm->buffer_position = 0;
if (png_get_uint_32(pm->buffer) != 13 ||
png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
png_error(pm->this.pread, "invalid IHDR");
/* Check the list of modifiers for modifications to the IHDR. */
mod = pm->modifications;
while (mod != NULL)
{
if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
(*mod->modify_fn)(pm, mod, 0))
{
mod->modified = 1;
modifier_setbuffer(pm);
}
/* Ignore removal or add if IHDR! */
mod = mod->next;
}
/* Cache information from the IHDR (the modified one.) */
pm->bit_depth = pm->buffer[8+8];
pm->colour_type = pm->buffer[8+8+1];
pm->state = modifier_IHDR;
pm->flush = 0;
break;
case modifier_IHDR:
default:
/* Read a new chunk and process it until we see PLTE, IDAT or
* IEND. 'flush' indicates that there is still some data to
* output from the preceding chunk.
*/
if ((cb = pm->flush) > 0)
{
if (cb > st) cb = st;
pm->flush -= cb;
store_read_imp(&pm->this, pb, cb);
pb += cb;
st -= cb;
if (st == 0) return;
}
/* No more bytes to flush, read a header, or handle a pending
* chunk.
*/
if (pm->pending_chunk != 0)
{
png_save_uint_32(pm->buffer, pm->pending_len);
png_save_uint_32(pm->buffer+4, pm->pending_chunk);
pm->pending_len = 0;
pm->pending_chunk = 0;
}
else
store_read_imp(&pm->this, pm->buffer, 8);
pm->buffer_count = 8;
pm->buffer_position = 0;
/* Check for something to modify or a terminator chunk. */
len = png_get_uint_32(pm->buffer);
chunk = png_get_uint_32(pm->buffer+4);
/* Terminators first, they may have to be delayed for added
* chunks
*/
if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
chunk == CHUNK_IEND)
{
mod = pm->modifications;
while (mod != NULL)
{
if ((mod->add == chunk ||
(mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
mod->modify_fn != NULL && !mod->modified && !mod->added)
{
/* Regardless of what the modify function does do not run
* this again.
*/
mod->added = 1;
if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
{
/* Reset the CRC on a new chunk */
if (pm->buffer_count > 0)
modifier_setbuffer(pm);
else
{
pm->buffer_position = 0;
mod->removed = 1;
}
/* The buffer has been filled with something (we assume)
* so output this. Pend the current chunk.
*/
pm->pending_len = len;
pm->pending_chunk = chunk;
break; /* out of while */
}
}
mod = mod->next;
}
/* Don't do any further processing if the buffer was modified -
* otherwise the code will end up modifying a chunk that was
* just added.
*/
if (mod != NULL)
break; /* out of switch */
}
/* If we get to here then this chunk may need to be modified. To
* do this it must be less than 1024 bytes in total size, otherwise
* it just gets flushed.
*/
if (len+12 <= sizeof pm->buffer)
{
store_read_imp(&pm->this, pm->buffer+pm->buffer_count,
len+12-pm->buffer_count);
pm->buffer_count = len+12;
/* Check for a modification, else leave it be. */
mod = pm->modifications;
while (mod != NULL)
{
if (mod->chunk == chunk)
{
if (mod->modify_fn == NULL)
{
/* Remove this chunk */
pm->buffer_count = pm->buffer_position = 0;
mod->removed = 1;
break; /* Terminate the while loop */
}
else if ((*mod->modify_fn)(pm, mod, 0))
{
mod->modified = 1;
/* The chunk may have been removed: */
if (pm->buffer_count == 0)
{
pm->buffer_position = 0;
break;
}
modifier_setbuffer(pm);
}
}
mod = mod->next;
}
}
else
pm->flush = len+12 - pm->buffer_count; /* data + crc */
/* Take the data from the buffer (if there is any). */
break;
}
/* Here to read from the modifier buffer (not directly from
* the store, as in the flush case above.)
*/
cb = pm->buffer_count - pm->buffer_position;
if (cb > st)
cb = st;
memcpy(pb, pm->buffer + pm->buffer_position, cb);
st -= cb;
pb += cb;
pm->buffer_position += cb;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
| 0
| 22,815
|
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'.
|
Code: int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen)
{
return sock->ops->bind(sock, addr, addrlen);
}
Commit Message: Fix order of arguments to compat_put_time[spec|val]
Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in
net/socket.c") introduced a bug where the helper functions to take
either a 64-bit or compat time[spec|val] got the arguments in the wrong
order, passing the kernel stack pointer off as a user pointer (and vice
versa).
Because of the user address range check, that in turn then causes an
EFAULT due to the user pointer range checking failing for the kernel
address. Incorrectly resuling in a failed system call for 32-bit
processes with a 64-bit kernel.
On odder architectures like HP-PA (with separate user/kernel address
spaces), it can be used read kernel memory.
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-399
| 0
| 12,413
|
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'.
|
Code: status_t NuPlayer::GenericSource::initFromDataSource() {
sp<MediaExtractor> extractor;
CHECK(mDataSource != NULL);
if (mIsWidevine) {
String8 mimeType;
float confidence;
sp<AMessage> dummy;
bool success;
success = SniffWVM(mDataSource, &mimeType, &confidence, &dummy);
if (!success
|| strcasecmp(
mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) {
ALOGE("unsupported widevine mime: %s", mimeType.string());
return UNKNOWN_ERROR;
}
mWVMExtractor = new WVMExtractor(mDataSource);
mWVMExtractor->setAdaptiveStreamingMode(true);
if (mUIDValid) {
mWVMExtractor->setUID(mUID);
}
extractor = mWVMExtractor;
} else {
extractor = MediaExtractor::Create(mDataSource,
mSniffedMIME.empty() ? NULL: mSniffedMIME.c_str());
}
if (extractor == NULL) {
return UNKNOWN_ERROR;
}
if (extractor->getDrmFlag()) {
checkDrmStatus(mDataSource);
}
mFileMeta = extractor->getMetaData();
if (mFileMeta != NULL) {
int64_t duration;
if (mFileMeta->findInt64(kKeyDuration, &duration)) {
mDurationUs = duration;
}
}
int32_t totalBitrate = 0;
size_t numtracks = extractor->countTracks();
if (numtracks == 0) {
return UNKNOWN_ERROR;
}
for (size_t i = 0; i < numtracks; ++i) {
sp<MediaSource> track = extractor->getTrack(i);
sp<MetaData> meta = extractor->getTrackMetaData(i);
const char *mime;
CHECK(meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp(mime, "audio/", 6)) {
if (mAudioTrack.mSource == NULL) {
mAudioTrack.mIndex = i;
mAudioTrack.mSource = track;
mAudioTrack.mPackets =
new AnotherPacketSource(mAudioTrack.mSource->getFormat());
if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {
mAudioIsVorbis = true;
} else {
mAudioIsVorbis = false;
}
}
} else if (!strncasecmp(mime, "video/", 6)) {
if (mVideoTrack.mSource == NULL) {
mVideoTrack.mIndex = i;
mVideoTrack.mSource = track;
mVideoTrack.mPackets =
new AnotherPacketSource(mVideoTrack.mSource->getFormat());
int32_t secure;
if (meta->findInt32(kKeyRequiresSecureBuffers, &secure)
&& secure) {
mIsWidevine = true;
if (mUIDValid) {
extractor->setUID(mUID);
}
}
}
}
if (track != NULL) {
mSources.push(track);
int64_t durationUs;
if (meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > mDurationUs) {
mDurationUs = durationUs;
}
}
int32_t bitrate;
if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) {
totalBitrate += bitrate;
} else {
totalBitrate = -1;
}
}
}
mBitrate = totalBitrate;
return OK;
}
Commit Message: GenericSource: reset mDrmManagerClient when mDataSource is cleared.
Bug: 25070434
Change-Id: Iade3472c496ac42456e42db35e402f7b66416f5b
(cherry picked from commit b41fd0d4929f0a89811bafcc4fd944b128f00ce2)
CWE ID: CWE-119
| 0
| 4,993
|
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'.
|
Code: FakeCrosDisksClient::FakeCrosDisksClient()
: unmount_call_count_(0),
unmount_success_(true),
format_call_count_(0),
format_success_(true),
rename_call_count_(0),
rename_success_(true),
weak_ptr_factory_(this) {}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <xiyuan@chromium.org>
Commit-Queue: Sam McNally <sammc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#567513}
CWE ID:
| 0
| 13,831
|
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'.
|
Code: MediaBuffer *readBuffer(FLAC__uint64 sample) {
return readBuffer(true, sample);
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
| 0
| 22,881
|
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'.
|
Code: Mat_Create4(const char* matname)
{
FILE *fp = NULL;
mat_t *mat = NULL;
#if defined(_WIN32) && defined(_MSC_VER)
wchar_t* wname = utf82u(matname);
if ( NULL != wname ) {
fp = _wfopen(wname, L"w+b");
free(wname);
}
#else
fp = fopen(matname, "w+b");
#endif
if ( !fp )
return NULL;
mat = (mat_t*)malloc(sizeof(*mat));
if ( NULL == mat ) {
fclose(fp);
Mat_Critical("Couldn't allocate memory for the MAT file");
return NULL;
}
mat->fp = fp;
mat->header = NULL;
mat->subsys_offset = NULL;
mat->filename = strdup_printf("%s",matname);
mat->version = MAT_FT_MAT4;
mat->byteswap = 0;
mat->mode = 0;
mat->bof = 0;
mat->next_index = 0;
mat->num_datasets = 0;
#if defined(MAT73) && MAT73
mat->refs_id = -1;
#endif
mat->dir = NULL;
Mat_Rewind(mat);
return mat;
}
Commit Message: Avoid uninitialized memory
As reported by https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16856
CWE ID:
| 0
| 11,779
|
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'.
|
Code: void helperTestQueryString(char const * uriString, int pairsExpected) {
UriParserStateA state;
UriUriA uri;
state.uri = &uri;
int res = uriParseUriA(&state, uriString);
ASSERT_TRUE(res == URI_SUCCESS);
UriQueryListA * queryList = NULL;
int itemCount = 0;
res = uriDissectQueryMallocA(&queryList, &itemCount,
uri.query.first, uri.query.afterLast);
ASSERT_TRUE(res == URI_SUCCESS);
ASSERT_TRUE(queryList != NULL);
ASSERT_TRUE(itemCount == pairsExpected);
uriFreeQueryListA(queryList);
uriFreeUriMembersA(&uri);
}
Commit Message: Fix uriParse*Ex* out-of-bounds read
CWE ID: CWE-125
| 0
| 19,660
|
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'.
|
Code: static int fm10k_clean_rx_irq(struct fm10k_q_vector *q_vector,
struct fm10k_ring *rx_ring,
int budget)
{
struct sk_buff *skb = rx_ring->skb;
unsigned int total_bytes = 0, total_packets = 0;
u16 cleaned_count = fm10k_desc_unused(rx_ring);
while (likely(total_packets < budget)) {
union fm10k_rx_desc *rx_desc;
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= FM10K_RX_BUFFER_WRITE) {
fm10k_alloc_rx_buffers(rx_ring, cleaned_count);
cleaned_count = 0;
}
rx_desc = FM10K_RX_DESC(rx_ring, rx_ring->next_to_clean);
if (!rx_desc->d.staterr)
break;
/* This memory barrier is needed to keep us from reading
* any other fields out of the rx_desc until we know the
* descriptor has been written back
*/
dma_rmb();
/* retrieve a buffer from the ring */
skb = fm10k_fetch_rx_buffer(rx_ring, rx_desc, skb);
/* exit if we failed to retrieve a buffer */
if (!skb)
break;
cleaned_count++;
/* fetch next buffer in frame if non-eop */
if (fm10k_is_non_eop(rx_ring, rx_desc))
continue;
/* verify the packet layout is correct */
if (fm10k_cleanup_headers(rx_ring, rx_desc, skb)) {
skb = NULL;
continue;
}
/* populate checksum, timestamp, VLAN, and protocol */
total_bytes += fm10k_process_skb_fields(rx_ring, rx_desc, skb);
fm10k_receive_skb(q_vector, skb);
/* reset skb pointer */
skb = NULL;
/* update budget accounting */
total_packets++;
}
/* place incomplete frames back on ring for completion */
rx_ring->skb = skb;
u64_stats_update_begin(&rx_ring->syncp);
rx_ring->stats.packets += total_packets;
rx_ring->stats.bytes += total_bytes;
u64_stats_update_end(&rx_ring->syncp);
q_vector->rx.total_packets += total_packets;
q_vector->rx.total_bytes += total_bytes;
return total_packets;
}
Commit Message: fm10k: Fix a potential NULL pointer dereference
Syzkaller report this:
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 4378 Comm: syz-executor.0 Tainted: G C 5.0.0+ #5
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:__lock_acquire+0x95b/0x3200 kernel/locking/lockdep.c:3573
Code: 00 0f 85 28 1e 00 00 48 81 c4 08 01 00 00 5b 5d 41 5c 41 5d 41 5e 41 5f c3 4c 89 ea 48 b8 00 00 00 00 00 fc ff df 48 c1 ea 03 <80> 3c 02 00 0f 85 cc 24 00 00 49 81 7d 00 e0 de 03 a6 41 bc 00 00
RSP: 0018:ffff8881e3c07a40 EFLAGS: 00010002
RAX: dffffc0000000000 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000010 RSI: 0000000000000000 RDI: 0000000000000080
RBP: 0000000000000000 R08: 0000000000000001 R09: 0000000000000000
R10: ffff8881e3c07d98 R11: ffff8881c7f21f80 R12: 0000000000000001
R13: 0000000000000080 R14: 0000000000000000 R15: 0000000000000001
FS: 00007fce2252e700(0000) GS:ffff8881f2400000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007fffc7eb0228 CR3: 00000001e5bea002 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
lock_acquire+0xff/0x2c0 kernel/locking/lockdep.c:4211
__mutex_lock_common kernel/locking/mutex.c:925 [inline]
__mutex_lock+0xdf/0x1050 kernel/locking/mutex.c:1072
drain_workqueue+0x24/0x3f0 kernel/workqueue.c:2934
destroy_workqueue+0x23/0x630 kernel/workqueue.c:4319
__do_sys_delete_module kernel/module.c:1018 [inline]
__se_sys_delete_module kernel/module.c:961 [inline]
__x64_sys_delete_module+0x30c/0x480 kernel/module.c:961
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fce2252dc58 EFLAGS: 00000246 ORIG_RAX: 00000000000000b0
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000020000140
RBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fce2252e6bc
R13: 00000000004bcca9 R14: 00000000006f6b48 R15: 00000000ffffffff
If alloc_workqueue fails, it should return -ENOMEM, otherwise may
trigger this NULL pointer dereference while unloading drivers.
Reported-by: Hulk Robot <hulkci@huawei.com>
Fixes: 0a38c17a21a0 ("fm10k: Remove create_workqueue")
Signed-off-by: Yue Haibing <yuehaibing@huawei.com>
Tested-by: Andrew Bowers <andrewx.bowers@intel.com>
Signed-off-by: Jeff Kirsher <jeffrey.t.kirsher@intel.com>
CWE ID: CWE-476
| 0
| 29,865
|
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'.
|
Code: static void nfs_write_rpcsetup(struct nfs_write_data *data,
unsigned int count, unsigned int offset,
int how, struct nfs_commit_info *cinfo)
{
struct nfs_page *req = data->header->req;
/* Set up the RPC argument and reply structs
* NB: take care not to mess about with data->commit et al. */
data->args.fh = NFS_FH(data->header->inode);
data->args.offset = req_offset(req) + offset;
/* pnfs_set_layoutcommit needs this */
data->mds_offset = data->args.offset;
data->args.pgbase = req->wb_pgbase + offset;
data->args.pages = data->pages.pagevec;
data->args.count = count;
data->args.context = get_nfs_open_context(req->wb_context);
data->args.lock_context = req->wb_lock_context;
data->args.stable = NFS_UNSTABLE;
switch (how & (FLUSH_STABLE | FLUSH_COND_STABLE)) {
case 0:
break;
case FLUSH_COND_STABLE:
if (nfs_reqs_to_commit(cinfo))
break;
default:
data->args.stable = NFS_FILE_SYNC;
}
data->res.fattr = &data->fattr;
data->res.count = count;
data->res.verf = &data->verf;
nfs_fattr_init(&data->fattr);
}
Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page
We should always make sure the cached page is up-to-date when we're
determining whether we can extend a write to cover the full page -- even
if we've received a write delegation from the server.
Commit c7559663 added logic to skip this check if we have a write
delegation, which can lead to data corruption such as the following
scenario if client B receives a write delegation from the NFS server:
Client A:
# echo 123456789 > /mnt/file
Client B:
# echo abcdefghi >> /mnt/file
# cat /mnt/file
0�D0�abcdefghi
Just because we hold a write delegation doesn't mean that we've read in
the entire page contents.
Cc: <stable@vger.kernel.org> # v3.11+
Signed-off-by: Scott Mayhew <smayhew@redhat.com>
Signed-off-by: Trond Myklebust <trond.myklebust@primarydata.com>
CWE ID: CWE-20
| 0
| 4,974
|
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'.
|
Code: static inline void tcp_init_undo(struct tcp_sock *tp)
{
tp->undo_marker = tp->snd_una;
/* Retransmission still in flight may cause DSACKs later. */
tp->undo_retrans = tp->retrans_out ? : -1;
}
Commit Message: tcp: make challenge acks less predictable
Yue Cao claims that current host rate limiting of challenge ACKS
(RFC 5961) could leak enough information to allow a patient attacker
to hijack TCP sessions. He will soon provide details in an academic
paper.
This patch increases the default limit from 100 to 1000, and adds
some randomization so that the attacker can no longer hijack
sessions without spending a considerable amount of probes.
Based on initial analysis and patch from Linus.
Note that we also have per socket rate limiting, so it is tempting
to remove the host limit in the future.
v2: randomize the count of challenge acks per second, not the period.
Fixes: 282f23c6ee34 ("tcp: implement RFC 5961 3.2")
Reported-by: Yue Cao <ycao009@ucr.edu>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Yuchung Cheng <ycheng@google.com>
Cc: Neal Cardwell <ncardwell@google.com>
Acked-by: Neal Cardwell <ncardwell@google.com>
Acked-by: Yuchung Cheng <ycheng@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
| 0
| 12,033
|
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'.
|
Code: bool FormContainsNonDefaultPasswordValue(const PasswordForm& password_form) {
return (!password_form.password_value.empty() &&
!password_form.password_value_is_default) ||
(!password_form.new_password_value.empty() &&
!password_form.new_password_value_is_default);
}
Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent
Unlike in AutofillAgent, the factory is no longer used in PAA.
R=dvadym@chromium.org
BUG=609010,609007,608100,608101,433486
Review-Url: https://codereview.chromium.org/1945723003
Cr-Commit-Position: refs/heads/master@{#391475}
CWE ID:
| 0
| 3,960
|
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'.
|
Code: static void ext4_lazyinode_timeout(unsigned long data)
{
struct task_struct *p = (struct task_struct *)data;
wake_up_process(p);
}
Commit Message: ext4: init timer earlier to avoid a kernel panic in __save_error_info
During mount, when we fail to open journal inode or root inode, the
__save_error_info will mod_timer. But actually s_err_report isn't
initialized yet and the kernel oops. The detailed information can
be found https://bugzilla.kernel.org/show_bug.cgi?id=32082.
The best way is to check whether the timer s_err_report is initialized
or not. But it seems that in include/linux/timer.h, we can't find a
good function to check the status of this timer, so this patch just
move the initializtion of s_err_report earlier so that we can avoid
the kernel panic. The corresponding del_timer is also added in the
error path.
Reported-by: Sami Liedes <sliedes@cc.hut.fi>
Signed-off-by: Tao Ma <boyu.mt@taobao.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
| 0
| 12,021
|
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'.
|
Code: void perf_callchain_kernel(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long ksp, fp;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
int graph = 0;
#endif
stack_trace_flush();
perf_callchain_store(entry, regs->tpc);
ksp = regs->u_regs[UREG_I6];
fp = ksp + STACK_BIAS;
do {
struct sparc_stackf *sf;
struct pt_regs *regs;
unsigned long pc;
if (!kstack_valid(current_thread_info(), fp))
break;
sf = (struct sparc_stackf *) fp;
regs = (struct pt_regs *) (sf + 1);
if (kstack_is_trap_frame(current_thread_info(), regs)) {
if (user_mode(regs))
break;
pc = regs->tpc;
fp = regs->u_regs[UREG_I6] + STACK_BIAS;
} else {
pc = sf->callers_pc;
fp = (unsigned long)sf->fp + STACK_BIAS;
}
perf_callchain_store(entry, pc);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
if ((pc + 8UL) == (unsigned long) &return_to_handler) {
int index = current->curr_ret_stack;
if (current->ret_stack && index >= graph) {
pc = current->ret_stack[index - graph].ret;
perf_callchain_store(entry, pc);
graph++;
}
}
#endif
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
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 <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: CWE-399
| 0
| 974
|
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'.
|
Code: write_one_file(Image *output, Image *image, int convert_to_8bit)
{
if (image->opts & FAST_WRITE)
image->image.flags |= PNG_IMAGE_FLAG_FAST;
if (image->opts & USE_STDIO)
{
FILE *f = tmpfile();
if (f != NULL)
{
if (png_image_write_to_stdio(&image->image, f, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
if (fflush(f) == 0)
{
rewind(f);
initimage(output, image->opts, "tmpfile", image->stride_extra);
output->input_file = f;
if (!checkopaque(image))
return 0;
}
else
return logclose(image, f, "tmpfile", ": flush: ");
}
else
{
fclose(f);
return logerror(image, "tmpfile", ": write failed", "");
}
}
else
return logerror(image, "tmpfile", ": open: ", strerror(errno));
}
else
{
static int counter = 0;
char name[32];
sprintf(name, "%s%d.png", tmpf, ++counter);
if (png_image_write_to_file(&image->image, name, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
initimage(output, image->opts, output->tmpfile_name,
image->stride_extra);
/* Afterwards, or freeimage will delete it! */
strcpy(output->tmpfile_name, name);
if (!checkopaque(image))
return 0;
}
else
return logerror(image, name, ": write failed", "");
}
/* 'output' has an initialized temporary image, read this back in and compare
* this against the original: there should be no change since the original
* format was written unmodified unless 'convert_to_8bit' was specified.
* However, if the original image was color-mapped, a simple read will zap
* the linear, color and maybe alpha flags, this will cause spurious failures
* under some circumstances.
*/
if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL))
{
png_uint_32 original_format = image->image.format;
if (convert_to_8bit)
original_format &= ~PNG_FORMAT_FLAG_LINEAR;
if ((output->image.format & BASE_FORMATS) !=
(original_format & BASE_FORMATS))
return logerror(image, image->file_name, ": format changed on read: ",
output->file_name);
return compare_two_images(image, output, 0/*via linear*/, NULL);
}
else
return logerror(output, output->tmpfile_name,
": read of new file failed", "");
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
| 1
| 21,590
|
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'.
|
Code: pango_glyph_string_x_to_index (PangoGlyphString *glyphs,
char *text,
int length,
PangoAnalysis *analysis,
int x_pos,
int *index,
gboolean *trailing)
{
int i;
int start_xpos = 0;
int end_xpos = 0;
int width = 0;
int start_index = -1;
int end_index = -1;
int cluster_chars = 0;
char *p;
gboolean found = FALSE;
/* Find the cluster containing the position */
width = 0;
if (analysis->level % 2) /* Right to left */
{
for (i = glyphs->num_glyphs - 1; i >= 0; i--)
width += glyphs->glyphs[i].geometry.width;
for (i = glyphs->num_glyphs - 1; i >= 0; i--)
{
if (glyphs->log_clusters[i] != start_index)
{
if (found)
{
end_index = glyphs->log_clusters[i];
end_xpos = width;
break;
}
else
{
start_index = glyphs->log_clusters[i];
start_xpos = width;
}
}
width -= glyphs->glyphs[i].geometry.width;
if (width <= x_pos && x_pos < width + glyphs->glyphs[i].geometry.width)
found = TRUE;
}
}
else /* Left to right */
{
for (i = 0; i < glyphs->num_glyphs; i++)
{
if (glyphs->log_clusters[i] != start_index)
{
if (found)
{
end_index = glyphs->log_clusters[i];
end_xpos = width;
break;
}
else
{
start_index = glyphs->log_clusters[i];
start_xpos = width;
}
}
if (width <= x_pos && x_pos < width + glyphs->glyphs[i].geometry.width)
found = TRUE;
width += glyphs->glyphs[i].geometry.width;
}
}
if (end_index == -1)
{
end_index = length;
end_xpos = (analysis->level % 2) ? 0 : width;
}
/* Calculate number of chars within cluster */
p = text + start_index;
while (p < text + end_index)
{
p = g_utf8_next_char (p);
cluster_chars++;
}
if (start_xpos == end_xpos)
{
if (index)
*index = start_index;
if (trailing)
*trailing = FALSE;
}
else
{
double cp = ((double)(x_pos - start_xpos) * cluster_chars) / (end_xpos - start_xpos);
/* LTR and right-to-left have to be handled separately
* here because of the edge condition when we are exactly
* at a pixel boundary; end_xpos goes with the next
* character for LTR, with the previous character for RTL.
*/
if (start_xpos < end_xpos) /* Left-to-right */
{
if (index)
{
char *p = text + start_index;
int i = 0;
while (i + 1 <= cp)
{
p = g_utf8_next_char (p);
i++;
}
*index = (p - text);
}
if (trailing)
*trailing = (cp - (int)cp >= 0.5) ? TRUE : FALSE;
}
else /* Right-to-left */
{
if (index)
{
char *p = text + start_index;
int i = 0;
while (i + 1 < cp)
{
p = g_utf8_next_char (p);
i++;
}
*index = (p - text);
}
if (trailing)
{
double cp_flip = cluster_chars - cp;
*trailing = (cp_flip - (int)cp_flip >= 0.5) ? FALSE : TRUE;
}
}
}
}
Commit Message: [glyphstring] Handle overflow with very long glyphstrings
CWE ID: CWE-189
| 0
| 8,360
|
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'.
|
Code: static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
return new_prog;
}
Commit Message: bpf: fix branch pruning logic
when the verifier detects that register contains a runtime constant
and it's compared with another constant it will prune exploration
of the branch that is guaranteed not to be taken at runtime.
This is all correct, but malicious program may be constructed
in such a way that it always has a constant comparison and
the other branch is never taken under any conditions.
In this case such path through the program will not be explored
by the verifier. It won't be taken at run-time either, but since
all instructions are JITed the malicious program may cause JITs
to complain about using reserved fields, etc.
To fix the issue we have to track the instructions explored by
the verifier and sanitize instructions that are dead at run time
with NOPs. We cannot reject such dead code, since llvm generates
it for valid C code, since it doesn't do as much data flow
analysis as the verifier does.
Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)")
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Daniel Borkmann <daniel@iogearbox.net>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
CWE ID: CWE-20
| 0
| 26,343
|
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'.
|
Code: void PrintHelp()
{
fprintf(stderr, "MP4Client command keys:\n"
"\tq: quit\n"
"\tX: kill\n"
"\to: connect to the specified URL\n"
"\tO: connect to the specified playlist\n"
"\tN: switch to the next URL in the playlist. Also works with \\n\n"
"\tP: jumps to a given number ahead in the playlist\n"
"\tr: reload current presentation\n"
"\tD: disconnects the current presentation\n"
"\tG: selects object or service ID\n"
"\n"
"\tp: play/pause the presentation\n"
"\ts: step one frame ahead\n"
"\tz: seek into presentation by percentage\n"
"\tT: seek into presentation by time\n"
"\tt: print current timing\n"
"\n"
"\tu: sends a command (BIFS or LASeR) to the main scene\n"
"\te: evaluates JavaScript code\n"
"\tZ: dumps output video to PNG\n"
"\n"
"\tw: view world info\n"
"\tv: view Object Descriptor list\n"
"\ti: view Object Descriptor info (by ID)\n"
"\tj: view Object Descriptor info (by number)\n"
"\tb: view media objects timing and buffering info\n"
"\tm: view media objects buffering and memory info\n"
"\td: dumps scene graph\n"
"\n"
"\tk: turns stress mode on/off\n"
"\tn: changes navigation mode\n"
"\tx: reset to last active viewpoint\n"
"\n"
"\t3: switch OpenGL on or off for 2D scenes\n"
"\n"
"\t4: forces 4/3 Aspect Ratio\n"
"\t5: forces 16/9 Aspect Ratio\n"
"\t6: forces no Aspect Ratio (always fill screen)\n"
"\t7: forces original Aspect Ratio (default)\n"
"\n"
"\tL: changes to new log level. CF MP4Client usage for possible values\n"
"\tT: select new tools to log. CF MP4Client usage for possible values\n"
"\n"
"\tl: list available modules\n"
"\tc: prints some GPAC configuration info\n"
"\tE: forces reload of GPAC configuration\n"
"\n"
"\tR: toggles run-time info display in window title bar on/off\n"
"\tF: toggle displaying of FPS in stderr on/off\n"
"\tg: print GPAC allocated memory\n"
"\th: print this message\n"
"\n"
"\tEXPERIMENTAL/UNSTABLE OPTIONS\n"
"\tC: Enable Streaming Cache\n"
"\tS: Stops Streaming Cache and save to file\n"
"\tA: Aborts Streaming Cache\n"
"\tM: specifies video cache memory for 2D objects\n"
"\n"
"MP4Client - GPAC command line player - version %s\n"
"GPAC Written by Jean Le Feuvre (c) 2001-2005 - ENST (c) 2005-200X\n",
GPAC_FULL_VERSION
);
}
Commit Message: add some boundary checks on gf_text_get_utf8_line (#1188)
CWE ID: CWE-787
| 0
| 28,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'.
|
Code: int64_t DownloadItemImpl::GetTotalBytes() const {
return total_bytes_;
}
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 <dtrainor@chromium.org>
Reviewed-by: Xing Liu <xingliu@chromium.org>
Reviewed-by: John Abd-El-Malek <jam@chromium.org>
Commit-Queue: Shakti Sahu <shaktisahu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#525810}
CWE ID: CWE-20
| 0
| 7,787
|
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'.
|
Code: jsonb_delete_idx(PG_FUNCTION_ARGS)
{
Jsonb *in = PG_GETARG_JSONB(0);
int idx = PG_GETARG_INT32(1);
JsonbParseState *state = NULL;
JsonbIterator *it;
uint32 r,
i = 0,
n;
JsonbValue v,
*res = NULL;
if (JB_ROOT_IS_SCALAR(in))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot delete from scalar")));
if (JB_ROOT_IS_OBJECT(in))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot delete from object using integer subscript")));
if (JB_ROOT_COUNT(in) == 0)
PG_RETURN_JSONB(in);
it = JsonbIteratorInit(&in->root);
r = JsonbIteratorNext(&it, &v, false);
Assert (r == WJB_BEGIN_ARRAY);
n = v.val.array.nElems;
if (idx < 0)
{
if (-idx > n)
idx = n;
else
idx = n + idx;
}
if (idx >= n)
PG_RETURN_JSONB(in);
pushJsonbValue(&state, r, NULL);
while ((r = JsonbIteratorNext(&it, &v, true)) != 0)
{
if (r == WJB_ELEM)
{
if (i++ == idx)
continue;
}
res = pushJsonbValue(&state, r, r < WJB_BEGIN_ARRAY ? &v : NULL);
}
Assert(res != NULL);
PG_RETURN_JSONB(JsonbValueToJsonb(res));
}
Commit Message:
CWE ID: CWE-119
| 0
| 17,020
|
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'.
|
Code: DevToolsConfirmInfoBarDelegate::DevToolsConfirmInfoBarDelegate(
InfoBarService* infobar_service,
const DevToolsWindow::InfoBarCallback& callback,
const string16& message)
: ConfirmInfoBarDelegate(infobar_service),
callback_(callback),
message_(message) {
}
Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception
This patch fixes the crash which happenes under the following conditions:
1. DevTools window is in undocked state
2. DevTools renderer is unresponsive
3. User attempts to close inspected page
BUG=322380
Review URL: https://codereview.chromium.org/84883002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
| 0
| 2,376
|
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'.
|
Code: PaintController::SubsequenceMarkers* PaintController::GetSubsequenceMarkers(
const DisplayItemClient& client) {
auto result = current_cached_subsequences_.find(&client);
if (result == current_cached_subsequences_.end())
return nullptr;
return &result->value;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <trchen@chromium.org>
> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org>
> Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#554653}
TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org>
Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
| 0
| 4,608
|
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'.
|
Code: static int __ap_poll_device(struct ap_device *ap_dev, unsigned long *flags)
{
if (!ap_dev->unregistered) {
if (ap_poll_queue(ap_dev, flags))
ap_dev->unregistered = 1;
if (ap_dev->reset == AP_RESET_DO)
ap_reset(ap_dev);
}
return 0;
}
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 <keescook@chromium.org>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
CWE ID: CWE-264
| 0
| 26,095
|
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'.
|
Code: static int ack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ack *pkt;
GIT_UNUSED(line);
GIT_UNUSED(len);
pkt = git__calloc(1, sizeof(git_pkt_ack));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ACK;
line += 3;
len -= 3;
if (len >= GIT_OID_HEXSZ) {
git_oid_fromstr(&pkt->oid, line + 1);
line += GIT_OID_HEXSZ + 1;
len -= GIT_OID_HEXSZ + 1;
}
if (len >= 7) {
if (!git__prefixcmp(line + 1, "continue"))
pkt->status = GIT_ACK_CONTINUE;
if (!git__prefixcmp(line + 1, "common"))
pkt->status = GIT_ACK_COMMON;
if (!git__prefixcmp(line + 1, "ready"))
pkt->status = GIT_ACK_READY;
}
*out = (git_pkt *) pkt;
return 0;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476
| 0
| 9,150
|
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'.
|
Code: static int napi_gro_complete(struct sk_buff *skb)
{
struct packet_type *ptype;
__be16 type = skb->protocol;
struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
int err = -ENOENT;
if (NAPI_GRO_CB(skb)->count == 1) {
skb_shinfo(skb)->gso_size = 0;
goto out;
}
rcu_read_lock();
list_for_each_entry_rcu(ptype, head, list) {
if (ptype->type != type || ptype->dev || !ptype->gro_complete)
continue;
err = ptype->gro_complete(skb);
break;
}
rcu_read_unlock();
if (err) {
WARN_ON(&ptype->list == head);
kfree_skb(skb);
return NET_RX_SUCCESS;
}
out:
return netif_receive_skb(skb);
}
Commit Message: veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <martin.ferrari@gmail.com>
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-399
| 0
| 10,968
|
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'.
|
Code: void RenderWidgetHostImpl::DidAllocateLocalSurfaceIdForAutoResize(
uint64_t sequence_number) {
if (!view_ || !sequence_number ||
last_auto_resize_request_number_ != sequence_number) {
return;
}
DCHECK(!view_->IsLocalSurfaceIdAllocationSuppressed());
viz::LocalSurfaceId local_surface_id(view_->GetLocalSurfaceId());
if (local_surface_id.is_valid()) {
ScreenInfo screen_info;
view_->GetScreenInfo(&screen_info);
Send(new ViewMsg_SetLocalSurfaceIdForAutoResize(
routing_id_, sequence_number, min_size_for_auto_resize_,
max_size_for_auto_resize_, screen_info, current_content_source_id_,
local_surface_id));
}
}
Commit Message: Force a flush of drawing to the widget when a dialog is shown.
BUG=823353
TEST=as in bug
Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260
Reviewed-on: https://chromium-review.googlesource.com/971661
Reviewed-by: Ken Buchanan <kenrb@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#544518}
CWE ID:
| 0
| 8,574
|
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'.
|
Code: static int ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir,
struct dentry *dentry, struct path *lowerpath,
struct kstat *stat, struct iattr *attr,
const char *link)
{
struct inode *wdir = workdir->d_inode;
struct inode *udir = upperdir->d_inode;
struct dentry *newdentry = NULL;
struct dentry *upper = NULL;
umode_t mode = stat->mode;
int err;
newdentry = ovl_lookup_temp(workdir, dentry);
err = PTR_ERR(newdentry);
if (IS_ERR(newdentry))
goto out;
upper = lookup_one_len(dentry->d_name.name, upperdir,
dentry->d_name.len);
err = PTR_ERR(upper);
if (IS_ERR(upper))
goto out1;
/* Can't properly set mode on creation because of the umask */
stat->mode &= S_IFMT;
err = ovl_create_real(wdir, newdentry, stat, link, NULL, true);
stat->mode = mode;
if (err)
goto out2;
if (S_ISREG(stat->mode)) {
struct path upperpath;
ovl_path_upper(dentry, &upperpath);
BUG_ON(upperpath.dentry != NULL);
upperpath.dentry = newdentry;
err = ovl_copy_up_data(lowerpath, &upperpath, stat->size);
if (err)
goto out_cleanup;
}
err = ovl_copy_xattr(lowerpath->dentry, newdentry);
if (err)
goto out_cleanup;
mutex_lock(&newdentry->d_inode->i_mutex);
err = ovl_set_attr(newdentry, stat);
if (!err && attr)
err = notify_change(newdentry, attr, NULL);
mutex_unlock(&newdentry->d_inode->i_mutex);
if (err)
goto out_cleanup;
err = ovl_do_rename(wdir, newdentry, udir, upper, 0);
if (err)
goto out_cleanup;
ovl_dentry_update(dentry, newdentry);
newdentry = NULL;
/*
* Non-directores become opaque when copied up.
*/
if (!S_ISDIR(stat->mode))
ovl_dentry_set_opaque(dentry, true);
out2:
dput(upper);
out1:
dput(newdentry);
out:
return err;
out_cleanup:
ovl_cleanup(wdir, newdentry);
goto out;
}
Commit Message: ovl: fix dentry reference leak
In ovl_copy_up_locked(), newdentry is leaked if the function exits through
out_cleanup as this just to out after calling ovl_cleanup() - which doesn't
actually release the ref on newdentry.
The out_cleanup segment should instead exit through out2 as certainly
newdentry leaks - and possibly upper does also, though this isn't caught
given the catch of newdentry.
Without this fix, something like the following is seen:
BUG: Dentry ffff880023e9eb20{i=f861,n=#ffff880023e82d90} still in use (1) [unmount of tmpfs tmpfs]
BUG: Dentry ffff880023ece640{i=0,n=bigfile} still in use (1) [unmount of tmpfs tmpfs]
when unmounting the upper layer after an error occurred in copyup.
An error can be induced by creating a big file in a lower layer with
something like:
dd if=/dev/zero of=/lower/a/bigfile bs=65536 count=1 seek=$((0xf000))
to create a large file (4.1G). Overlay an upper layer that is too small
(on tmpfs might do) and then induce a copy up by opening it writably.
Reported-by: Ulrich Obergfell <uobergfe@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Miklos Szeredi <miklos@szeredi.hu>
Cc: <stable@vger.kernel.org> # v3.18+
CWE ID: CWE-399
| 1
| 25,035
|
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'.
|
Code: void AddIncompatibleApplicationsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"incompatibleApplicationsResetCardTitle",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_RESET_CARD_TITLE},
{"incompatibleApplicationsSubpageSubtitle",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_SUBPAGE_SUBTITLE},
{"incompatibleApplicationsSubpageSubtitleNoAdminRights",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_SUBPAGE_SUBTITLE_NO_ADMIN_RIGHTS},
{"incompatibleApplicationsListTitle",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_LIST_TITLE},
{"incompatibleApplicationsRemoveButton",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_REMOVE_BUTTON},
{"incompatibleApplicationsUpdateButton",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_UPDATE_BUTTON},
{"incompatibleApplicationsDone",
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_DONE},
};
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
base::string16 learn_how_text = l10n_util::GetStringFUTF16(
IDS_SETTINGS_INCOMPATIBLE_APPLICATIONS_SUBPAGE_LEARN_HOW,
base::ASCIIToUTF16("chrome://placeholder"));
html_source->AddString("incompatibleApplicationsSubpageLearnHow",
learn_how_text);
}
Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles
This change clarifies the wording around the password saving and
autofill toggles.
Bug: 822465
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670
Reviewed-on: https://chromium-review.googlesource.com/970541
Commit-Queue: Jan Wilken Dörrie <jdoerrie@chromium.org>
Reviewed-by: Vaclav Brozek <vabr@chromium.org>
Reviewed-by: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#544661}
CWE ID: CWE-200
| 0
| 11,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'.
|
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
| 1
| 20,195
|
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'.
|
Code: void DatabaseImpl::IDBThreadHelper::Clear(
int64_t transaction_id,
int64_t object_store_id,
scoped_refptr<IndexedDBCallbacks> callbacks) {
DCHECK(idb_thread_checker_.CalledOnValidThread());
if (!connection_->IsConnected())
return;
IndexedDBTransaction* transaction =
connection_->GetTransaction(transaction_id);
if (!transaction)
return;
connection_->database()->Clear(transaction, object_store_id, callbacks);
}
Commit Message: [IndexedDB] Fixed transaction use-after-free vuln
Bug: 725032
Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa
Reviewed-on: https://chromium-review.googlesource.com/518483
Reviewed-by: Joshua Bell <jsbell@chromium.org>
Commit-Queue: Daniel Murphy <dmurph@chromium.org>
Cr-Commit-Position: refs/heads/master@{#475952}
CWE ID: CWE-416
| 0
| 7,492
|
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'.
|
Code: static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
Commit Message: Slightly different fix for #714
CWE ID: CWE-834
| 1
| 2,406
|
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'.
|
Code: static double filter_quadratic_bspline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- x * x + 0.75);
if (x <= 1.5) return (0.5 * x * x - 1.5 * x + 1.125);
return 0.0;
}
Commit Message: gdImageScaleTwoPass memory leak fix
Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and
confirmed by @vapier. This bug actually bit me in production and I'm
very thankful that it was reported with an easy fix.
Fixes #173.
CWE ID: CWE-399
| 0
| 26,440
|
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'.
|
Code: void RenderFrameHostManager::ClearRFHsPendingShutdown() {
pending_delete_hosts_.clear();
}
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
| 2,395
|
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'.
|
Code: OJPEGReadHeaderInfo(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfo";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(sp->readheader_done==0);
sp->image_width=tif->tif_dir.td_imagewidth;
sp->image_length=tif->tif_dir.td_imagelength;
if isTiled(tif)
{
sp->strile_width=tif->tif_dir.td_tilewidth;
sp->strile_length=tif->tif_dir.td_tilelength;
sp->strile_length_total=((sp->image_length+sp->strile_length-1)/sp->strile_length)*sp->strile_length;
}
else
{
sp->strile_width=sp->image_width;
sp->strile_length=tif->tif_dir.td_rowsperstrip;
sp->strile_length_total=sp->image_length;
}
if (tif->tif_dir.td_samplesperpixel==1)
{
sp->samples_per_pixel=1;
sp->plane_sample_offset=0;
sp->samples_per_pixel_per_plane=sp->samples_per_pixel;
sp->subsampling_hor=1;
sp->subsampling_ver=1;
}
else
{
if (tif->tif_dir.td_samplesperpixel!=3)
{
TIFFErrorExt(tif->tif_clientdata,module,"SamplesPerPixel %d not supported for this compression scheme",sp->samples_per_pixel);
return(0);
}
sp->samples_per_pixel=3;
sp->plane_sample_offset=0;
if (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)
sp->samples_per_pixel_per_plane=3;
else
sp->samples_per_pixel_per_plane=1;
}
if (sp->strile_length<sp->image_length)
{
if (sp->strile_length%(sp->subsampling_ver*8)!=0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Incompatible vertical subsampling and image strip/tile length");
return(0);
}
sp->restart_interval=(uint16)(((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8)));
}
if (OJPEGReadHeaderInfoSec(tif)==0)
return(0);
sp->sos_end[0].log=1;
sp->sos_end[0].in_buffer_source=sp->in_buffer_source;
sp->sos_end[0].in_buffer_next_strile=sp->in_buffer_next_strile;
sp->sos_end[0].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
sp->sos_end[0].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo;
sp->readheader_done=1;
return(1);
}
Commit Message: * libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in
OJPEGPreDecode(). This will avoid a divide by zero, and potential other issues.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2611
CWE ID: CWE-369
| 0
| 26,148
|
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'.
|
Code: void LayerTreeCoordinator::syncDisplayState()
{
#if ENABLE(REQUEST_ANIMATION_FRAME) && !USE(REQUEST_ANIMATION_FRAME_TIMER) && !USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
m_webPage->corePage()->mainFrame()->view()->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(currentTime()));
#endif
m_webPage->layoutIfNeeded();
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
| 0
| 7,690
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.