CVE ID
stringlengths
13
43
CVE Page
stringlengths
45
48
CWE ID
stringclasses
90 values
codeLink
stringlengths
46
139
commit_id
stringlengths
6
81
commit_message
stringlengths
3
13.3k
func_after
stringlengths
14
241k
func_before
stringlengths
14
241k
lang
stringclasses
3 values
project
stringclasses
309 values
vul
int8
0
1
CVE-2011-3050
https://www.cvedetails.com/cve/CVE-2011-3050/
CWE-399
https://github.com/chromium/chromium/commit/3da579b85a36e95c03d06b7c4ce9d618af4107bf
3da579b85a36e95c03d06b7c4ce9d618af4107bf
Relands cl 16982 as it wasn't the cause of the build breakage. Here's the description for that cl: Lands http://codereview.chromium.org/115505 for bug http://crbug.com/4030 for tyoshino. BUG=http://crbug.com/4030 TEST=make sure control-w dismisses bookmark manager. Review URL: http://codereview.chromium.org/113902 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@16987 0039d316-1c4b-4281-b951-d872f2087c98
std::wstring BookmarkManagerView::GetWindowTitle() const { return l10n_util::GetString(IDS_BOOKMARK_MANAGER_TITLE); }
std::wstring BookmarkManagerView::GetWindowTitle() const { return l10n_util::GetString(IDS_BOOKMARK_MANAGER_TITLE); }
C
Chrome
0
CVE-2014-0069
https://www.cvedetails.com/cve/CVE-2014-0069/
CWE-119
https://github.com/torvalds/linux/commit/5d81de8e8667da7135d3a32a964087c0faf5483f
5d81de8e8667da7135d3a32a964087c0faf5483f
cifs: ensure that uncached writes handle unmapped areas correctly It's possible for userland to pass down an iovec via writev() that has a bogus user pointer in it. If that happens and we're doing an uncached write, then we can end up getting less bytes than we expect from the call to iov_iter_copy_from_user. This is CVE-2014-0069 cifs_iovec_write isn't set up to handle that situation however. It'll blindly keep chugging through the page array and not filling those pages with anything useful. Worse yet, we'll later end up with a negative number in wdata->tailsz, which will confuse the sending routines and cause an oops at the very least. Fix this by having the copy phase of cifs_iovec_write stop copying data in this situation and send the last write as a short one. At the same time, we want to avoid sending a zero-length write to the server, so break out of the loop and set rc to -EFAULT if that happens. This also allows us to handle the case where no address in the iovec is valid. [Note: Marking this for stable on v3.4+ kernels, but kernels as old as v2.6.38 may have a similar problem and may need similar fix] Cc: <[email protected]> # v3.4+ Reviewed-by: Pavel Shilovsky <[email protected]> Reported-by: Al Viro <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]>
cifs_strict_readv(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct inode *inode = file_inode(iocb->ki_filp); struct cifsInodeInfo *cinode = CIFS_I(inode); struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb); struct cifsFileInfo *cfile = (struct cifsFileInfo *) iocb->ki_filp->private_data; struct cifs_tcon *tcon = tlink_tcon(cfile->tlink); int rc = -EACCES; /* * In strict cache mode we need to read from the server all the time * if we don't have level II oplock because the server can delay mtime * change - so we can't make a decision about inode invalidating. * And we can also fail with pagereading if there are mandatory locks * on pages affected by this read but not on the region from pos to * pos+len-1. */ if (!CIFS_CACHE_READ(cinode)) return cifs_user_readv(iocb, iov, nr_segs, pos); if (cap_unix(tcon->ses) && (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) && ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NOPOSIXBRL) == 0)) return generic_file_aio_read(iocb, iov, nr_segs, pos); /* * We need to hold the sem to be sure nobody modifies lock list * with a brlock that prevents reading. */ down_read(&cinode->lock_sem); if (!cifs_find_lock_conflict(cfile, pos, iov_length(iov, nr_segs), tcon->ses->server->vals->shared_lock_type, NULL, CIFS_READ_OP)) rc = generic_file_aio_read(iocb, iov, nr_segs, pos); up_read(&cinode->lock_sem); return rc; }
cifs_strict_readv(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct inode *inode = file_inode(iocb->ki_filp); struct cifsInodeInfo *cinode = CIFS_I(inode); struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb); struct cifsFileInfo *cfile = (struct cifsFileInfo *) iocb->ki_filp->private_data; struct cifs_tcon *tcon = tlink_tcon(cfile->tlink); int rc = -EACCES; /* * In strict cache mode we need to read from the server all the time * if we don't have level II oplock because the server can delay mtime * change - so we can't make a decision about inode invalidating. * And we can also fail with pagereading if there are mandatory locks * on pages affected by this read but not on the region from pos to * pos+len-1. */ if (!CIFS_CACHE_READ(cinode)) return cifs_user_readv(iocb, iov, nr_segs, pos); if (cap_unix(tcon->ses) && (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) && ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NOPOSIXBRL) == 0)) return generic_file_aio_read(iocb, iov, nr_segs, pos); /* * We need to hold the sem to be sure nobody modifies lock list * with a brlock that prevents reading. */ down_read(&cinode->lock_sem); if (!cifs_find_lock_conflict(cfile, pos, iov_length(iov, nr_segs), tcon->ses->server->vals->shared_lock_type, NULL, CIFS_READ_OP)) rc = generic_file_aio_read(iocb, iov, nr_segs, pos); up_read(&cinode->lock_sem); return rc; }
C
linux
0
CVE-2019-17351
https://www.cvedetails.com/cve/CVE-2019-17351/
CWE-400
https://github.com/torvalds/linux/commit/6ef36ab967c71690ebe7e5ef997a8be4da3bc844
6ef36ab967c71690ebe7e5ef997a8be4da3bc844
xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>
static struct resource *additional_memory_resource(phys_addr_t size) { struct resource *res; int ret; res = kzalloc(sizeof(*res), GFP_KERNEL); if (!res) return NULL; res->name = "System RAM"; res->flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY; ret = allocate_resource(&iomem_resource, res, size, 0, -1, PAGES_PER_SECTION * PAGE_SIZE, NULL, NULL); if (ret < 0) { pr_err("Cannot allocate new System RAM resource\n"); kfree(res); return NULL; } #ifdef CONFIG_SPARSEMEM { unsigned long limit = 1UL << (MAX_PHYSMEM_BITS - PAGE_SHIFT); unsigned long pfn = res->start >> PAGE_SHIFT; if (pfn > limit) { pr_err("New System RAM resource outside addressable RAM (%lu > %lu)\n", pfn, limit); release_memory_resource(res); return NULL; } } #endif return res; }
static struct resource *additional_memory_resource(phys_addr_t size) { struct resource *res; int ret; res = kzalloc(sizeof(*res), GFP_KERNEL); if (!res) return NULL; res->name = "System RAM"; res->flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY; ret = allocate_resource(&iomem_resource, res, size, 0, -1, PAGES_PER_SECTION * PAGE_SIZE, NULL, NULL); if (ret < 0) { pr_err("Cannot allocate new System RAM resource\n"); kfree(res); return NULL; } #ifdef CONFIG_SPARSEMEM { unsigned long limit = 1UL << (MAX_PHYSMEM_BITS - PAGE_SHIFT); unsigned long pfn = res->start >> PAGE_SHIFT; if (pfn > limit) { pr_err("New System RAM resource outside addressable RAM (%lu > %lu)\n", pfn, limit); release_memory_resource(res); return NULL; } } #endif return res; }
C
linux
0
CVE-2016-8633
https://www.cvedetails.com/cve/CVE-2016-8633/
CWE-119
https://github.com/torvalds/linux/commit/667121ace9dbafb368618dbabcf07901c962ddac
667121ace9dbafb368618dbabcf07901c962ddac
firewire: net: guard against rx buffer overflows The IP-over-1394 driver firewire-net lacked input validation when handling incoming fragmented datagrams. A maliciously formed fragment with a respectively large datagram_offset would cause a memcpy past the datagram buffer. So, drop any packets carrying a fragment with offset + length larger than datagram_size. In addition, ensure that - GASP header, unfragmented encapsulation header, or fragment encapsulation header actually exists before we access it, - the encapsulated datagram or fragment is of nonzero size. Reported-by: Eyal Itkin <[email protected]> Reviewed-by: Eyal Itkin <[email protected]> Fixes: CVE 2016-8633 Cc: [email protected] Signed-off-by: Stefan Richter <[email protected]>
static inline void fwnet_make_sf_hdr(struct rfc2734_header *hdr, unsigned lf, unsigned dg_size, unsigned fg_off, unsigned dgl) { hdr->w0 = fwnet_set_hdr_lf(lf) | fwnet_set_hdr_dg_size(dg_size) | fwnet_set_hdr_fg_off(fg_off); hdr->w1 = fwnet_set_hdr_dgl(dgl); }
static inline void fwnet_make_sf_hdr(struct rfc2734_header *hdr, unsigned lf, unsigned dg_size, unsigned fg_off, unsigned dgl) { hdr->w0 = fwnet_set_hdr_lf(lf) | fwnet_set_hdr_dg_size(dg_size) | fwnet_set_hdr_fg_off(fg_off); hdr->w1 = fwnet_set_hdr_dgl(dgl); }
C
linux
0
CVE-2016-7125
https://www.cvedetails.com/cve/CVE-2016-7125/
CWE-74
https://github.com/php/php-src/commit/8763c6090d627d8bb0ee1d030c30e58f406be9ce?w=1
8763c6090d627d8bb0ee1d030c30e58f406be9ce?w=1
Fix bug #72681 - consume data even if we're not storing them
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */ { const char *p, *q; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; int skip = 0; PHP_VAR_UNSERIALIZE_INIT(var_hash); p = val; while (p < endptr) { zval **tmp; q = p; skip = 0; while (*q != PS_DELIMITER) { if (++q >= endptr) goto break_outer_loop; } if (p[0] == PS_UNDEF_MARKER) { p++; has_value = 0; } else { has_value = 1; } namelen = q - p; name = estrndup(p, namelen); q++; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { skip = 1; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { if (!skip) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } } else { var_push_dtor_no_addref(&var_hash, &current); efree(name); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } if (!skip) { PS_ADD_VARL(name, namelen); } skip: efree(name); p = q; } break_outer_loop: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */ { const char *p, *q; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); p = val; while (p < endptr) { zval **tmp; q = p; while (*q != PS_DELIMITER) { if (++q >= endptr) goto break_outer_loop; } if (p[0] == PS_UNDEF_MARKER) { p++; has_value = 0; } else { has_value = 1; } namelen = q - p; name = estrndup(p, namelen); q++; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { goto skip; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { var_push_dtor_no_addref(&var_hash, &current); efree(name); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); skip: efree(name); p = q; } break_outer_loop: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */
C
php-src
1
CVE-2018-6151
https://www.cvedetails.com/cve/CVE-2018-6151/
CWE-125
https://github.com/chromium/chromium/commit/cbb2c0940d4e3914ccd74f6466ff4cb9e50e0e86
cbb2c0940d4e3914ccd74f6466ff4cb9e50e0e86
Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate. DownloadManager has public SetDelegate method and tests and or other subsystems can install their own implementations of the delegate. Bug: 805905 Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8 TBR: tests updated to follow the API change. Reviewed-on: https://chromium-review.googlesource.com/894702 Reviewed-by: David Vallet <[email protected]> Reviewed-by: Min Qin <[email protected]> Cr-Commit-Position: refs/heads/master@{#533515}
void DownloadCoreServiceImpl::Shutdown() { if (download_manager_created_) { BrowserContext::GetDownloadManager(profile_)->Shutdown(); } #if BUILDFLAG(ENABLE_EXTENSIONS) extension_event_router_.reset(); #endif manager_delegate_.reset(); download_history_.reset(); }
void DownloadCoreServiceImpl::Shutdown() { if (download_manager_created_) { BrowserContext::GetDownloadManager(profile_)->Shutdown(); } #if BUILDFLAG(ENABLE_EXTENSIONS) extension_event_router_.reset(); #endif manager_delegate_.reset(); download_history_.reset(); }
C
Chrome
0
CVE-2010-2520
https://www.cvedetails.com/cve/CVE-2010-2520/
CWE-119
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=888cd1843e935fe675cf2ac303116d4ed5b9d54b
888cd1843e935fe675cf2ac303116d4ed5b9d54b
null
Round_None( EXEC_OP_ FT_F26Dot6 distance, FT_F26Dot6 compensation ) { FT_F26Dot6 val; FT_UNUSED_EXEC; if ( distance >= 0 ) { val = distance + compensation; if ( distance && val < 0 ) val = 0; } else { val = distance - compensation; if ( val > 0 ) val = 0; } return val; }
Round_None( EXEC_OP_ FT_F26Dot6 distance, FT_F26Dot6 compensation ) { FT_F26Dot6 val; FT_UNUSED_EXEC; if ( distance >= 0 ) { val = distance + compensation; if ( distance && val < 0 ) val = 0; } else { val = distance - compensation; if ( val > 0 ) val = 0; } return val; }
C
savannah
0
CVE-2016-3824
https://www.cvedetails.com/cve/CVE-2016-3824/
CWE-119
https://android.googlesource.com/platform/frameworks/av/+/b351eabb428c7ca85a34513c64601f437923d576
b351eabb428c7ca85a34513c64601f437923d576
DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
status_t OMXNodeInstance::createPersistentInputSurface( sp<IGraphicBufferProducer> *bufferProducer, sp<IGraphicBufferConsumer> *bufferConsumer) { String8 name("GraphicBufferSource"); sp<IGraphicBufferProducer> producer; sp<IGraphicBufferConsumer> consumer; BufferQueue::createBufferQueue(&producer, &consumer); consumer->setConsumerName(name); consumer->setConsumerUsageBits(GRALLOC_USAGE_HW_VIDEO_ENCODER); sp<BufferQueue::ProxyConsumerListener> proxy = new BufferQueue::ProxyConsumerListener(NULL); status_t err = consumer->consumerConnect(proxy, false); if (err != NO_ERROR) { ALOGE("Error connecting to BufferQueue: %s (%d)", strerror(-err), err); return err; } *bufferProducer = producer; *bufferConsumer = consumer; return OK; }
status_t OMXNodeInstance::createPersistentInputSurface( sp<IGraphicBufferProducer> *bufferProducer, sp<IGraphicBufferConsumer> *bufferConsumer) { String8 name("GraphicBufferSource"); sp<IGraphicBufferProducer> producer; sp<IGraphicBufferConsumer> consumer; BufferQueue::createBufferQueue(&producer, &consumer); consumer->setConsumerName(name); consumer->setConsumerUsageBits(GRALLOC_USAGE_HW_VIDEO_ENCODER); sp<BufferQueue::ProxyConsumerListener> proxy = new BufferQueue::ProxyConsumerListener(NULL); status_t err = consumer->consumerConnect(proxy, false); if (err != NO_ERROR) { ALOGE("Error connecting to BufferQueue: %s (%d)", strerror(-err), err); return err; } *bufferProducer = producer; *bufferConsumer = consumer; return OK; }
C
Android
0
CVE-2015-7872
https://www.cvedetails.com/cve/CVE-2015-7872/
CWE-20
https://github.com/torvalds/linux/commit/ce1fad2740c648a4340f6f6c391a8a83769d2e8c
ce1fad2740c648a4340f6f6c391a8a83769d2e8c
Merge branch 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs Pull key handling fixes from David Howells: "Here are two patches, the first of which at least should go upstream immediately: (1) Prevent a user-triggerable crash in the keyrings destructor when a negatively instantiated keyring is garbage collected. I have also seen this triggered for user type keys. (2) Prevent the user from using requesting that a keyring be created and instantiated through an upcall. Doing so is probably safe since the keyring type ignores the arguments to its instantiation function - but we probably shouldn't let keyrings be created in this manner" * 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs: KEYS: Don't permit request_key() to construct a new keyring KEYS: Fix crash when attempt to garbage collect an uninstantiated keyring
static void key_gc_timer_func(unsigned long data) { kenter(""); key_gc_next_run = LONG_MAX; key_schedule_gc_links(); }
static void key_gc_timer_func(unsigned long data) { kenter(""); key_gc_next_run = LONG_MAX; key_schedule_gc_links(); }
C
linux
0
CVE-2013-7421
https://www.cvedetails.com/cve/CVE-2013-7421/
CWE-264
https://github.com/torvalds/linux/commit/5d26a105b5a73e5635eae0629b42fa0a90e07b7b
5d26a105b5a73e5635eae0629b42fa0a90e07b7b
crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
static void __exit blowfish_mod_fini(void) { crypto_unregister_alg(&alg); }
static void __exit blowfish_mod_fini(void) { crypto_unregister_alg(&alg); }
C
linux
0
CVE-2016-9794
https://www.cvedetails.com/cve/CVE-2016-9794/
CWE-416
https://github.com/torvalds/linux/commit/3aa02cb664c5fb1042958c8d1aa8c35055a2ebc4
3aa02cb664c5fb1042958c8d1aa8c35055a2ebc4
ALSA: pcm : Call kill_fasync() in stream lock Currently kill_fasync() is called outside the stream lock in snd_pcm_period_elapsed(). This is potentially racy, since the stream may get released even during the irq handler is running. Although snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't guarantee that the irq handler finishes, thus the kill_fasync() call outside the stream spin lock may be invoked after the substream is detached, as recently reported by KASAN. As a quick workaround, move kill_fasync() call inside the stream lock. The fasync is rarely used interface, so this shouldn't have a big impact from the performance POV. Ideally, we should implement some sync mechanism for the proper finish of stream and irq handler. But this oneliner should suffice for most cases, so far. Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>
int snd_interval_refine(struct snd_interval *i, const struct snd_interval *v) { int changed = 0; if (snd_BUG_ON(snd_interval_empty(i))) return -EINVAL; if (i->min < v->min) { i->min = v->min; i->openmin = v->openmin; changed = 1; } else if (i->min == v->min && !i->openmin && v->openmin) { i->openmin = 1; changed = 1; } if (i->max > v->max) { i->max = v->max; i->openmax = v->openmax; changed = 1; } else if (i->max == v->max && !i->openmax && v->openmax) { i->openmax = 1; changed = 1; } if (!i->integer && v->integer) { i->integer = 1; changed = 1; } if (i->integer) { if (i->openmin) { i->min++; i->openmin = 0; } if (i->openmax) { i->max--; i->openmax = 0; } } else if (!i->openmin && !i->openmax && i->min == i->max) i->integer = 1; if (snd_interval_checkempty(i)) { snd_interval_none(i); return -EINVAL; } return changed; }
int snd_interval_refine(struct snd_interval *i, const struct snd_interval *v) { int changed = 0; if (snd_BUG_ON(snd_interval_empty(i))) return -EINVAL; if (i->min < v->min) { i->min = v->min; i->openmin = v->openmin; changed = 1; } else if (i->min == v->min && !i->openmin && v->openmin) { i->openmin = 1; changed = 1; } if (i->max > v->max) { i->max = v->max; i->openmax = v->openmax; changed = 1; } else if (i->max == v->max && !i->openmax && v->openmax) { i->openmax = 1; changed = 1; } if (!i->integer && v->integer) { i->integer = 1; changed = 1; } if (i->integer) { if (i->openmin) { i->min++; i->openmin = 0; } if (i->openmax) { i->max--; i->openmax = 0; } } else if (!i->openmin && !i->openmax && i->min == i->max) i->integer = 1; if (snd_interval_checkempty(i)) { snd_interval_none(i); return -EINVAL; } return changed; }
C
linux
0
CVE-2011-2834
https://www.cvedetails.com/cve/CVE-2011-2834/
CWE-399
https://github.com/chromium/chromium/commit/3a766e0115e9799db766a88554b9ab12ee5bf2a4
3a766e0115e9799db766a88554b9ab12ee5bf2a4
Apply libxml fix for undefined namespaces. BUG=93472 Review URL: http://codereview.chromium.org/7747031 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@98359 0039d316-1c4b-4281-b951-d872f2087c98
xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op) { int total = 0; int equal, ret; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; xmlNodePtr bak; xmlDocPtr bakd; int pp; int cs; CHECK_ERROR0; comp = ctxt->comp; switch (op->op) { case XPATH_OP_END: return (0); case XPATH_OP_AND: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 0)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval &= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_OR: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 1)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval |= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_EQUAL: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value) equal = xmlXPathEqualValues(ctxt); else equal = xmlXPathNotEqualValues(ctxt); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal)); return (total); case XPATH_OP_CMP: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ret = xmlXPathCompareValues(ctxt, op->value, op->value2); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret)); return (total); case XPATH_OP_PLUS: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) { ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); } CHECK_ERROR0; if (op->value == 0) xmlXPathSubValues(ctxt); else if (op->value == 1) xmlXPathAddValues(ctxt); else if (op->value == 2) xmlXPathValueFlipSign(ctxt); else if (op->value == 3) { CAST_TO_NUMBER; CHECK_TYPE0(XPATH_NUMBER); } return (total); case XPATH_OP_MULT: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value == 0) xmlXPathMultValues(ctxt); else if (op->value == 1) xmlXPathDivValues(ctxt); else if (op->value == 2) xmlXPathModValues(ctxt); return (total); case XPATH_OP_UNION: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; CHECK_TYPE0(XPATH_NODESET); arg2 = valuePop(ctxt); CHECK_TYPE0(XPATH_NODESET); arg1 = valuePop(ctxt); if ((arg1->nodesetval == NULL) || ((arg2->nodesetval != NULL) && (arg2->nodesetval->nodeNr != 0))) { arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval, arg2->nodesetval); } valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_ROOT: xmlXPathRoot(ctxt); return (total); case XPATH_OP_NODE: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); case XPATH_OP_RESET: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ctxt->context->node = NULL; return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0); return (total); } case XPATH_OP_VALUE: valuePush(ctxt, xmlXPathCacheObjectCopy(ctxt->context, (xmlXPathObjectPtr) op->value4)); return (total); case XPATH_OP_VARIABLE:{ xmlXPathObjectPtr val; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->value5 == NULL) { val = xmlXPathVariableLookup(ctxt->context, op->value4); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } else { const xmlChar *URI; URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n", (char *) op->value4, (char *)op->value5); ctxt->error = XPATH_UNDEF_PREFIX_ERROR; return (total); } val = xmlXPathVariableLookupNS(ctxt->context, op->value4, URI); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } return (total); } case XPATH_OP_FUNCTION:{ xmlXPathFunction func; const xmlChar *oldFunc, *oldFuncURI; int i; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (ctxt->valueNr < op->value) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } for (i = 0; i < op->value; i++) if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } if (op->cache != NULL) XML_CAST_FPTR(func) = op->cache; else { const xmlChar *URI = NULL; if (op->value5 == NULL) func = xmlXPathFunctionLookup(ctxt->context, op->value4); else { URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n", (char *)op->value4, (char *)op->value5); ctxt->error = XPATH_UNDEF_PREFIX_ERROR; return (total); } func = xmlXPathFunctionLookupNS(ctxt->context, op->value4, URI); } if (func == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s not found\n", (char *)op->value4); XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR); } op->cache = XML_CAST_FPTR(func); op->cacheURI = (void *) URI; } oldFunc = ctxt->context->function; oldFuncURI = ctxt->context->functionURI; ctxt->context->function = op->value4; ctxt->context->functionURI = op->cacheURI; func(ctxt, op->value); ctxt->context->function = oldFunc; ctxt->context->functionURI = oldFuncURI; return (total); } case XPATH_OP_ARG: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); ctxt->context->contextSize = cs; ctxt->context->proximityPosition = pp; ctxt->context->node = bak; ctxt->context->doc = bakd; CHECK_ERROR0; if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); ctxt->context->doc = bakd; ctxt->context->node = bak; CHECK_ERROR0; } return (total); case XPATH_OP_PREDICATE: case XPATH_OP_FILTER:{ xmlXPathObjectPtr res; xmlXPathObjectPtr obj, tmp; xmlNodeSetPtr newset = NULL; xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; int i; /* * Optimization for ()[1] selection i.e. the first elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && #ifdef XP_OPTIMIZED_FILTER_FIRST /* * FILTER TODO: Can we assume that the inner processing * will result in an ordered list if we have an * XPATH_OP_FILTER? * What about an additional field or flag on * xmlXPathObject like @sorted ? This way we wouln'd need * to assume anything, so it would be more robust and * easier to optimize. */ ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */ (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */ #else (comp->steps[op->ch1].op == XPATH_OP_SORT) && #endif (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */ xmlXPathObjectPtr val; val = comp->steps[op->ch2].value4; if ((val != NULL) && (val->type == XPATH_NUMBER) && (val->floatval == 1.0)) { xmlNodePtr first = NULL; total += xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1], &first); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the first value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) ctxt->value->nodesetval->nodeNr = 1; return (total); } } /* * Optimization for ()[last()] selection i.e. the last elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && (comp->steps[op->ch1].op == XPATH_OP_SORT) && (comp->steps[op->ch2].op == XPATH_OP_SORT)) { int f = comp->steps[op->ch2].ch1; if ((f != -1) && (comp->steps[f].op == XPATH_OP_FUNCTION) && (comp->steps[f].value5 == NULL) && (comp->steps[f].value == 0) && (comp->steps[f].value4 != NULL) && (xmlStrEqual (comp->steps[f].value4, BAD_CAST "last"))) { xmlNodePtr last = NULL; total += xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], &last); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the last value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeTab != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { ctxt->value->nodesetval->nodeTab[0] = ctxt->value->nodesetval->nodeTab[ctxt-> value-> nodesetval-> nodeNr - 1]; ctxt->value->nodesetval->nodeNr = 1; } return (total); } } /* * Process inner predicates first. * Example "index[parent::book][1]": * ... * PREDICATE <-- we are here "[1]" * PREDICATE <-- process "[parent::book]" first * SORT * COLLECT 'parent' 'name' 'node' book * NODE * ELEM Object is a number : 1 */ if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 == -1) return (total); if (ctxt->value == NULL) return (total); oldnode = ctxt->context->node; #ifdef LIBXML_XPTR_ENABLED /* * Hum are we filtering the result of an XPointer expression */ if (ctxt->value->type == XPATH_LOCATIONSET) { xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; ctxt->context->node = NULL; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation need to be tested to * decided whether the filter succeeded or not */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPtrLocationSetAdd(newlocset, xmlXPathObjectCopy (oldlocset->locTab[i])); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } /* * The result is used as the new evaluation locset. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); ctxt->context->node = oldnode; return (total); } #endif /* LIBXML_XPTR_ENABLED */ /* * Extract the old set, and then evaluate the result of the * expression for all the element in the set. use it to grow * up a new set. */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; oldnode = ctxt->context->node; oldDoc = ctxt->context->doc; ctxt->context->node = NULL; if ((oldset == NULL) || (oldset->nodeNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; /* if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; res = valuePop(ctxt); if (res != NULL) xmlXPathFreeObject(res); */ valuePush(ctxt, obj); ctxt->context->node = oldnode; CHECK_ERROR0; } else { tmp = NULL; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ newset = xmlXPathNodeSetCreate(NULL); /* * SPEC XPath 1.0: * "For each node in the node-set to be filtered, the * PredicateExpr is evaluated with that node as the * context node, with the number of nodes in the * node-set as the context size, and with the proximity * position of the node in the node-set with respect to * the axis as the context position;" * @oldset is the node-set" to be filtered. * * SPEC XPath 1.0: * "only predicates change the context position and * context size (see [2.4 Predicates])." * Example: * node-set context pos * nA 1 * nB 2 * nC 3 * After applying predicate [position() > 1] : * node-set context pos * nB 1 * nC 2 * * removed the first node in the node-set, then * the context position of the */ for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of * a single item in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) && (oldset->nodeTab[i]->doc != NULL)) ctxt->context->doc = oldset->nodeTab[i]->doc; if (tmp == NULL) { tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); } else { xmlXPathNodeSetAddUnique(tmp->nodesetval, ctxt->context->node); } valuePush(ctxt, tmp); ctxt->context->contextSize = oldset->nodeNr; ctxt->context->proximityPosition = i + 1; /* * Evaluate the predicate against the context node. * Can/should we optimize position() predicates * here (e.g. "[1]")? */ if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation needs to be tested to * decide whether the filter succeeded or not */ /* * OPTIMIZE TODO: Can we use * xmlXPathNodeSetAdd*Unique()* instead? */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { valuePop(ctxt); xmlXPathNodeSetClear(tmp->nodesetval, 1); /* * Don't free the temporary nodeset * in order to avoid massive recreation inside this * loop. */ } else tmp = NULL; ctxt->context->node = NULL; } if (tmp != NULL) xmlXPathReleaseObject(ctxt->context, tmp); /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; /* may want to move this past the '}' later */ ctxt->context->doc = oldDoc; valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); } ctxt->context->node = oldnode; return (total); } case XPATH_OP_SORT: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { xmlXPathNodeSetSort(ctxt->value->nodesetval); } return (total); #ifdef LIBXML_XPTR_ENABLED case XPATH_OP_RANGETO:{ xmlXPathObjectPtr range; xmlXPathObjectPtr res, obj; xmlXPathObjectPtr tmp; xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; xmlNodeSetPtr oldset; int i, j; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->ch2 == -1) return (total); if (ctxt->value->type == XPATH_LOCATIONSET) { /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->node = NULL; ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); if (res->type == XPATH_LOCATIONSET) { xmlLocationSetPtr rloc = (xmlLocationSetPtr)res->user; for (j=0; j<rloc->locNr; j++) { range = xmlXPtrNewRange( oldlocset->locTab[i]->user, oldlocset->locTab[i]->index, rloc->locTab[j]->user2, rloc->locTab[j]->index2); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } } } else { range = xmlXPtrNewRangeNodeObject( (xmlNodePtr)oldlocset->locTab[i]->user, res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset,range); } } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } else { /* Not a location set */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; ctxt->context->node = NULL; newlocset = xmlXPtrLocationSetCreate(NULL); if (oldset != NULL) { for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of a single item * in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; /* * OPTIMIZE TODO: Avoid recreation for every iteration. */ tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); range = xmlXPtrNewRangeNodeObject(oldset->nodeTab[i], res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } } /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); return (total); } #endif /* LIBXML_XPTR_ENABLED */ }
xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op) { int total = 0; int equal, ret; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; xmlNodePtr bak; xmlDocPtr bakd; int pp; int cs; CHECK_ERROR0; comp = ctxt->comp; switch (op->op) { case XPATH_OP_END: return (0); case XPATH_OP_AND: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 0)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval &= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_OR: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 1)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval |= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_EQUAL: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value) equal = xmlXPathEqualValues(ctxt); else equal = xmlXPathNotEqualValues(ctxt); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal)); return (total); case XPATH_OP_CMP: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ret = xmlXPathCompareValues(ctxt, op->value, op->value2); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret)); return (total); case XPATH_OP_PLUS: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) { ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); } CHECK_ERROR0; if (op->value == 0) xmlXPathSubValues(ctxt); else if (op->value == 1) xmlXPathAddValues(ctxt); else if (op->value == 2) xmlXPathValueFlipSign(ctxt); else if (op->value == 3) { CAST_TO_NUMBER; CHECK_TYPE0(XPATH_NUMBER); } return (total); case XPATH_OP_MULT: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value == 0) xmlXPathMultValues(ctxt); else if (op->value == 1) xmlXPathDivValues(ctxt); else if (op->value == 2) xmlXPathModValues(ctxt); return (total); case XPATH_OP_UNION: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; CHECK_TYPE0(XPATH_NODESET); arg2 = valuePop(ctxt); CHECK_TYPE0(XPATH_NODESET); arg1 = valuePop(ctxt); if ((arg1->nodesetval == NULL) || ((arg2->nodesetval != NULL) && (arg2->nodesetval->nodeNr != 0))) { arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval, arg2->nodesetval); } valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_ROOT: xmlXPathRoot(ctxt); return (total); case XPATH_OP_NODE: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); case XPATH_OP_RESET: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ctxt->context->node = NULL; return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0); return (total); } case XPATH_OP_VALUE: valuePush(ctxt, xmlXPathCacheObjectCopy(ctxt->context, (xmlXPathObjectPtr) op->value4)); return (total); case XPATH_OP_VARIABLE:{ xmlXPathObjectPtr val; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->value5 == NULL) { val = xmlXPathVariableLookup(ctxt->context, op->value4); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } else { const xmlChar *URI; URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n", (char *) op->value4, (char *)op->value5); return (total); } val = xmlXPathVariableLookupNS(ctxt->context, op->value4, URI); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } return (total); } case XPATH_OP_FUNCTION:{ xmlXPathFunction func; const xmlChar *oldFunc, *oldFuncURI; int i; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (ctxt->valueNr < op->value) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } for (i = 0; i < op->value; i++) if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } if (op->cache != NULL) XML_CAST_FPTR(func) = op->cache; else { const xmlChar *URI = NULL; if (op->value5 == NULL) func = xmlXPathFunctionLookup(ctxt->context, op->value4); else { URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n", (char *)op->value4, (char *)op->value5); return (total); } func = xmlXPathFunctionLookupNS(ctxt->context, op->value4, URI); } if (func == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s not found\n", (char *)op->value4); XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR); } op->cache = XML_CAST_FPTR(func); op->cacheURI = (void *) URI; } oldFunc = ctxt->context->function; oldFuncURI = ctxt->context->functionURI; ctxt->context->function = op->value4; ctxt->context->functionURI = op->cacheURI; func(ctxt, op->value); ctxt->context->function = oldFunc; ctxt->context->functionURI = oldFuncURI; return (total); } case XPATH_OP_ARG: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); ctxt->context->contextSize = cs; ctxt->context->proximityPosition = pp; ctxt->context->node = bak; ctxt->context->doc = bakd; CHECK_ERROR0; if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); ctxt->context->doc = bakd; ctxt->context->node = bak; CHECK_ERROR0; } return (total); case XPATH_OP_PREDICATE: case XPATH_OP_FILTER:{ xmlXPathObjectPtr res; xmlXPathObjectPtr obj, tmp; xmlNodeSetPtr newset = NULL; xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; int i; /* * Optimization for ()[1] selection i.e. the first elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && #ifdef XP_OPTIMIZED_FILTER_FIRST /* * FILTER TODO: Can we assume that the inner processing * will result in an ordered list if we have an * XPATH_OP_FILTER? * What about an additional field or flag on * xmlXPathObject like @sorted ? This way we wouln'd need * to assume anything, so it would be more robust and * easier to optimize. */ ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */ (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */ #else (comp->steps[op->ch1].op == XPATH_OP_SORT) && #endif (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */ xmlXPathObjectPtr val; val = comp->steps[op->ch2].value4; if ((val != NULL) && (val->type == XPATH_NUMBER) && (val->floatval == 1.0)) { xmlNodePtr first = NULL; total += xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1], &first); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the first value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) ctxt->value->nodesetval->nodeNr = 1; return (total); } } /* * Optimization for ()[last()] selection i.e. the last elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && (comp->steps[op->ch1].op == XPATH_OP_SORT) && (comp->steps[op->ch2].op == XPATH_OP_SORT)) { int f = comp->steps[op->ch2].ch1; if ((f != -1) && (comp->steps[f].op == XPATH_OP_FUNCTION) && (comp->steps[f].value5 == NULL) && (comp->steps[f].value == 0) && (comp->steps[f].value4 != NULL) && (xmlStrEqual (comp->steps[f].value4, BAD_CAST "last"))) { xmlNodePtr last = NULL; total += xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], &last); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the last value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeTab != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { ctxt->value->nodesetval->nodeTab[0] = ctxt->value->nodesetval->nodeTab[ctxt-> value-> nodesetval-> nodeNr - 1]; ctxt->value->nodesetval->nodeNr = 1; } return (total); } } /* * Process inner predicates first. * Example "index[parent::book][1]": * ... * PREDICATE <-- we are here "[1]" * PREDICATE <-- process "[parent::book]" first * SORT * COLLECT 'parent' 'name' 'node' book * NODE * ELEM Object is a number : 1 */ if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 == -1) return (total); if (ctxt->value == NULL) return (total); oldnode = ctxt->context->node; #ifdef LIBXML_XPTR_ENABLED /* * Hum are we filtering the result of an XPointer expression */ if (ctxt->value->type == XPATH_LOCATIONSET) { xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; ctxt->context->node = NULL; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation need to be tested to * decided whether the filter succeeded or not */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPtrLocationSetAdd(newlocset, xmlXPathObjectCopy (oldlocset->locTab[i])); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } /* * The result is used as the new evaluation locset. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); ctxt->context->node = oldnode; return (total); } #endif /* LIBXML_XPTR_ENABLED */ /* * Extract the old set, and then evaluate the result of the * expression for all the element in the set. use it to grow * up a new set. */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; oldnode = ctxt->context->node; oldDoc = ctxt->context->doc; ctxt->context->node = NULL; if ((oldset == NULL) || (oldset->nodeNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; /* if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; res = valuePop(ctxt); if (res != NULL) xmlXPathFreeObject(res); */ valuePush(ctxt, obj); ctxt->context->node = oldnode; CHECK_ERROR0; } else { tmp = NULL; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ newset = xmlXPathNodeSetCreate(NULL); /* * SPEC XPath 1.0: * "For each node in the node-set to be filtered, the * PredicateExpr is evaluated with that node as the * context node, with the number of nodes in the * node-set as the context size, and with the proximity * position of the node in the node-set with respect to * the axis as the context position;" * @oldset is the node-set" to be filtered. * * SPEC XPath 1.0: * "only predicates change the context position and * context size (see [2.4 Predicates])." * Example: * node-set context pos * nA 1 * nB 2 * nC 3 * After applying predicate [position() > 1] : * node-set context pos * nB 1 * nC 2 * * removed the first node in the node-set, then * the context position of the */ for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of * a single item in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) && (oldset->nodeTab[i]->doc != NULL)) ctxt->context->doc = oldset->nodeTab[i]->doc; if (tmp == NULL) { tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); } else { xmlXPathNodeSetAddUnique(tmp->nodesetval, ctxt->context->node); } valuePush(ctxt, tmp); ctxt->context->contextSize = oldset->nodeNr; ctxt->context->proximityPosition = i + 1; /* * Evaluate the predicate against the context node. * Can/should we optimize position() predicates * here (e.g. "[1]")? */ if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation needs to be tested to * decide whether the filter succeeded or not */ /* * OPTIMIZE TODO: Can we use * xmlXPathNodeSetAdd*Unique()* instead? */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { valuePop(ctxt); xmlXPathNodeSetClear(tmp->nodesetval, 1); /* * Don't free the temporary nodeset * in order to avoid massive recreation inside this * loop. */ } else tmp = NULL; ctxt->context->node = NULL; } if (tmp != NULL) xmlXPathReleaseObject(ctxt->context, tmp); /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; /* may want to move this past the '}' later */ ctxt->context->doc = oldDoc; valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); } ctxt->context->node = oldnode; return (total); } case XPATH_OP_SORT: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { xmlXPathNodeSetSort(ctxt->value->nodesetval); } return (total); #ifdef LIBXML_XPTR_ENABLED case XPATH_OP_RANGETO:{ xmlXPathObjectPtr range; xmlXPathObjectPtr res, obj; xmlXPathObjectPtr tmp; xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; xmlNodeSetPtr oldset; int i, j; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->ch2 == -1) return (total); if (ctxt->value->type == XPATH_LOCATIONSET) { /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->node = NULL; ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); if (res->type == XPATH_LOCATIONSET) { xmlLocationSetPtr rloc = (xmlLocationSetPtr)res->user; for (j=0; j<rloc->locNr; j++) { range = xmlXPtrNewRange( oldlocset->locTab[i]->user, oldlocset->locTab[i]->index, rloc->locTab[j]->user2, rloc->locTab[j]->index2); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } } } else { range = xmlXPtrNewRangeNodeObject( (xmlNodePtr)oldlocset->locTab[i]->user, res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset,range); } } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } else { /* Not a location set */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; ctxt->context->node = NULL; newlocset = xmlXPtrLocationSetCreate(NULL); if (oldset != NULL) { for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of a single item * in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; /* * OPTIMIZE TODO: Avoid recreation for every iteration. */ tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); range = xmlXPtrNewRangeNodeObject(oldset->nodeTab[i], res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } } /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); return (total); } #endif /* LIBXML_XPTR_ENABLED */ }
C
Chrome
1
CVE-2011-4112
https://www.cvedetails.com/cve/CVE-2011-4112/
CWE-264
https://github.com/torvalds/linux/commit/550fd08c2cebad61c548def135f67aba284c6162
550fd08c2cebad61c548def135f67aba284c6162
net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static void proc_APList_on_close( struct inode *inode, struct file *file ) { struct proc_data *data = file->private_data; struct proc_dir_entry *dp = PDE(inode); struct net_device *dev = dp->data; struct airo_info *ai = dev->ml_priv; APListRid APList_rid; int i; if ( !data->writelen ) return; memset( &APList_rid, 0, sizeof(APList_rid) ); APList_rid.len = cpu_to_le16(sizeof(APList_rid)); for( i = 0; i < 4 && data->writelen >= (i+1)*6*3; i++ ) { int j; for( j = 0; j < 6*3 && data->wbuffer[j+i*6*3]; j++ ) { switch(j%3) { case 0: APList_rid.ap[i][j/3]= hex_to_bin(data->wbuffer[j+i*6*3])<<4; break; case 1: APList_rid.ap[i][j/3]|= hex_to_bin(data->wbuffer[j+i*6*3]); break; } } } disable_MAC(ai, 1); writeAPListRid(ai, &APList_rid, 1); enable_MAC(ai, 1); }
static void proc_APList_on_close( struct inode *inode, struct file *file ) { struct proc_data *data = file->private_data; struct proc_dir_entry *dp = PDE(inode); struct net_device *dev = dp->data; struct airo_info *ai = dev->ml_priv; APListRid APList_rid; int i; if ( !data->writelen ) return; memset( &APList_rid, 0, sizeof(APList_rid) ); APList_rid.len = cpu_to_le16(sizeof(APList_rid)); for( i = 0; i < 4 && data->writelen >= (i+1)*6*3; i++ ) { int j; for( j = 0; j < 6*3 && data->wbuffer[j+i*6*3]; j++ ) { switch(j%3) { case 0: APList_rid.ap[i][j/3]= hex_to_bin(data->wbuffer[j+i*6*3])<<4; break; case 1: APList_rid.ap[i][j/3]|= hex_to_bin(data->wbuffer[j+i*6*3]); break; } } } disable_MAC(ai, 1); writeAPListRid(ai, &APList_rid, 1); enable_MAC(ai, 1); }
C
linux
0
CVE-2011-2918
https://www.cvedetails.com/cve/CVE-2011-2918/
CWE-399
https://github.com/torvalds/linux/commit/a8b0ca17b80e92faab46ee7179ba9e99ccb61233
a8b0ca17b80e92faab46ee7179ba9e99ccb61233
perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]>
static void mipspmu_disable(struct pmu *pmu) { if (mipspmu) mipspmu->stop(); }
static void mipspmu_disable(struct pmu *pmu) { if (mipspmu) mipspmu->stop(); }
C
linux
0
CVE-2012-1146
https://www.cvedetails.com/cve/CVE-2012-1146/
null
https://github.com/torvalds/linux/commit/371528caec553785c37f73fa3926ea0de84f986f
371528caec553785c37f73fa3926ea0de84f986f
mm: memcg: Correct unregistring of events attached to the same eventfd There is an issue when memcg unregisters events that were attached to the same eventfd: - On the first call mem_cgroup_usage_unregister_event() removes all events attached to a given eventfd, and if there were no events left, thresholds->primary would become NULL; - Since there were several events registered, cgroups core will call mem_cgroup_usage_unregister_event() again, but now kernel will oops, as the function doesn't expect that threshold->primary may be NULL. That's a good question whether mem_cgroup_usage_unregister_event() should actually remove all events in one go, but nowadays it can't do any better as cftype->unregister_event callback doesn't pass any private event-associated cookie. So, let's fix the issue by simply checking for threshold->primary. FWIW, w/o the patch the following oops may be observed: BUG: unable to handle kernel NULL pointer dereference at 0000000000000004 IP: [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0 Pid: 574, comm: kworker/0:2 Not tainted 3.3.0-rc4+ #9 Bochs Bochs RIP: 0010:[<ffffffff810be32c>] [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0 RSP: 0018:ffff88001d0b9d60 EFLAGS: 00010246 Process kworker/0:2 (pid: 574, threadinfo ffff88001d0b8000, task ffff88001de91cc0) Call Trace: [<ffffffff8107092b>] cgroup_event_remove+0x2b/0x60 [<ffffffff8103db94>] process_one_work+0x174/0x450 [<ffffffff8103e413>] worker_thread+0x123/0x2d0 Cc: stable <[email protected]> Signed-off-by: Anton Vorontsov <[email protected]> Acked-by: KAMEZAWA Hiroyuki <[email protected]> Cc: Kirill A. Shutemov <[email protected]> Cc: Michal Hocko <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); if (!thresholds->primary) goto unlock; usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); unlock: mutex_unlock(&memcg->thresholds_lock); }
static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); mutex_unlock(&memcg->thresholds_lock); }
C
linux
1
CVE-2016-1639
https://www.cvedetails.com/cve/CVE-2016-1639/
null
https://github.com/chromium/chromium/commit/c66b1fc49870c514b1c1e8b53498153176d7ec2b
c66b1fc49870c514b1c1e8b53498153176d7ec2b
cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224}
void UserSelectionScreen::OnUserActivity(const ui::Event* event) { if (!password_clear_timer_.IsRunning()) { password_clear_timer_.Start( FROM_HERE, base::TimeDelta::FromSeconds(kPasswordClearTimeoutSec), this, &UserSelectionScreen::OnPasswordClearTimerExpired); } password_clear_timer_.Reset(); }
void UserSelectionScreen::OnUserActivity(const ui::Event* event) { if (!password_clear_timer_.IsRunning()) { password_clear_timer_.Start( FROM_HERE, base::TimeDelta::FromSeconds(kPasswordClearTimeoutSec), this, &UserSelectionScreen::OnPasswordClearTimerExpired); } password_clear_timer_.Reset(); }
C
Chrome
0
CVE-2014-3645
https://www.cvedetails.com/cve/CVE-2014-3645/
CWE-20
https://github.com/torvalds/linux/commit/bfd0a56b90005f8c8a004baf407ad90045c2b11e
bfd0a56b90005f8c8a004baf407ad90045c2b11e
nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <[email protected]> Signed-off-by: Nadav Har'El <[email protected]> Signed-off-by: Jun Nakajima <[email protected]> Signed-off-by: Xinhao Xu <[email protected]> Signed-off-by: Yang Zhang <[email protected]> Signed-off-by: Gleb Natapov <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
static u64 ept_rsvd_mask(u64 spte, int level) { int i; u64 mask = 0; for (i = 51; i > boot_cpu_data.x86_phys_bits; i--) mask |= (1ULL << i); if (level > 2) /* bits 7:3 reserved */ mask |= 0xf8; else if (level == 2) { if (spte & (1ULL << 7)) /* 2MB ref, bits 20:12 reserved */ mask |= 0x1ff000; else /* bits 6:3 reserved */ mask |= 0x78; } return mask; }
static u64 ept_rsvd_mask(u64 spte, int level) { int i; u64 mask = 0; for (i = 51; i > boot_cpu_data.x86_phys_bits; i--) mask |= (1ULL << i); if (level > 2) /* bits 7:3 reserved */ mask |= 0xf8; else if (level == 2) { if (spte & (1ULL << 7)) /* 2MB ref, bits 20:12 reserved */ mask |= 0x1ff000; else /* bits 6:3 reserved */ mask |= 0x78; } return mask; }
C
linux
0
CVE-2016-3699
https://www.cvedetails.com/cve/CVE-2016-3699/
CWE-264
https://github.com/mjg59/linux/commit/a4a5ed2835e8ea042868b7401dced3f517cafa76
a4a5ed2835e8ea042868b7401dced3f517cafa76
acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <[email protected]>
static u8 __init acpi_table_checksum(u8 *buffer, u32 length) { u8 sum = 0; u8 *end = buffer + length; while (buffer < end) sum = (u8) (sum + *(buffer++)); return sum; }
static u8 __init acpi_table_checksum(u8 *buffer, u32 length) { u8 sum = 0; u8 *end = buffer + length; while (buffer < end) sum = (u8) (sum + *(buffer++)); return sum; }
C
linux
0
null
null
null
https://github.com/chromium/chromium/commit/ec14f31eca3a51f665432973552ee575635132b3
ec14f31eca3a51f665432973552ee575635132b3
[EFL] Change the behavior of ewk_view_scale_set. https://bugs.webkit.org/show_bug.cgi?id=70078 Reviewed by Eric Seidel. Remove center point basis zoom alignment from ewk_view_scale_set to call Page::setPageScaleFactor without any adjustment. * ewk/ewk_view.cpp: (ewk_view_scale_set): * ewk/ewk_view.h: git-svn-id: svn://svn.chromium.org/blink/trunk@103288 bbb929c8-8fbe-4397-9dbb-9b2b20218538
static Eina_Bool _ewk_view_smart_enable_render(Ewk_View_Smart_Data* smartData) { WRN("not supported by engine. smartData=%p", smartData); return false; }
static Eina_Bool _ewk_view_smart_enable_render(Ewk_View_Smart_Data* smartData) { WRN("not supported by engine. smartData=%p", smartData); return false; }
C
Chrome
0
CVE-2018-6111
https://www.cvedetails.com/cve/CVE-2018-6111/
CWE-20
https://github.com/chromium/chromium/commit/3c8e4852477d5b1e2da877808c998dc57db9460f
3c8e4852477d5b1e2da877808c998dc57db9460f
DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157}
double GetEventTimestamp(const Maybe<double>& timestamp) { return (GetEventTimeTicks(timestamp) - base::TimeTicks()).InSecondsF(); }
double GetEventTimestamp(const Maybe<double>& timestamp) { return (GetEventTimeTicks(timestamp) - base::TimeTicks()).InSecondsF(); }
C
Chrome
0
CVE-2017-5508
https://www.cvedetails.com/cve/CVE-2017-5508/
CWE-119
https://github.com/ImageMagick/ImageMagick/commit/c073a7712d82476b5fbee74856c46b88af9c3175
c073a7712d82476b5fbee74856c46b88af9c3175
https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31161
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif }
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } sans=NULL; for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif }
C
ImageMagick
0
CVE-2014-3183
https://www.cvedetails.com/cve/CVE-2014-3183/
CWE-119
https://github.com/torvalds/linux/commit/51217e69697fba92a06e07e16f55c9a52d8e8945
51217e69697fba92a06e07e16f55c9a52d8e8945
HID: logitech: fix bounds checking on LED report size The check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request() is wrong; the current check doesn't make any sense -- the report allocated by HID core in hid_hw_raw_request() can be much larger than DJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't handle this properly at all. Fix the check by actually trimming down the report size properly if it is too large. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]>
static int logi_dj_recv_switch_to_dj_mode(struct dj_receiver_dev *djrcv_dev, unsigned timeout) { struct dj_report *dj_report; int retval; dj_report = kzalloc(sizeof(struct dj_report), GFP_KERNEL); if (!dj_report) return -ENOMEM; dj_report->report_id = REPORT_ID_DJ_SHORT; dj_report->device_index = 0xFF; dj_report->report_type = REPORT_TYPE_CMD_SWITCH; dj_report->report_params[CMD_SWITCH_PARAM_DEVBITFIELD] = 0x3F; dj_report->report_params[CMD_SWITCH_PARAM_TIMEOUT_SECONDS] = (u8)timeout; retval = logi_dj_recv_send_report(djrcv_dev, dj_report); kfree(dj_report); /* * Ugly sleep to work around a USB 3.0 bug when the receiver is still * processing the "switch-to-dj" command while we send an other command. * 50 msec should gives enough time to the receiver to be ready. */ msleep(50); return retval; }
static int logi_dj_recv_switch_to_dj_mode(struct dj_receiver_dev *djrcv_dev, unsigned timeout) { struct dj_report *dj_report; int retval; dj_report = kzalloc(sizeof(struct dj_report), GFP_KERNEL); if (!dj_report) return -ENOMEM; dj_report->report_id = REPORT_ID_DJ_SHORT; dj_report->device_index = 0xFF; dj_report->report_type = REPORT_TYPE_CMD_SWITCH; dj_report->report_params[CMD_SWITCH_PARAM_DEVBITFIELD] = 0x3F; dj_report->report_params[CMD_SWITCH_PARAM_TIMEOUT_SECONDS] = (u8)timeout; retval = logi_dj_recv_send_report(djrcv_dev, dj_report); kfree(dj_report); /* * Ugly sleep to work around a USB 3.0 bug when the receiver is still * processing the "switch-to-dj" command while we send an other command. * 50 msec should gives enough time to the receiver to be ready. */ msleep(50); return retval; }
C
linux
0
CVE-2016-5216
https://www.cvedetails.com/cve/CVE-2016-5216/
CWE-416
https://github.com/chromium/chromium/commit/bf6a6765d44b09c64b8c75d749efb84742a250e7
bf6a6765d44b09c64b8c75d749efb84742a250e7
[pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781}
FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param, FPDF_WIDESTRING url, FPDF_WIDESTRING data, FPDF_WIDESTRING encode) { std::string url_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url)); std::string data_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data)); std::string encode_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode)); std::string javascript = "alert(\"Put:" + url_str + "," + data_str + "," + encode_str + "\")"; return true; }
FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param, FPDF_WIDESTRING url, FPDF_WIDESTRING data, FPDF_WIDESTRING encode) { std::string url_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url)); std::string data_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data)); std::string encode_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode)); std::string javascript = "alert(\"Put:" + url_str + "," + data_str + "," + encode_str + "\")"; return true; }
C
Chrome
0
CVE-2012-4467
https://www.cvedetails.com/cve/CVE-2012-4467/
CWE-399
https://github.com/torvalds/linux/commit/ed6fe9d614fc1bca95eb8c0ccd0e92db00ef9d5d
ed6fe9d614fc1bca95eb8c0ccd0e92db00ef9d5d
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 <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>
struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; }
struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; }
C
linux
0
CVE-2017-6991
https://www.cvedetails.com/cve/CVE-2017-6991/
CWE-119
https://github.com/chromium/chromium/commit/3bfe67c9c4b45eb713326aae7a67c8f7390dae08
3bfe67c9c4b45eb713326aae7a67c8f7390dae08
sqlite: safely move pointer values through SQL. This lands https://www.sqlite.org/src/timeline?c=d6a44b35 in third_party/sqlite/src/ and third_party/sqlite/patches/0013-Add-new-interfaces-sqlite3_bind_pointer-sqlite3_resu.patch and re-generates third_party/sqlite/amalgamation/* using the script at third_party/sqlite/google_generate_amalgamation.sh. The CL also adds a layout test that verifies the patch works as intended. BUG=742407 Change-Id: I2e1a457459cd2e975e6241b630e7b79c82545981 Reviewed-on: https://chromium-review.googlesource.com/572976 Reviewed-by: Chris Mumford <[email protected]> Commit-Queue: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#487275}
static Bitmask columnsInIndex(Index *pIdx){ Bitmask m = 0; int j; for(j=pIdx->nColumn-1; j>=0; j--){ int x = pIdx->aiColumn[j]; if( x>=0 ){ testcase( x==BMS-1 ); testcase( x==BMS-2 ); if( x<BMS-1 ) m |= MASKBIT(x); } } return m; }
static Bitmask columnsInIndex(Index *pIdx){ Bitmask m = 0; int j; for(j=pIdx->nColumn-1; j>=0; j--){ int x = pIdx->aiColumn[j]; if( x>=0 ){ testcase( x==BMS-1 ); testcase( x==BMS-2 ); if( x<BMS-1 ) m |= MASKBIT(x); } } return m; }
C
Chrome
0
CVE-2016-4071
https://www.cvedetails.com/cve/CVE-2016-4071/
CWE-20
https://git.php.net/?p=php-src.git;a=commit;h=6e25966544fb1d2f3d7596e060ce9c9269bbdcf8
6e25966544fb1d2f3d7596e060ce9c9269bbdcf8
null
PHP_FUNCTION(snmprealwalk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_1); }
PHP_FUNCTION(snmprealwalk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_1); }
C
php
0
CVE-2017-9059
https://www.cvedetails.com/cve/CVE-2017-9059/
CWE-404
https://github.com/torvalds/linux/commit/c70422f760c120480fee4de6c38804c72aa26bc1
c70422f760c120480fee4de6c38804c72aa26bc1
Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ...
static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols) { if (ols->st_stateowner->so_is_open_owner && !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED)) return nfserr_bad_stateid; return nfs_ok; }
static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols) { if (ols->st_stateowner->so_is_open_owner && !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED)) return nfserr_bad_stateid; return nfs_ok; }
C
linux
0
CVE-2018-18352
https://www.cvedetails.com/cve/CVE-2018-18352/
CWE-732
https://github.com/chromium/chromium/commit/a9cbaa7a40e2b2723cfc2f266c42f4980038a949
a9cbaa7a40e2b2723cfc2f266c42f4980038a949
Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258}
void WebMediaPlayerImpl::OnVideoAverageKeyframeDistanceUpdate() { UpdateBackgroundVideoOptimizationState(); }
void WebMediaPlayerImpl::OnVideoAverageKeyframeDistanceUpdate() { UpdateBackgroundVideoOptimizationState(); }
C
Chrome
0
CVE-2018-6151
https://www.cvedetails.com/cve/CVE-2018-6151/
CWE-125
https://github.com/chromium/chromium/commit/cbb2c0940d4e3914ccd74f6466ff4cb9e50e0e86
cbb2c0940d4e3914ccd74f6466ff4cb9e50e0e86
Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate. DownloadManager has public SetDelegate method and tests and or other subsystems can install their own implementations of the delegate. Bug: 805905 Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8 TBR: tests updated to follow the API change. Reviewed-on: https://chromium-review.googlesource.com/894702 Reviewed-by: David Vallet <[email protected]> Reviewed-by: Min Qin <[email protected]> Cr-Commit-Position: refs/heads/master@{#533515}
void BlockUntilOriginDataRemoved( const base::Time& delete_begin, const base::Time& delete_end, int remove_mask, std::unique_ptr<BrowsingDataFilterBuilder> filter_builder) { content::BrowsingDataRemoverCompletionObserver completion_observer( remover_); remover_->RemoveWithFilterAndReply( delete_begin, delete_end, remove_mask, content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, std::move(filter_builder), &completion_observer); base::TaskScheduler::GetInstance()->FlushForTesting(); completion_observer.BlockUntilCompletion(); }
void BlockUntilOriginDataRemoved( const base::Time& delete_begin, const base::Time& delete_end, int remove_mask, std::unique_ptr<BrowsingDataFilterBuilder> filter_builder) { content::BrowsingDataRemoverCompletionObserver completion_observer( remover_); remover_->RemoveWithFilterAndReply( delete_begin, delete_end, remove_mask, content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, std::move(filter_builder), &completion_observer); base::TaskScheduler::GetInstance()->FlushForTesting(); completion_observer.BlockUntilCompletion(); }
C
Chrome
0
CVE-2015-4644
https://www.cvedetails.com/cve/CVE-2015-4644/
null
https://git.php.net/?p=php-src.git;a=commit;h=2cc4e69cc6d8dbc4b3568ad3dd583324a7c11d64
2cc4e69cc6d8dbc4b3568ad3dd583324a7c11d64
null
static void _php_pgsql_notice_handler(void *resource_id, const char *message) { php_pgsql_notice *notice; TSRMLS_FETCH(); if (! PGG(ignore_notices)) { notice = (php_pgsql_notice *)emalloc(sizeof(php_pgsql_notice)); notice->message = _php_pgsql_trim_message(message, (int *)&notice->len); if (PGG(log_notices)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s", notice->message); } zend_hash_index_update(&PGG(notices), (ulong)resource_id, (void **)&notice, sizeof(php_pgsql_notice *), NULL); } }
static void _php_pgsql_notice_handler(void *resource_id, const char *message) { php_pgsql_notice *notice; TSRMLS_FETCH(); if (! PGG(ignore_notices)) { notice = (php_pgsql_notice *)emalloc(sizeof(php_pgsql_notice)); notice->message = _php_pgsql_trim_message(message, (int *)&notice->len); if (PGG(log_notices)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s", notice->message); } zend_hash_index_update(&PGG(notices), (ulong)resource_id, (void **)&notice, sizeof(php_pgsql_notice *), NULL); } }
C
php
0
CVE-2011-2875
https://www.cvedetails.com/cve/CVE-2011-2875/
CWE-20
https://github.com/chromium/chromium/commit/ab5e55ff333def909d025ac45da9ffa0d88a63f2
ab5e55ff333def909d025ac45da9ffa0d88a63f2
Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
RTCVoidRequestImpl::~RTCVoidRequestImpl() { }
RTCVoidRequestImpl::~RTCVoidRequestImpl() { }
C
Chrome
0
CVE-2014-7822
https://www.cvedetails.com/cve/CVE-2014-7822/
CWE-264
https://github.com/torvalds/linux/commit/8d0207652cbe27d1f962050737848e5ad4671958
8d0207652cbe27d1f962050737848e5ad4671958
->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]>
static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma) { int err; err = generic_file_mmap(file, vma); if (err) return err; vma->vm_ops = &ubifs_file_vm_ops; return 0; }
static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma) { int err; err = generic_file_mmap(file, vma); if (err) return err; vma->vm_ops = &ubifs_file_vm_ops; return 0; }
C
linux
0
CVE-2017-8065
https://www.cvedetails.com/cve/CVE-2017-8065/
CWE-119
https://github.com/torvalds/linux/commit/3b30460c5b0ed762be75a004e924ec3f8711e032
3b30460c5b0ed762be75a004e924ec3f8711e032
crypto: ccm - move cbcmac input off the stack Commit f15f05b0a5de ("crypto: ccm - switch to separate cbcmac driver") refactored the CCM driver to allow separate implementations of the underlying MAC to be provided by a platform. However, in doing so, it moved some data from the linear region to the stack, which violates the SG constraints when the stack is virtually mapped. So move idata/odata back to the request ctx struct, of which we can reasonably expect that it has been allocated using kmalloc() et al. Reported-by: Johannes Berg <[email protected]> Fixes: f15f05b0a5de ("crypto: ccm - switch to separate cbcmac driver") Signed-off-by: Ard Biesheuvel <[email protected]> Tested-by: Johannes Berg <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
static int crypto_ccm_auth(struct aead_request *req, struct scatterlist *plain, unsigned int cryptlen) { struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); AHASH_REQUEST_ON_STACK(ahreq, ctx->mac); unsigned int assoclen = req->assoclen; struct scatterlist sg[3]; u8 *odata = pctx->odata; u8 *idata = pctx->idata; int ilen, err; /* format control data for input */ err = format_input(odata, req, cryptlen); if (err) goto out; sg_init_table(sg, 3); sg_set_buf(&sg[0], odata, 16); /* format associated data and compute into mac */ if (assoclen) { ilen = format_adata(idata, assoclen); sg_set_buf(&sg[1], idata, ilen); sg_chain(sg, 3, req->src); } else { ilen = 0; sg_chain(sg, 2, req->src); } ahash_request_set_tfm(ahreq, ctx->mac); ahash_request_set_callback(ahreq, pctx->flags, NULL, NULL); ahash_request_set_crypt(ahreq, sg, NULL, assoclen + ilen + 16); err = crypto_ahash_init(ahreq); if (err) goto out; err = crypto_ahash_update(ahreq); if (err) goto out; /* we need to pad the MAC input to a round multiple of the block size */ ilen = 16 - (assoclen + ilen) % 16; if (ilen < 16) { memset(idata, 0, ilen); sg_init_table(sg, 2); sg_set_buf(&sg[0], idata, ilen); if (plain) sg_chain(sg, 2, plain); plain = sg; cryptlen += ilen; } ahash_request_set_crypt(ahreq, plain, pctx->odata, cryptlen); err = crypto_ahash_finup(ahreq); out: return err; }
static int crypto_ccm_auth(struct aead_request *req, struct scatterlist *plain, unsigned int cryptlen) { struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); AHASH_REQUEST_ON_STACK(ahreq, ctx->mac); unsigned int assoclen = req->assoclen; struct scatterlist sg[3]; u8 odata[16]; u8 idata[16]; int ilen, err; /* format control data for input */ err = format_input(odata, req, cryptlen); if (err) goto out; sg_init_table(sg, 3); sg_set_buf(&sg[0], odata, 16); /* format associated data and compute into mac */ if (assoclen) { ilen = format_adata(idata, assoclen); sg_set_buf(&sg[1], idata, ilen); sg_chain(sg, 3, req->src); } else { ilen = 0; sg_chain(sg, 2, req->src); } ahash_request_set_tfm(ahreq, ctx->mac); ahash_request_set_callback(ahreq, pctx->flags, NULL, NULL); ahash_request_set_crypt(ahreq, sg, NULL, assoclen + ilen + 16); err = crypto_ahash_init(ahreq); if (err) goto out; err = crypto_ahash_update(ahreq); if (err) goto out; /* we need to pad the MAC input to a round multiple of the block size */ ilen = 16 - (assoclen + ilen) % 16; if (ilen < 16) { memset(idata, 0, ilen); sg_init_table(sg, 2); sg_set_buf(&sg[0], idata, ilen); if (plain) sg_chain(sg, 2, plain); plain = sg; cryptlen += ilen; } ahash_request_set_crypt(ahreq, plain, pctx->odata, cryptlen); err = crypto_ahash_finup(ahreq); out: return err; }
C
linux
1
CVE-2016-6787
https://www.cvedetails.com/cve/CVE-2016-6787/
CWE-264
https://github.com/torvalds/linux/commit/f63a8daa5812afef4f06c962351687e1ff9ccb2b
f63a8daa5812afef4f06c962351687e1ff9ccb2b
perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>
void update_perf_cpu_limits(void) { u64 tmp = perf_sample_period_ns; tmp *= sysctl_perf_cpu_time_max_percent; do_div(tmp, 100); ACCESS_ONCE(perf_sample_allowed_ns) = tmp; }
void update_perf_cpu_limits(void) { u64 tmp = perf_sample_period_ns; tmp *= sysctl_perf_cpu_time_max_percent; do_div(tmp, 100); ACCESS_ONCE(perf_sample_allowed_ns) = tmp; }
C
linux
0
CVE-2017-9375
https://www.cvedetails.com/cve/CVE-2017-9375/
CWE-835
https://git.qemu.org/?p=qemu.git;a=commit;h=96d87bdda3919bb16f754b3d3fd1227e1f38f13c
96d87bdda3919bb16f754b3d3fd1227e1f38f13c
null
static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size) { XHCIState *xhci = ptr; uint32_t ret; switch (reg) { case 0x00: /* HCIVERSION, CAPLENGTH */ ret = 0x01000000 | LEN_CAP; break; case 0x04: /* HCSPARAMS 1 */ ret = ((xhci->numports_2+xhci->numports_3)<<24) | (xhci->numintrs<<8) | xhci->numslots; break; case 0x08: /* HCSPARAMS 2 */ ret = 0x0000000f; break; case 0x0c: /* HCSPARAMS 3 */ ret = 0x00000000; break; case 0x10: /* HCCPARAMS */ if (sizeof(dma_addr_t) == 4) { ret = 0x00080000 | (xhci->max_pstreams_mask << 12); } else { ret = 0x00080001 | (xhci->max_pstreams_mask << 12); } break; case 0x14: /* DBOFF */ ret = OFF_DOORBELL; break; case 0x18: /* RTSOFF */ ret = OFF_RUNTIME; break; /* extended capabilities */ case 0x20: /* Supported Protocol:00 */ ret = 0x02000402; /* USB 2.0 */ break; case 0x24: /* Supported Protocol:04 */ ret = 0x20425355; /* "USB " */ break; case 0x28: /* Supported Protocol:08 */ if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { ret = (xhci->numports_2<<8) | (xhci->numports_3+1); } else { ret = (xhci->numports_2<<8) | 1; } break; case 0x2c: /* Supported Protocol:0c */ ret = 0x00000000; /* reserved */ break; case 0x30: /* Supported Protocol:00 */ ret = 0x03000002; /* USB 3.0 */ break; case 0x34: /* Supported Protocol:04 */ ret = 0x20425355; /* "USB " */ break; case 0x38: /* Supported Protocol:08 */ if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { ret = (xhci->numports_3<<8) | 1; } else { ret = (xhci->numports_3<<8) | (xhci->numports_2+1); } break; case 0x3c: /* Supported Protocol:0c */ ret = 0x00000000; /* reserved */ break; default: trace_usb_xhci_unimplemented("cap read", reg); ret = 0; } trace_usb_xhci_cap_read(reg, ret); return ret; }
static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size) { XHCIState *xhci = ptr; uint32_t ret; switch (reg) { case 0x00: /* HCIVERSION, CAPLENGTH */ ret = 0x01000000 | LEN_CAP; break; case 0x04: /* HCSPARAMS 1 */ ret = ((xhci->numports_2+xhci->numports_3)<<24) | (xhci->numintrs<<8) | xhci->numslots; break; case 0x08: /* HCSPARAMS 2 */ ret = 0x0000000f; break; case 0x0c: /* HCSPARAMS 3 */ ret = 0x00000000; break; case 0x10: /* HCCPARAMS */ if (sizeof(dma_addr_t) == 4) { ret = 0x00080000 | (xhci->max_pstreams_mask << 12); } else { ret = 0x00080001 | (xhci->max_pstreams_mask << 12); } break; case 0x14: /* DBOFF */ ret = OFF_DOORBELL; break; case 0x18: /* RTSOFF */ ret = OFF_RUNTIME; break; /* extended capabilities */ case 0x20: /* Supported Protocol:00 */ ret = 0x02000402; /* USB 2.0 */ break; case 0x24: /* Supported Protocol:04 */ ret = 0x20425355; /* "USB " */ break; case 0x28: /* Supported Protocol:08 */ if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { ret = (xhci->numports_2<<8) | (xhci->numports_3+1); } else { ret = (xhci->numports_2<<8) | 1; } break; case 0x2c: /* Supported Protocol:0c */ ret = 0x00000000; /* reserved */ break; case 0x30: /* Supported Protocol:00 */ ret = 0x03000002; /* USB 3.0 */ break; case 0x34: /* Supported Protocol:04 */ ret = 0x20425355; /* "USB " */ break; case 0x38: /* Supported Protocol:08 */ if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) { ret = (xhci->numports_3<<8) | 1; } else { ret = (xhci->numports_3<<8) | (xhci->numports_2+1); } break; case 0x3c: /* Supported Protocol:0c */ ret = 0x00000000; /* reserved */ break; default: trace_usb_xhci_unimplemented("cap read", reg); ret = 0; } trace_usb_xhci_cap_read(reg, ret); return ret; }
C
qemu
0
CVE-2015-1232
https://www.cvedetails.com/cve/CVE-2015-1232/
CWE-119
https://github.com/chromium/chromium/commit/5576cbc1d3e214dfbb5d3ffcdbe82aa8ba0088fc
5576cbc1d3e214dfbb5d3ffcdbe82aa8ba0088fc
MidiManagerUsb should not trust indices provided by renderer. MidiManagerUsb::DispatchSendMidiData takes |port_index| parameter. As it is provided by a renderer possibly under the control of an attacker, we must validate the given index before using it. BUG=456516 Review URL: https://codereview.chromium.org/907793002 Cr-Commit-Position: refs/heads/master@{#315303}
void Finalize() { manager_->EndSession(client_.get()); }
void Finalize() { manager_->EndSession(client_.get()); }
C
Chrome
0
CVE-2016-10166
https://www.cvedetails.com/cve/CVE-2016-10166/
CWE-191
https://github.com/libgd/libgd/commit/60bfb401ad5a4a8ae995dcd36372fe15c71e1a35
60bfb401ad5a4a8ae995dcd36372fe15c71e1a35
Fix potential unsigned underflow No need to decrease `u`, so we don't do it. While we're at it, we also factor out the overflow check of the loop, what improves performance and readability. This issue has been reported by Stefan Esser to [email protected].
BGD_DECLARE(int) gdTransformAffineGetImage(gdImagePtr *dst, const gdImagePtr src, gdRectPtr src_area, const double affine[6]) { int res; double m[6]; gdRect bbox; gdRect area_full; if (src_area == NULL) { area_full.x = 0; area_full.y = 0; area_full.width = gdImageSX(src); area_full.height = gdImageSY(src); src_area = &area_full; } gdTransformAffineBoundingBox(src_area, affine, &bbox); *dst = gdImageCreateTrueColor(bbox.width, bbox.height); if (*dst == NULL) { return GD_FALSE; } (*dst)->saveAlphaFlag = 1; if (!src->trueColor) { gdImagePaletteToTrueColor(src); } /* Translate to dst origin (0,0) */ gdAffineTranslate(m, -bbox.x, -bbox.y); gdAffineConcat(m, affine, m); gdImageAlphaBlending(*dst, 0); res = gdTransformAffineCopy(*dst, 0,0, src, src_area, m); if (res != GD_TRUE) { gdImageDestroy(*dst); *dst = NULL; return GD_FALSE; } else { return GD_TRUE; } }
BGD_DECLARE(int) gdTransformAffineGetImage(gdImagePtr *dst, const gdImagePtr src, gdRectPtr src_area, const double affine[6]) { int res; double m[6]; gdRect bbox; gdRect area_full; if (src_area == NULL) { area_full.x = 0; area_full.y = 0; area_full.width = gdImageSX(src); area_full.height = gdImageSY(src); src_area = &area_full; } gdTransformAffineBoundingBox(src_area, affine, &bbox); *dst = gdImageCreateTrueColor(bbox.width, bbox.height); if (*dst == NULL) { return GD_FALSE; } (*dst)->saveAlphaFlag = 1; if (!src->trueColor) { gdImagePaletteToTrueColor(src); } /* Translate to dst origin (0,0) */ gdAffineTranslate(m, -bbox.x, -bbox.y); gdAffineConcat(m, affine, m); gdImageAlphaBlending(*dst, 0); res = gdTransformAffineCopy(*dst, 0,0, src, src_area, m); if (res != GD_TRUE) { gdImageDestroy(*dst); *dst = NULL; return GD_FALSE; } else { return GD_TRUE; } }
C
libgd
0
CVE-2018-16425
https://www.cvedetails.com/cve/CVE-2018-16425/
CWE-415
https://github.com/OpenSC/OpenSC/commit/360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.
static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; }
static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; }
C
OpenSC
0
null
null
null
https://github.com/chromium/chromium/commit/b051cdb6465736e7233cd22b807e255554378206
b051cdb6465736e7233cd22b807e255554378206
OpenSSL: don't allow the server certificate to change during renegotiation. This mirrors r229611, but for OpenSSL. BUG=306959 Review URL: https://codereview.chromium.org/177143004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@254022 0039d316-1c4b-4281-b951-d872f2087c98
int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) { return ERR_NOT_IMPLEMENTED; }
int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) { return ERR_NOT_IMPLEMENTED; }
C
Chrome
0
CVE-2016-5220
https://www.cvedetails.com/cve/CVE-2016-5220/
CWE-200
https://github.com/chromium/chromium/commit/c6f0d22d508a551a40fc8bd7418941b77435aac3
c6f0d22d508a551a40fc8bd7418941b77435aac3
omnibox: experiment with restoring placeholder when caret shows Shows the "Search Google or type a URL" omnibox placeholder even when the caret (text edit cursor) is showing / when focused. views::Textfield works this way, as does <input placeholder="">. Omnibox and the NTP's "fakebox" are exceptions in this regard and this experiment makes this more consistent. [email protected] BUG=955585 Change-Id: I23c299c0973f2feb43f7a2be3bd3425a80b06c2d Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1582315 Commit-Queue: Dan Beam <[email protected]> Reviewed-by: Tommy Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#654279}
void OmniboxViewViews::OnCompositingEnded(ui::Compositor* compositor) { if (latency_histogram_state_ == COMPOSITING_STARTED) { DCHECK(!insert_char_time_.is_null()); UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency", base::TimeTicks::Now() - insert_char_time_); insert_char_time_ = base::TimeTicks(); latency_histogram_state_ = NOT_ACTIVE; } }
void OmniboxViewViews::OnCompositingEnded(ui::Compositor* compositor) { if (latency_histogram_state_ == COMPOSITING_STARTED) { DCHECK(!insert_char_time_.is_null()); UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency", base::TimeTicks::Now() - insert_char_time_); insert_char_time_ = base::TimeTicks(); latency_histogram_state_ = NOT_ACTIVE; } }
C
Chrome
0
CVE-2011-4112
https://www.cvedetails.com/cve/CVE-2011-4112/
CWE-264
https://github.com/torvalds/linux/commit/550fd08c2cebad61c548def135f67aba284c6162
550fd08c2cebad61c548def135f67aba284c6162
net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]>
isdn_net_adjust_hdr(struct sk_buff *skb, struct net_device *dev) { isdn_net_local *lp = netdev_priv(dev); if (!skb) return; if (lp->p_encap == ISDN_NET_ENCAP_ETHER) { const int pullsize = skb_network_offset(skb) - ETH_HLEN; if (pullsize > 0) { printk(KERN_DEBUG "isdn_net: Pull junk %d\n", pullsize); skb_pull(skb, pullsize); } } }
isdn_net_adjust_hdr(struct sk_buff *skb, struct net_device *dev) { isdn_net_local *lp = netdev_priv(dev); if (!skb) return; if (lp->p_encap == ISDN_NET_ENCAP_ETHER) { const int pullsize = skb_network_offset(skb) - ETH_HLEN; if (pullsize > 0) { printk(KERN_DEBUG "isdn_net: Pull junk %d\n", pullsize); skb_pull(skb, pullsize); } } }
C
linux
0
CVE-2019-10664
https://www.cvedetails.com/cve/CVE-2019-10664/
CWE-89
https://github.com/domoticz/domoticz/commit/ee70db46f81afa582c96b887b73bcd2a86feda00
ee70db46f81afa582c96b887b73bcd2a86feda00
Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
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] = "&lt; 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] = "&gt; 10" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_KMH) { szLegendLabels[0] = "&lt; 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] = "&gt; 36" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_MPH) { szLegendLabels[0] = "&lt; 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] = "&gt; 46" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_Knots) { szLegendLabels[0] = "&lt; 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] = "&gt; 41" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_Beaufort) { szLegendLabels[0] = "&lt; 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] = "&gt; 12" + m_sql.m_windsign; } else { szLegendLabels[0] = "&lt; 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] = "&gt; 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 }
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] = "&lt; 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] = "&gt; 10" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_KMH) { szLegendLabels[0] = "&lt; 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] = "&gt; 36" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_MPH) { szLegendLabels[0] = "&lt; 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] = "&gt; 46" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_Knots) { szLegendLabels[0] = "&lt; 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] = "&gt; 41" + m_sql.m_windsign; } else if (m_sql.m_windunit == WINDUNIT_Beaufort) { szLegendLabels[0] = "&lt; 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] = "&gt; 12" + m_sql.m_windsign; } else { szLegendLabels[0] = "&lt; 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] = "&gt; 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 }
C
domoticz
0
CVE-2018-6063
https://www.cvedetails.com/cve/CVE-2018-6063/
CWE-787
https://github.com/chromium/chromium/commit/673ce95d481ea9368c4d4d43ac756ba1d6d9e608
673ce95d481ea9368c4d4d43ac756ba1d6d9e608
Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268}
void RenderProcessHostImpl::RemoveFrameWithSite( BrowserContext* browser_context, RenderProcessHost* render_process_host, const GURL& site_url) { if (!ShouldTrackProcessForSite(browser_context, render_process_host, site_url)) return; SiteProcessCountTracker* tracker = static_cast<SiteProcessCountTracker*>( browser_context->GetUserData(kCommittedSiteProcessCountTrackerKey)); if (!tracker) { tracker = new SiteProcessCountTracker(); browser_context->SetUserData(kCommittedSiteProcessCountTrackerKey, base::WrapUnique(tracker)); } tracker->DecrementSiteProcessCount(site_url, render_process_host->GetID()); }
void RenderProcessHostImpl::RemoveFrameWithSite( BrowserContext* browser_context, RenderProcessHost* render_process_host, const GURL& site_url) { if (!ShouldTrackProcessForSite(browser_context, render_process_host, site_url)) return; SiteProcessCountTracker* tracker = static_cast<SiteProcessCountTracker*>( browser_context->GetUserData(kCommittedSiteProcessCountTrackerKey)); if (!tracker) { tracker = new SiteProcessCountTracker(); browser_context->SetUserData(kCommittedSiteProcessCountTrackerKey, base::WrapUnique(tracker)); } tracker->DecrementSiteProcessCount(site_url, render_process_host->GetID()); }
C
Chrome
0
CVE-2016-9446
https://www.cvedetails.com/cve/CVE-2016-9446/
CWE-200
https://cgit.freedesktop.org/gstreamer/gst-plugins-bad/commit/gst/vmnc/vmncdec.c?id=4cb1bcf1422bbcd79c0f683edb7ee85e3f7a31fe
4cb1bcf1422bbcd79c0f683edb7ee85e3f7a31fe
null
plugin_init (GstPlugin * plugin) { if (!gst_element_register (plugin, "vmncdec", GST_RANK_PRIMARY, GST_TYPE_VMNC_DEC)) return FALSE; return TRUE; }
plugin_init (GstPlugin * plugin) { if (!gst_element_register (plugin, "vmncdec", GST_RANK_PRIMARY, GST_TYPE_VMNC_DEC)) return FALSE; return TRUE; }
C
gstreamer
0
CVE-2016-5219
https://www.cvedetails.com/cve/CVE-2016-5219/
CWE-416
https://github.com/chromium/chromium/commit/a4150b688a754d3d10d2ca385155b1c95d77d6ae
a4150b688a754d3d10d2ca385155b1c95d77d6ae
Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568}
bool GLES2DecoderImpl::DeletePathsCHROMIUMHelper(GLuint first_client_id, GLsizei range) { GLuint last_client_id; if (range < 1 || !base::CheckAdd(first_client_id, range - 1) .AssignIfValid(&last_client_id)) return false; path_manager()->RemovePaths(first_client_id, last_client_id); return true; }
bool GLES2DecoderImpl::DeletePathsCHROMIUMHelper(GLuint first_client_id, GLsizei range) { GLuint last_client_id; if (range < 1 || !base::CheckAdd(first_client_id, range - 1) .AssignIfValid(&last_client_id)) return false; path_manager()->RemovePaths(first_client_id, last_client_id); return true; }
C
Chrome
0
CVE-2012-5135
https://www.cvedetails.com/cve/CVE-2012-5135/
CWE-399
https://github.com/chromium/chromium/commit/b755ebba29dd405d6f1e4cf70f5bc81ffd33b0f6
b755ebba29dd405d6f1e4cf70f5bc81ffd33b0f6
Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98
bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintNodeUnderContextMenu, OnPrintNodeUnderContextMenu) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_ResetScriptedPrintCount, ResetScriptedPrintCount) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; }
bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintNodeUnderContextMenu, OnPrintNodeUnderContextMenu) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_ResetScriptedPrintCount, ResetScriptedPrintCount) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; }
C
Chrome
0
CVE-2014-9940
https://www.cvedetails.com/cve/CVE-2014-9940/
CWE-416
https://github.com/torvalds/linux/commit/60a2362f769cf549dc466134efe71c8bf9fbaaba
60a2362f769cf549dc466134efe71c8bf9fbaaba
regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[email protected]>
static struct regulator *create_regulator(struct regulator_dev *rdev, struct device *dev, const char *supply_name) { struct regulator *regulator; char buf[REG_STR_SIZE]; int err, size; regulator = kzalloc(sizeof(*regulator), GFP_KERNEL); if (regulator == NULL) return NULL; mutex_lock(&rdev->mutex); regulator->rdev = rdev; list_add(&regulator->list, &rdev->consumer_list); if (dev) { regulator->dev = dev; /* Add a link to the device sysfs entry */ size = scnprintf(buf, REG_STR_SIZE, "%s-%s", dev->kobj.name, supply_name); if (size >= REG_STR_SIZE) goto overflow_err; regulator->supply_name = kstrdup(buf, GFP_KERNEL); if (regulator->supply_name == NULL) goto overflow_err; err = sysfs_create_link(&rdev->dev.kobj, &dev->kobj, buf); if (err) { rdev_warn(rdev, "could not add device link %s err %d\n", dev->kobj.name, err); /* non-fatal */ } } else { regulator->supply_name = kstrdup(supply_name, GFP_KERNEL); if (regulator->supply_name == NULL) goto overflow_err; } regulator->debugfs = debugfs_create_dir(regulator->supply_name, rdev->debugfs); if (!regulator->debugfs) { rdev_warn(rdev, "Failed to create debugfs directory\n"); } else { debugfs_create_u32("uA_load", 0444, regulator->debugfs, &regulator->uA_load); debugfs_create_u32("min_uV", 0444, regulator->debugfs, &regulator->min_uV); debugfs_create_u32("max_uV", 0444, regulator->debugfs, &regulator->max_uV); } /* * Check now if the regulator is an always on regulator - if * it is then we don't need to do nearly so much work for * enable/disable calls. */ if (!_regulator_can_change_status(rdev) && _regulator_is_enabled(rdev)) regulator->always_on = true; mutex_unlock(&rdev->mutex); return regulator; overflow_err: list_del(&regulator->list); kfree(regulator); mutex_unlock(&rdev->mutex); return NULL; }
static struct regulator *create_regulator(struct regulator_dev *rdev, struct device *dev, const char *supply_name) { struct regulator *regulator; char buf[REG_STR_SIZE]; int err, size; regulator = kzalloc(sizeof(*regulator), GFP_KERNEL); if (regulator == NULL) return NULL; mutex_lock(&rdev->mutex); regulator->rdev = rdev; list_add(&regulator->list, &rdev->consumer_list); if (dev) { regulator->dev = dev; /* Add a link to the device sysfs entry */ size = scnprintf(buf, REG_STR_SIZE, "%s-%s", dev->kobj.name, supply_name); if (size >= REG_STR_SIZE) goto overflow_err; regulator->supply_name = kstrdup(buf, GFP_KERNEL); if (regulator->supply_name == NULL) goto overflow_err; err = sysfs_create_link(&rdev->dev.kobj, &dev->kobj, buf); if (err) { rdev_warn(rdev, "could not add device link %s err %d\n", dev->kobj.name, err); /* non-fatal */ } } else { regulator->supply_name = kstrdup(supply_name, GFP_KERNEL); if (regulator->supply_name == NULL) goto overflow_err; } regulator->debugfs = debugfs_create_dir(regulator->supply_name, rdev->debugfs); if (!regulator->debugfs) { rdev_warn(rdev, "Failed to create debugfs directory\n"); } else { debugfs_create_u32("uA_load", 0444, regulator->debugfs, &regulator->uA_load); debugfs_create_u32("min_uV", 0444, regulator->debugfs, &regulator->min_uV); debugfs_create_u32("max_uV", 0444, regulator->debugfs, &regulator->max_uV); } /* * Check now if the regulator is an always on regulator - if * it is then we don't need to do nearly so much work for * enable/disable calls. */ if (!_regulator_can_change_status(rdev) && _regulator_is_enabled(rdev)) regulator->always_on = true; mutex_unlock(&rdev->mutex); return regulator; overflow_err: list_del(&regulator->list); kfree(regulator); mutex_unlock(&rdev->mutex); return NULL; }
C
linux
0
CVE-2013-7421
https://www.cvedetails.com/cve/CVE-2013-7421/
CWE-264
https://github.com/torvalds/linux/commit/5d26a105b5a73e5635eae0629b42fa0a90e07b7b
5d26a105b5a73e5635eae0629b42fa0a90e07b7b
crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
static void __exit sha1_powerpc_mod_fini(void) { crypto_unregister_shash(&alg); }
static void __exit sha1_powerpc_mod_fini(void) { crypto_unregister_shash(&alg); }
C
linux
0
CVE-2017-6439
https://www.cvedetails.com/cve/CVE-2017-6439/
CWE-787
https://github.com/libimobiledevice/libplist/commit/32ee5213fe64f1e10ec76c1ee861ee6f233120dd
32ee5213fe64f1e10ec76c1ee861ee6f233120dd
bplist: Fix data range check for string/data/dict/array nodes Passing a size of 0xFFFFFFFFFFFFFFFF to parse_string_node() might result in a memcpy with a size of -1, leading to undefined behavior. This commit makes sure that the actual node data (which depends on the size) is in the range start_of_object..start_of_object+size. Credit to OSS-Fuzz
static plist_t parse_unicode_node(const char **bnode, uint64_t size) { plist_data_t data = plist_new_plist_data(); uint64_t i = 0; uint16_t *unicodestr = NULL; char *tmpstr = NULL; long items_read = 0; long items_written = 0; data->type = PLIST_STRING; unicodestr = (uint16_t*) malloc(sizeof(uint16_t) * size); if (!unicodestr) { plist_free_data(data); PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(uint16_t) * size); return NULL; } for (i = 0; i < size; i++) unicodestr[i] = be16toh(((uint16_t*)*bnode)[i]); tmpstr = plist_utf16_to_utf8(unicodestr, size, &items_read, &items_written); free(unicodestr); if (!tmpstr) { plist_free_data(data); return NULL; } tmpstr[items_written] = '\0'; data->type = PLIST_STRING; data->strval = realloc(tmpstr, items_written+1); if (!data->strval) data->strval = tmpstr; data->length = items_written; return node_create(NULL, data); }
static plist_t parse_unicode_node(const char **bnode, uint64_t size) { plist_data_t data = plist_new_plist_data(); uint64_t i = 0; uint16_t *unicodestr = NULL; char *tmpstr = NULL; long items_read = 0; long items_written = 0; data->type = PLIST_STRING; unicodestr = (uint16_t*) malloc(sizeof(uint16_t) * size); if (!unicodestr) { plist_free_data(data); PLIST_BIN_ERR("%s: Could not allocate %" PRIu64 " bytes\n", __func__, sizeof(uint16_t) * size); return NULL; } for (i = 0; i < size; i++) unicodestr[i] = be16toh(((uint16_t*)*bnode)[i]); tmpstr = plist_utf16_to_utf8(unicodestr, size, &items_read, &items_written); free(unicodestr); if (!tmpstr) { plist_free_data(data); return NULL; } tmpstr[items_written] = '\0'; data->type = PLIST_STRING; data->strval = realloc(tmpstr, items_written+1); if (!data->strval) data->strval = tmpstr; data->length = items_written; return node_create(NULL, data); }
C
libplist
0
null
null
null
https://github.com/chromium/chromium/commit/27c68f543e5eba779902447445dfb05ec3f5bf75
27c68f543e5eba779902447445dfb05ec3f5bf75
Revert of Add accelerated VP9 decode infrastructure and an implementation for VA-API. (patchset #7 id:260001 of https://codereview.chromium.org/1318863003/ ) Reason for revert: I think this patch broke compile step for Chromium Linux ChromeOS MSan Builder. First failing build: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20Linux%20ChromeOS%20MSan%20Builder/builds/8310 All recent builds: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20Linux%20ChromeOS%20MSan%20Builder?numbuilds=200 Sorry for the revert. I'll re-revert if I'm wrong. Cheers, Tommy Original issue's description: > Add accelerated VP9 decode infrastructure and an implementation for VA-API. > > - Add a hardware/platform-independent VP9Decoder class and related > infrastructure, implementing AcceleratedVideoDecoder interface. VP9Decoder > performs the initial stages of the decode process, which are to be done > on host/in software, such as stream parsing and reference frame management. > > - Add a VP9Accelerator interface, used by the VP9Decoder to offload the > remaining stages of the decode process to hardware. VP9Accelerator > implementations are platform-specific. > > - Add the first implementation of VP9Accelerator - VaapiVP9Accelerator - and > integrate it with VaapiVideoDecodeAccelerator, for devices which provide > hardware VP9 acceleration through VA-API. Hook it up to the new > infrastructure and VP9Decoder. > > - Extend Vp9Parser to provide functionality required by VP9Decoder and > VP9Accelerator, including superframe parsing, handling of loop filter > and segmentation initialization, state persistence across frames and > resetting when needed. Also add code calculating segmentation dequants > and loop filter levels. > > - Update vp9_parser_unittest to the new Vp9Parser interface and flow. > > TEST=vp9_parser_unittest,vda_unittest,Chrome VP9 playback > BUG=chrome-os-partner:41469,chrome-os-partner:41470,chromium:525331 > [email protected] > > Committed: https://crrev.com/e3cc0a661b8abfdc74f569940949bc1f336ece40 > Cr-Commit-Position: refs/heads/master@{#349312} [email protected],[email protected],[email protected],[email protected],[email protected] NOPRESUBMIT=true NOTREECHECKS=true NOTRY=true BUG=chrome-os-partner:41469,chrome-os-partner:41470,chromium:525331 Review URL: https://codereview.chromium.org/1357513002 Cr-Commit-Position: refs/heads/master@{#349443}
bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture(
bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( const scoped_refptr<VP9Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP9PictureToVaapiDecodeSurface(pic); vaapi_dec_->SurfaceReady(dec_surface); return true; }
C
Chrome
1
CVE-2017-9211
https://www.cvedetails.com/cve/CVE-2017-9211/
CWE-476
https://github.com/torvalds/linux/commit/9933e113c2e87a9f46a40fde8dafbf801dca1ab9
9933e113c2e87a9f46a40fde8dafbf801dca1ab9
crypto: skcipher - Add missing API setkey checks The API setkey checks for key sizes and alignment went AWOL during the skcipher conversion. This patch restores them. Cc: <[email protected]> Fixes: 4e6c3df4d729 ("crypto: skcipher - Add low-level skcipher...") Reported-by: Baozeng <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { spawn->base.frontend = &crypto_skcipher_type2; return crypto_grab_spawn(&spawn->base, name, type, mask); }
int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { spawn->base.frontend = &crypto_skcipher_type2; return crypto_grab_spawn(&spawn->base, name, type, mask); }
C
linux
0
CVE-2019-17178
https://www.cvedetails.com/cve/CVE-2019-17178/
CWE-772
https://github.com/akallabeth/FreeRDP/commit/fc80ab45621bd966f70594c0b7393ec005a94007
fc80ab45621bd966f70594c0b7393ec005a94007
Fixed #5645: realloc return handling
static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { size_t i = 0; for(i = 0; i < lz77_encoded->size; i++) { unsigned val = lz77_encoded->data[i]; addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); if(val > 256) /*for a length code, 3 more things have to be added*/ { unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; unsigned length_extra_bits = lz77_encoded->data[++i]; unsigned distance_code = lz77_encoded->data[++i]; unsigned distance_index = distance_code; unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; unsigned distance_extra_bits = lz77_encoded->data[++i]; addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), HuffmanTree_getLength(tree_d, distance_code)); addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); } } }
static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { size_t i = 0; for(i = 0; i < lz77_encoded->size; i++) { unsigned val = lz77_encoded->data[i]; addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); if(val > 256) /*for a length code, 3 more things have to be added*/ { unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; unsigned length_extra_bits = lz77_encoded->data[++i]; unsigned distance_code = lz77_encoded->data[++i]; unsigned distance_index = distance_code; unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; unsigned distance_extra_bits = lz77_encoded->data[++i]; addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), HuffmanTree_getLength(tree_d, distance_code)); addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); } } }
C
FreeRDP
0
CVE-2017-5093
https://www.cvedetails.com/cve/CVE-2017-5093/
CWE-20
https://github.com/chromium/chromium/commit/0720b02e4f303ea6b114d4ae9453e3a7ff55f8dc
0720b02e4f303ea6b114d4ae9453e3a7ff55f8dc
If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884}
std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost( const GURL& url) { return CreateWebUI(url, std::string()); }
std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost( const GURL& url) { return CreateWebUI(url, std::string()); }
C
Chrome
0
CVE-2016-5770
https://www.cvedetails.com/cve/CVE-2016-5770/
CWE-190
https://github.com/php/php-src/commit/7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1
7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1
Fix bug #72262 - do not overflow int
static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */
static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */
C
php-src
1
CVE-2014-3167
https://www.cvedetails.com/cve/CVE-2014-3167/
null
https://github.com/chromium/chromium/commit/44f1431b20c16d8f8da0ce8ff7bbf2adddcdd785
44f1431b20c16d8f8da0ce8ff7bbf2adddcdd785
Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950}
FloatRect SVGLayoutSupport::localOverflowRectForPaintInvalidation(const LayoutObject& object) { ASSERT(!object.isSVGRoot()); if (object.styleRef().visibility() != VISIBLE && !object.enclosingLayer()->hasVisibleContent()) return FloatRect(); FloatRect paintInvalidationRect = object.paintInvalidationRectInLocalSVGCoordinates(); if (int outlineOutset = object.styleRef().outlineOutsetExtent()) paintInvalidationRect.inflate(outlineOutset); return paintInvalidationRect; }
FloatRect SVGLayoutSupport::localOverflowRectForPaintInvalidation(const LayoutObject& object) { ASSERT(!object.isSVGRoot()); if (object.styleRef().visibility() != VISIBLE && !object.enclosingLayer()->hasVisibleContent()) return FloatRect(); FloatRect paintInvalidationRect = object.paintInvalidationRectInLocalSVGCoordinates(); if (int outlineOutset = object.styleRef().outlineOutsetExtent()) paintInvalidationRect.inflate(outlineOutset); return paintInvalidationRect; }
C
Chrome
0
CVE-2012-2890
https://www.cvedetails.com/cve/CVE-2012-2890/
CWE-399
https://github.com/chromium/chromium/commit/a6f7726de20450074a01493e4e85409ce3f2595a
a6f7726de20450074a01493e4e85409ce3f2595a
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
void DocumentLoader::setupForReplace() { if (!mainResourceData()) return; maybeFinishLoadingMultipartContent(); maybeCreateArchive(); m_writer.end(); frameLoader()->setReplacing(); m_gotFirstByte = false; stopLoadingSubresources(); stopLoadingPlugIns(); #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML) clearArchiveResources(); #endif }
void DocumentLoader::setupForReplace() { if (!mainResourceData()) return; maybeFinishLoadingMultipartContent(); maybeCreateArchive(); m_writer.end(); frameLoader()->setReplacing(); m_gotFirstByte = false; stopLoadingSubresources(); stopLoadingPlugIns(); #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML) clearArchiveResources(); #endif }
C
Chrome
0
CVE-2012-1179
https://www.cvedetails.com/cve/CVE-2012-1179/
CWE-264
https://github.com/torvalds/linux/commit/4a1d704194a441bf83c636004a479e01360ec850
4a1d704194a441bf83c636004a479e01360ec850
mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>
sector_t map_swap_page(struct page *page, struct block_device **bdev) { swp_entry_t entry; entry.val = page_private(page); return map_swap_entry(entry, bdev); }
sector_t map_swap_page(struct page *page, struct block_device **bdev) { swp_entry_t entry; entry.val = page_private(page); return map_swap_entry(entry, bdev); }
C
linux
0
null
null
null
https://github.com/chromium/chromium/commit/9d02cda7a634fbd6e53d98091f618057f0174387
9d02cda7a634fbd6e53d98091f618057f0174387
Coverity: Fixing pass by value. CID=101462, 101458, 101437, 101471, 101467 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9006023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@115257 0039d316-1c4b-4281-b951-d872f2087c98
void AdjustComponents(int delta, url_parse::Parsed* parsed) { AdjustComponent(delta, &(parsed->username)); AdjustComponent(delta, &(parsed->password)); AdjustComponent(delta, &(parsed->host)); AdjustComponent(delta, &(parsed->port)); AdjustComponent(delta, &(parsed->path)); AdjustComponent(delta, &(parsed->query)); AdjustComponent(delta, &(parsed->ref)); }
void AdjustComponents(int delta, url_parse::Parsed* parsed) { AdjustComponent(delta, &(parsed->username)); AdjustComponent(delta, &(parsed->password)); AdjustComponent(delta, &(parsed->host)); AdjustComponent(delta, &(parsed->port)); AdjustComponent(delta, &(parsed->path)); AdjustComponent(delta, &(parsed->query)); AdjustComponent(delta, &(parsed->ref)); }
C
Chrome
0
CVE-2012-0045
https://www.cvedetails.com/cve/CVE-2012-0045/
null
https://github.com/torvalds/linux/commit/c2226fc9e87ba3da060e47333657cd6616652b84
c2226fc9e87ba3da060e47333657cd6616652b84
KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]>
static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt, struct tss_segment_32 *tss) { int ret; if (ctxt->ops->set_cr(ctxt, 3, tss->cr3)) return emulate_gp(ctxt, 0); ctxt->_eip = tss->eip; ctxt->eflags = tss->eflags | 2; ctxt->regs[VCPU_REGS_RAX] = tss->eax; ctxt->regs[VCPU_REGS_RCX] = tss->ecx; ctxt->regs[VCPU_REGS_RDX] = tss->edx; ctxt->regs[VCPU_REGS_RBX] = tss->ebx; ctxt->regs[VCPU_REGS_RSP] = tss->esp; ctxt->regs[VCPU_REGS_RBP] = tss->ebp; ctxt->regs[VCPU_REGS_RSI] = tss->esi; ctxt->regs[VCPU_REGS_RDI] = tss->edi; /* * SDM says that segment selectors are loaded before segment * descriptors */ set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS); set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS); /* * Now load segment descriptors. If fault happenes at this stage * it is handled in a context of new task */ ret = load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; }
static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt, struct tss_segment_32 *tss) { int ret; if (ctxt->ops->set_cr(ctxt, 3, tss->cr3)) return emulate_gp(ctxt, 0); ctxt->_eip = tss->eip; ctxt->eflags = tss->eflags | 2; ctxt->regs[VCPU_REGS_RAX] = tss->eax; ctxt->regs[VCPU_REGS_RCX] = tss->ecx; ctxt->regs[VCPU_REGS_RDX] = tss->edx; ctxt->regs[VCPU_REGS_RBX] = tss->ebx; ctxt->regs[VCPU_REGS_RSP] = tss->esp; ctxt->regs[VCPU_REGS_RBP] = tss->ebp; ctxt->regs[VCPU_REGS_RSI] = tss->esi; ctxt->regs[VCPU_REGS_RDI] = tss->edi; /* * SDM says that segment selectors are loaded before segment * descriptors */ set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS); set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS); /* * Now load segment descriptors. If fault happenes at this stage * it is handled in a context of new task */ ret = load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS); if (ret != X86EMUL_CONTINUE) return ret; ret = load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; }
C
linux
0
CVE-2015-7665
https://www.cvedetails.com/cve/CVE-2015-7665/
CWE-200
https://git.savannah.gnu.org/cgit/wget.git/commit/?id=075d7556964f5a871a73c22ac4b69f5361295099
075d7556964f5a871a73c22ac4b69f5361295099
null
ftp_loop_internal (struct url *u, struct fileinfo *f, ccon *con, char **local_file, bool force_full_retrieve) { int count, orig_lp; wgint restval, len = 0, qtyread = 0; char *tms, *locf; const char *tmrate = NULL; uerr_t err; struct_stat st; /* Declare WARC variables. */ bool warc_enabled = (opt.warc_filename != NULL); FILE *warc_tmp = NULL; ip_address *warc_ip = NULL; wgint last_expected_bytes = 0; /* Get the target, and set the name for the message accordingly. */ if ((f == NULL) && (con->target)) { /* Explicit file (like ".listing"). */ locf = con->target; } else { /* URL-derived file. Consider "-O file" name. */ xfree (con->target); con->target = url_file_name (u, NULL); if (!opt.output_document) locf = con->target; else locf = opt.output_document; } /* If the output_document was given, then this check was already done and the file didn't exist. Hence the !opt.output_document */ /* If we receive .listing file it is necessary to determine system type of the ftp server even if opn.noclobber is given. Thus we must ignore opt.noclobber in order to establish connection with the server and get system type. */ if (opt.noclobber && !opt.output_document && file_exists_p (con->target) && !((con->cmd & DO_LIST) && !(con->cmd & DO_RETR))) { logprintf (LOG_VERBOSE, _("File %s already there; not retrieving.\n"), quote (con->target)); /* If the file is there, we suppose it's retrieved OK. */ return RETROK; } /* Remove it if it's a link. */ remove_link (con->target); count = 0; if (con->st & ON_YOUR_OWN) con->st = ON_YOUR_OWN; orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0; /* THE loop. */ do { /* Increment the pass counter. */ ++count; sleep_between_retrievals (count); if (con->st & ON_YOUR_OWN) { con->cmd = 0; con->cmd |= (DO_RETR | LEAVE_PENDING); if (con->csock != -1) con->cmd &= ~ (DO_LOGIN | DO_CWD); else con->cmd |= (DO_LOGIN | DO_CWD); } else /* not on your own */ { if (con->csock != -1) con->cmd &= ~DO_LOGIN; else con->cmd |= DO_LOGIN; if (con->st & DONE_CWD) con->cmd &= ~DO_CWD; else con->cmd |= DO_CWD; } /* For file RETR requests, we can write a WARC record. We record the file contents to a temporary file. */ if (warc_enabled && (con->cmd & DO_RETR) && warc_tmp == NULL) { warc_tmp = warc_tempfile (); if (warc_tmp == NULL) return WARC_TMP_FOPENERR; if (!con->proxy && con->csock != -1) { warc_ip = (ip_address *) alloca (sizeof (ip_address)); socket_ip_address (con->csock, warc_ip, ENDPOINT_PEER); } } /* Decide whether or not to restart. */ if (con->cmd & DO_LIST) restval = 0; else if (force_full_retrieve) restval = 0; else if (opt.start_pos >= 0) restval = opt.start_pos; else if (opt.always_rest && stat (locf, &st) == 0 && S_ISREG (st.st_mode)) /* When -c is used, continue from on-disk size. (Can't use hstat.len even if count>1 because we don't want a failed first attempt to clobber existing data.) */ restval = st.st_size; else if (count > 1) restval = qtyread; /* start where the previous run left off */ else restval = 0; /* Get the current time string. */ tms = datetime_str (time (NULL)); /* Print fetch message, if opt.verbose. */ if (opt.verbose) { char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); char tmp[256]; strcpy (tmp, " "); if (count > 1) sprintf (tmp, _("(try:%2d)"), count); logprintf (LOG_VERBOSE, "--%s-- %s\n %s => %s\n", tms, hurl, tmp, quote (locf)); #ifdef WINDOWS ws_changetitle (hurl); #endif xfree (hurl); } /* Send getftp the proper length, if fileinfo was provided. */ if (f && f->type != FT_SYMLINK) len = f->size; else len = 0; /* If we are working on a WARC record, getftp should also write to the warc_tmp file. */ err = getftp (u, len, &qtyread, restval, con, count, &last_expected_bytes, warc_tmp); if (con->csock == -1) con->st &= ~DONE_CWD; else con->st |= DONE_CWD; switch (err) { case HOSTERR: case CONIMPOSSIBLE: case FWRITEERR: case FOPENERR: case FTPNSFOD: case FTPLOGINC: case FTPNOPASV: case CONTNOTSUPPORTED: case UNLINKERR: case WARC_TMP_FWRITEERR: /* Fatal errors, give up. */ if (warc_tmp != NULL) fclose (warc_tmp); return err; case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR: case WRITEFAILED: case FTPUNKNOWNTYPE: case FTPSYSERR: case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV: case FOPEN_EXCL_ERR: printwhat (count, opt.ntry); /* non-fatal errors */ if (err == FOPEN_EXCL_ERR) { /* Re-determine the file name. */ xfree (con->target); con->target = url_file_name (u, NULL); locf = con->target; } continue; case FTPRETRINT: /* If the control connection was closed, the retrieval will be considered OK if f->size == len. */ if (!f || qtyread != f->size) { printwhat (count, opt.ntry); continue; } break; case RETRFINISHED: /* Great! */ break; default: /* Not as great. */ abort (); } tms = datetime_str (time (NULL)); if (!opt.spider) tmrate = retr_rate (qtyread - restval, con->dltime); /* If we get out of the switch above without continue'ing, we've successfully downloaded a file. Remember this fact. */ downloaded_file (FILE_DOWNLOADED_NORMALLY, locf); if (con->st & ON_YOUR_OWN) { fd_close (con->csock); con->csock = -1; } if (!opt.spider) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s]\n\n") : _("%s (%s) - %s saved [%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (locf), number_to_static_string (qtyread)); } if (!opt.verbose && !opt.quiet) { /* Need to hide the password from the URL. The `if' is here so that we don't do the needless allocation every time. */ char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); logprintf (LOG_NONVERBOSE, "%s URL: %s [%s] -> \"%s\" [%d]\n", tms, hurl, number_to_static_string (qtyread), locf, count); xfree (hurl); } if (warc_enabled && (con->cmd & DO_RETR)) { /* Create and store a WARC resource record for the retrieved file. */ bool warc_res; warc_res = warc_write_resource_record (NULL, u->url, NULL, NULL, warc_ip, NULL, warc_tmp, -1); if (! warc_res) return WARC_ERR; /* warc_write_resource_record has also closed warc_tmp. */ warc_tmp = NULL; } if (con->cmd & DO_LIST) /* This is a directory listing file. */ { if (!opt.remove_listing) /* --dont-remove-listing was specified, so do count this towards the number of bytes and files downloaded. */ { total_downloaded_bytes += qtyread; numurls++; } /* Deletion of listing files is not controlled by --delete-after, but by the more specific option --dont-remove-listing, and the code to do this deletion is in another function. */ } else if (!opt.spider) /* This is not a directory listing file. */ { /* Unlike directory listing files, don't pretend normal files weren't downloaded if they're going to be deleted. People seeding proxies, for instance, may want to know how many bytes and files they've downloaded through it. */ total_downloaded_bytes += qtyread; numurls++; if (opt.delete_after && !input_file_url (opt.input_filename)) { DEBUGP (("\ Removing file due to --delete-after in ftp_loop_internal():\n")); logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf); if (unlink (locf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); } } /* Restore the original leave-pendingness. */ if (orig_lp) con->cmd |= LEAVE_PENDING; else con->cmd &= ~LEAVE_PENDING; if (local_file) *local_file = xstrdup (locf); if (warc_tmp != NULL) fclose (warc_tmp); return RETROK; } while (!opt.ntry || (count < opt.ntry)); if (con->csock != -1 && (con->st & ON_YOUR_OWN)) { fd_close (con->csock); con->csock = -1; } if (warc_tmp != NULL) fclose (warc_tmp); return TRYLIMEXC; }
ftp_loop_internal (struct url *u, struct fileinfo *f, ccon *con, char **local_file, bool force_full_retrieve) { int count, orig_lp; wgint restval, len = 0, qtyread = 0; char *tms, *locf; const char *tmrate = NULL; uerr_t err; struct_stat st; /* Declare WARC variables. */ bool warc_enabled = (opt.warc_filename != NULL); FILE *warc_tmp = NULL; ip_address *warc_ip = NULL; wgint last_expected_bytes = 0; /* Get the target, and set the name for the message accordingly. */ if ((f == NULL) && (con->target)) { /* Explicit file (like ".listing"). */ locf = con->target; } else { /* URL-derived file. Consider "-O file" name. */ xfree (con->target); con->target = url_file_name (u, NULL); if (!opt.output_document) locf = con->target; else locf = opt.output_document; } /* If the output_document was given, then this check was already done and the file didn't exist. Hence the !opt.output_document */ /* If we receive .listing file it is necessary to determine system type of the ftp server even if opn.noclobber is given. Thus we must ignore opt.noclobber in order to establish connection with the server and get system type. */ if (opt.noclobber && !opt.output_document && file_exists_p (con->target) && !((con->cmd & DO_LIST) && !(con->cmd & DO_RETR))) { logprintf (LOG_VERBOSE, _("File %s already there; not retrieving.\n"), quote (con->target)); /* If the file is there, we suppose it's retrieved OK. */ return RETROK; } /* Remove it if it's a link. */ remove_link (con->target); count = 0; if (con->st & ON_YOUR_OWN) con->st = ON_YOUR_OWN; orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0; /* THE loop. */ do { /* Increment the pass counter. */ ++count; sleep_between_retrievals (count); if (con->st & ON_YOUR_OWN) { con->cmd = 0; con->cmd |= (DO_RETR | LEAVE_PENDING); if (con->csock != -1) con->cmd &= ~ (DO_LOGIN | DO_CWD); else con->cmd |= (DO_LOGIN | DO_CWD); } else /* not on your own */ { if (con->csock != -1) con->cmd &= ~DO_LOGIN; else con->cmd |= DO_LOGIN; if (con->st & DONE_CWD) con->cmd &= ~DO_CWD; else con->cmd |= DO_CWD; } /* For file RETR requests, we can write a WARC record. We record the file contents to a temporary file. */ if (warc_enabled && (con->cmd & DO_RETR) && warc_tmp == NULL) { warc_tmp = warc_tempfile (); if (warc_tmp == NULL) return WARC_TMP_FOPENERR; if (!con->proxy && con->csock != -1) { warc_ip = (ip_address *) alloca (sizeof (ip_address)); socket_ip_address (con->csock, warc_ip, ENDPOINT_PEER); } } /* Decide whether or not to restart. */ if (con->cmd & DO_LIST) restval = 0; else if (force_full_retrieve) restval = 0; else if (opt.start_pos >= 0) restval = opt.start_pos; else if (opt.always_rest && stat (locf, &st) == 0 && S_ISREG (st.st_mode)) /* When -c is used, continue from on-disk size. (Can't use hstat.len even if count>1 because we don't want a failed first attempt to clobber existing data.) */ restval = st.st_size; else if (count > 1) restval = qtyread; /* start where the previous run left off */ else restval = 0; /* Get the current time string. */ tms = datetime_str (time (NULL)); /* Print fetch message, if opt.verbose. */ if (opt.verbose) { char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); char tmp[256]; strcpy (tmp, " "); if (count > 1) sprintf (tmp, _("(try:%2d)"), count); logprintf (LOG_VERBOSE, "--%s-- %s\n %s => %s\n", tms, hurl, tmp, quote (locf)); #ifdef WINDOWS ws_changetitle (hurl); #endif xfree (hurl); } /* Send getftp the proper length, if fileinfo was provided. */ if (f && f->type != FT_SYMLINK) len = f->size; else len = 0; /* If we are working on a WARC record, getftp should also write to the warc_tmp file. */ err = getftp (u, len, &qtyread, restval, con, count, &last_expected_bytes, warc_tmp); if (con->csock == -1) con->st &= ~DONE_CWD; else con->st |= DONE_CWD; switch (err) { case HOSTERR: case CONIMPOSSIBLE: case FWRITEERR: case FOPENERR: case FTPNSFOD: case FTPLOGINC: case FTPNOPASV: case CONTNOTSUPPORTED: case UNLINKERR: case WARC_TMP_FWRITEERR: /* Fatal errors, give up. */ if (warc_tmp != NULL) fclose (warc_tmp); return err; case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR: case WRITEFAILED: case FTPUNKNOWNTYPE: case FTPSYSERR: case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV: case FOPEN_EXCL_ERR: printwhat (count, opt.ntry); /* non-fatal errors */ if (err == FOPEN_EXCL_ERR) { /* Re-determine the file name. */ xfree (con->target); con->target = url_file_name (u, NULL); locf = con->target; } continue; case FTPRETRINT: /* If the control connection was closed, the retrieval will be considered OK if f->size == len. */ if (!f || qtyread != f->size) { printwhat (count, opt.ntry); continue; } break; case RETRFINISHED: /* Great! */ break; default: /* Not as great. */ abort (); } tms = datetime_str (time (NULL)); if (!opt.spider) tmrate = retr_rate (qtyread - restval, con->dltime); /* If we get out of the switch above without continue'ing, we've successfully downloaded a file. Remember this fact. */ downloaded_file (FILE_DOWNLOADED_NORMALLY, locf); if (con->st & ON_YOUR_OWN) { fd_close (con->csock); con->csock = -1; } if (!opt.spider) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s]\n\n") : _("%s (%s) - %s saved [%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (locf), number_to_static_string (qtyread)); } if (!opt.verbose && !opt.quiet) { /* Need to hide the password from the URL. The `if' is here so that we don't do the needless allocation every time. */ char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); logprintf (LOG_NONVERBOSE, "%s URL: %s [%s] -> \"%s\" [%d]\n", tms, hurl, number_to_static_string (qtyread), locf, count); xfree (hurl); } if (warc_enabled && (con->cmd & DO_RETR)) { /* Create and store a WARC resource record for the retrieved file. */ bool warc_res; warc_res = warc_write_resource_record (NULL, u->url, NULL, NULL, warc_ip, NULL, warc_tmp, -1); if (! warc_res) return WARC_ERR; /* warc_write_resource_record has also closed warc_tmp. */ warc_tmp = NULL; } if (con->cmd & DO_LIST) /* This is a directory listing file. */ { if (!opt.remove_listing) /* --dont-remove-listing was specified, so do count this towards the number of bytes and files downloaded. */ { total_downloaded_bytes += qtyread; numurls++; } /* Deletion of listing files is not controlled by --delete-after, but by the more specific option --dont-remove-listing, and the code to do this deletion is in another function. */ } else if (!opt.spider) /* This is not a directory listing file. */ { /* Unlike directory listing files, don't pretend normal files weren't downloaded if they're going to be deleted. People seeding proxies, for instance, may want to know how many bytes and files they've downloaded through it. */ total_downloaded_bytes += qtyread; numurls++; if (opt.delete_after && !input_file_url (opt.input_filename)) { DEBUGP (("\ Removing file due to --delete-after in ftp_loop_internal():\n")); logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf); if (unlink (locf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); } } /* Restore the original leave-pendingness. */ if (orig_lp) con->cmd |= LEAVE_PENDING; else con->cmd &= ~LEAVE_PENDING; if (local_file) *local_file = xstrdup (locf); if (warc_tmp != NULL) fclose (warc_tmp); return RETROK; } while (!opt.ntry || (count < opt.ntry)); if (con->csock != -1 && (con->st & ON_YOUR_OWN)) { fd_close (con->csock); con->csock = -1; } if (warc_tmp != NULL) fclose (warc_tmp); return TRYLIMEXC; }
C
savannah
0
CVE-2013-1826
https://www.cvedetails.com/cve/CVE-2013-1826/
null
https://github.com/torvalds/linux/commit/864745d291b5ba80ea0bd0edcbe67273de368836
864745d291b5ba80ea0bd0edcbe67273de368836
xfrm_user: return error pointer instead of NULL When dump_one_state() returns an error, e.g. because of a too small buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL instead of an error pointer. But its callers expect an error pointer and therefore continue to operate on a NULL skbuff. This could lead to a privilege escalation (execution of user code in kernel context) if the attacker has CAP_NET_ADMIN and is able to map address 0. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb, struct xfrm_policy *xp, int dir, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; if (dump_one_policy(xp, dir, 0, &info) < 0) { kfree_skb(skb); return NULL; } return skb; }
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb, struct xfrm_policy *xp, int dir, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; if (dump_one_policy(xp, dir, 0, &info) < 0) { kfree_skb(skb); return NULL; } return skb; }
C
linux
0
CVE-2016-1666
https://www.cvedetails.com/cve/CVE-2016-1666/
null
https://github.com/chromium/chromium/commit/8b10115b2410b4bde18e094ad9fb8c5056134c87
8b10115b2410b4bde18e094ad9fb8c5056134c87
Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652}
bool IsValidHostName(base::StringPiece host, base::StringPiece domain_in_lower_case, SubdomainPermission subdomain_permission, base::StringPiece* tld) { if (host.find(domain_in_lower_case) == base::StringPiece::npos) return false; size_t tld_length = net::registry_controlled_domains::GetCanonicalHostRegistryLength( host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); if ((tld_length == 0) || (tld_length == std::string::npos)) return false; base::StringPiece host_minus_tld = host.substr(0, host.length() - tld_length - 1); if (tld) *tld = host.substr(host.length() - tld_length); if (base::LowerCaseEqualsASCII(host_minus_tld, domain_in_lower_case)) return true; if (subdomain_permission == ALLOW_SUBDOMAIN) { std::string dot_domain("."); domain_in_lower_case.AppendToString(&dot_domain); return base::EndsWith(host_minus_tld, dot_domain, base::CompareCase::INSENSITIVE_ASCII); } std::string www_domain("www."); domain_in_lower_case.AppendToString(&www_domain); return base::LowerCaseEqualsASCII(host_minus_tld, www_domain); }
bool IsValidHostName(base::StringPiece host, base::StringPiece domain_in_lower_case, SubdomainPermission subdomain_permission, base::StringPiece* tld) { if (host.find(domain_in_lower_case) == base::StringPiece::npos) return false; size_t tld_length = net::registry_controlled_domains::GetCanonicalHostRegistryLength( host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); if ((tld_length == 0) || (tld_length == std::string::npos)) return false; base::StringPiece host_minus_tld = host.substr(0, host.length() - tld_length - 1); if (tld) *tld = host.substr(host.length() - tld_length); if (base::LowerCaseEqualsASCII(host_minus_tld, domain_in_lower_case)) return true; if (subdomain_permission == ALLOW_SUBDOMAIN) { std::string dot_domain("."); domain_in_lower_case.AppendToString(&dot_domain); return base::EndsWith(host_minus_tld, dot_domain, base::CompareCase::INSENSITIVE_ASCII); } std::string www_domain("www."); domain_in_lower_case.AppendToString(&www_domain); return base::LowerCaseEqualsASCII(host_minus_tld, www_domain); }
C
Chrome
0
CVE-2018-6049
https://www.cvedetails.com/cve/CVE-2018-6049/
null
https://github.com/chromium/chromium/commit/56762260ca8ef62578fa4718b7d47711f7e120dc
56762260ca8ef62578fa4718b7d47711f7e120dc
Elide the permission bubble title from the head of the string. Long URLs can be used to spoof other origins in the permission bubble title. This CL customises the title to be elided from the head, which ensures that the maximal amount of the URL host is displayed in the case where the URL is too long and causes the string to overflow. Implementing the ellision means that the title cannot be multiline (where elision is not well supported). Note that in English, the window title is a string "$ORIGIN wants to", so the non-origin component will not be elided. In other languages, the non-origin component may appear fully or partly before the origin (e.g. in Filipino, "Gusto ng $ORIGIN na"), so it may be elided there if the URL is sufficiently long. This is not optimal, but the URLs that are sufficiently long to trigger the elision are probably malicious, and displaying the most relevant component of the URL is most important for security purposes. BUG=774438 Change-Id: I75c2364b10bf69bf337c7f4970481bf1809f6aae Reviewed-on: https://chromium-review.googlesource.com/768312 Reviewed-by: Ben Wells <[email protected]> Reviewed-by: Lucas Garron <[email protected]> Reviewed-by: Matt Giuca <[email protected]> Commit-Queue: Dominick Ng <[email protected]> Cr-Commit-Position: refs/heads/master@{#516921}
int PermissionsBubbleDialogDelegateView::GetDialogButtons() const { return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL; }
int PermissionsBubbleDialogDelegateView::GetDialogButtons() const { return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL; }
C
Chrome
0
CVE-2016-3841
https://www.cvedetails.com/cve/CVE-2016-3841/
CWE-416
https://github.com/torvalds/linux/commit/45f6fad84cc305103b28d73482b344d7f5b76f39
45f6fad84cc305103b28d73482b344d7f5b76f39
ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>
struct ipv6_txoptions *ipv6_update_options(struct sock *sk, struct ipv6_txoptions *opt) { if (inet_sk(sk)->is_icsk) { if (opt && !((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) && inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) { struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen; icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie); } } opt = xchg((__force struct ipv6_txoptions **)&inet6_sk(sk)->opt, opt); sk_dst_reset(sk); return opt; }
struct ipv6_txoptions *ipv6_update_options(struct sock *sk, struct ipv6_txoptions *opt) { if (inet_sk(sk)->is_icsk) { if (opt && !((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) && inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) { struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen; icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie); } } opt = xchg(&inet6_sk(sk)->opt, opt); sk_dst_reset(sk); return opt; }
C
linux
1
CVE-2016-7141
https://www.cvedetails.com/cve/CVE-2016-7141/
CWE-287
https://github.com/curl/curl/commit/curl-7_50_2~32
curl-7_50_2~32
nss: refuse previously loaded certificate from file ... when we are not asked to use a certificate from file
CURLcode Curl_nss_force_init(struct Curl_easy *data) { CURLcode result; if(!nss_initlock) { if(data) failf(data, "unable to initialize NSS, curl_global_init() should have " "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL"); return CURLE_FAILED_INIT; } PR_Lock(nss_initlock); result = nss_init(data); PR_Unlock(nss_initlock); return result; }
CURLcode Curl_nss_force_init(struct Curl_easy *data) { CURLcode result; if(!nss_initlock) { if(data) failf(data, "unable to initialize NSS, curl_global_init() should have " "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL"); return CURLE_FAILED_INIT; } PR_Lock(nss_initlock); result = nss_init(data); PR_Unlock(nss_initlock); return result; }
C
curl
0
CVE-2011-3896
https://www.cvedetails.com/cve/CVE-2011-3896/
CWE-119
https://github.com/chromium/chromium/commit/5925dff83699508b5e2735afb0297dfb310e159d
5925dff83699508b5e2735afb0297dfb310e159d
Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
bool Browser::HasCompletedUnloadProcessing() const { return is_attempting_to_close_browser_ && tabs_needing_before_unload_fired_.empty() && tabs_needing_unload_fired_.empty(); }
bool Browser::HasCompletedUnloadProcessing() const { return is_attempting_to_close_browser_ && tabs_needing_before_unload_fired_.empty() && tabs_needing_unload_fired_.empty(); }
C
Chrome
0
CVE-2013-2141
https://www.cvedetails.com/cve/CVE-2013-2141/
CWE-399
https://github.com/torvalds/linux/commit/b9e146d8eb3b9ecae5086d373b50fa0c1f3e7f0f
b9e146d8eb3b9ecae5086d373b50fa0c1f3e7f0f
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 <[email protected]> Reviewed-by: PaX Team <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: Al Viro <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
int kill_pid_info(int sig, struct siginfo *info, struct pid *pid) { int error = -ESRCH; struct task_struct *p; rcu_read_lock(); retry: p = pid_task(pid, PIDTYPE_PID); if (p) { error = group_send_sig_info(sig, info, p); if (unlikely(error == -ESRCH)) /* * The task was unhashed in between, try again. * If it is dead, pid_task() will return NULL, * if we race with de_thread() it will find the * new leader. */ goto retry; } rcu_read_unlock(); return error; }
int kill_pid_info(int sig, struct siginfo *info, struct pid *pid) { int error = -ESRCH; struct task_struct *p; rcu_read_lock(); retry: p = pid_task(pid, PIDTYPE_PID); if (p) { error = group_send_sig_info(sig, info, p); if (unlikely(error == -ESRCH)) /* * The task was unhashed in between, try again. * If it is dead, pid_task() will return NULL, * if we race with de_thread() it will find the * new leader. */ goto retry; } rcu_read_unlock(); return error; }
C
linux
0
CVE-2011-3108
https://www.cvedetails.com/cve/CVE-2011-3108/
CWE-399
https://github.com/chromium/chromium/commit/9f4633c617ef393ba4709cba7d8fa23101b64025
9f4633c617ef393ba4709cba7d8fa23101b64025
Http cache: Test deleting an entry with a pending_entry when adding the truncated flag. BUG=125159 TEST=net_unittests Review URL: https://chromiumcodereview.appspot.com/10356113 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139331 0039d316-1c4b-4281-b951-d872f2087c98
std::string status_and_headers() const { return std::string(status) + "\n" + std::string(headers); }
std::string status_and_headers() const { return std::string(status) + "\n" + std::string(headers); }
C
Chrome
0
CVE-2018-6031
https://www.cvedetails.com/cve/CVE-2018-6031/
CWE-416
https://github.com/chromium/chromium/commit/01c9a7e71ca435651723e8cbcab0b3ad4c5351e2
01c9a7e71ca435651723e8cbcab0b3ad4c5351e2
[pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#515056}
bool PDFiumEngine::TryLoadingDoc(const std::string& password, bool* needs_password) { *needs_password = false; if (doc_) { FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_); return true; } const char* password_cstr = nullptr; if (!password.empty()) { password_cstr = password.c_str(); password_tries_remaining_--; } if (doc_loader_->IsDocumentComplete() && !FPDFAvail_IsLinearized(fpdf_availability_)) { doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr); } else { doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr); } if (!doc_) { if (FPDF_GetLastError() == FPDF_ERR_PASSWORD) *needs_password = true; return false; } FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_); return true; }
bool PDFiumEngine::TryLoadingDoc(const std::string& password, bool* needs_password) { *needs_password = false; if (doc_) { FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_); return true; } const char* password_cstr = nullptr; if (!password.empty()) { password_cstr = password.c_str(); password_tries_remaining_--; } if (doc_loader_->IsDocumentComplete() && !FPDFAvail_IsLinearized(fpdf_availability_)) { doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr); } else { doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr); } if (!doc_) { if (FPDF_GetLastError() == FPDF_ERR_PASSWORD) *needs_password = true; return false; } FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_); return true; }
C
Chrome
0
CVE-2017-17862
https://www.cvedetails.com/cve/CVE-2017-17862/
CWE-20
https://github.com/torvalds/linux/commit/c131187db2d3fa2f8bf32fdf4e9a4ef805168467
c131187db2d3fa2f8bf32fdf4e9a4ef805168467
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 <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]>
static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; }
static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; }
C
linux
0
CVE-2016-5219
https://www.cvedetails.com/cve/CVE-2016-5219/
CWE-416
https://github.com/chromium/chromium/commit/a4150b688a754d3d10d2ca385155b1c95d77d6ae
a4150b688a754d3d10d2ca385155b1c95d77d6ae
Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568}
error::Error GLES2DecoderImpl::HandleGetFragDataLocation( uint32_t immediate_data_size, const volatile void* cmd_data) { if (!feature_info_->IsWebGL2OrES3Context()) return error::kUnknownCommand; const volatile gles2::cmds::GetFragDataLocation& c = *static_cast<const volatile gles2::cmds::GetFragDataLocation*>(cmd_data); Bucket* bucket = GetBucket(c.name_bucket_id); if (!bucket) { return error::kInvalidArguments; } std::string name_str; if (!bucket->GetAsString(&name_str)) { return error::kInvalidArguments; } return GetFragDataLocationHelper( c.program, c.location_shm_id, c.location_shm_offset, name_str); }
error::Error GLES2DecoderImpl::HandleGetFragDataLocation( uint32_t immediate_data_size, const volatile void* cmd_data) { if (!feature_info_->IsWebGL2OrES3Context()) return error::kUnknownCommand; const volatile gles2::cmds::GetFragDataLocation& c = *static_cast<const volatile gles2::cmds::GetFragDataLocation*>(cmd_data); Bucket* bucket = GetBucket(c.name_bucket_id); if (!bucket) { return error::kInvalidArguments; } std::string name_str; if (!bucket->GetAsString(&name_str)) { return error::kInvalidArguments; } return GetFragDataLocationHelper( c.program, c.location_shm_id, c.location_shm_offset, name_str); }
C
Chrome
0
CVE-2012-2816
https://www.cvedetails.com/cve/CVE-2012-2816/
null
https://github.com/chromium/chromium/commit/cd0bd79d6ebdb72183e6f0833673464cc10b3600
cd0bd79d6ebdb72183e6f0833673464cc10b3600
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
WebGLId WebGraphicsContext3DCommandBufferImpl::createBuffer() { GLuint o; gl_->GenBuffers(1, &o); return o; }
WebGLId WebGraphicsContext3DCommandBufferImpl::createBuffer() { GLuint o; gl_->GenBuffers(1, &o); return o; }
C
Chrome
0
CVE-2018-17204
https://www.cvedetails.com/cve/CVE-2018-17204/
CWE-617
https://github.com/openvswitch/ovs/commit/4af6da3b275b764b1afe194df6499b33d2bf4cde
4af6da3b275b764b1afe194df6499b33d2bf4cde
ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <[email protected]> Reviewed-by: Yifeng Sun <[email protected]>
ofputil_match_to_ofp11_match(const struct match *match, struct ofp11_match *ofmatch) { uint32_t wc = 0; memset(ofmatch, 0, sizeof *ofmatch); ofmatch->omh.type = htons(OFPMT_STANDARD); ofmatch->omh.length = htons(OFPMT11_STANDARD_LENGTH); if (!match->wc.masks.in_port.ofp_port) { wc |= OFPFW11_IN_PORT; } else { ofmatch->in_port = ofputil_port_to_ofp11(match->flow.in_port.ofp_port); } ofmatch->dl_src = match->flow.dl_src; ofmatch->dl_src_mask = eth_addr_invert(match->wc.masks.dl_src); ofmatch->dl_dst = match->flow.dl_dst; ofmatch->dl_dst_mask = eth_addr_invert(match->wc.masks.dl_dst); if (match->wc.masks.vlan_tci == htons(0)) { wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP; } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI) && !(match->flow.vlan_tci & htons(VLAN_CFI))) { ofmatch->dl_vlan = htons(OFPVID11_NONE); wc |= OFPFW11_DL_VLAN_PCP; } else { if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) { ofmatch->dl_vlan = htons(OFPVID11_ANY); } else { ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci)); } if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) { wc |= OFPFW11_DL_VLAN_PCP; } else { ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci); } } if (!match->wc.masks.dl_type) { wc |= OFPFW11_DL_TYPE; } else { ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type); } if (!(match->wc.masks.nw_tos & IP_DSCP_MASK)) { wc |= OFPFW11_NW_TOS; } else { ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK; } if (!match->wc.masks.nw_proto) { wc |= OFPFW11_NW_PROTO; } else { ofmatch->nw_proto = match->flow.nw_proto; } ofmatch->nw_src = match->flow.nw_src; ofmatch->nw_src_mask = ~match->wc.masks.nw_src; ofmatch->nw_dst = match->flow.nw_dst; ofmatch->nw_dst_mask = ~match->wc.masks.nw_dst; if (!match->wc.masks.tp_src) { wc |= OFPFW11_TP_SRC; } else { ofmatch->tp_src = match->flow.tp_src; } if (!match->wc.masks.tp_dst) { wc |= OFPFW11_TP_DST; } else { ofmatch->tp_dst = match->flow.tp_dst; } if (!(match->wc.masks.mpls_lse[0] & htonl(MPLS_LABEL_MASK))) { wc |= OFPFW11_MPLS_LABEL; } else { ofmatch->mpls_label = htonl(mpls_lse_to_label( match->flow.mpls_lse[0])); } if (!(match->wc.masks.mpls_lse[0] & htonl(MPLS_TC_MASK))) { wc |= OFPFW11_MPLS_TC; } else { ofmatch->mpls_tc = mpls_lse_to_tc(match->flow.mpls_lse[0]); } ofmatch->metadata = match->flow.metadata; ofmatch->metadata_mask = ~match->wc.masks.metadata; ofmatch->wildcards = htonl(wc); }
ofputil_match_to_ofp11_match(const struct match *match, struct ofp11_match *ofmatch) { uint32_t wc = 0; memset(ofmatch, 0, sizeof *ofmatch); ofmatch->omh.type = htons(OFPMT_STANDARD); ofmatch->omh.length = htons(OFPMT11_STANDARD_LENGTH); if (!match->wc.masks.in_port.ofp_port) { wc |= OFPFW11_IN_PORT; } else { ofmatch->in_port = ofputil_port_to_ofp11(match->flow.in_port.ofp_port); } ofmatch->dl_src = match->flow.dl_src; ofmatch->dl_src_mask = eth_addr_invert(match->wc.masks.dl_src); ofmatch->dl_dst = match->flow.dl_dst; ofmatch->dl_dst_mask = eth_addr_invert(match->wc.masks.dl_dst); if (match->wc.masks.vlan_tci == htons(0)) { wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP; } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI) && !(match->flow.vlan_tci & htons(VLAN_CFI))) { ofmatch->dl_vlan = htons(OFPVID11_NONE); wc |= OFPFW11_DL_VLAN_PCP; } else { if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) { ofmatch->dl_vlan = htons(OFPVID11_ANY); } else { ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci)); } if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) { wc |= OFPFW11_DL_VLAN_PCP; } else { ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci); } } if (!match->wc.masks.dl_type) { wc |= OFPFW11_DL_TYPE; } else { ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type); } if (!(match->wc.masks.nw_tos & IP_DSCP_MASK)) { wc |= OFPFW11_NW_TOS; } else { ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK; } if (!match->wc.masks.nw_proto) { wc |= OFPFW11_NW_PROTO; } else { ofmatch->nw_proto = match->flow.nw_proto; } ofmatch->nw_src = match->flow.nw_src; ofmatch->nw_src_mask = ~match->wc.masks.nw_src; ofmatch->nw_dst = match->flow.nw_dst; ofmatch->nw_dst_mask = ~match->wc.masks.nw_dst; if (!match->wc.masks.tp_src) { wc |= OFPFW11_TP_SRC; } else { ofmatch->tp_src = match->flow.tp_src; } if (!match->wc.masks.tp_dst) { wc |= OFPFW11_TP_DST; } else { ofmatch->tp_dst = match->flow.tp_dst; } if (!(match->wc.masks.mpls_lse[0] & htonl(MPLS_LABEL_MASK))) { wc |= OFPFW11_MPLS_LABEL; } else { ofmatch->mpls_label = htonl(mpls_lse_to_label( match->flow.mpls_lse[0])); } if (!(match->wc.masks.mpls_lse[0] & htonl(MPLS_TC_MASK))) { wc |= OFPFW11_MPLS_TC; } else { ofmatch->mpls_tc = mpls_lse_to_tc(match->flow.mpls_lse[0]); } ofmatch->metadata = match->flow.metadata; ofmatch->metadata_mask = ~match->wc.masks.metadata; ofmatch->wildcards = htonl(wc); }
C
ovs
0
CVE-2014-9644
https://www.cvedetails.com/cve/CVE-2014-9644/
CWE-264
https://github.com/torvalds/linux/commit/4943ba16bbc2db05115707b3ff7b4874e9e3c560
4943ba16bbc2db05115707b3ff7b4874e9e3c560
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 <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
static u64 l3hash(u64 p1, u64 p2, u64 k1, u64 k2, u64 len) { u64 rh, rl, t, z = 0; /* fully reduce (p1,p2)+(len,0) mod p127 */ t = p1 >> 63; p1 &= m63; ADD128(p1, p2, len, t); /* At this point, (p1,p2) is at most 2^127+(len<<64) */ t = (p1 > m63) + ((p1 == m63) && (p2 == m64)); ADD128(p1, p2, z, t); p1 &= m63; /* compute (p1,p2)/(2^64-2^32) and (p1,p2)%(2^64-2^32) */ t = p1 + (p2 >> 32); t += (t >> 32); t += (u32)t > 0xfffffffeu; p1 += (t >> 32); p2 += (p1 << 32); /* compute (p1+k1)%p64 and (p2+k2)%p64 */ p1 += k1; p1 += (0 - (p1 < k1)) & 257; p2 += k2; p2 += (0 - (p2 < k2)) & 257; /* compute (p1+k1)*(p2+k2)%p64 */ MUL64(rh, rl, p1, p2); t = rh >> 56; ADD128(t, rl, z, rh); rh <<= 8; ADD128(t, rl, z, rh); t += t << 8; rl += t; rl += (0 - (rl < t)) & 257; rl += (0 - (rl > p64-1)) & 257; return rl; }
static u64 l3hash(u64 p1, u64 p2, u64 k1, u64 k2, u64 len) { u64 rh, rl, t, z = 0; /* fully reduce (p1,p2)+(len,0) mod p127 */ t = p1 >> 63; p1 &= m63; ADD128(p1, p2, len, t); /* At this point, (p1,p2) is at most 2^127+(len<<64) */ t = (p1 > m63) + ((p1 == m63) && (p2 == m64)); ADD128(p1, p2, z, t); p1 &= m63; /* compute (p1,p2)/(2^64-2^32) and (p1,p2)%(2^64-2^32) */ t = p1 + (p2 >> 32); t += (t >> 32); t += (u32)t > 0xfffffffeu; p1 += (t >> 32); p2 += (p1 << 32); /* compute (p1+k1)%p64 and (p2+k2)%p64 */ p1 += k1; p1 += (0 - (p1 < k1)) & 257; p2 += k2; p2 += (0 - (p2 < k2)) & 257; /* compute (p1+k1)*(p2+k2)%p64 */ MUL64(rh, rl, p1, p2); t = rh >> 56; ADD128(t, rl, z, rh); rh <<= 8; ADD128(t, rl, z, rh); t += t << 8; rl += t; rl += (0 - (rl < t)) & 257; rl += (0 - (rl > p64-1)) & 257; return rl; }
C
linux
0
CVE-2011-4324
https://www.cvedetails.com/cve/CVE-2011-4324/
null
https://github.com/torvalds/linux/commit/dc0b027dfadfcb8a5504f7d8052754bf8d501ab9
dc0b027dfadfcb8a5504f7d8052754bf8d501ab9
NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]>
static int nfs4_xdr_dec_fsinfo(struct rpc_rqst *req, __be32 *p, struct nfs_fsinfo *fsinfo) { struct xdr_stream xdr; struct compound_hdr hdr; int status; xdr_init_decode(&xdr, &req->rq_rcv_buf, p); status = decode_compound_hdr(&xdr, &hdr); if (!status) status = decode_putfh(&xdr); if (!status) status = decode_fsinfo(&xdr, fsinfo); if (!status) status = nfs4_stat_to_errno(hdr.status); return status; }
static int nfs4_xdr_dec_fsinfo(struct rpc_rqst *req, __be32 *p, struct nfs_fsinfo *fsinfo) { struct xdr_stream xdr; struct compound_hdr hdr; int status; xdr_init_decode(&xdr, &req->rq_rcv_buf, p); status = decode_compound_hdr(&xdr, &hdr); if (!status) status = decode_putfh(&xdr); if (!status) status = decode_fsinfo(&xdr, fsinfo); if (!status) status = nfs4_stat_to_errno(hdr.status); return status; }
C
linux
0
CVE-2015-6640
https://www.cvedetails.com/cve/CVE-2015-6640/
CWE-264
https://android.googlesource.com/kernel%2Fcommon/+/69bfe2d957d903521d32324190c2754cb073be15
69bfe2d957d903521d32324190c2754cb073be15
mm: fix prctl_set_vma_anon_name prctl_set_vma_anon_name could attempt to set the name across two vmas at the same time due to a typo, which might corrupt the vma list. Fix it to use tmp instead of end to limit the name setting to a single vma at a time. Change-Id: Ie32d8ddb0fd547efbeedd6528acdab5ca5b308b4 Reported-by: Jed Davis <[email protected]> Signed-off-by: Colin Cross <[email protected]>
SYSCALL_DEFINE2(setdomainname, char __user *, name, int, len) { int errno; char tmp[__NEW_UTS_LEN]; if (!ns_capable(current->nsproxy->uts_ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; if (len < 0 || len > __NEW_UTS_LEN) return -EINVAL; down_write(&uts_sem); errno = -EFAULT; if (!copy_from_user(tmp, name, len)) { struct new_utsname *u = utsname(); memcpy(u->domainname, tmp, len); memset(u->domainname + len, 0, sizeof(u->domainname) - len); errno = 0; } uts_proc_notify(UTS_PROC_DOMAINNAME); up_write(&uts_sem); return errno; }
SYSCALL_DEFINE2(setdomainname, char __user *, name, int, len) { int errno; char tmp[__NEW_UTS_LEN]; if (!ns_capable(current->nsproxy->uts_ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; if (len < 0 || len > __NEW_UTS_LEN) return -EINVAL; down_write(&uts_sem); errno = -EFAULT; if (!copy_from_user(tmp, name, len)) { struct new_utsname *u = utsname(); memcpy(u->domainname, tmp, len); memset(u->domainname + len, 0, sizeof(u->domainname) - len); errno = 0; } uts_proc_notify(UTS_PROC_DOMAINNAME); up_write(&uts_sem); return errno; }
C
Android
0
CVE-2014-1713
https://www.cvedetails.com/cve/CVE-2014-1713/
CWE-399
https://github.com/chromium/chromium/commit/f85a87ec670ad0fce9d98d90c9a705b72a288154
f85a87ec670ad0fce9d98d90c9a705b72a288154
document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
static void convert2Method(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { throwTypeError(ExceptionMessages::failedToExecute("convert2", "TestObject", ExceptionMessages::notEnoughArguments(1, info.Length())), info.GetIsolate()); return; } TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_VOID(TestNode*, value, V8TestNode::toNativeWithTypeCheck(info.GetIsolate(), info[0])); imp->convert2(value); }
static void convert2Method(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { throwTypeError(ExceptionMessages::failedToExecute("convert2", "TestObject", ExceptionMessages::notEnoughArguments(1, info.Length())), info.GetIsolate()); return; } TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_VOID(TestNode*, value, V8TestNode::toNativeWithTypeCheck(info.GetIsolate(), info[0])); imp->convert2(value); }
C
Chrome
0
CVE-2016-6250
https://www.cvedetails.com/cve/CVE-2016-6250/
CWE-190
https://github.com/libarchive/libarchive/commit/3014e198
3014e198
Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives * Don't cast size_t to int, since this can lead to overflow on machines where sizeof(int) < sizeof(size_t) * Check a + b > limit by writing it as a > limit || b > limit || a + b > limit to avoid problems when a + b wraps around.
write_to_temp(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; ssize_t written; const unsigned char *b; b = (const unsigned char *)buff; while (s) { written = write(iso9660->temp_fd, b, s); if (written < 0) { archive_set_error(&a->archive, errno, "Can't write to temporary file"); return (ARCHIVE_FATAL); } s -= written; b += written; } return (ARCHIVE_OK); }
write_to_temp(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; ssize_t written; const unsigned char *b; b = (const unsigned char *)buff; while (s) { written = write(iso9660->temp_fd, b, s); if (written < 0) { archive_set_error(&a->archive, errno, "Can't write to temporary file"); return (ARCHIVE_FATAL); } s -= written; b += written; } return (ARCHIVE_OK); }
C
libarchive
0
CVE-2017-2633
https://www.cvedetails.com/cve/CVE-2017-2633/
CWE-125
https://git.qemu.org/?p=qemu.git;a=commitdiff;h=9f64916da20eea67121d544698676295bbb105a7
9f64916da20eea67121d544698676295bbb105a7
null
static void vnc_zrle_stop(VncState *vs) { /* switch back to normal output/zlib buffers */ vs->zrle.zrle = vs->output; vs->output = vs->zrle.tmp; }
static void vnc_zrle_stop(VncState *vs) { /* switch back to normal output/zlib buffers */ vs->zrle.zrle = vs->output; vs->output = vs->zrle.tmp; }
C
qemu
0
null
null
null
https://github.com/chromium/chromium/commit/f1a142d29ad1dfaecd3b609051b476440289ec72
f1a142d29ad1dfaecd3b609051b476440289ec72
Fix print media page size by using the value we compute. BUG=82472 TEST=NONE (in bug) Review URL: http://codereview.chromium.org/8344016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@106160 0039d316-1c4b-4281-b951-d872f2087c98
int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() { DCHECK_EQ(RENDERING, state_); if (IsFinalPageRendered()) return -1; return pages_to_render_[current_page_index_++]; }
int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() { DCHECK_EQ(RENDERING, state_); if (IsFinalPageRendered()) return -1; return pages_to_render_[current_page_index_++]; }
C
Chrome
0
CVE-2016-5219
https://www.cvedetails.com/cve/CVE-2016-5219/
CWE-416
https://github.com/chromium/chromium/commit/a4150b688a754d3d10d2ca385155b1c95d77d6ae
a4150b688a754d3d10d2ca385155b1c95d77d6ae
Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568}
error::Error GLES2DecoderPassthroughImpl::DoBeginRasterCHROMIUM( GLuint texture_id, GLuint sk_color, GLuint msaa_sample_count, GLboolean can_use_lcd_text, GLint color_type) { NOTIMPLEMENTED(); return error::kNoError; }
error::Error GLES2DecoderPassthroughImpl::DoBeginRasterCHROMIUM( GLuint texture_id, GLuint sk_color, GLuint msaa_sample_count, GLboolean can_use_lcd_text, GLint color_type) { NOTIMPLEMENTED(); return error::kNoError; }
C
Chrome
0
CVE-2016-6520
https://www.cvedetails.com/cve/CVE-2016-6520/
CWE-125
https://github.com/ImageMagick/ImageMagick/commit/76401e172ea3a55182be2b8e2aca4d07270f6da6
76401e172ea3a55182be2b8e2aca4d07270f6da6
Evaluate lazy pixel cache morphology to prevent buffer overflow (bug report from Ibrahim M. El-Sayed)
static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); }
static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); }
C
ImageMagick
0
CVE-2019-11811
https://www.cvedetails.com/cve/CVE-2019-11811/
CWE-416
https://github.com/torvalds/linux/commit/401e7e88d4ef80188ffa07095ac00456f901b8c4
401e7e88d4ef80188ffa07095ac00456f901b8c4
ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]>
static void intf_mem_outb(const struct si_sm_io *io, unsigned int offset, unsigned char b) { writeb(b, (io->addr)+(offset * io->regspacing)); }
static void intf_mem_outb(const struct si_sm_io *io, unsigned int offset, unsigned char b) { writeb(b, (io->addr)+(offset * io->regspacing)); }
C
linux
0
CVE-2018-20856
https://www.cvedetails.com/cve/CVE-2018-20856/
CWE-416
https://github.com/torvalds/linux/commit/54648cf1ec2d7f4b6a71767799c45676a138ca24
54648cf1ec2d7f4b6a71767799c45676a138ca24
block: blk_init_allocated_queue() set q->fq as NULL in the fail case We find the memory use-after-free issue in __blk_drain_queue() on the kernel 4.14. After read the latest kernel 4.18-rc6 we think it has the same problem. Memory is allocated for q->fq in the blk_init_allocated_queue(). If the elevator init function called with error return, it will run into the fail case to free the q->fq. Then the __blk_drain_queue() uses the same memory after the free of the q->fq, it will lead to the unpredictable event. The patch is to set q->fq as NULL in the fail case of blk_init_allocated_queue(). Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery") Cc: <[email protected]> Reviewed-by: Ming Lei <[email protected]> Reviewed-by: Bart Van Assche <[email protected]> Signed-off-by: xiao jin <[email protected]> Signed-off-by: Jens Axboe <[email protected]>
struct request *blk_get_request(struct request_queue *q, unsigned int op, blk_mq_req_flags_t flags) { struct request *req; WARN_ON_ONCE(op & REQ_NOWAIT); WARN_ON_ONCE(flags & ~(BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_PREEMPT)); if (q->mq_ops) { req = blk_mq_alloc_request(q, op, flags); if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn) q->mq_ops->initialize_rq_fn(req); } else { req = blk_old_get_request(q, op, flags); if (!IS_ERR(req) && q->initialize_rq_fn) q->initialize_rq_fn(req); } return req; }
struct request *blk_get_request(struct request_queue *q, unsigned int op, blk_mq_req_flags_t flags) { struct request *req; WARN_ON_ONCE(op & REQ_NOWAIT); WARN_ON_ONCE(flags & ~(BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_PREEMPT)); if (q->mq_ops) { req = blk_mq_alloc_request(q, op, flags); if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn) q->mq_ops->initialize_rq_fn(req); } else { req = blk_old_get_request(q, op, flags); if (!IS_ERR(req) && q->initialize_rq_fn) q->initialize_rq_fn(req); } return req; }
C
linux
0
CVE-2017-0377
https://www.cvedetails.com/cve/CVE-2017-0377/
CWE-200
https://github.com/torproject/tor/commit/665baf5ed5c6186d973c46cdea165c0548027350
665baf5ed5c6186d973c46cdea165c0548027350
Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377.
microdesc_has_curve25519_onion_key(const microdesc_t *md) { if (!md) { return 0; } if (!md->onion_curve25519_pkey) { return 0; } if (tor_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key, CURVE25519_PUBKEY_LEN)) { return 0; } return 1; }
microdesc_has_curve25519_onion_key(const microdesc_t *md) { if (!md) { return 0; } if (!md->onion_curve25519_pkey) { return 0; } if (tor_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key, CURVE25519_PUBKEY_LEN)) { return 0; } return 1; }
C
tor
0
null
null
null
https://github.com/chromium/chromium/commit/dc3857aac17be72c96f28d860d875235b3be349a
dc3857aac17be72c96f28d860d875235b3be349a
Unreviewed, rolling out r142736. http://trac.webkit.org/changeset/142736 https://bugs.webkit.org/show_bug.cgi?id=109716 Broke ABI, nightly builds crash on launch (Requested by ap on #webkit). Patch by Sheriff Bot <[email protected]> on 2013-02-13 Source/WebKit2: * Shared/APIClientTraits.cpp: (WebKit): * Shared/APIClientTraits.h: * UIProcess/API/C/WKPage.h: * UIProcess/API/gtk/WebKitLoaderClient.cpp: (attachLoaderClientToView): * WebProcess/InjectedBundle/API/c/WKBundlePage.h: * WebProcess/qt/QtBuiltinBundlePage.cpp: (WebKit::QtBuiltinBundlePage::QtBuiltinBundlePage): Tools: * MiniBrowser/mac/WK2BrowserWindowController.m: (-[WK2BrowserWindowController awakeFromNib]): * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: (WTR::InjectedBundlePage::InjectedBundlePage): * WebKitTestRunner/TestController.cpp: (WTR::TestController::createWebViewWithOptions): git-svn-id: svn://svn.chromium.org/blink/trunk@142762 bbb929c8-8fbe-4397-9dbb-9b2b20218538
bool InjectedBundlePage::shouldDeleteRange(WKBundlePageRef page, WKBundleRangeHandleRef range, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldDeleteRange(range); }
bool InjectedBundlePage::shouldDeleteRange(WKBundlePageRef page, WKBundleRangeHandleRef range, const void* clientInfo) { return static_cast<InjectedBundlePage*>(const_cast<void*>(clientInfo))->shouldDeleteRange(range); }
C
Chrome
0
CVE-2018-6096
https://www.cvedetails.com/cve/CVE-2018-6096/
null
https://github.com/chromium/chromium/commit/36f801fdbec07d116a6f4f07bb363f10897d6a51
36f801fdbec07d116a6f4f07bb363f10897d6a51
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 <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790}
bool WebContentsImpl::IsCurrentlyAudible() { return audio_stream_monitor()->IsCurrentlyAudible(); }
bool WebContentsImpl::IsCurrentlyAudible() { return audio_stream_monitor()->IsCurrentlyAudible(); }
C
Chrome
0
CVE-2015-0274
https://www.cvedetails.com/cve/CVE-2015-0274/
CWE-19
https://github.com/torvalds/linux/commit/8275cdd0e7ac550dcce2b3ef6d2fb3b808c1ae59
8275cdd0e7ac550dcce2b3ef6d2fb3b808c1ae59
xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]>
xfs_attr_rmtval_remove( struct xfs_da_args *args) { struct xfs_mount *mp = args->dp->i_mount; xfs_dablk_t lblkno; int blkcnt; int error; int done; trace_xfs_attr_rmtval_remove(args); /* * Roll through the "value", invalidating the attribute value's blocks. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; while (blkcnt > 0) { struct xfs_bmbt_irec map; struct xfs_buf *bp; xfs_daddr_t dblkno; int dblkcnt; int nmap; /* * Try to remember where we decided to put the value. */ nmap = 1; error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno, blkcnt, &map, &nmap, XFS_BMAPI_ATTRFORK); if (error) return(error); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock), dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount); /* * If the "remote" value is in the cache, remove it. */ bp = xfs_incore(mp->m_ddev_targp, dblkno, dblkcnt, XBF_TRYLOCK); if (bp) { xfs_buf_stale(bp); xfs_buf_relse(bp); bp = NULL; } lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; } /* * Keep de-allocating extents until the remote-value region is gone. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; done = 0; while (!done) { int committed; xfs_bmap_init(args->flist, args->firstblock); error = xfs_bunmapi(args->trans, args->dp, lblkno, blkcnt, XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA, 1, args->firstblock, args->flist, &done); if (!error) { error = xfs_bmap_finish(&args->trans, args->flist, &committed); } if (error) { ASSERT(committed); args->trans = NULL; xfs_bmap_cancel(args->flist); return error; } /* * bmap_finish() may have committed the last trans and started * a new one. We need the inode to be in all transactions. */ if (committed) xfs_trans_ijoin(args->trans, args->dp, 0); /* * Close out trans and start the next one in the chain. */ error = xfs_trans_roll(&args->trans, args->dp); if (error) return (error); } return(0); }
xfs_attr_rmtval_remove( struct xfs_da_args *args) { struct xfs_mount *mp = args->dp->i_mount; xfs_dablk_t lblkno; int blkcnt; int error; int done; trace_xfs_attr_rmtval_remove(args); /* * Roll through the "value", invalidating the attribute value's blocks. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; while (blkcnt > 0) { struct xfs_bmbt_irec map; struct xfs_buf *bp; xfs_daddr_t dblkno; int dblkcnt; int nmap; /* * Try to remember where we decided to put the value. */ nmap = 1; error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno, blkcnt, &map, &nmap, XFS_BMAPI_ATTRFORK); if (error) return(error); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock), dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount); /* * If the "remote" value is in the cache, remove it. */ bp = xfs_incore(mp->m_ddev_targp, dblkno, dblkcnt, XBF_TRYLOCK); if (bp) { xfs_buf_stale(bp); xfs_buf_relse(bp); bp = NULL; } lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; } /* * Keep de-allocating extents until the remote-value region is gone. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; done = 0; while (!done) { int committed; xfs_bmap_init(args->flist, args->firstblock); error = xfs_bunmapi(args->trans, args->dp, lblkno, blkcnt, XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA, 1, args->firstblock, args->flist, &done); if (!error) { error = xfs_bmap_finish(&args->trans, args->flist, &committed); } if (error) { ASSERT(committed); args->trans = NULL; xfs_bmap_cancel(args->flist); return error; } /* * bmap_finish() may have committed the last trans and started * a new one. We need the inode to be in all transactions. */ if (committed) xfs_trans_ijoin(args->trans, args->dp, 0); /* * Close out trans and start the next one in the chain. */ error = xfs_trans_roll(&args->trans, args->dp); if (error) return (error); } return(0); }
C
linux
0
CVE-2012-2895
https://www.cvedetails.com/cve/CVE-2012-2895/
CWE-119
https://github.com/chromium/chromium/commit/16dcd30c215801941d9890859fd79a234128fc3e
16dcd30c215801941d9890859fd79a234128fc3e
Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
SafeBrowsingState::~SafeBrowsingState() {}
SafeBrowsingState::~SafeBrowsingState() {}
C
Chrome
0
CVE-2016-0835
https://www.cvedetails.com/cve/CVE-2016-0835/
CWE-119
https://android.googlesource.com/platform/external/libmpeg2/+/ba604d336b40fd4bde1622f64d67135bdbd61301
ba604d336b40fd4bde1622f64d67135bdbd61301
Fix for handling streams which resulted in negative num_mbs_left Bug: 26070014 Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f
void impeg2d_dec_user_data(dec_state_t *ps_dec) { UWORD32 u4_start_code; stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while(u4_start_code == USER_DATA_START_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); while((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { impeg2d_bit_stream_flush(ps_stream,8); } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } }
void impeg2d_dec_user_data(dec_state_t *ps_dec) { UWORD32 u4_start_code; stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while(u4_start_code == USER_DATA_START_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); while((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { impeg2d_bit_stream_flush(ps_stream,8); } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } }
C
Android
0
CVE-2018-7186
https://www.cvedetails.com/cve/CVE-2018-7186/
CWE-119
https://github.com/DanBloomberg/leptonica/commit/ee301cb2029db8a6289c5295daa42bba7715e99a
ee301cb2029db8a6289c5295daa42bba7715e99a
Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf().
selDestroy(SEL **psel) { l_int32 i; SEL *sel; PROCNAME("selDestroy"); if (psel == NULL) { L_WARNING("ptr address is NULL!\n", procName); return; } if ((sel = *psel) == NULL) return; for (i = 0; i < sel->sy; i++) LEPT_FREE(sel->data[i]); LEPT_FREE(sel->data); if (sel->name) LEPT_FREE(sel->name); LEPT_FREE(sel); *psel = NULL; return; }
selDestroy(SEL **psel) { l_int32 i; SEL *sel; PROCNAME("selDestroy"); if (psel == NULL) { L_WARNING("ptr address is NULL!\n", procName); return; } if ((sel = *psel) == NULL) return; for (i = 0; i < sel->sy; i++) LEPT_FREE(sel->data[i]); LEPT_FREE(sel->data); if (sel->name) LEPT_FREE(sel->name); LEPT_FREE(sel); *psel = NULL; return; }
C
leptonica
0
CVE-2018-6053
https://www.cvedetails.com/cve/CVE-2018-6053/
CWE-200
https://github.com/chromium/chromium/commit/6c6888565ff1fde9ef21ef17c27ad4c8304643d2
6c6888565ff1fde9ef21ef17c27ad4c8304643d2
TopSites: Clear thumbnails from the cache when their URLs get removed We already cleared the thumbnails from persistent storage, but they remained in the in-memory cache, so they remained accessible (until the next Chrome restart) even after all browsing data was cleared. Bug: 758169 Change-Id: Id916d22358430a82e6d5043ac04fa463a32f824f Reviewed-on: https://chromium-review.googlesource.com/758640 Commit-Queue: Marc Treib <[email protected]> Reviewed-by: Sylvain Defresne <[email protected]> Cr-Commit-Position: refs/heads/master@{#514861}
void AddPageToHistory(const GURL& url) { RedirectList redirects; redirects.push_back(url); history_service()->AddPage( url, base::Time::Now(), reinterpret_cast<ContextID>(1), 0, GURL(), redirects, ui::PAGE_TRANSITION_TYPED, history::SOURCE_BROWSED, false); }
void AddPageToHistory(const GURL& url) { RedirectList redirects; redirects.push_back(url); history_service()->AddPage( url, base::Time::Now(), reinterpret_cast<ContextID>(1), 0, GURL(), redirects, ui::PAGE_TRANSITION_TYPED, history::SOURCE_BROWSED, false); }
C
Chrome
0
CVE-2016-10133
https://www.cvedetails.com/cve/CVE-2016-10133/
CWE-119
http://git.ghostscript.com/?p=mujs.git;a=commit;h=77ab465f1c394bb77f00966cd950650f3f53cb24
77ab465f1c394bb77f00966cd950650f3f53cb24
null
void js_setproperty(js_State *J, int idx, const char *name) { jsR_setproperty(J, js_toobject(J, idx), name); js_pop(J, 1); }
void js_setproperty(js_State *J, int idx, const char *name) { jsR_setproperty(J, js_toobject(J, idx), name); js_pop(J, 1); }
C
ghostscript
0
null
null
null
https://github.com/chromium/chromium/commit/3290c948762c47292fb388de8318859ee22b6688
3290c948762c47292fb388de8318859ee22b6688
GTK: Fix a couple minor popup window icon menu bugs. BUG=26265,26268 Review URL: http://codereview.chromium.org/360023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@31009 0039d316-1c4b-4281-b951-d872f2087c98
void BrowserTitlebar::Init() { GtkWidget* container_hbox = gtk_hbox_new(FALSE, 0); container_ = gtk_event_box_new(); gtk_widget_set_name(container_, "chrome-browser-titlebar"); gtk_event_box_set_visible_window(GTK_EVENT_BOX(container_), FALSE); gtk_container_add(GTK_CONTAINER(container_), container_hbox); g_signal_connect(G_OBJECT(container_), "scroll-event", G_CALLBACK(OnScroll), this); g_signal_connect(window_, "window-state-event", G_CALLBACK(OnWindowStateChanged), this); if (browser_window_->browser()->profile()->IsOffTheRecord() && browser_window_->browser()->type() == Browser::TYPE_NORMAL) { GtkWidget* spy_guy = gtk_image_new_from_pixbuf(GetOTRAvatar()); gtk_misc_set_alignment(GTK_MISC(spy_guy), 0.0, 1.0); GtkWidget* spy_frame = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_alignment_set_padding(GTK_ALIGNMENT(spy_frame), kOTRMaximizedTopSpacing, kOTRBottomSpacing, kOTRSideSpacing, kOTRSideSpacing); gtk_widget_set_size_request(spy_guy, -1, 0); gtk_container_add(GTK_CONTAINER(spy_frame), spy_guy); gtk_box_pack_start(GTK_BOX(container_hbox), spy_frame, FALSE, FALSE, 0); } titlebar_alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); if (browser_window_->browser()->type() == Browser::TYPE_NORMAL) { gtk_box_pack_start(GTK_BOX(container_hbox), titlebar_alignment_, TRUE, TRUE, 0); gtk_container_add(GTK_CONTAINER(titlebar_alignment_), browser_window_->tabstrip()->widget()); } else { gtk_box_pack_start(GTK_BOX(container_hbox), titlebar_alignment_, TRUE, TRUE, 0); GtkWidget* app_mode_hbox = gtk_hbox_new(FALSE, kIconTitleSpacing); gtk_container_add(GTK_CONTAINER(titlebar_alignment_), app_mode_hbox); gtk_box_pack_start(GTK_BOX(app_mode_hbox), browser_window_->tabstrip()->widget(), FALSE, FALSE, 0); GtkWidget* favicon_event_box = gtk_event_box_new(); gtk_event_box_set_visible_window(GTK_EVENT_BOX(favicon_event_box), FALSE); g_signal_connect(favicon_event_box, "button-press-event", G_CALLBACK(OnButtonPressed), this); gtk_box_pack_start(GTK_BOX(app_mode_hbox), favicon_event_box, FALSE, FALSE, 0); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); app_mode_favicon_ = gtk_image_new_from_pixbuf( rb.GetRTLEnabledPixbufNamed(IDR_PRODUCT_LOGO_16)); g_object_set_data(G_OBJECT(app_mode_favicon_), "left-align-popup", reinterpret_cast<void*>(true)); gtk_container_add(GTK_CONTAINER(favicon_event_box), app_mode_favicon_); app_mode_title_ = gtk_label_new(NULL); gtk_label_set_ellipsize(GTK_LABEL(app_mode_title_), PANGO_ELLIPSIZE_END); gtk_misc_set_alignment(GTK_MISC(app_mode_title_), 0.0, 0.5); gtk_box_pack_start(GTK_BOX(app_mode_hbox), app_mode_title_, TRUE, TRUE, 0); theme_provider_ = GtkThemeProvider::GetFrom( browser_window_->browser()->profile()); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); theme_provider_->InitThemesFor(this); UpdateTitleAndIcon(); } titlebar_buttons_box_ = gtk_vbox_new(FALSE, 0); GtkWidget* buttons_hbox = gtk_hbox_new(FALSE, kButtonSpacing); top_padding_ = gtk_fixed_new(); gtk_widget_set_size_request(top_padding_, -1, kButtonOuterPadding); gtk_box_pack_start(GTK_BOX(titlebar_buttons_box_), top_padding_, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(titlebar_buttons_box_), buttons_hbox, FALSE, FALSE, 0); if (CommandLine::ForCurrentProcess()->HasSwitch("glen")) { close_button_.reset(BuildTitlebarButton(IDR_GLEN, IDR_GLEN, IDR_GLEN, buttons_hbox, IDS_GLEN)); } else { close_button_.reset(BuildTitlebarButton(IDR_CLOSE, IDR_CLOSE_P, IDR_CLOSE_H, buttons_hbox, IDS_XPFRAME_CLOSE_TOOLTIP)); } restore_button_.reset(BuildTitlebarButton(IDR_RESTORE, IDR_RESTORE_P, IDR_RESTORE_H, buttons_hbox, IDS_XPFRAME_RESTORE_TOOLTIP)); maximize_button_.reset(BuildTitlebarButton(IDR_MAXIMIZE, IDR_MAXIMIZE_P, IDR_MAXIMIZE_H, buttons_hbox, IDS_XPFRAME_MAXIMIZE_TOOLTIP)); minimize_button_.reset(BuildTitlebarButton(IDR_MINIMIZE, IDR_MINIMIZE_P, IDR_MINIMIZE_H, buttons_hbox, IDS_XPFRAME_MINIMIZE_TOOLTIP)); gtk_widget_size_request(close_button_->widget(), &close_button_req_); gtk_widget_size_request(minimize_button_->widget(), &minimize_button_req_); gtk_widget_size_request(restore_button_->widget(), &restore_button_req_); gtk_box_pack_end(GTK_BOX(container_hbox), titlebar_buttons_box_, FALSE, FALSE, 0); gtk_widget_show_all(container_); ActiveWindowWatcherX::AddObserver(this); }
void BrowserTitlebar::Init() { GtkWidget* container_hbox = gtk_hbox_new(FALSE, 0); container_ = gtk_event_box_new(); gtk_widget_set_name(container_, "chrome-browser-titlebar"); gtk_event_box_set_visible_window(GTK_EVENT_BOX(container_), FALSE); gtk_container_add(GTK_CONTAINER(container_), container_hbox); g_signal_connect(G_OBJECT(container_), "scroll-event", G_CALLBACK(OnScroll), this); g_signal_connect(window_, "window-state-event", G_CALLBACK(OnWindowStateChanged), this); if (browser_window_->browser()->profile()->IsOffTheRecord() && browser_window_->browser()->type() == Browser::TYPE_NORMAL) { GtkWidget* spy_guy = gtk_image_new_from_pixbuf(GetOTRAvatar()); gtk_misc_set_alignment(GTK_MISC(spy_guy), 0.0, 1.0); GtkWidget* spy_frame = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_alignment_set_padding(GTK_ALIGNMENT(spy_frame), kOTRMaximizedTopSpacing, kOTRBottomSpacing, kOTRSideSpacing, kOTRSideSpacing); gtk_widget_set_size_request(spy_guy, -1, 0); gtk_container_add(GTK_CONTAINER(spy_frame), spy_guy); gtk_box_pack_start(GTK_BOX(container_hbox), spy_frame, FALSE, FALSE, 0); } titlebar_alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); if (browser_window_->browser()->type() == Browser::TYPE_NORMAL) { gtk_box_pack_start(GTK_BOX(container_hbox), titlebar_alignment_, TRUE, TRUE, 0); gtk_container_add(GTK_CONTAINER(titlebar_alignment_), browser_window_->tabstrip()->widget()); } else { gtk_box_pack_start(GTK_BOX(container_hbox), titlebar_alignment_, TRUE, TRUE, 0); GtkWidget* app_mode_hbox = gtk_hbox_new(FALSE, kIconTitleSpacing); gtk_container_add(GTK_CONTAINER(titlebar_alignment_), app_mode_hbox); gtk_box_pack_start(GTK_BOX(app_mode_hbox), browser_window_->tabstrip()->widget(), FALSE, FALSE, 0); GtkWidget* favicon_event_box = gtk_event_box_new(); gtk_event_box_set_visible_window(GTK_EVENT_BOX(favicon_event_box), FALSE); g_signal_connect(favicon_event_box, "button-press-event", G_CALLBACK(OnButtonPressed), this); gtk_box_pack_start(GTK_BOX(app_mode_hbox), favicon_event_box, FALSE, FALSE, 0); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); app_mode_favicon_ = gtk_image_new_from_pixbuf( rb.GetRTLEnabledPixbufNamed(IDR_PRODUCT_LOGO_16)); g_object_set_data(G_OBJECT(app_mode_favicon_), "left-align-popup", reinterpret_cast<void*>(true)); gtk_container_add(GTK_CONTAINER(favicon_event_box), app_mode_favicon_); app_mode_title_ = gtk_label_new(NULL); gtk_label_set_ellipsize(GTK_LABEL(app_mode_title_), PANGO_ELLIPSIZE_END); gtk_misc_set_alignment(GTK_MISC(app_mode_title_), 0.0, 0.5); gtk_box_pack_start(GTK_BOX(app_mode_hbox), app_mode_title_, TRUE, TRUE, 0); theme_provider_ = GtkThemeProvider::GetFrom( browser_window_->browser()->profile()); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); theme_provider_->InitThemesFor(this); UpdateTitleAndIcon(); } titlebar_buttons_box_ = gtk_vbox_new(FALSE, 0); GtkWidget* buttons_hbox = gtk_hbox_new(FALSE, kButtonSpacing); top_padding_ = gtk_fixed_new(); gtk_widget_set_size_request(top_padding_, -1, kButtonOuterPadding); gtk_box_pack_start(GTK_BOX(titlebar_buttons_box_), top_padding_, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(titlebar_buttons_box_), buttons_hbox, FALSE, FALSE, 0); if (CommandLine::ForCurrentProcess()->HasSwitch("glen")) { close_button_.reset(BuildTitlebarButton(IDR_GLEN, IDR_GLEN, IDR_GLEN, buttons_hbox, IDS_GLEN)); } else { close_button_.reset(BuildTitlebarButton(IDR_CLOSE, IDR_CLOSE_P, IDR_CLOSE_H, buttons_hbox, IDS_XPFRAME_CLOSE_TOOLTIP)); } restore_button_.reset(BuildTitlebarButton(IDR_RESTORE, IDR_RESTORE_P, IDR_RESTORE_H, buttons_hbox, IDS_XPFRAME_RESTORE_TOOLTIP)); maximize_button_.reset(BuildTitlebarButton(IDR_MAXIMIZE, IDR_MAXIMIZE_P, IDR_MAXIMIZE_H, buttons_hbox, IDS_XPFRAME_MAXIMIZE_TOOLTIP)); minimize_button_.reset(BuildTitlebarButton(IDR_MINIMIZE, IDR_MINIMIZE_P, IDR_MINIMIZE_H, buttons_hbox, IDS_XPFRAME_MINIMIZE_TOOLTIP)); gtk_widget_size_request(close_button_->widget(), &close_button_req_); gtk_widget_size_request(minimize_button_->widget(), &minimize_button_req_); gtk_widget_size_request(restore_button_->widget(), &restore_button_req_); gtk_box_pack_end(GTK_BOX(container_hbox), titlebar_buttons_box_, FALSE, FALSE, 0); gtk_widget_show_all(container_); ActiveWindowWatcherX::AddObserver(this); }
C
Chrome
0
CVE-2017-9059
https://www.cvedetails.com/cve/CVE-2017-9059/
CWE-404
https://github.com/torvalds/linux/commit/c70422f760c120480fee4de6c38804c72aa26bc1
c70422f760c120480fee4de6c38804c72aa26bc1
Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ...
nfssvc_decode_createargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_createargs *args) { if ( !(p = decode_fh(p, &args->fh)) || !(p = decode_filename(p, &args->name, &args->len))) return 0; p = decode_sattr(p, &args->attrs); return xdr_argsize_check(rqstp, p); }
nfssvc_decode_createargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_createargs *args) { if ( !(p = decode_fh(p, &args->fh)) || !(p = decode_filename(p, &args->name, &args->len))) return 0; p = decode_sattr(p, &args->attrs); return xdr_argsize_check(rqstp, p); }
C
linux
0
CVE-2014-3175
https://www.cvedetails.com/cve/CVE-2014-3175/
null
https://github.com/chromium/chromium/commit/4843d98517bd37e5940cd04627c6cfd2ac774d11
4843d98517bd37e5940cd04627c6cfd2ac774d11
Remove clock resolution page load histograms. These were temporary metrics intended to understand whether high/low resolution clocks adversely impact page load metrics. After collecting a few months of data it was determined that clock resolution doesn't adversely impact our metrics, and it that these histograms were no longer needed. BUG=394757 Review-Url: https://codereview.chromium.org/2155143003 Cr-Commit-Position: refs/heads/master@{#406143}
void CorePageLoadMetricsObserver::OnFirstPaint( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaintImmediate, timing.first_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaintImmediate, timing.first_paint.value()); } }
void CorePageLoadMetricsObserver::OnFirstPaint( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaintImmediate, timing.first_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaintImmediate, timing.first_paint.value()); } }
C
Chrome
0
CVE-2016-3890
https://www.cvedetails.com/cve/CVE-2016-3890/
CWE-264
https://android.googlesource.com/platform/system/core/+/014b01706cc64dc9c2ad94a96f62e07c058d0b5d
014b01706cc64dc9c2ad94a96f62e07c058d0b5d
adb: use asocket's close function when closing. close_all_sockets was assuming that all registered local sockets used local_socket_close as their close function. However, this is not true for JDWP sockets. Bug: http://b/28347842 Change-Id: I40a1174845cd33f15f30ce70828a7081cd5a087e (cherry picked from commit 53eb31d87cb84a4212f4850bf745646e1fb12814)
static asocket* create_host_service_socket(const char* name, const char* serial) { asocket* s; s = host_service_to_socket(name, serial); if (s != NULL) { D("LS(%d) bound to '%s'", s->id, name); return s; } return s; }
static asocket* create_host_service_socket(const char* name, const char* serial) { asocket* s; s = host_service_to_socket(name, serial); if (s != NULL) { D("LS(%d) bound to '%s'", s->id, name); return s; } return s; }
C
Android
0
CVE-2012-2895
https://www.cvedetails.com/cve/CVE-2012-2895/
CWE-119
https://github.com/chromium/chromium/commit/baef1ffd73db183ca50c854e1779ed7f6e5100a8
baef1ffd73db183ca50c854e1779ed7f6e5100a8
Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
void GDataCacheMetadataMap::ScanCacheDirectory( const std::vector<FilePath>& cache_paths, GDataCache::CacheSubDirectoryType sub_dir_type, CacheMap* cache_map) { file_util::FileEnumerator enumerator( cache_paths[sub_dir_type], false, // not recursive static_cast<file_util::FileEnumerator::FileType>( file_util::FileEnumerator::FILES | file_util::FileEnumerator::SHOW_SYM_LINKS), util::kWildCard); for (FilePath current = enumerator.Next(); !current.empty(); current = enumerator.Next()) { std::string resource_id; std::string md5; std::string extra_extension; util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension); int cache_state = GDataCache::CACHE_STATE_NONE; if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED) { CacheMap::iterator iter = cache_map->find(resource_id); if (iter != cache_map->end()) { // Entry exists, update pinned state. iter->second.cache_state = GDataCache::SetCachePinned(iter->second.cache_state); continue; } cache_state = GDataCache::SetCachePinned(cache_state); } else if (sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING) { // If we're scanning outgoing directory, entry must exist, update its // dirty state. // If entry doesn't exist, it's a logic error from previous execution, // ignore this outgoing symlink and move on. CacheMap::iterator iter = cache_map->find(resource_id); if (iter != cache_map->end()) { // Entry exists, update dirty state. iter->second.cache_state = GDataCache::SetCacheDirty(iter->second.cache_state); } else { NOTREACHED() << "Dirty cache file MUST have actual file blob"; } continue; } else if (extra_extension == util::kMountedArchiveFileExtension) { // Mounted archives in cache should be unmounted upon logout/shutdown. // But if we encounter a mounted file at start, delete it and create an // entry with not PRESENT state. DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT); file_util::Delete(current, false); } else { // Scanning other directories means that cache file is actually present. cache_state = GDataCache::SetCachePresent(cache_state); } cache_map->insert(std::make_pair( resource_id, GDataCache::CacheEntry(md5, sub_dir_type, cache_state))); } }
void GDataCacheMetadataMap::ScanCacheDirectory( const std::vector<FilePath>& cache_paths, GDataCache::CacheSubDirectoryType sub_dir_type, CacheMap* cache_map, ResourceIdToFilePathMap* processed_file_map) { DCHECK(cache_map); DCHECK(processed_file_map); file_util::FileEnumerator enumerator( cache_paths[sub_dir_type], false, // not recursive static_cast<file_util::FileEnumerator::FileType>( file_util::FileEnumerator::FILES | file_util::FileEnumerator::SHOW_SYM_LINKS), util::kWildCard); for (FilePath current = enumerator.Next(); !current.empty(); current = enumerator.Next()) { std::string resource_id; std::string md5; std::string extra_extension; util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension); int cache_state = GDataCache::CACHE_STATE_NONE; if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED) { std::string reason; if (!IsValidSymbolicLink(current, sub_dir_type, cache_paths, &reason)) { LOG(WARNING) << "Removing an invalid symlink: " << current.value() << ": " << reason; util::DeleteSymlink(current); continue; } CacheMap::iterator iter = cache_map->find(resource_id); if (iter != cache_map->end()) { // Entry exists, update pinned state. iter->second.cache_state = GDataCache::SetCachePinned(iter->second.cache_state); processed_file_map->insert(std::make_pair(resource_id, current)); continue; } cache_state = GDataCache::SetCachePinned(cache_state); } else if (sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING) { std::string reason; if (!IsValidSymbolicLink(current, sub_dir_type, cache_paths, &reason)) { LOG(WARNING) << "Removing an invalid symlink: " << current.value() << ": " << reason; util::DeleteSymlink(current); continue; } CacheMap::iterator iter = cache_map->find(resource_id); if (iter == cache_map->end() || !iter->second.IsDirty()) { LOG(WARNING) << "Removing an symlink to a non-dirty file: " << current.value(); util::DeleteSymlink(current); continue; } processed_file_map->insert(std::make_pair(resource_id, current)); continue; } else if (sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT || sub_dir_type == GDataCache::CACHE_TYPE_TMP) { FilePath unused; if (file_util::ReadSymbolicLink(current, &unused)) { LOG(WARNING) << "Removing a symlink in persistent/tmp directory" << current.value(); util::DeleteSymlink(current); continue; } if (extra_extension == util::kMountedArchiveFileExtension) { DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT); file_util::Delete(current, false); } else { cache_state = GDataCache::SetCachePresent(cache_state); if (md5 == util::kLocallyModifiedFileExtension) { if (sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT) { cache_state |= GDataCache::SetCacheDirty(cache_state); } else { LOG(WARNING) << "Removing a dirty file in tmp directory: " << current.value(); file_util::Delete(current, false); continue; } } } } else { NOTREACHED() << "Unexpected sub directory type: " << sub_dir_type; } cache_map->insert(std::make_pair( resource_id, GDataCache::CacheEntry(md5, sub_dir_type, cache_state))); processed_file_map->insert(std::make_pair(resource_id, current)); } }
C
Chrome
1
CVE-2015-8324
https://www.cvedetails.com/cve/CVE-2015-8324/
null
https://github.com/torvalds/linux/commit/744692dc059845b2a3022119871846e74d4f6e11
744692dc059845b2a3022119871846e74d4f6e11
ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]>
static int __init init_ext4_fs(void) { int err; err = init_ext4_system_zone(); if (err) return err; ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj); if (!ext4_kset) goto out4; ext4_proc_root = proc_mkdir("fs/ext4", NULL); err = init_ext4_mballoc(); if (err) goto out3; err = init_ext4_xattr(); if (err) goto out2; err = init_inodecache(); if (err) goto out1; register_as_ext2(); register_as_ext3(); err = register_filesystem(&ext4_fs_type); if (err) goto out; return 0; out: unregister_as_ext2(); unregister_as_ext3(); destroy_inodecache(); out1: exit_ext4_xattr(); out2: exit_ext4_mballoc(); out3: remove_proc_entry("fs/ext4", NULL); kset_unregister(ext4_kset); out4: exit_ext4_system_zone(); return err; }
static int __init init_ext4_fs(void) { int err; err = init_ext4_system_zone(); if (err) return err; ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj); if (!ext4_kset) goto out4; ext4_proc_root = proc_mkdir("fs/ext4", NULL); err = init_ext4_mballoc(); if (err) goto out3; err = init_ext4_xattr(); if (err) goto out2; err = init_inodecache(); if (err) goto out1; register_as_ext2(); register_as_ext3(); err = register_filesystem(&ext4_fs_type); if (err) goto out; return 0; out: unregister_as_ext2(); unregister_as_ext3(); destroy_inodecache(); out1: exit_ext4_xattr(); out2: exit_ext4_mballoc(); out3: remove_proc_entry("fs/ext4", NULL); kset_unregister(ext4_kset); out4: exit_ext4_system_zone(); return err; }
C
linux
0
CVE-2011-3055
https://www.cvedetails.com/cve/CVE-2011-3055/
null
https://github.com/chromium/chromium/commit/e9372a1bfd3588a80fcf49aa07321f0971dd6091
e9372a1bfd3588a80fcf49aa07321f0971dd6091
[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
static void withScriptExecutionContextAndScriptStateAttributeAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.TestObj.withScriptExecutionContextAndScriptStateAttribute._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); TestObj* v = V8TestObj::HasInstance(value) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(value)) : 0; ScriptState* state = ScriptState::current(); if (!state) return; ScriptExecutionContext* scriptContext = getScriptExecutionContext(); if (!scriptContext) return; imp->setWithScriptExecutionContextAndScriptStateAttribute(state, scriptContext, WTF::getPtr(v)); if (state.hadException()) throwError(state.exception(), info.GetIsolate()); return; }
static void withScriptExecutionContextAndScriptStateAttributeAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.TestObj.withScriptExecutionContextAndScriptStateAttribute._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); TestObj* v = V8TestObj::HasInstance(value) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(value)) : 0; ScriptState* state = ScriptState::current(); if (!state) return; ScriptExecutionContext* scriptContext = getScriptExecutionContext(); if (!scriptContext) return; imp->setWithScriptExecutionContextAndScriptStateAttribute(state, scriptContext, WTF::getPtr(v)); if (state.hadException()) throwError(state.exception(), info.GetIsolate()); return; }
C
Chrome
0