func
stringlengths
0
484k
target
int64
0
1
cwe
listlengths
0
4
project
stringclasses
799 values
commit_id
stringlengths
40
40
hash
float64
1,215,700,430,453,689,100,000,000B
340,281,914,521,452,260,000,000,000,000B
size
int64
1
24k
message
stringlengths
0
13.3k
unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) { zlentry entry; if (p == NULL || p[0] == ZIP_END) return 0; if (sstr) *sstr = NULL; zipEntry(p, &entry); if (ZIP_IS_STR(entry.encoding)) { if (sstr) { *slen = entry.len; *sstr = p+entry.headersize; } } else { if (sval) { *sval = zipLoadInteger(p+entry.headersize,entry.encoding); } } return 1; }
0
[ "CWE-190" ]
redis
f6a40570fa63d5afdd596c78083d754081d80ae3
54,776,647,695,959,480,000,000,000,000,000,000,000
18
Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628) - fix possible heap corruption in ziplist and listpack resulting by trying to allocate more than the maximum size of 4GB. - prevent ziplist (hash and zset) from reaching size of above 1GB, will be converted to HT encoding, that's not a useful size. - prevent listpack (stream) from reaching size of above 1GB. - XADD will start a new listpack if the new record may cause the previous listpack to grow over 1GB. - XADD will respond with an error if a single stream record is over 1GB - List type (ziplist in quicklist) was truncating strings that were over 4GB, now it'll respond with an error.
static void tcp_chr_update_read_handler(CharDriverState *chr, GMainContext *context) { TCPCharDriver *s = chr->opaque; if (!s->connected) { return; } remove_fd_in_watch(chr); if (s->ioc) { chr->fd_in_tag = io_add_watch_poll(s->ioc, tcp_chr_read_poll, tcp_chr_read, chr, context); } }
0
[ "CWE-416" ]
qemu
a4afa548fc6dd9842ed86639b4d37d4d1c4ad480
198,744,349,615,614,840,000,000,000,000,000,000,000
17
char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
void sqlite3WindowDelete(sqlite3 *db, Window *p){ if( p ){ sqlite3WindowUnlinkFromSelect(p); sqlite3ExprDelete(db, p->pFilter); sqlite3ExprListDelete(db, p->pPartition); sqlite3ExprListDelete(db, p->pOrderBy); sqlite3ExprDelete(db, p->pEnd); sqlite3ExprDelete(db, p->pStart); sqlite3DbFree(db, p->zName); sqlite3DbFree(db, p->zBase); sqlite3DbFree(db, p); } }
0
[ "CWE-476" ]
sqlite
75e95e1fcd52d3ec8282edb75ac8cd0814095d54
34,015,962,190,283,540,000,000,000,000,000,000,000
13
When processing constant integer values in ORDER BY clauses of window definitions (see check-in [7e4809eadfe99ebf]) be sure to fully disable the constant value to avoid an invalid pointer dereference if the expression is ever duplicated. This fixes a crash report from Yongheng and Rui. FossilOrigin-Name: 1ca0bd982ab1183bbafce0d260e4dceda5eb766ed2e7793374a88d1ae0bdd2ca
f_json_encode(typval_T *argvars, typval_T *rettv) { rettv->v_type = VAR_STRING; rettv->vval.v_string = json_encode(&argvars[0], 0); }
0
[ "CWE-78" ]
vim
8c62a08faf89663e5633dc5036cd8695c80f1075
306,137,656,929,614,840,000,000,000,000,000,000,000
5
patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.
signcolumn_on(win_T *wp) { if (*wp->w_p_scl == 'n') return FALSE; if (*wp->w_p_scl == 'y') return TRUE; return (wp->w_buffer->b_signlist != NULL # ifdef FEAT_NETBEANS_INTG || wp->w_buffer->b_has_sign_column # endif ); }
0
[ "CWE-20" ]
vim
d0b5138ba4bccff8a744c99836041ef6322ed39a
127,173,928,497,678,300,000,000,000,000,000,000,000
12
patch 8.0.0056 Problem: When setting 'filetype' there is no check for a valid name. Solution: Only allow valid characters in 'filetype', 'syntax' and 'keymap'.
int fuse_set_acl(struct inode *inode, struct posix_acl *acl, int type) { struct fuse_conn *fc = get_fuse_conn(inode); const char *name; int ret; if (fuse_is_bad(inode)) return -EIO; if (!fc->posix_acl || fc->no_setxattr) return -EOPNOTSUPP; if (type == ACL_TYPE_ACCESS) name = XATTR_NAME_POSIX_ACL_ACCESS; else if (type == ACL_TYPE_DEFAULT) name = XATTR_NAME_POSIX_ACL_DEFAULT; else return -EINVAL; if (acl) { /* * Fuse userspace is responsible for updating access * permissions in the inode, if needed. fuse_setxattr * invalidates the inode attributes, which will force * them to be refreshed the next time they are used, * and it also updates i_ctime. */ size_t size = posix_acl_xattr_size(acl->a_count); void *value; if (size > PAGE_SIZE) return -E2BIG; value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; ret = posix_acl_to_xattr(fc->user_ns, acl, value, size); if (ret < 0) { kfree(value); return ret; } ret = fuse_setxattr(inode, name, value, size, 0); kfree(value); } else { ret = fuse_removexattr(inode, name); } forget_all_cached_acls(inode); fuse_invalidate_attr(inode); return ret; }
0
[ "CWE-459" ]
linux
5d069dbe8aaf2a197142558b6fb2978189ba3454
1,883,347,907,890,635,000,000,000,000,000,000,000
53
fuse: fix bad inode Jan Kara's analysis of the syzbot report (edited): The reproducer opens a directory on FUSE filesystem, it then attaches dnotify mark to the open directory. After that a fuse_do_getattr() call finds that attributes returned by the server are inconsistent, and calls make_bad_inode() which, among other things does: inode->i_mode = S_IFREG; This then confuses dnotify which doesn't tear down its structures properly and eventually crashes. Avoid calling make_bad_inode() on a live inode: switch to a private flag on the fuse inode. Also add the test to ops which the bad_inode_ops would have caught. This bug goes back to the initial merge of fuse in 2.6.14... Reported-by: [email protected] Signed-off-by: Miklos Szeredi <[email protected]> Tested-by: Jan Kara <[email protected]> Cc: <[email protected]>
void die_mem(void) { die(421, LOG_ERR, MSG_OUT_OF_MEMORY); }
0
[ "CWE-434" ]
pure-ftpd
37ad222868e52271905b94afea4fc780d83294b4
220,954,815,835,613,300,000,000,000,000,000,000,000
4
Initialize the max upload file size when quotas are enabled Due to an unwanted check, files causing the quota to be exceeded were deleted after the upload, but not during the upload. The bug was introduced in 2009 in version 1.0.23 Spotted by @DroidTest, thanks!
find_nextcmd(char_u *p) { while (*p != '|' && *p != '\n') { if (*p == NUL) return NULL; ++p; } return (p + 1); }
0
[ "CWE-78" ]
vim
8c62a08faf89663e5633dc5036cd8695c80f1075
249,004,353,824,092,500,000,000,000,000,000,000,000
10
patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.
static size_t fr_dhcp_vp2attr(VALUE_PAIR *vp, uint8_t *p, size_t room) { size_t length; uint32_t lvalue; /* * FIXME: Check room! */ room = room; /* -Wunused */ /* * Search for all attributes of the same * type, and pack them into the same * attribute. */ switch (vp->type) { case PW_TYPE_BYTE: length = 1; *p = vp->vp_integer & 0xff; break; case PW_TYPE_SHORT: length = 2; p[0] = (vp->vp_integer >> 8) & 0xff; p[1] = vp->vp_integer & 0xff; break; case PW_TYPE_INTEGER: length = 4; lvalue = htonl(vp->vp_integer); memcpy(p, &lvalue, 4); break; case PW_TYPE_IPADDR: length = 4; memcpy(p, &vp->vp_ipaddr, 4); break; case PW_TYPE_ETHERNET: length = 6; memcpy(p, &vp->vp_ether, 6); break; case PW_TYPE_STRING: memcpy(p, vp->vp_strvalue, vp->length); length = vp->length; break; case PW_TYPE_TLV: /* FIXME: split it on 255? */ memcpy(p, vp->vp_tlv, vp->length); length = vp->length; break; case PW_TYPE_OCTETS: memcpy(p, vp->vp_octets, vp->length); length = vp->length; break; default: fr_strerror_printf("BAD TYPE2 %d", vp->type); length = 0; break; } return length; }
0
[ "CWE-399" ]
freeradius-server
4dc7800b866f889a1247685bbaa6dd4238a56279
52,765,755,640,295,700,000,000,000,000,000,000,000
66
Fix endless loop when there are multiple DHCP options
GF_Err cslg_box_size(GF_Box *s) { GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s; ptr->size += 20; return GF_OK; }
0
[ "CWE-787" ]
gpac
388ecce75d05e11fc8496aa4857b91245007d26e
230,602,833,927,760,800,000,000,000,000,000,000,000
7
fixed #1587
bgp_read (struct thread *thread) { int ret; u_char type = 0; struct peer *peer; bgp_size_t size; char notify_data_length[2]; /* Yes first of all get peer pointer. */ peer = THREAD_ARG (thread); peer->t_read = NULL; /* For non-blocking IO check. */ if (peer->status == Connect) { bgp_connect_check (peer); goto done; } else { if (peer->fd < 0) { zlog_err ("bgp_read peer's fd is negative value %d", peer->fd); return -1; } BGP_READ_ON (peer->t_read, bgp_read, peer->fd); } /* Read packet header to determine type of the packet */ if (peer->packet_size == 0) peer->packet_size = BGP_HEADER_SIZE; if (stream_get_endp (peer->ibuf) < BGP_HEADER_SIZE) { ret = bgp_read_packet (peer); /* Header read error or partial read packet. */ if (ret < 0) goto done; /* Get size and type. */ stream_forward_getp (peer->ibuf, BGP_MARKER_SIZE); memcpy (notify_data_length, stream_pnt (peer->ibuf), 2); size = stream_getw (peer->ibuf); type = stream_getc (peer->ibuf); if (BGP_DEBUG (normal, NORMAL) && type != 2 && type != 0) zlog_debug ("%s rcv message type %d, length (excl. header) %d", peer->host, type, size - BGP_HEADER_SIZE); /* Marker check */ if (((type == BGP_MSG_OPEN) || (type == BGP_MSG_KEEPALIVE)) && ! bgp_marker_all_one (peer->ibuf, BGP_MARKER_SIZE)) { bgp_notify_send (peer, BGP_NOTIFY_HEADER_ERR, BGP_NOTIFY_HEADER_NOT_SYNC); goto done; } /* BGP type check. */ if (type != BGP_MSG_OPEN && type != BGP_MSG_UPDATE && type != BGP_MSG_NOTIFY && type != BGP_MSG_KEEPALIVE && type != BGP_MSG_ROUTE_REFRESH_NEW && type != BGP_MSG_ROUTE_REFRESH_OLD && type != BGP_MSG_CAPABILITY) { if (BGP_DEBUG (normal, NORMAL)) plog_debug (peer->log, "%s unknown message type 0x%02x", peer->host, type); bgp_notify_send_with_data (peer, BGP_NOTIFY_HEADER_ERR, BGP_NOTIFY_HEADER_BAD_MESTYPE, &type, 1); goto done; } /* Mimimum packet length check. */ if ((size < BGP_HEADER_SIZE) || (size > BGP_MAX_PACKET_SIZE) || (type == BGP_MSG_OPEN && size < BGP_MSG_OPEN_MIN_SIZE) || (type == BGP_MSG_UPDATE && size < BGP_MSG_UPDATE_MIN_SIZE) || (type == BGP_MSG_NOTIFY && size < BGP_MSG_NOTIFY_MIN_SIZE) || (type == BGP_MSG_KEEPALIVE && size != BGP_MSG_KEEPALIVE_MIN_SIZE) || (type == BGP_MSG_ROUTE_REFRESH_NEW && size < BGP_MSG_ROUTE_REFRESH_MIN_SIZE) || (type == BGP_MSG_ROUTE_REFRESH_OLD && size < BGP_MSG_ROUTE_REFRESH_MIN_SIZE) || (type == BGP_MSG_CAPABILITY && size < BGP_MSG_CAPABILITY_MIN_SIZE)) { if (BGP_DEBUG (normal, NORMAL)) plog_debug (peer->log, "%s bad message length - %d for %s", peer->host, size, type == 128 ? "ROUTE-REFRESH" : bgp_type_str[(int) type]); bgp_notify_send_with_data (peer, BGP_NOTIFY_HEADER_ERR, BGP_NOTIFY_HEADER_BAD_MESLEN, (u_char *) notify_data_length, 2); goto done; } /* Adjust size to message length. */ peer->packet_size = size; } ret = bgp_read_packet (peer); if (ret < 0) goto done; /* Get size and type again. */ size = stream_getw_from (peer->ibuf, BGP_MARKER_SIZE); type = stream_getc_from (peer->ibuf, BGP_MARKER_SIZE + 2); /* BGP packet dump function. */ bgp_dump_packet (peer, type, peer->ibuf); size = (peer->packet_size - BGP_HEADER_SIZE); /* Read rest of the packet and call each sort of packet routine */ switch (type) { case BGP_MSG_OPEN: peer->open_in++; bgp_open_receive (peer, size); /* XXX return value ignored! */ break; case BGP_MSG_UPDATE: peer->readtime = time(NULL); /* Last read timer reset */ bgp_update_receive (peer, size); break; case BGP_MSG_NOTIFY: bgp_notify_receive (peer, size); break; case BGP_MSG_KEEPALIVE: peer->readtime = time(NULL); /* Last read timer reset */ bgp_keepalive_receive (peer, size); break; case BGP_MSG_ROUTE_REFRESH_NEW: case BGP_MSG_ROUTE_REFRESH_OLD: peer->refresh_in++; bgp_route_refresh_receive (peer, size); break; case BGP_MSG_CAPABILITY: peer->dynamic_cap_in++; bgp_capability_receive (peer, size); break; } /* Clear input buffer. */ peer->packet_size = 0; if (peer->ibuf) stream_reset (peer->ibuf); done: if (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER)) { if (BGP_DEBUG (events, EVENTS)) zlog_debug ("%s [Event] Accepting BGP peer delete", peer->host); peer_delete (peer); } return 0; }
0
[ "CWE-119" ]
quagga
5861739f8c38bc36ea9955e5cb2be2bf2f482d70
109,352,594,758,732,730,000,000,000,000,000,000,000
161
bgpd: Open option parse errors don't NOTIFY, resulting in abort & DoS * bgp_packet.c: (bgp_open_receive) Errors from bgp_open_option_parse are detected, and the code will stop processing the OPEN and return. However it does so without calling bgp_notify_send to send a NOTIFY - which means the peer FSM doesn't get stopped, and bgp_read will be called again later. Because it returns, it doesn't go through the code near the end of the function that removes the current message from the peer input streaam. Thus the next call to bgp_read will try to parse a half-parsed stream as if it were a new BGP message, leading to an assert later in the code when it tries to read stuff that isn't there. Add the required call to bgp_notify_send before returning. * bgp_open.c: (bgp_capability_as4) Be a bit stricter, check the length field corresponds to the only value it can be, which is the amount we're going to read off the stream. And make sure the capability flag gets set, so callers can know this capability was read, regardless. (peek_for_as4_capability) Let bgp_capability_as4 do the length check.
static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) { char *f_org, *f_dest; int f_org_len, f_dest_len; long height, width, threshold; gdImagePtr im_org, im_dest, im_tmp; char *fn_org = NULL; char *fn_dest = NULL; FILE *org, *dest; int dest_height = -1; int dest_width = -1; int org_height, org_width; int white, black; int color, color_org, median; int int_threshold; int x, y; float x_ratio, y_ratio; long ignore_warning; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { return; } fn_org = f_org; fn_dest = f_dest; dest_height = height; dest_width = width; int_threshold = threshold; /* Check threshold value */ if (int_threshold < 0 || int_threshold > 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold); RETURN_FALSE; } /* Check origin file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename"); /* Check destination file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename"); /* Open origin file */ org = VCWD_FOPEN(fn_org, "rb"); if (!org) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org); RETURN_FALSE; } /* Open destination file */ dest = VCWD_FOPEN(fn_dest, "wb"); if (!dest) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest); RETURN_FALSE; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im_org = gdImageCreateFromJpegEx(org, ignore_warning); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_PNG */ default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported"); RETURN_FALSE; break; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == NULL ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); RETURN_FALSE; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); fclose(org); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer"); RETURN_FALSE; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } int_threshold = int_threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < int_threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageDestroy (im_tmp ); gdImageWBMP(im_dest, black , dest); fflush(dest); fclose(dest); gdImageDestroy(im_dest); RETURN_TRUE; }
0
[ "CWE-787" ]
php-src
1bd103df00f49cf4d4ade2cfe3f456ac058a4eae
146,689,725,264,105,230,000,000,000,000,000,000,000
174
Fix bug #72730 - imagegammacorrect allows arbitrary write access
void ssh_bind_set_blocking(ssh_bind sshbind, int blocking) { sshbind->blocking = blocking ? 1 : 0; }
0
[ "CWE-310" ]
libssh
e99246246b4061f7e71463f8806b9dcad65affa0
66,436,326,604,983,380,000,000,000,000,000,000,000
3
security: fix for vulnerability CVE-2014-0017 When accepting a new connection, a forking server based on libssh forks and the child process handles the request. The RAND_bytes() function of openssl doesn't reset its state after the fork, but simply adds the current process id (getpid) to the PRNG state, which is not guaranteed to be unique. This can cause several children to end up with same PRNG state which is a security issue.
PHP_FUNCTION(scandir) { char *dirn; int dirn_len; long flags = 0; char **namelist; int n, i; zval *zcontext = NULL; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lr", &dirn, &dirn_len, &flags, &zcontext) == FAILURE) { return; } if (dirn_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Directory name cannot be empty"); RETURN_FALSE; } if (zcontext) { context = php_stream_context_from_zval(zcontext, 0); } if (flags == PHP_SCANDIR_SORT_ASCENDING) { n = php_stream_scandir(dirn, &namelist, context, (void *) php_stream_dirent_alphasort); } else if (flags == PHP_SCANDIR_SORT_NONE) { n = php_stream_scandir(dirn, &namelist, context, NULL); } else { n = php_stream_scandir(dirn, &namelist, context, (void *) php_stream_dirent_alphasortr); } if (n < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "(errno %d): %s", errno, strerror(errno)); RETURN_FALSE; } array_init(return_value); for (i = 0; i < n; i++) { add_next_index_string(return_value, namelist[i], 0); } if (n) { efree(namelist); } }
1
[ "CWE-19" ]
php-src
be9b2a95adb504abd5acdc092d770444ad6f6854
239,845,067,077,705,940,000,000,000,000,000,000,000
45
Fixed bug #69418 - more s->p fixes for filenames
GF_Box *bloc_New() { ISOM_DECL_BOX_ALLOC(GF_BaseLocationBox, GF_ISOM_BOX_TYPE_TRIK); return (GF_Box *)tmp; }
0
[ "CWE-125" ]
gpac
bceb03fd2be95097a7b409ea59914f332fb6bc86
162,726,655,246,920,660,000,000,000,000,000,000,000
5
fixed 2 possible heap overflows (inc. #1088)
static int vrend_renderer_transfer_internal(struct vrend_context *ctx, struct vrend_resource *res, const struct vrend_transfer_info *info, int transfer_mode) { const struct iovec *iov; int num_iovs; if (!info->box) return EINVAL; vrend_hw_switch_context(ctx, true); assert(check_transfer_iovec(res, info)); if (info->iovec && info->iovec_cnt) { iov = info->iovec; num_iovs = info->iovec_cnt; } else { iov = res->iov; num_iovs = res->num_iovs; } #ifdef ENABLE_MINIGBM_ALLOCATION if (res->gbm_bo && (transfer_mode == VIRGL_TRANSFER_TO_HOST || !has_bit(res->storage_bits, VREND_STORAGE_EGL_IMAGE))) { assert(!info->synchronized); return virgl_gbm_transfer(res->gbm_bo, transfer_mode, iov, num_iovs, info); } #endif if (!check_transfer_bounds(res, info)) { vrend_report_context_error(ctx, VIRGL_ERROR_CTX_TRANSFER_IOV_BOUNDS, res->id); return EINVAL; } if (!check_iov_bounds(res, info, iov, num_iovs)) { vrend_report_context_error(ctx, VIRGL_ERROR_CTX_TRANSFER_IOV_BOUNDS, res->id); return EINVAL; } switch (transfer_mode) { case VIRGL_TRANSFER_TO_HOST: return vrend_renderer_transfer_write_iov(ctx, res, iov, num_iovs, info); case VIRGL_TRANSFER_FROM_HOST: return vrend_renderer_transfer_send_iov(ctx, res, iov, num_iovs, info); default: assert(0); } return 0; }
0
[ "CWE-787" ]
virglrenderer
95e581fd181b213c2ed7cdc63f2abc03eaaa77ec
73,016,196,099,344,880,000,000,000,000,000,000,000
51
vrend: Add test to resource OOB write and fix it v2: Also check that no depth != 1 has been send when none is due Closes: #250 Signed-off-by: Gert Wollny <[email protected]> Reviewed-by: Chia-I Wu <[email protected]>
static av_cold int dnxhd_decode_close(AVCodecContext *avctx) { DNXHDContext *ctx = avctx->priv_data; ff_free_vlc(&ctx->ac_vlc); ff_free_vlc(&ctx->dc_vlc); ff_free_vlc(&ctx->run_vlc); av_freep(&ctx->rows); return 0; }
0
[ "CWE-125" ]
FFmpeg
f31fc4755f69ab26bf6e8be47875b7dcede8e29e
28,254,768,277,242,985,000,000,000,000,000,000,000
12
avcodec/dnxhddec: Move mb height check out of non hr branch Fixes: out of array access Fixes: poc.dnxhd Found-by: Bingchang, Liu@VARAS of IIE Signed-off-by: Michael Niedermayer <[email protected]> (cherry picked from commit 296debd213bd6dce7647cedd34eb64e5b94cdc92) Signed-off-by: Michael Niedermayer <[email protected]>
void usb_buffer_dmasync_sg(const struct usb_device *dev, int is_in, struct scatterlist *sg, int n_hw_ents) { struct usb_bus *bus; struct device *controller; if (!dev || !(bus = dev->bus) || !(controller = bus->sysdev) || !controller->dma_mask) return; dma_sync_sg_for_cpu(controller, sg, n_hw_ents, is_in ? DMA_FROM_DEVICE : DMA_TO_DEVICE); }
0
[ "CWE-400", "CWE-703" ]
linux
704620afc70cf47abb9d6a1a57f3825d2bca49cf
252,706,917,434,284,000,000,000,000,000,000,000,000
15
USB: check usb_get_extra_descriptor for proper size When reading an extra descriptor, we need to properly check the minimum and maximum size allowed, to prevent from invalid data being sent by a device. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Co-developed-by: Linus Torvalds <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>
static int tg3_bmcr_reset(struct tg3 *tp) { u32 phy_control; int limit, err; /* OK, reset it, and poll the BMCR_RESET bit until it * clears or we time out. */ phy_control = BMCR_RESET; err = tg3_writephy(tp, MII_BMCR, phy_control); if (err != 0) return -EBUSY; limit = 5000; while (limit--) { err = tg3_readphy(tp, MII_BMCR, &phy_control); if (err != 0) return -EBUSY; if ((phy_control & BMCR_RESET) == 0) { udelay(40); break; } udelay(10); } if (limit < 0) return -EBUSY; return 0; }
0
[ "CWE-476", "CWE-119" ]
linux
715230a44310a8cf66fbfb5a46f9a62a9b2de424
208,971,380,334,235,740,000,000,000,000,000,000,000
30
tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <[email protected]> Reported-by: Oded Horovitz <[email protected]> Reported-by: Brad Spengler <[email protected]> Cc: [email protected] Cc: Matt Carlson <[email protected]> Signed-off-by: David S. Miller <[email protected]>
size_t olm_pk_signing_public_key_length(void) { return olm::encode_base64_length(ED25519_PUBLIC_KEY_LENGTH); }
0
[ "CWE-787" ]
olm
ccc0d122ee1b4d5e5ca4ec1432086be17d5f901b
245,363,197,810,681,200,000,000,000,000,000,000,000
3
olm_pk_decrypt: Ensure inputs are of correct length.
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; // Special case of managed counter: Usage instead of Value in Meter table, and we don't want to calculate last value 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 { //week,year,month 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 { //this meter has no decimals, so return the use peaks 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; //CM113 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; //CM113 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"]; //First check if we had any usage in the short log, if not, its probably a meter without usage 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) { //realtime graph 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; //If method == 1, provide BOTH hourly and instant usage for combined graph { //bars / hour 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 + (method == 1 ? ":30" : ":00"); //^^ not necessarily bad, but is currently inconsistent with all other day graphs root["result"][ii]["d"] = LastDateTime + ":00"; long long ulTotalValue = ulLastValue - ulFirstValue; if (ulTotalValue == 0) { //Could be the P1 Gas Meter, only transmits one every 1 a 2 hours 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) { //bars / hour 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 = float(actValue - ulFirstValue); //prevents graph from going crazy if the meter counter resets float TotalValue = (actValue >= ulFirstValue) ? float(actValue - ulFirstValue) : actValue; //if (TotalValue != 0) { 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 { //realtime graph 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); //if (TotalValue != 0) { 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)) { //add last value root["result"][ii]["d"] = LastDateTime + ":00"; unsigned long long ulTotalValue = ulLastValue - ulFirstValue; float TotalValue = float(ulTotalValue); //if (TotalValue != 0) { 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) { //Looks like we have a GAP somewhere, finish the last hour 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; //init dir list 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 { //Todo ! 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 { //Still todo ! 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); //Subtract one week 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++; } } //add today (have to calculate it) 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); //Subtract one week 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: //value already set above! break; default: szValue = "0"; break; } root["result"][ii]["v"] = szValue; ii++; } } } //add today (have to calculate it) 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: //value already set above! 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") { //Subtract one month time_t monthbefore; getNoon(monthbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon, tm1.tm_mday); } else { //Subtract one year 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; //Actual Year 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++; } } //add today (have to calculate it) 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++; } //Previous Year 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++; } } //add today (have to calculate it) 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++; } } //add today (have to calculate it) 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++; } } //add today (have to calculate it) 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++; } //Previous Year 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++; } } //add today (have to calculate it) 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++; } //Previous Year 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) { //Actual Year 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; } } //Previous Year 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()) { //CM113 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()) { //CM180i 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) { //Add last counter value 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) { //Add last counter value 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) { //Add last counter value 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) { //Add last counter value sprintf(szTmp, "%d", atoi(sValue.c_str())); root["counter"] = szTmp; } else { root["counter"] = "0"; } //Actual Year 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++; } } //Past Year 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++; } } } //add today (have to calculate it) 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++; } } //add today (have to calculate it) 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++; } //Previous Year 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") { // Need to get all values of the end date so 23:59:59 is appended to the date string 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++; } } //add today (have to calculate it) 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++; } } //add today (have to calculate it) 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++; } } //add today (have to calculate it) 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++; } } } //add today (have to calculate it) 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++; } } //add today (have to calculate it) 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 }
0
[ "CWE-89" ]
domoticz
ee70db46f81afa582c96b887b73bcd2a86feda00
189,470,439,754,055,120,000,000,000,000,000,000,000
3,881
Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
exif_data_load_data_entry (ExifData *data, ExifEntry *entry, const unsigned char *d, unsigned int size, unsigned int offset) { unsigned int s, doff; entry->tag = exif_get_short (d + offset + 0, data->priv->order); entry->format = exif_get_short (d + offset + 2, data->priv->order); entry->components = exif_get_long (d + offset + 4, data->priv->order); /* FIXME: should use exif_tag_get_name_in_ifd here but entry->parent * has not been set yet */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading entry 0x%x ('%s')...", entry->tag, exif_tag_get_name (entry->tag)); /* {0,1,2,4,8} x { 0x00000000 .. 0xffffffff } * -> { 0x000000000 .. 0x7fffffff8 } */ s = exif_format_get_size(entry->format) * entry->components; if ((s < entry->components) || (s == 0)){ return 0; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ if (s > 4) doff = exif_get_long (d + offset + 8, data->priv->order); else doff = offset + 8; /* Sanity checks */ if (doff >= size) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Tag starts past end of buffer (%u > %u)", doff, size); return 0; } if (s > size - doff) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Tag data goes past end of buffer (%u > %u)", doff+s, size); return 0; } entry->data = exif_data_alloc (data, s); if (entry->data) { entry->size = s; memcpy (entry->data, d + doff, s); } else { EXIF_LOG_NO_MEMORY(data->priv->log, "ExifData", s); return 0; } /* If this is the MakerNote, remember the offset */ if (entry->tag == EXIF_TAG_MAKER_NOTE) { if (!entry->data) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found with empty data"); } else if (entry->size > 6) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found (%02x %02x %02x %02x " "%02x %02x %02x...).", entry->data[0], entry->data[1], entry->data[2], entry->data[3], entry->data[4], entry->data[5], entry->data[6]); } data->priv->offset_mnote = doff; } return 1; }
0
[ "CWE-190", "CWE-787" ]
libexif
75aa73267fdb1e0ebfbc00369e7312bac43d0566
275,938,330,846,733,770,000,000,000,000,000,000,000
73
fix CVE-2019-9278 avoid the use of unsafe integer overflow checking constructs (unsigned integer operations cannot overflow, so "u1 + u2 > u1" can be optimized away) check for the actual sizes, which should also handle the overflows document other places google patched, but do not seem relevant due to other restrictions fixes https://github.com/libexif/libexif/issues/26
fm_mgr_config_connect ( IN p_fm_config_conx_hdlt p_hdl ) { fm_config_conx_hdl *hdl = p_hdl; fm_mgr_config_errno_t res = FM_CONF_OK; int fail_count = 0; if ( (res = fm_mgr_config_mgr_connect(hdl, FM_MGR_SM)) == FM_CONF_INIT_ERR ) { res = FM_CONF_INIT_ERR; goto cleanup; } if(res != FM_CONF_OK) fail_count++; if ( (res = fm_mgr_config_mgr_connect(hdl, FM_MGR_PM)) == FM_CONF_INIT_ERR ) { res = FM_CONF_INIT_ERR; goto cleanup; } if(res != FM_CONF_OK) fail_count++; if ( (res = fm_mgr_config_mgr_connect(hdl, FM_MGR_FE)) == FM_CONF_INIT_ERR ) { res = FM_CONF_INIT_ERR; goto cleanup; } if(res != FM_CONF_OK) fail_count++; if(fail_count < 4){ res = FM_CONF_OK; } cleanup: return res; }
0
[ "CWE-362" ]
opa-fm
c5759e7b76f5bf844be6c6641cc1b356bbc83869
158,558,358,561,673,630,000,000,000,000,000,000,000
44
Fix scripts and code that use well-known tmp files.
static void sev_es_sync_to_ghcb(struct vcpu_svm *svm) { struct kvm_vcpu *vcpu = &svm->vcpu; struct ghcb *ghcb = svm->sev_es.ghcb; /* * The GHCB protocol so far allows for the following data * to be returned: * GPRs RAX, RBX, RCX, RDX * * Copy their values, even if they may not have been written during the * VM-Exit. It's the guest's responsibility to not consume random data. */ ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]); ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]); ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]); ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]); }
0
[ "CWE-459" ]
linux
683412ccf61294d727ead4a73d97397396e69a6b
80,999,021,635,491,760,000,000,000,000,000,000,000
18
KVM: SEV: add cache flush to solve SEV cache incoherency issues Flush the CPU caches when memory is reclaimed from an SEV guest (where reclaim also includes it being unmapped from KVM's memslots). Due to lack of coherency for SEV encrypted memory, failure to flush results in silent data corruption if userspace is malicious/broken and doesn't ensure SEV guest memory is properly pinned and unpinned. Cache coherency is not enforced across the VM boundary in SEV (AMD APM vol.2 Section 15.34.7). Confidential cachelines, generated by confidential VM guests have to be explicitly flushed on the host side. If a memory page containing dirty confidential cachelines was released by VM and reallocated to another user, the cachelines may corrupt the new user at a later time. KVM takes a shortcut by assuming all confidential memory remain pinned until the end of VM lifetime. Therefore, KVM does not flush cache at mmu_notifier invalidation events. Because of this incorrect assumption and the lack of cache flushing, malicous userspace can crash the host kernel: creating a malicious VM and continuously allocates/releases unpinned confidential memory pages when the VM is running. Add cache flush operations to mmu_notifier operations to ensure that any physical memory leaving the guest VM get flushed. In particular, hook mmu_notifier_invalidate_range_start and mmu_notifier_release events and flush cache accordingly. The hook after releasing the mmu lock to avoid contention with other vCPUs. Cc: [email protected] Suggested-by: Sean Christpherson <[email protected]> Reported-by: Mingwei Zhang <[email protected]> Signed-off-by: Mingwei Zhang <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
QVectorPath::~QVectorPath() { if (m_hints & ShouldUseCacheHint) { CacheEntry *e = m_cache; while (e) { if (e->data) e->cleanup(e->engine, e->data); CacheEntry *n = e->next; delete e; e = n; } } }
0
[ "CWE-787" ]
qtbase
6b400e3147dcfd8cc3a393ace1bd118c93762e0c
174,355,243,938,003,500,000,000,000,000,000,000,000
13
Improve fix for avoiding huge number of tiny dashes Some pathological cases were not caught by the previous fix. Fixes: QTBUG-95239 Pick-to: 6.2 6.1 5.15 Change-Id: I0337ee3923ff93ccb36c4d7b810a9c0667354cc5 Reviewed-by: Robert Löhning <[email protected]>
static void analysis_emul_restore(RzCore *core, RzConfigHold *hc, RzDebugTrace *dt, RzAnalysisEsilTrace *et) { rz_config_hold_restore(hc); rz_config_hold_free(hc); rz_debug_trace_free(core->dbg->trace); rz_analysis_esil_trace_free(core->analysis->esil->trace); core->analysis->esil->trace = et; core->dbg->trace = dt; }
0
[ "CWE-703" ]
rizin
6ce71d8aa3dafe3cdb52d5d72ae8f4b95916f939
183,353,557,505,630,000,000,000,000,000,000,000,000
8
Initialize retctx,ctx before freeing the inner elements In rz_core_analysis_type_match retctx structure was initialized on the stack only after a "goto out_function", where a field of that structure was freed. When the goto path is taken, the field is not properly initialized and it cause cause a crash of Rizin or have other effects. Fixes: CVE-2021-4022
word32 SetSequence(word32 len, byte* output) { output[0] = SEQUENCE | CONSTRUCTED; return SetLength(len, output + 1) + 1; }
0
[ "CWE-254" ]
mysql-server
e7061f7e5a96c66cb2e0bf46bec7f6ff35801a69
219,838,060,372,036,000,000,000,000,000,000,000,000
6
Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.
static bool check_same_owner(struct task_struct *p) { const struct cred *cred = current_cred(), *pcred; bool match; rcu_read_lock(); pcred = __task_cred(p); match = (cred->euid == pcred->euid || cred->euid == pcred->uid); rcu_read_unlock(); return match; }
0
[ "CWE-703", "CWE-835" ]
linux
f26f9aff6aaf67e9a430d16c266f91b13a5bff64
291,968,361,877,782,540,000,000,000,000,000,000,000
12
Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]>
void tracing_start(void) { struct ring_buffer *buffer; unsigned long flags; if (tracing_disabled) return; raw_spin_lock_irqsave(&global_trace.start_lock, flags); if (--global_trace.stop_count) { if (global_trace.stop_count < 0) { /* Someone screwed up their debugging */ WARN_ON_ONCE(1); global_trace.stop_count = 0; } goto out; } /* Prevent the buffers from switching */ arch_spin_lock(&global_trace.max_lock); buffer = global_trace.trace_buffer.buffer; if (buffer) ring_buffer_record_enable(buffer); #ifdef CONFIG_TRACER_MAX_TRACE buffer = global_trace.max_buffer.buffer; if (buffer) ring_buffer_record_enable(buffer); #endif arch_spin_unlock(&global_trace.max_lock); out: raw_spin_unlock_irqrestore(&global_trace.start_lock, flags); }
0
[ "CWE-415" ]
linux
4397f04575c44e1440ec2e49b6302785c95fd2f8
86,262,480,888,928,670,000,000,000,000,000,000,000
36
tracing: Fix possible double free on failure of allocating trace buffer Jing Xia and Chunyan Zhang reported that on failing to allocate part of the tracing buffer, memory is freed, but the pointers that point to them are not initialized back to NULL, and later paths may try to free the freed memory again. Jing and Chunyan fixed one of the locations that does this, but missed a spot. Link: http://lkml.kernel.org/r/[email protected] Cc: [email protected] Fixes: 737223fbca3b1 ("tracing: Consolidate buffer allocation code") Reported-by: Jing Xia <[email protected]> Reported-by: Chunyan Zhang <[email protected]> Signed-off-by: Steven Rostedt (VMware) <[email protected]>
static void tctx_task_work(struct callback_head *cb) { bool uring_locked = false; struct io_ring_ctx *ctx = NULL; struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work); while (1) { struct io_wq_work_node *node1, *node2; spin_lock_irq(&tctx->task_lock); node1 = tctx->prio_task_list.first; node2 = tctx->task_list.first; INIT_WQ_LIST(&tctx->task_list); INIT_WQ_LIST(&tctx->prio_task_list); if (!node2 && !node1) tctx->task_running = false; spin_unlock_irq(&tctx->task_lock); if (!node2 && !node1) break; if (node1) handle_prev_tw_list(node1, &ctx, &uring_locked); if (node2) handle_tw_list(node2, &ctx, &uring_locked); cond_resched(); if (data_race(!tctx->task_list.first) && data_race(!tctx->prio_task_list.first) && uring_locked) io_submit_flush_completions(ctx); } ctx_flush_and_put(ctx, &uring_locked); /* relaxed read is enough as only the task itself sets ->in_idle */ if (unlikely(atomic_read(&tctx->in_idle))) io_uring_drop_tctx_refs(current); }
0
[ "CWE-416" ]
linux
9cae36a094e7e9d6e5fe8b6dcd4642138b3eb0c7
19,913,624,362,063,710,000,000,000,000,000,000,000
38
io_uring: reinstate the inflight tracking After some debugging, it was realized that we really do still need the old inflight tracking for any file type that has io_uring_fops assigned. If we don't, then trivial circular references will mean that we never get the ctx cleaned up and hence it'll leak. Just bring back the inflight tracking, which then also means we can eliminate the conditional dropping of the file when task_work is queued. Fixes: d5361233e9ab ("io_uring: drop the old style inflight file tracking") Signed-off-by: Jens Axboe <[email protected]>
static int virtcons_freeze(struct virtio_device *vdev) { struct ports_device *portdev; struct port *port; portdev = vdev->priv; vdev->config->reset(vdev); virtqueue_disable_cb(portdev->c_ivq); cancel_work_sync(&portdev->control_work); cancel_work_sync(&portdev->config_work); /* * Once more: if control_work_handler() was running, it would * enable the cb as the last step. */ virtqueue_disable_cb(portdev->c_ivq); remove_controlq_data(portdev); list_for_each_entry(port, &portdev->ports, list) { virtqueue_disable_cb(port->in_vq); virtqueue_disable_cb(port->out_vq); /* * We'll ask the host later if the new invocation has * the port opened or closed. */ port->host_connected = false; remove_port_data(port); } remove_vqs(portdev); return 0; }
0
[ "CWE-119", "CWE-787" ]
linux
c4baad50297d84bde1a7ad45e50c73adae4a2192
182,020,656,561,416,050,000,000,000,000,000,000,000
33
virtio-console: avoid DMA from stack put_chars() stuffs the buffer it gets into an sg, but that buffer may be on the stack. This breaks with CONFIG_VMAP_STACK=y (for me, it manifested as printks getting turned into NUL bytes). Signed-off-by: Omar Sandoval <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Reviewed-by: Amit Shah <[email protected]>
lexer_skip_empty_statements (parser_context_t *context_p) /**< context */ { lexer_skip_spaces (context_p); while (context_p->source_p < context_p->source_end_p && *context_p->source_p == LIT_CHAR_SEMICOLON) { lexer_consume_next_character (context_p); lexer_skip_spaces (context_p); } context_p->token.flags = (uint8_t) (context_p->token.flags | LEXER_NO_SKIP_SPACES); } /* lexer_skip_empty_statements */
0
[ "CWE-288" ]
jerryscript
f3a420b672927037beb4508d7bdd68fb25d2caf6
132,914,853,410,743,600,000,000,000,000,000,000,000
12
Fix class static block opening brace parsing (#4942) The next character should not be consumed after finding the static block opening brace. This patch fixes #4916. JerryScript-DCO-1.0-Signed-off-by: Martin Negyokru [email protected]
} #undef CHECK_VAL #undef CHECK_STR #undef CHECK_FRAC return recompute_set; } static void dasher_forward_manifest_raw(GF_DasherCtx *ctx, GF_DashStream *ds, const char *manifest, const char *manifest_name) { GF_FilterPacket *pck; u32 size; u8 *output; size = (u32) strlen(manifest); pck = gf_filter_pck_new_alloc(ctx->opid, size+1, &output); if (!pck) return; memcpy(output, manifest, size); output[size] = 0; gf_filter_pck_set_framing(pck, GF_TRUE, GF_TRUE); gf_filter_pck_set_seek_flag(pck, GF_TRUE); if (manifest_name) { if (ctx->out_path) { char *url = gf_url_concatenate(ctx->out_path, manifest_name); gf_filter_pck_set_property(pck, GF_PROP_PCK_FILENAME, &PROP_STRING_NO_COPY(url) ); } else {
0
[ "CWE-787" ]
gpac
ea1eca00fd92fa17f0e25ac25652622924a9a6a0
37,216,007,860,611,364,000,000,000,000,000,000,000
27
fixed #2138
static int em_ret_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long cs; int cpl = ctxt->ops->cpl(ctxt); rc = emulate_pop(ctxt, &ctxt->_eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; if (ctxt->op_bytes == 4) ctxt->_eip = (u32)ctxt->_eip; rc = emulate_pop(ctxt, &cs, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; /* Outer-privilege level return is not implemented */ if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl) return X86EMUL_UNHANDLEABLE; rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS); return rc; }
1
[]
kvm
d1442d85cc30ea75f7d399474ca738e0bc96f715
299,508,775,925,335,600,000,000,000,000,000,000,000
20
KVM: x86: Handle errors when RIP is set during far jumps Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not handle this case, and may result in failed vm-entry once the assignment is done. The tricky part of doing so is that loading the new CS affects the VMCS/VMCB state, so if we fail during loading the new RIP, we are left in unconsistent state. Therefore, this patch saves on 64-bit the old CS descriptor and restores it if loading RIP failed. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !defined(OS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // defined(OS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; }
0
[]
electron
ea1f402417022c59c0794e97c87e6be2553989e7
266,438,099,735,919,340,000,000,000,000,000,000,000
45
fix: ensure ElectronBrowser mojo service is only bound to appropriate render frames (#33323) (#33350) * fix: ensure ElectronBrowser mojo service is only bound to authorized render frames Notes: no-notes * refactor: extract electron API IPC to its own mojo interface * fix: just check main frame not primary main frame
void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct page *page) { struct f2fs_inode *ri = &F2FS_NODE(page)->i; if (!f2fs_enable_inode_chksum(sbi, page)) return; ri->i_inode_checksum = cpu_to_le32(f2fs_inode_chksum(sbi, page)); }
0
[ "CWE-125" ]
linux
e34438c903b653daca2b2a7de95aed46226f8ed3
50,145,662,393,043,730,000,000,000,000,000,000,000
9
f2fs: fix to do sanity check with node footer and iblocks This patch adds to do sanity check with below fields of inode to avoid reported panic. - node footer - iblocks https://bugzilla.kernel.org/show_bug.cgi?id=200223 - Overview BUG() triggered in f2fs_truncate_inode_blocks() when un-mounting a mounted f2fs image after writing to it - Reproduce - POC (poc.c) static void activity(char *mpoint) { char *foo_bar_baz; int err; static int buf[8192]; memset(buf, 0, sizeof(buf)); err = asprintf(&foo_bar_baz, "%s/foo/bar/baz", mpoint); // open / write / read int fd = open(foo_bar_baz, O_RDWR | O_TRUNC, 0777); if (fd >= 0) { write(fd, (char *)buf, 517); write(fd, (char *)buf, sizeof(buf)); close(fd); } } int main(int argc, char *argv[]) { activity(argv[1]); return 0; } - Kernel meesage [ 552.479723] F2FS-fs (loop0): Mounted with checkpoint version = 2 [ 556.451891] ------------[ cut here ]------------ [ 556.451899] kernel BUG at fs/f2fs/node.c:987! [ 556.452920] invalid opcode: 0000 [#1] SMP KASAN PTI [ 556.453936] CPU: 1 PID: 1310 Comm: umount Not tainted 4.18.0-rc1+ #4 [ 556.455213] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 [ 556.457140] RIP: 0010:f2fs_truncate_inode_blocks+0x4a7/0x6f0 [ 556.458280] Code: e8 ae ea ff ff 41 89 c7 c1 e8 1f 84 c0 74 0a 41 83 ff fe 0f 85 35 ff ff ff 81 85 b0 fe ff ff fb 03 00 00 e9 f7 fd ff ff 0f 0b <0f> 0b e8 62 b7 9a 00 48 8b bd a0 fe ff ff e8 56 54 ae ff 48 8b b5 [ 556.462015] RSP: 0018:ffff8801f292f808 EFLAGS: 00010286 [ 556.463068] RAX: ffffed003e73242d RBX: ffff8801f292f958 RCX: ffffffffb88b81bc [ 556.464479] RDX: 0000000000000000 RSI: 0000000000000004 RDI: ffff8801f3992164 [ 556.465901] RBP: ffff8801f292f980 R08: ffffed003e73242d R09: ffffed003e73242d [ 556.467311] R10: 0000000000000001 R11: ffffed003e73242c R12: 00000000fffffc64 [ 556.468706] R13: ffff8801f3992000 R14: 0000000000000058 R15: 00000000ffff8801 [ 556.470117] FS: 00007f8029297840(0000) GS:ffff8801f6f00000(0000) knlGS:0000000000000000 [ 556.471702] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 556.472838] CR2: 000055f5f57305d8 CR3: 00000001f18b0000 CR4: 00000000000006e0 [ 556.474265] Call Trace: [ 556.474782] ? f2fs_alloc_nid_failed+0xf0/0xf0 [ 556.475686] ? truncate_nodes+0x980/0x980 [ 556.476516] ? pagecache_get_page+0x21f/0x2f0 [ 556.477412] ? __asan_loadN+0xf/0x20 [ 556.478153] ? __get_node_page+0x331/0x5b0 [ 556.478992] ? reweight_entity+0x1e6/0x3b0 [ 556.479826] f2fs_truncate_blocks+0x55e/0x740 [ 556.480709] ? f2fs_truncate_data_blocks+0x20/0x20 [ 556.481689] ? __radix_tree_lookup+0x34/0x160 [ 556.482630] ? radix_tree_lookup+0xd/0x10 [ 556.483445] f2fs_truncate+0xd4/0x1a0 [ 556.484206] f2fs_evict_inode+0x5ce/0x630 [ 556.485032] evict+0x16f/0x290 [ 556.485664] iput+0x280/0x300 [ 556.486300] dentry_unlink_inode+0x165/0x1e0 [ 556.487169] __dentry_kill+0x16a/0x260 [ 556.487936] dentry_kill+0x70/0x250 [ 556.488651] shrink_dentry_list+0x125/0x260 [ 556.489504] shrink_dcache_parent+0xc1/0x110 [ 556.490379] ? shrink_dcache_sb+0x200/0x200 [ 556.491231] ? bit_wait_timeout+0xc0/0xc0 [ 556.492047] do_one_tree+0x12/0x40 [ 556.492743] shrink_dcache_for_umount+0x3f/0xa0 [ 556.493656] generic_shutdown_super+0x43/0x1c0 [ 556.494561] kill_block_super+0x52/0x80 [ 556.495341] kill_f2fs_super+0x62/0x70 [ 556.496105] deactivate_locked_super+0x6f/0xa0 [ 556.497004] deactivate_super+0x5e/0x80 [ 556.497785] cleanup_mnt+0x61/0xa0 [ 556.498492] __cleanup_mnt+0x12/0x20 [ 556.499218] task_work_run+0xc8/0xf0 [ 556.499949] exit_to_usermode_loop+0x125/0x130 [ 556.500846] do_syscall_64+0x138/0x170 [ 556.501609] entry_SYSCALL_64_after_hwframe+0x44/0xa9 [ 556.502659] RIP: 0033:0x7f8028b77487 [ 556.503384] Code: 83 c8 ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 31 f6 e9 09 00 00 00 66 0f 1f 84 00 00 00 00 00 b8 a6 00 00 00 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 8b 0d e1 c9 2b 00 f7 d8 64 89 01 48 [ 556.507137] RSP: 002b:00007fff9f2e3598 EFLAGS: 00000246 ORIG_RAX: 00000000000000a6 [ 556.508637] RAX: 0000000000000000 RBX: 0000000000ebd030 RCX: 00007f8028b77487 [ 556.510069] RDX: 0000000000000001 RSI: 0000000000000000 RDI: 0000000000ec41e0 [ 556.511481] RBP: 0000000000ec41e0 R08: 0000000000000000 R09: 0000000000000014 [ 556.512892] R10: 00000000000006b2 R11: 0000000000000246 R12: 00007f802908083c [ 556.514320] R13: 0000000000000000 R14: 0000000000ebd210 R15: 00007fff9f2e3820 [ 556.515745] Modules linked in: snd_hda_codec_generic snd_hda_intel snd_hda_codec snd_hwdep snd_hda_core snd_pcm snd_timer snd mac_hid i2c_piix4 soundcore ib_iser rdma_cm iw_cm ib_cm ib_core iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi raid10 raid456 async_raid6_recov async_memcpy async_pq async_xor async_tx raid1 raid0 multipath linear 8139too crct10dif_pclmul crc32_pclmul qxl drm_kms_helper syscopyarea aesni_intel sysfillrect sysimgblt fb_sys_fops ttm drm aes_x86_64 crypto_simd cryptd 8139cp glue_helper mii pata_acpi floppy [ 556.529276] ---[ end trace 4ce02f25ff7d3df5 ]--- [ 556.530340] RIP: 0010:f2fs_truncate_inode_blocks+0x4a7/0x6f0 [ 556.531513] Code: e8 ae ea ff ff 41 89 c7 c1 e8 1f 84 c0 74 0a 41 83 ff fe 0f 85 35 ff ff ff 81 85 b0 fe ff ff fb 03 00 00 e9 f7 fd ff ff 0f 0b <0f> 0b e8 62 b7 9a 00 48 8b bd a0 fe ff ff e8 56 54 ae ff 48 8b b5 [ 556.535330] RSP: 0018:ffff8801f292f808 EFLAGS: 00010286 [ 556.536395] RAX: ffffed003e73242d RBX: ffff8801f292f958 RCX: ffffffffb88b81bc [ 556.537824] RDX: 0000000000000000 RSI: 0000000000000004 RDI: ffff8801f3992164 [ 556.539290] RBP: ffff8801f292f980 R08: ffffed003e73242d R09: ffffed003e73242d [ 556.540709] R10: 0000000000000001 R11: ffffed003e73242c R12: 00000000fffffc64 [ 556.542131] R13: ffff8801f3992000 R14: 0000000000000058 R15: 00000000ffff8801 [ 556.543579] FS: 00007f8029297840(0000) GS:ffff8801f6f00000(0000) knlGS:0000000000000000 [ 556.545180] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 556.546338] CR2: 000055f5f57305d8 CR3: 00000001f18b0000 CR4: 00000000000006e0 [ 556.547809] ================================================================== [ 556.549248] BUG: KASAN: stack-out-of-bounds in arch_tlb_gather_mmu+0x52/0x170 [ 556.550672] Write of size 8 at addr ffff8801f292fd10 by task umount/1310 [ 556.552338] CPU: 1 PID: 1310 Comm: umount Tainted: G D 4.18.0-rc1+ #4 [ 556.553886] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 [ 556.555756] Call Trace: [ 556.556264] dump_stack+0x7b/0xb5 [ 556.556944] print_address_description+0x70/0x290 [ 556.557903] kasan_report+0x291/0x390 [ 556.558649] ? arch_tlb_gather_mmu+0x52/0x170 [ 556.559537] __asan_store8+0x57/0x90 [ 556.560268] arch_tlb_gather_mmu+0x52/0x170 [ 556.561110] tlb_gather_mmu+0x12/0x40 [ 556.561862] exit_mmap+0x123/0x2a0 [ 556.562555] ? __ia32_sys_munmap+0x50/0x50 [ 556.563384] ? exit_aio+0x98/0x230 [ 556.564079] ? __x32_compat_sys_io_submit+0x260/0x260 [ 556.565099] ? taskstats_exit+0x1f4/0x640 [ 556.565925] ? kasan_check_read+0x11/0x20 [ 556.566739] ? mm_update_next_owner+0x322/0x380 [ 556.567652] mmput+0x8b/0x1d0 [ 556.568260] do_exit+0x43a/0x1390 [ 556.568937] ? mm_update_next_owner+0x380/0x380 [ 556.569855] ? deactivate_super+0x5e/0x80 [ 556.570668] ? cleanup_mnt+0x61/0xa0 [ 556.571395] ? __cleanup_mnt+0x12/0x20 [ 556.572156] ? task_work_run+0xc8/0xf0 [ 556.572917] ? exit_to_usermode_loop+0x125/0x130 [ 556.573861] rewind_stack_do_exit+0x17/0x20 [ 556.574707] RIP: 0033:0x7f8028b77487 [ 556.575428] Code: Bad RIP value. [ 556.576106] RSP: 002b:00007fff9f2e3598 EFLAGS: 00000246 ORIG_RAX: 00000000000000a6 [ 556.577599] RAX: 0000000000000000 RBX: 0000000000ebd030 RCX: 00007f8028b77487 [ 556.579020] RDX: 0000000000000001 RSI: 0000000000000000 RDI: 0000000000ec41e0 [ 556.580422] RBP: 0000000000ec41e0 R08: 0000000000000000 R09: 0000000000000014 [ 556.581833] R10: 00000000000006b2 R11: 0000000000000246 R12: 00007f802908083c [ 556.583252] R13: 0000000000000000 R14: 0000000000ebd210 R15: 00007fff9f2e3820 [ 556.584983] The buggy address belongs to the page: [ 556.585961] page:ffffea0007ca4bc0 count:0 mapcount:0 mapping:0000000000000000 index:0x0 [ 556.587540] flags: 0x2ffff0000000000() [ 556.588296] raw: 02ffff0000000000 0000000000000000 dead000000000200 0000000000000000 [ 556.589822] raw: 0000000000000000 0000000000000000 00000000ffffffff 0000000000000000 [ 556.591359] page dumped because: kasan: bad access detected [ 556.592786] Memory state around the buggy address: [ 556.593753] ffff8801f292fc00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 556.595191] ffff8801f292fc80: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 00 00 00 00 [ 556.596613] >ffff8801f292fd00: 00 00 f3 00 00 00 00 f3 f3 00 00 00 00 f4 f4 f4 [ 556.598044] ^ [ 556.598797] ffff8801f292fd80: f3 f3 f3 f3 00 00 00 00 00 00 00 00 00 00 00 00 [ 556.600225] ffff8801f292fe00: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 00 f4 f4 f4 [ 556.601647] ================================================================== - Location https://elixir.bootlin.com/linux/v4.18-rc1/source/fs/f2fs/node.c#L987 case NODE_DIND_BLOCK: err = truncate_nodes(&dn, nofs, offset[1], 3); cont = 0; break; default: BUG(); <--- } Reported-by Wen Xu <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]>
CompositeDeepScanLine::readPixels(int start, int end) { size_t parts = _Data->_file.size() + _Data->_part.size(); // total of files+parts vector<DeepFrameBuffer> framebuffers(parts); vector< vector<unsigned int> > counts(parts); // // for each part, a pointer to an array of channels // vector<vector< vector<float *> > > pointers(parts); vector<const Header *> headers(parts); { size_t i; for(i=0;i<_Data->_file.size();i++) { headers[i] = &_Data->_file[i]->header(); } for(size_t j=0;j<_Data->_part.size();j++) { headers[i+j] = &_Data->_part[j]->header(); } } for(size_t i=0;i<parts;i++) { _Data->handleDeepFrameBuffer(framebuffers[i],counts[i],pointers[i],*headers[i],start,end); } // // set frame buffers and read scanlines from all parts // TODO what happens if SCANLINE not in data window? // { size_t i=0; for(i=0;i<_Data->_file.size();i++) { _Data->_file[i]->setFrameBuffer(framebuffers[i]); _Data->_file[i]->readPixelSampleCounts(start,end); } for(size_t j=0;j<_Data->_part.size();j++) { _Data->_part[j]->setFrameBuffer(framebuffers[i+j]); _Data->_part[j]->readPixelSampleCounts(start,end); } } // // total width // size_t total_width = _Data->_dataWindow.size().x+1; size_t total_pixels = total_width*(end-start+1); vector<unsigned int> total_sizes(total_pixels); vector<unsigned int> num_sources(total_pixels); //number of parts with non-zero sample count size_t overall_sample_count=0; // sum of all samples in all images between start and end // // accumulate pixel counts // for(size_t ptr=0;ptr<total_pixels;ptr++) { total_sizes[ptr]=0; num_sources[ptr]=0; for(size_t j=0;j<parts;j++) { total_sizes[ptr]+=counts[j][ptr]; if(counts[j][ptr]>0) num_sources[ptr]++; } overall_sample_count+=total_sizes[ptr]; } // // allocate arrays for pixel data // samples array accessed as in pixels[channel][sample] // vector<vector<float> > samples( _Data->_channels.size() ); for(size_t channel=0;channel<_Data->_channels.size();channel++) { if( channel!=1 || _Data->_zback) { samples[channel].resize(overall_sample_count); } } for(size_t channel=0;channel<samples.size();channel++) { if( channel!=1 || _Data->_zback) { samples[channel].resize(overall_sample_count); // // allocate pointers for channel data // size_t offset=0; for(size_t pixel=0;pixel<total_pixels;pixel++) { for(size_t part=0 ; part<parts && offset<overall_sample_count ; part++ ) { pointers[part][channel][pixel]=&samples[channel][offset]; offset+=counts[part][pixel]; } } } } // // read data // for(size_t i=0;i<_Data->_file.size();i++) { _Data->_file[i]->readPixels(start,end); } for(size_t j=0;j<_Data->_part.size();j++) { _Data->_part[j]->readPixels(start,end); } // // composite pixels and write back to framebuffer // // turn vector of strings into array of char * // and make sure 'ZBack' channel is correct vector<const char *> names(_Data->_channels.size()); for(size_t i=0;i<names.size();i++) { names[i]=_Data->_channels[i].c_str(); } if(!_Data->_zback) names[1]=names[0]; // no zback channel, so make it point to z TaskGroup g; for(int y=start;y<=end;y++) { ThreadPool::addGlobalTask(new LineCompositeTask(&g,_Data,y,start,&names,&pointers,&total_sizes,&num_sources)); }//next row }
0
[ "CWE-125" ]
openexr
e79d2296496a50826a15c667bf92bdc5a05518b4
129,325,533,649,819,800,000,000,000,000,000,000,000
166
fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <[email protected]>
void gs_lib_ctx_set_cms_context( const gs_memory_t *mem, void *cms_context ) { if (mem == NULL) return; mem->gs_lib_ctx->cms_context = cms_context; }
0
[]
ghostpdl
6d444c273da5499a4cd72f21cb6d4c9a5256807d
57,496,402,604,787,175,000,000,000,000,000,000,000
6
Bug 697178: Add a file permissions callback For the rare occasions when the graphics library directly opens a file (currently for reading), this allows us to apply any restrictions on file access normally applied in the interpteter.
int dns_select(s2s_t s2s, char *ip, int *port, time_t now, dnscache_t dns, int allow_bad) { /* list of results */ dnsres_t l_reuse[DNS_MAX_RESULTS]; dnsres_t l_aaaa[DNS_MAX_RESULTS]; dnsres_t l_a[DNS_MAX_RESULTS]; dnsres_t l_bad[DNS_MAX_RESULTS]; /* running weight sums of results */ int rw_reuse[DNS_MAX_RESULTS]; int rw_aaaa[DNS_MAX_RESULTS]; int rw_a[DNS_MAX_RESULTS]; int s_reuse = 0, s_aaaa = 0, s_a = 0, s_bad = 0; /* count */ int p_reuse = 0, p_aaaa = 0, p_a = 0; /* list prio */ int wt_reuse = 0, wt_aaaa = 0, wt_a = 0; /* weight total */ int c_expired_good = 0; union xhashv xhv; dnsres_t res; char *ipport; int ipport_len; char *c; int c_len; char *tmp; /* for all results: * - if not expired * - put highest priority reuseable addrs into list1 * - put highest priority ipv6 addrs into list2 * - put highest priority ipv4 addrs into list3 * - put bad addrs into list4 * - pick weighted random entry from first non-empty list */ if (dns->results == NULL) { log_debug(ZONE, "negative cache entry for '%s'", dns->name); return -1; } log_debug(ZONE, "selecting DNS result for '%s'", dns->name); xhv.dnsres_val = &res; if (xhash_iter_first(dns->results)) { dnsres_t bad = NULL; do { xhash_iter_get(dns->results, (const char **) &ipport, &ipport_len, xhv.val); if (s2s->dns_bad_timeout > 0) bad = xhash_getx(s2s->dns_bad, ipport, ipport_len); if (now > res->expiry) { /* good host? */ if (bad == NULL) c_expired_good++; log_debug(ZONE, "host '%s' expired", res->key); continue; } else if (bad != NULL && !(now > bad->expiry)) { /* bad host (connection failure) */ l_bad[s_bad++] = res; log_debug(ZONE, "host '%s' bad", res->key); } else if (s2s->out_reuse && xhash_getx(s2s->out_host, ipport, ipport_len) != NULL) { /* existing connection */ log_debug(ZONE, "host '%s' exists", res->key); if (s_reuse == 0 || p_reuse > res->prio) { p_reuse = res->prio; s_reuse = 0; wt_reuse = 0; log_debug(ZONE, "reset prio list, using prio %d", res->prio); } if (res->prio <= p_reuse) { l_reuse[s_reuse] = res; wt_reuse += res->weight; rw_reuse[s_reuse] = wt_reuse; s_reuse++; log_debug(ZONE, "added host with weight %d (%d), running weight %d", (res->weight >> 8), res->weight, wt_reuse); } else { log_debug(ZONE, "ignored host with prio %d", res->prio); } } else if (memchr(ipport, ':', ipport_len) != NULL) { /* ipv6 */ log_debug(ZONE, "host '%s' IPv6", res->key); if (s_aaaa == 0 || p_aaaa > res->prio) { p_aaaa = res->prio; s_aaaa = 0; wt_aaaa = 0; log_debug(ZONE, "reset prio list, using prio %d", res->prio); } if (res->prio <= p_aaaa) { l_aaaa[s_aaaa] = res; wt_aaaa += res->weight; rw_aaaa[s_aaaa] = wt_aaaa; s_aaaa++; log_debug(ZONE, "added host with weight %d (%d), running weight %d", (res->weight >> 8), res->weight, wt_aaaa); } else { log_debug(ZONE, "ignored host with prio %d", res->prio); } } else { /* ipv4 */ log_debug(ZONE, "host '%s' IPv4", res->key); if (s_a == 0 || p_a > res->prio) { p_a = res->prio; s_a = 0; wt_a = 0; log_debug(ZONE, "reset prio list, using prio %d", res->prio); } if (res->prio <= p_a) { l_a[s_a] = res; wt_a += res->weight; rw_a[s_a] = wt_a; s_a++; log_debug(ZONE, "added host with weight %d (%d), running weight %d", (res->weight >> 8), res->weight, wt_a); } else { log_debug(ZONE, "ignored host with prio %d", res->prio); } } } while(xhash_iter_next(dns->results)); } /* pick a result at weighted random (RFC 2782) * all weights are guaranteed to be >= 16 && <= 16776960 * (assuming max 50 hosts, the total/running sums won't exceed 2^31) */ ipport = NULL; if (s_reuse > 0) { int i, r; log_debug(ZONE, "using existing hosts, total weight %d", wt_reuse); assert((wt_reuse + 1) > 0); r = rand() % (wt_reuse + 1); log_debug(ZONE, "random number %d", r); for (i = 0; i < s_reuse; i++) if (rw_reuse[i] >= r) { log_debug(ZONE, "selected host '%s', running weight %d", l_reuse[i]->key, rw_reuse[i]); ipport = l_reuse[i]->key; break; } } else if (s_aaaa > 0 && (s_a == 0 || p_aaaa <= p_a)) { int i, r; log_debug(ZONE, "using IPv6 hosts, total weight %d", wt_aaaa); assert((wt_aaaa + 1) > 0); r = rand() % (wt_aaaa + 1); log_debug(ZONE, "random number %d", r); for (i = 0; i < s_aaaa; i++) if (rw_aaaa[i] >= r) { log_debug(ZONE, "selected host '%s', running weight %d", l_aaaa[i]->key, rw_aaaa[i]); ipport = l_aaaa[i]->key; break; } } else if (s_a > 0) { int i, r; log_debug(ZONE, "using IPv4 hosts, total weight %d", wt_a); assert((wt_a + 1) > 0); r = rand() % (wt_a + 1); log_debug(ZONE, "random number %d", r); for (i = 0; i < s_a; i++) if (rw_a[i] >= r) { log_debug(ZONE, "selected host '%s', running weight %d", l_a[i]->key, rw_a[i]); ipport = l_a[i]->key; break; } } else if (s_bad > 0) { ipport = l_bad[rand() % s_bad]->key; log_debug(ZONE, "using bad hosts, allow_bad=%d", allow_bad); /* there are expired good hosts, expire cache immediately */ if (c_expired_good > 0) { log_debug(ZONE, "expiring this DNS cache entry, %d expired hosts", c_expired_good); dns->expiry = 0; } if (!allow_bad) return -1; } /* results cannot all expire before the collection does */ assert(ipport != NULL); /* copy the ip and port to the packet */ ipport_len = strlen(ipport); c = strchr(ipport, '/'); strncpy(ip, ipport, c-ipport); ip[c-ipport] = '\0'; c++; c_len = ipport_len - (c - ipport); tmp = strndup(c, c_len); *port = atoi(tmp); free(tmp); return 0; }
0
[ "CWE-20" ]
jabberd2
aabcffae560d5fd00cd1d2ffce5d760353cf0a4d
118,889,037,424,168,200,000,000,000,000,000,000,000
214
Fixed possibility of Unsolicited Dialback Attacks
entry_guard_add_to_sample_impl(guard_selection_t *gs, const uint8_t *rsa_id_digest, const char *nickname, const tor_addr_port_t *bridge_addrport) { const int GUARD_LIFETIME = get_guard_lifetime(); tor_assert(gs); // XXXX #20827 take ed25519 identity here too. /* Make sure we can actually identify the guard. */ if (BUG(!rsa_id_digest && !bridge_addrport)) return NULL; // LCOV_EXCL_LINE entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t)); /* persistent fields */ guard->is_persistent = (rsa_id_digest != NULL); guard->selection_name = tor_strdup(gs->name); if (rsa_id_digest) memcpy(guard->identity, rsa_id_digest, DIGEST_LEN); if (nickname) strlcpy(guard->nickname, nickname, sizeof(guard->nickname)); guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10); tor_free(guard->sampled_by_version); guard->sampled_by_version = tor_strdup(VERSION); guard->currently_listed = 1; guard->confirmed_idx = -1; /* non-persistent fields */ guard->is_reachable = GUARD_REACHABLE_MAYBE; if (bridge_addrport) guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport)); smartlist_add(gs->sampled_entry_guards, guard); guard->in_selection = gs; entry_guard_set_filtered_flags(get_options(), gs, guard); entry_guards_changed_for_guard_selection(gs); return guard; }
0
[ "CWE-200" ]
tor
665baf5ed5c6186d973c46cdea165c0548027350
263,632,333,513,381,700,000,000,000,000,000,000,000
40
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.
static int do_check_common(struct bpf_verifier_env *env, int subprog) { bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); struct bpf_verifier_state *state; struct bpf_reg_state *regs; int ret, i; env->prev_linfo = NULL; env->pass_cnt++; state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); if (!state) return -ENOMEM; state->curframe = 0; state->speculative = false; state->branches = 1; state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); if (!state->frame[0]) { kfree(state); return -ENOMEM; } env->cur_state = state; init_func_state(env, state->frame[0], BPF_MAIN_FUNC /* callsite */, 0 /* frameno */, subprog); regs = state->frame[state->curframe]->regs; if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { ret = btf_prepare_func_args(env, subprog, regs); if (ret) goto out; for (i = BPF_REG_1; i <= BPF_REG_5; i++) { if (regs[i].type == PTR_TO_CTX) mark_reg_known_zero(env, regs, i); else if (regs[i].type == SCALAR_VALUE) mark_reg_unknown(env, regs, i); else if (regs[i].type == PTR_TO_MEM_OR_NULL) { const u32 mem_size = regs[i].mem_size; mark_reg_known_zero(env, regs, i); regs[i].mem_size = mem_size; regs[i].id = ++env->id_gen; } } } else { /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; mark_reg_known_zero(env, regs, BPF_REG_1); ret = btf_check_func_arg_match(env, subprog, regs); if (ret == -EFAULT) /* unlikely verifier bug. abort. * ret == 0 and ret < 0 are sadly acceptable for * main() function due to backward compatibility. * Like socket filter program may be written as: * int bpf_prog(struct pt_regs *ctx) * and never dereference that ctx in the program. * 'struct pt_regs' is a type mismatch for socket * filter that should be using 'struct __sk_buff'. */ goto out; } ret = do_check(env); out: /* check for NULL is necessary, since cur_state can be freed inside * do_check() under memory pressure. */ if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } while (!pop_stack(env, NULL, NULL, false)); if (!ret && pop_log) bpf_vlog_reset(&env->log, 0); free_states(env); if (ret) /* clean aux data in case subprog was rejected */ sanitize_insn_aux_data(env); return ret; }
0
[ "CWE-307" ]
linux
350a5c4dd2452ea999cc5e1d4a8dbf12de2f97ef
98,538,750,795,775,080,000,000,000,000,000,000,000
81
bpf: Dont allow vmlinux BTF to be used in map_create and prog_load. The syzbot got FD of vmlinux BTF and passed it into map_create which caused crash in btf_type_id_size() when it tried to access resolved_ids. The vmlinux BTF doesn't have 'resolved_ids' and 'resolved_sizes' initialized to save memory. To avoid such issues disallow using vmlinux BTF in prog_load and map_create commands. Fixes: 5329722057d4 ("bpf: Assign ID to vmlinux BTF and return extra info for BTF in GET_OBJ_INFO") Reported-by: [email protected] Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Yonghong Song <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
g_init(const char* app_name) { #if defined(_WIN32) WSADATA wsadata; WSAStartup(2, &wsadata); #endif setlocale(LC_CTYPE, ""); if (app_name != 0) { if (app_name[0] != 0) { if (!g_directory_exist("/tmp/.xrdp")) { g_create_dir("/tmp/.xrdp"); g_chmod_hex("/tmp/.xrdp", 0x1777); } snprintf(g_temp_base, sizeof(g_temp_base), "/tmp/.xrdp/%s-XXXXXX", app_name); snprintf(g_temp_base_org, sizeof(g_temp_base_org), "/tmp/.xrdp/%s-XXXXXX", app_name); if (mkdtemp(g_temp_base) == 0) { printf("g_init: mkdtemp failed [%s]\n", g_temp_base); } } } }
1
[]
xrdp
cadad6e181d2a67698e5eb7cacd6b233ae29eb97
124,142,626,038,934,400,000,000,000,000,000,000,000
28
/tmp cleanup
static int ctnetlink_parse_tuple_ip(struct nlattr *attr, struct nf_conntrack_tuple *tuple, u_int32_t flags) { struct nlattr *tb[CTA_IP_MAX+1]; int ret = 0; ret = nla_parse_nested_deprecated(tb, CTA_IP_MAX, attr, NULL, NULL); if (ret < 0) return ret; ret = nla_validate_nested_deprecated(attr, CTA_IP_MAX, cta_ip_nla_policy, NULL); if (ret) return ret; switch (tuple->src.l3num) { case NFPROTO_IPV4: ret = ipv4_nlattr_to_tuple(tb, tuple, flags); break; case NFPROTO_IPV6: ret = ipv6_nlattr_to_tuple(tb, tuple, flags); break; } return ret; }
0
[ "CWE-120" ]
linux
1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6
308,577,646,435,838,800,000,000,000,000,000,000,000
27
netfilter: ctnetlink: add a range check for l3/l4 protonum The indexes to the nf_nat_l[34]protos arrays come from userspace. So check the tuple's family, e.g. l3num, when creating the conntrack in order to prevent an OOB memory access during setup. Here is an example kernel panic on 4.14.180 when userspace passes in an index greater than NFPROTO_NUMPROTO. Internal error: Oops - BUG: 0 [#1] PREEMPT SMP Modules linked in:... Process poc (pid: 5614, stack limit = 0x00000000a3933121) CPU: 4 PID: 5614 Comm: poc Tainted: G S W O 4.14.180-g051355490483 Hardware name: Qualcomm Technologies, Inc. SM8150 V2 PM8150 Google Inc. MSM task: 000000002a3dfffe task.stack: 00000000a3933121 pc : __cfi_check_fail+0x1c/0x24 lr : __cfi_check_fail+0x1c/0x24 ... Call trace: __cfi_check_fail+0x1c/0x24 name_to_dev_t+0x0/0x468 nfnetlink_parse_nat_setup+0x234/0x258 ctnetlink_parse_nat_setup+0x4c/0x228 ctnetlink_new_conntrack+0x590/0xc40 nfnetlink_rcv_msg+0x31c/0x4d4 netlink_rcv_skb+0x100/0x184 nfnetlink_rcv+0xf4/0x180 netlink_unicast+0x360/0x770 netlink_sendmsg+0x5a0/0x6a4 ___sys_sendmsg+0x314/0x46c SyS_sendmsg+0xb4/0x108 el0_svc_naked+0x34/0x38 This crash is not happening since 5.4+, however, ctnetlink still allows for creating entries with unsupported layer 3 protocol number. Fixes: c1d10adb4a521 ("[NETFILTER]: Add ctnetlink port for nf_conntrack") Signed-off-by: Will McVicker <[email protected]> [[email protected]: rebased original patch on top of nf.git] Signed-off-by: Pablo Neira Ayuso <[email protected]>
void flush_thread(void) { struct thread_info *thread = current_thread_info(); struct task_struct *tsk = current; flush_ptrace_hw_breakpoint(tsk); memset(thread->used_cp, 0, sizeof(thread->used_cp)); memset(&tsk->thread.debug, 0, sizeof(struct debug_info)); memset(&thread->fpstate, 0, sizeof(union fp_state)); thread_notify(THREAD_NOTIFY_FLUSH, thread); }
0
[ "CWE-284", "CWE-264" ]
linux
a4780adeefd042482f624f5e0d577bf9cdcbb760
129,639,801,702,238,490,000,000,000,000,000,000,000
13
ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to prevent it from being used as a covert channel between two tasks. There are more and more applications coming to Windows RT, Wine could support them, but mostly they expect to have the thread environment block (TEB) in TPIDRURW. This patch preserves that register per thread instead of clearing it. Unlike the TPIDRURO, which is already switched, the TPIDRURW can be updated from userspace so needs careful treatment in the case that we modify TPIDRURW and call fork(). To avoid this we must always read TPIDRURW in copy_thread. Signed-off-by: André Hentschel <[email protected]> Signed-off-by: Will Deacon <[email protected]> Signed-off-by: Jonathan Austin <[email protected]> Signed-off-by: Russell King <[email protected]>
void dvb_frontend_sleep_until(ktime_t *waketime, u32 add_usec) { s32 delta; *waketime = ktime_add_us(*waketime, add_usec); delta = ktime_us_delta(ktime_get_boottime(), *waketime); if (delta > 2500) { msleep((delta - 1500) / 1000); delta = ktime_us_delta(ktime_get_boottime(), *waketime); } if (delta > 0) udelay(delta); }
0
[ "CWE-416" ]
linux
b1cb7372fa822af6c06c8045963571d13ad6348b
142,723,777,913,880,000,000,000,000,000,000,000,000
13
dvb_frontend: don't use-after-free the frontend struct dvb_frontend_invoke_release() may free the frontend struct. So, the free logic can't update it anymore after calling it. That's OK, as __dvb_frontend_free() is called only when the krefs are zeroed, so nobody is using it anymore. That should fix the following KASAN error: The KASAN report looks like this (running on kernel 3e0cc09a3a2c40ec1ffb6b4e12da86e98feccb11 (4.14-rc5+)): ================================================================== BUG: KASAN: use-after-free in __dvb_frontend_free+0x113/0x120 Write of size 8 at addr ffff880067d45a00 by task kworker/0:1/24 CPU: 0 PID: 24 Comm: kworker/0:1 Not tainted 4.14.0-rc5-43687-g06ab8a23e0e6 #545 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 Workqueue: usb_hub_wq hub_event Call Trace: __dump_stack lib/dump_stack.c:16 dump_stack+0x292/0x395 lib/dump_stack.c:52 print_address_description+0x78/0x280 mm/kasan/report.c:252 kasan_report_error mm/kasan/report.c:351 kasan_report+0x23d/0x350 mm/kasan/report.c:409 __asan_report_store8_noabort+0x1c/0x20 mm/kasan/report.c:435 __dvb_frontend_free+0x113/0x120 drivers/media/dvb-core/dvb_frontend.c:156 dvb_frontend_put+0x59/0x70 drivers/media/dvb-core/dvb_frontend.c:176 dvb_frontend_detach+0x120/0x150 drivers/media/dvb-core/dvb_frontend.c:2803 dvb_usb_adapter_frontend_exit+0xd6/0x160 drivers/media/usb/dvb-usb/dvb-usb-dvb.c:340 dvb_usb_adapter_exit drivers/media/usb/dvb-usb/dvb-usb-init.c:116 dvb_usb_exit+0x9b/0x200 drivers/media/usb/dvb-usb/dvb-usb-init.c:132 dvb_usb_device_exit+0xa5/0xf0 drivers/media/usb/dvb-usb/dvb-usb-init.c:295 usb_unbind_interface+0x21c/0xa90 drivers/usb/core/driver.c:423 __device_release_driver drivers/base/dd.c:861 device_release_driver_internal+0x4f1/0x5c0 drivers/base/dd.c:893 device_release_driver+0x1e/0x30 drivers/base/dd.c:918 bus_remove_device+0x2f4/0x4b0 drivers/base/bus.c:565 device_del+0x5c4/0xab0 drivers/base/core.c:1985 usb_disable_device+0x1e9/0x680 drivers/usb/core/message.c:1170 usb_disconnect+0x260/0x7a0 drivers/usb/core/hub.c:2124 hub_port_connect drivers/usb/core/hub.c:4754 hub_port_connect_change drivers/usb/core/hub.c:5009 port_event drivers/usb/core/hub.c:5115 hub_event+0x1318/0x3740 drivers/usb/core/hub.c:5195 process_one_work+0xc73/0x1d90 kernel/workqueue.c:2119 worker_thread+0x221/0x1850 kernel/workqueue.c:2253 kthread+0x363/0x440 kernel/kthread.c:231 ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431 Allocated by task 24: save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59 save_stack+0x43/0xd0 mm/kasan/kasan.c:447 set_track mm/kasan/kasan.c:459 kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:551 kmem_cache_alloc_trace+0x11e/0x2d0 mm/slub.c:2772 kmalloc ./include/linux/slab.h:493 kzalloc ./include/linux/slab.h:666 dtt200u_fe_attach+0x4c/0x110 drivers/media/usb/dvb-usb/dtt200u-fe.c:212 dtt200u_frontend_attach+0x35/0x80 drivers/media/usb/dvb-usb/dtt200u.c:136 dvb_usb_adapter_frontend_init+0x32b/0x660 drivers/media/usb/dvb-usb/dvb-usb-dvb.c:286 dvb_usb_adapter_init drivers/media/usb/dvb-usb/dvb-usb-init.c:86 dvb_usb_init drivers/media/usb/dvb-usb/dvb-usb-init.c:162 dvb_usb_device_init+0xf73/0x17f0 drivers/media/usb/dvb-usb/dvb-usb-init.c:277 dtt200u_usb_probe+0xa1/0xe0 drivers/media/usb/dvb-usb/dtt200u.c:155 usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26b/0x3c0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932 generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174 usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26b/0x3c0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457 hub_port_connect drivers/usb/core/hub.c:4903 hub_port_connect_change drivers/usb/core/hub.c:5009 port_event drivers/usb/core/hub.c:5115 hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195 process_one_work+0xc73/0x1d90 kernel/workqueue.c:2119 worker_thread+0x221/0x1850 kernel/workqueue.c:2253 kthread+0x363/0x440 kernel/kthread.c:231 ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431 Freed by task 24: save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59 save_stack+0x43/0xd0 mm/kasan/kasan.c:447 set_track mm/kasan/kasan.c:459 kasan_slab_free+0x72/0xc0 mm/kasan/kasan.c:524 slab_free_hook mm/slub.c:1390 slab_free_freelist_hook mm/slub.c:1412 slab_free mm/slub.c:2988 kfree+0xf6/0x2f0 mm/slub.c:3919 dtt200u_fe_release+0x3c/0x50 drivers/media/usb/dvb-usb/dtt200u-fe.c:202 dvb_frontend_invoke_release.part.13+0x1c/0x30 drivers/media/dvb-core/dvb_frontend.c:2790 dvb_frontend_invoke_release drivers/media/dvb-core/dvb_frontend.c:2789 __dvb_frontend_free+0xad/0x120 drivers/media/dvb-core/dvb_frontend.c:153 dvb_frontend_put+0x59/0x70 drivers/media/dvb-core/dvb_frontend.c:176 dvb_frontend_detach+0x120/0x150 drivers/media/dvb-core/dvb_frontend.c:2803 dvb_usb_adapter_frontend_exit+0xd6/0x160 drivers/media/usb/dvb-usb/dvb-usb-dvb.c:340 dvb_usb_adapter_exit drivers/media/usb/dvb-usb/dvb-usb-init.c:116 dvb_usb_exit+0x9b/0x200 drivers/media/usb/dvb-usb/dvb-usb-init.c:132 dvb_usb_device_exit+0xa5/0xf0 drivers/media/usb/dvb-usb/dvb-usb-init.c:295 usb_unbind_interface+0x21c/0xa90 drivers/usb/core/driver.c:423 __device_release_driver drivers/base/dd.c:861 device_release_driver_internal+0x4f1/0x5c0 drivers/base/dd.c:893 device_release_driver+0x1e/0x30 drivers/base/dd.c:918 bus_remove_device+0x2f4/0x4b0 drivers/base/bus.c:565 device_del+0x5c4/0xab0 drivers/base/core.c:1985 usb_disable_device+0x1e9/0x680 drivers/usb/core/message.c:1170 usb_disconnect+0x260/0x7a0 drivers/usb/core/hub.c:2124 hub_port_connect drivers/usb/core/hub.c:4754 hub_port_connect_change drivers/usb/core/hub.c:5009 port_event drivers/usb/core/hub.c:5115 hub_event+0x1318/0x3740 drivers/usb/core/hub.c:5195 process_one_work+0xc73/0x1d90 kernel/workqueue.c:2119 worker_thread+0x221/0x1850 kernel/workqueue.c:2253 kthread+0x363/0x440 kernel/kthread.c:231 ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431 The buggy address belongs to the object at ffff880067d45500 which belongs to the cache kmalloc-2048 of size 2048 The buggy address is located 1280 bytes inside of 2048-byte region [ffff880067d45500, ffff880067d45d00) The buggy address belongs to the page: page:ffffea00019f5000 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0 flags: 0x100000000008100(slab|head) raw: 0100000000008100 0000000000000000 0000000000000000 00000001000f000f raw: dead000000000100 dead000000000200 ffff88006c002d80 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff880067d45900: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880067d45980: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880067d45a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff880067d45a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880067d45b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: ead666000a5f ("media: dvb_frontend: only use kref after initialized") Reported-by: Andrey Konovalov <[email protected]> Suggested-by: Matthias Schwarzott <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]>
EmitMousePositionSeparator(TScreen *screen, Char line[], unsigned count) { switch (screen->extend_coords) { case SET_SGR_EXT_MODE_MOUSE: case SET_URXVT_EXT_MODE_MOUSE: case SET_PIXEL_POSITION_MOUSE: line[count++] = ';'; break; } return count; }
0
[ "CWE-399" ]
xterm-snapshots
82ba55b8f994ab30ff561a347b82ea340ba7075c
171,056,381,517,520,380,000,000,000,000,000,000,000
11
snapshot of project "xterm", label xterm-365d
WalSndDone(WalSndSendDataCallback send_data) { XLogRecPtr replicatedPtr; /* ... let's just be real sure we're caught up ... */ send_data(); /* * Check a write location to see whether all the WAL have successfully * been replicated if this walsender is connecting to a standby such as * pg_receivexlog which always returns an invalid flush location. * Otherwise, check a flush location. */ replicatedPtr = XLogRecPtrIsInvalid(MyWalSnd->flush) ? MyWalSnd->write : MyWalSnd->flush; if (WalSndCaughtUp && sentPtr == replicatedPtr && !pq_is_send_pending()) { /* Inform the standby that XLOG streaming is done */ EndCommand("COPY 0", DestRemote); pq_flush(); proc_exit(0); } if (!waiting_for_ping_response) WalSndKeepalive(true); }
0
[ "CWE-89" ]
postgres
2b3a8b20c2da9f39ffecae25ab7c66974fbc0d3b
55,903,193,233,802,690,000,000,000,000,000,000,000
27
Be more careful to not lose sync in the FE/BE protocol. If any error occurred while we were in the middle of reading a protocol message from the client, we could lose sync, and incorrectly try to interpret a part of another message as a new protocol message. That will usually lead to an "invalid frontend message" error that terminates the connection. However, this is a security issue because an attacker might be able to deliberately cause an error, inject a Query message in what's supposed to be just user data, and have the server execute it. We were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other operations that could ereport(ERROR) in the middle of processing a message, but a query cancel interrupt or statement timeout could nevertheless cause it to happen. Also, the V2 fastpath and COPY handling were not so careful. It's very difficult to recover in the V2 COPY protocol, so we will just terminate the connection on error. In practice, that's what happened previously anyway, as we lost protocol sync. To fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set whenever we're in the middle of reading a message. When it's set, we cannot safely ERROR out and continue running, because we might've read only part of a message. PqCommReadingMsg acts somewhat similarly to critical sections in that if an error occurs while it's set, the error handler will force the connection to be terminated, as if the error was FATAL. It's not implemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted to PANIC in critical sections, because we want to be able to use PG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes advantage of that to prevent an OOM error from terminating the connection. To prevent unnecessary connection terminations, add a holdoff mechanism similar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel interrupts, but still allow die interrupts. The rules on which interrupts are processed when are now a bit more complicated, so refactor ProcessInterrupts() and the calls to it in signal handlers so that the signal handlers always call it if ImmediateInterruptOK is set, and ProcessInterrupts() can decide to not do anything if the other conditions are not met. Reported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund. Backpatch to all supported versions. Security: CVE-2015-0244
camel_imapx_server_sync_changes_sync (CamelIMAPXServer *is, CamelIMAPXMailbox *mailbox, gboolean can_influence_flags, GCancellable *cancellable, GError **error) { guint i, jj, on, on_orset, off_orset; GPtrArray *changed_uids; GArray *on_user = NULL, *off_user = NULL; CamelFolder *folder; CamelMessageInfo *info; CamelFolderChangeInfo *expunged_changes = NULL; GList *expunged_removed_list = NULL; GHashTable *stamps; guint32 permanentflags; struct _uidset_state uidset, uidset_expunge; gint unread_change = 0; gboolean use_real_junk_path = FALSE; gboolean use_real_trash_path = FALSE; gboolean remove_deleted_flags = FALSE; gboolean is_real_trash_folder = FALSE; gboolean is_real_junk_folder = FALSE; gboolean has_uidplus_capability; gboolean expunge_deleted; gboolean nothing_to_do; gboolean success; g_return_val_if_fail (CAMEL_IS_IMAPX_SERVER (is), FALSE); g_return_val_if_fail (CAMEL_IS_IMAPX_MAILBOX (mailbox), FALSE); folder = imapx_server_ref_folder (is, mailbox); g_return_val_if_fail (folder != NULL, FALSE); /* We calculate two masks, a mask of all flags which have been * turned off and a mask of all flags which have been turned * on. If either of these aren't 0, then we have work to do, * and we fire off a job to do it. * * User flags are a bit more tricky, we rely on the user * flags being sorted, and then we create a bunch of lists; * one for each flag being turned off, including each * info being turned off, and one for each flag being turned on. */ changed_uids = camel_folder_summary_get_changed (camel_folder_get_folder_summary (folder)); if (changed_uids->len == 0) { camel_folder_free_uids (folder, changed_uids); g_object_unref (folder); return TRUE; } camel_folder_sort_uids (folder, changed_uids); stamps = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) camel_pstring_free, NULL); if (can_influence_flags) { CamelIMAPXSettings *settings; settings = camel_imapx_server_ref_settings (is); use_real_junk_path = camel_imapx_settings_get_use_real_junk_path (settings); if (use_real_junk_path) { CamelFolder *junk_folder = NULL; gchar *real_junk_path; real_junk_path = camel_imapx_settings_dup_real_junk_path (settings); if (real_junk_path) { junk_folder = camel_store_get_folder_sync ( camel_folder_get_parent_store (folder), real_junk_path, 0, cancellable, NULL); } is_real_junk_folder = junk_folder == folder; use_real_junk_path = junk_folder != NULL; g_clear_object (&junk_folder); g_free (real_junk_path); } use_real_trash_path = camel_imapx_settings_get_use_real_trash_path (settings); if (use_real_trash_path) { CamelFolder *trash_folder = NULL; gchar *real_trash_path; real_trash_path = camel_imapx_settings_dup_real_trash_path (settings); if (real_trash_path) trash_folder = camel_store_get_folder_sync ( camel_folder_get_parent_store (folder), real_trash_path, 0, cancellable, NULL); is_real_trash_folder = trash_folder == folder; /* Remove deleted flags in all but the trash folder itself */ remove_deleted_flags = !trash_folder || !is_real_trash_folder; use_real_trash_path = trash_folder != NULL; g_clear_object (&trash_folder); g_free (real_trash_path); } g_object_unref (settings); } if (changed_uids->len > 20) camel_folder_summary_prepare_fetch_all (camel_folder_get_folder_summary (folder), NULL); camel_folder_summary_lock (camel_folder_get_folder_summary (folder)); off_orset = on_orset = 0; for (i = 0; i < changed_uids->len; i++) { CamelIMAPXMessageInfo *xinfo; guint32 flags, sflags; const CamelNamedFlags *local_uflags, *server_uflags; const gchar *uid; guint j = 0; uid = g_ptr_array_index (changed_uids, i); info = camel_folder_summary_get (camel_folder_get_folder_summary (folder), uid); xinfo = info ? CAMEL_IMAPX_MESSAGE_INFO (info) : NULL; if (!info || !xinfo) { g_clear_object (&info); continue; } if (!camel_message_info_get_folder_flagged (info)) { g_clear_object (&info); continue; } camel_message_info_property_lock (info); g_hash_table_insert (stamps, (gpointer) camel_message_info_pooldup_uid (info), GUINT_TO_POINTER (camel_message_info_get_folder_flagged_stamp (info))); flags = camel_message_info_get_flags (info) & CAMEL_IMAPX_SERVER_FLAGS; sflags = camel_imapx_message_info_get_server_flags (xinfo) & CAMEL_IMAPX_SERVER_FLAGS; if (can_influence_flags) { gboolean move_to_real_junk; gboolean move_to_real_trash; gboolean move_to_inbox; move_to_real_junk = use_real_junk_path && (flags & CAMEL_MESSAGE_JUNK); move_to_real_trash = use_real_trash_path && remove_deleted_flags && (flags & CAMEL_MESSAGE_DELETED); move_to_inbox = is_real_junk_folder && !move_to_real_junk && !move_to_real_trash && (camel_message_info_get_flags (info) & CAMEL_MESSAGE_NOTJUNK) != 0; if (move_to_real_junk) camel_imapx_folder_add_move_to_real_junk ( CAMEL_IMAPX_FOLDER (folder), uid); if (move_to_real_trash) camel_imapx_folder_add_move_to_real_trash ( CAMEL_IMAPX_FOLDER (folder), uid); if (move_to_inbox) camel_imapx_folder_add_move_to_inbox ( CAMEL_IMAPX_FOLDER (folder), uid); } if (flags != sflags) { off_orset |= (flags ^ sflags) & ~flags; on_orset |= (flags ^ sflags) & flags; } local_uflags = camel_message_info_get_user_flags (info); server_uflags = camel_imapx_message_info_get_server_user_flags (xinfo); if (!camel_named_flags_equal (local_uflags, server_uflags)) { guint ii, jj, llen, slen; llen = local_uflags ? camel_named_flags_get_length (local_uflags) : 0; slen = server_uflags ? camel_named_flags_get_length (server_uflags) : 0; for (ii = 0, jj = 0; ii < llen || jj < slen;) { gint res; if (ii < llen) { const gchar *local_name = camel_named_flags_get (local_uflags, ii); if (jj < slen) { const gchar *server_name = camel_named_flags_get (server_uflags, jj); res = g_strcmp0 (local_name, server_name); } else if (local_name && *local_name) res = -1; else { ii++; continue; } } else { res = 1; } if (res == 0) { ii++; jj++; } else { GArray *user_set; const gchar *user_flag_name; struct _imapx_flag_change *change = NULL, add = { 0 }; if (res < 0) { if (on_user == NULL) on_user = g_array_new (FALSE, FALSE, sizeof (struct _imapx_flag_change)); user_set = on_user; user_flag_name = camel_named_flags_get (local_uflags, ii); ii++; } else { if (off_user == NULL) off_user = g_array_new (FALSE, FALSE, sizeof (struct _imapx_flag_change)); user_set = off_user; user_flag_name = camel_named_flags_get (server_uflags, jj); jj++; } /* Could sort this and binary search */ for (j = 0; j < user_set->len; j++) { change = &g_array_index (user_set, struct _imapx_flag_change, j); if (g_strcmp0 (change->name, user_flag_name) == 0) goto found; } add.name = g_strdup (user_flag_name); add.infos = g_ptr_array_new (); g_array_append_val (user_set, add); change = &add; found: g_object_ref (info); g_ptr_array_add (change->infos, info); } } } camel_message_info_property_unlock (info); g_clear_object (&info); } camel_folder_summary_unlock (camel_folder_get_folder_summary (folder)); nothing_to_do = (on_orset == 0) && (off_orset == 0) && (on_user == NULL) && (off_user == NULL); if (nothing_to_do) { imapx_sync_free_user (on_user); imapx_sync_free_user (off_user); imapx_unset_folder_flagged_flag (camel_folder_get_folder_summary (folder), changed_uids, remove_deleted_flags); camel_folder_free_uids (folder, changed_uids); g_hash_table_destroy (stamps); g_object_unref (folder); return TRUE; } if (!camel_imapx_server_ensure_selected_sync (is, mailbox, cancellable, error)) { imapx_sync_free_user (on_user); imapx_sync_free_user (off_user); camel_folder_free_uids (folder, changed_uids); g_hash_table_destroy (stamps); g_object_unref (folder); return FALSE; } imapx_uidset_init (&uidset_expunge, 0, 100); has_uidplus_capability = CAMEL_IMAPX_HAVE_CAPABILITY (is->priv->cinfo, UIDPLUS); expunge_deleted = is_real_trash_folder && !remove_deleted_flags; permanentflags = camel_imapx_mailbox_get_permanentflags (mailbox); success = TRUE; for (on = 0; on < 2 && success; on++) { guint32 orset = on ? on_orset : off_orset; GArray *user_set = on ? on_user : off_user; for (jj = 0; jj < G_N_ELEMENTS (flags_table) && success; jj++) { guint32 flag = flags_table[jj].flag; CamelIMAPXCommand *ic = NULL, *ic_expunge = NULL; if ((orset & flag) == 0) continue; c (is->priv->tagprefix, "checking/storing %s flags '%s'\n", on ? "on" : "off", flags_table[jj].name); imapx_uidset_init (&uidset, 0, 100); for (i = 0; i < changed_uids->len && success; i++) { CamelMessageInfo *info; CamelIMAPXMessageInfo *xinfo; gboolean remove_deleted_flag; guint32 flags; guint32 sflags; gint send, send_expunge = 0; /* the 'stamps' hash table contains only those uid-s, which were also flagged, not only 'dirty' */ if (!g_hash_table_contains (stamps, changed_uids->pdata[i])) continue; info = camel_folder_summary_get (camel_folder_get_folder_summary (folder), changed_uids->pdata[i]); xinfo = info ? CAMEL_IMAPX_MESSAGE_INFO (info) : NULL; if (!info || !xinfo) { g_clear_object (&info); continue; } flags = (camel_message_info_get_flags (info) & CAMEL_IMAPX_SERVER_FLAGS) & permanentflags; sflags = (camel_imapx_message_info_get_server_flags (xinfo) & CAMEL_IMAPX_SERVER_FLAGS) & permanentflags; send = 0; remove_deleted_flag = remove_deleted_flags && (flags & CAMEL_MESSAGE_DELETED); if (remove_deleted_flag) { /* Remove the DELETED flag so the * message appears normally in the * real Trash folder when copied. */ flags &= ~CAMEL_MESSAGE_DELETED; } else if (expunge_deleted && (flags & CAMEL_MESSAGE_DELETED) != 0) { if (has_uidplus_capability) { if (!ic_expunge) ic_expunge = camel_imapx_command_new (is, CAMEL_IMAPX_JOB_EXPUNGE, "UID EXPUNGE "); send_expunge = imapx_uidset_add (&uidset_expunge, ic_expunge, camel_message_info_get_uid (info)); } if (!expunged_changes) expunged_changes = camel_folder_change_info_new (); camel_folder_change_info_remove_uid (expunged_changes, camel_message_info_get_uid (info)); expunged_removed_list = g_list_prepend (expunged_removed_list, (gpointer) camel_pstring_strdup (camel_message_info_get_uid (info))); } if ( (on && (((flags ^ sflags) & flags) & flag)) || (!on && (((flags ^ sflags) & ~flags) & flag))) { if (ic == NULL) { ic = camel_imapx_command_new (is, CAMEL_IMAPX_JOB_SYNC_CHANGES, "UID STORE "); } send = imapx_uidset_add (&uidset, ic, camel_message_info_get_uid (info)); } if (send == 1 || (i == changed_uids->len - 1 && ic && imapx_uidset_done (&uidset, ic))) { camel_imapx_command_add (ic, " %tFLAGS.SILENT (%t)", on ? "+" : "-", flags_table[jj].name); success = camel_imapx_server_process_command_sync (is, ic, _("Error syncing changes"), cancellable, error); camel_imapx_command_unref (ic); ic = NULL; if (!success) { g_clear_object (&info); break; } } if (has_uidplus_capability && ( send_expunge == 1 || (i == changed_uids->len - 1 && ic_expunge && imapx_uidset_done (&uidset_expunge, ic_expunge)))) { success = camel_imapx_server_process_command_sync (is, ic_expunge, _("Error expunging message"), cancellable, error); camel_imapx_command_unref (ic_expunge); ic_expunge = NULL; if (!success) { g_clear_object (&info); break; } camel_folder_changed (folder, expunged_changes); camel_folder_summary_remove_uids (camel_folder_get_folder_summary (folder), expunged_removed_list); camel_folder_change_info_free (expunged_changes); expunged_changes = NULL; g_list_free_full (expunged_removed_list, (GDestroyNotify) camel_pstring_free); expunged_removed_list = NULL; } if (flag == CAMEL_MESSAGE_SEEN) { /* Remember how the server's unread count will change if this * command succeeds */ if (on) unread_change--; else unread_change++; } /* The second round and the server doesn't support saving user flags, thus store them at least locally */ if (on && (permanentflags & CAMEL_MESSAGE_USER) == 0) { camel_imapx_message_info_take_server_user_flags (xinfo, camel_message_info_dup_user_flags (info)); } g_clear_object (&info); } if (ic && imapx_uidset_done (&uidset, ic)) { camel_imapx_command_add (ic, " %tFLAGS.SILENT (%t)", on ? "+" : "-", flags_table[jj].name); success = camel_imapx_server_process_command_sync (is, ic, _("Error syncing changes"), cancellable, error); camel_imapx_command_unref (ic); ic = NULL; if (!success) break; } if (has_uidplus_capability && ic_expunge && imapx_uidset_done (&uidset_expunge, ic_expunge)) { success = camel_imapx_server_process_command_sync (is, ic_expunge, _("Error expunging message"), cancellable, error); camel_imapx_command_unref (ic_expunge); ic_expunge = NULL; if (!success) break; camel_folder_changed (folder, expunged_changes); camel_folder_summary_remove_uids (camel_folder_get_folder_summary (folder), expunged_removed_list); camel_folder_change_info_free (expunged_changes); expunged_changes = NULL; g_list_free_full (expunged_removed_list, (GDestroyNotify) camel_pstring_free); expunged_removed_list = NULL; } g_warn_if_fail (ic == NULL); g_warn_if_fail (ic_expunge == NULL); } if (user_set && (permanentflags & CAMEL_MESSAGE_USER) != 0 && success) { CamelIMAPXCommand *ic = NULL; for (jj = 0; jj < user_set->len && success; jj++) { struct _imapx_flag_change *c = &g_array_index (user_set, struct _imapx_flag_change, jj); imapx_uidset_init (&uidset, 0, 100); for (i = 0; i < c->infos->len; i++) { CamelMessageInfo *info = c->infos->pdata[i]; /* When expunging deleted in the real Trash folder, then skip those deleted, because they are gone now. */ if (expunge_deleted && has_uidplus_capability && (((camel_message_info_get_flags (info) & CAMEL_IMAPX_SERVER_FLAGS) & permanentflags) & CAMEL_MESSAGE_DELETED) != 0) { if (ic && i == c->infos->len - 1 && imapx_uidset_done (&uidset, ic)) goto store_changes; continue; } if (ic == NULL) ic = camel_imapx_command_new (is, CAMEL_IMAPX_JOB_SYNC_CHANGES, "UID STORE "); if (imapx_uidset_add (&uidset, ic, camel_message_info_get_uid (info)) == 1 || (i == c->infos->len - 1 && imapx_uidset_done (&uidset, ic))) { gchar *utf7; store_changes: utf7 = camel_utf8_utf7 (c->name); camel_imapx_command_add (ic, " %tFLAGS.SILENT (%t)", on ? "+" : "-", utf7 ? utf7 : c->name); g_free (utf7); success = camel_imapx_server_process_command_sync (is, ic, _("Error syncing changes"), cancellable, error); camel_imapx_command_unref (ic); ic = NULL; if (!success) break; } } } g_warn_if_fail (ic == NULL); } } if (success && expunged_changes && expunge_deleted && !has_uidplus_capability) { CamelIMAPXCommand *ic; ic = camel_imapx_command_new (is, CAMEL_IMAPX_JOB_EXPUNGE, "EXPUNGE"); success = camel_imapx_server_process_command_sync (is, ic, _("Error expunging message"), cancellable, error); camel_imapx_command_unref (ic); } if (success && expunged_changes) { camel_folder_changed (folder, expunged_changes); camel_folder_summary_remove_uids (camel_folder_get_folder_summary (folder), expunged_removed_list); } if (expunged_changes) { camel_folder_change_info_free (expunged_changes); expunged_changes = NULL; } if (expunged_removed_list) { g_list_free_full (expunged_removed_list, (GDestroyNotify) camel_pstring_free); expunged_removed_list = NULL; } if (success) { CamelFolderSummary *folder_summary; CamelStore *parent_store; guint32 unseen; parent_store = camel_folder_get_parent_store (folder); folder_summary = camel_folder_get_folder_summary (folder); camel_folder_summary_lock (folder_summary); for (i = 0; i < changed_uids->len; i++) { CamelMessageInfo *info; CamelIMAPXMessageInfo *xinfo; gboolean set_folder_flagged; guint32 has_flags, set_server_flags; gboolean changed_meanwhile; const gchar *uid; uid = g_ptr_array_index (changed_uids, i); /* the 'stamps' hash table contains only those uid-s, which were also flagged, not only 'dirty' */ if (!g_hash_table_contains (stamps, uid)) continue; info = camel_folder_summary_get (folder_summary, uid); xinfo = info ? CAMEL_IMAPX_MESSAGE_INFO (info) : NULL; if (!info || !xinfo) { g_clear_object (&info); continue; } camel_message_info_property_lock (info); changed_meanwhile = camel_message_info_get_folder_flagged_stamp (info) != GPOINTER_TO_UINT (g_hash_table_lookup (stamps, uid)); has_flags = camel_message_info_get_flags (info); set_server_flags = has_flags & CAMEL_IMAPX_SERVER_FLAGS; if (!remove_deleted_flags || !(has_flags & CAMEL_MESSAGE_DELETED)) { set_folder_flagged = FALSE; } else { /* to stare back the \Deleted flag */ set_server_flags &= ~CAMEL_MESSAGE_DELETED; set_folder_flagged = TRUE; } if ((permanentflags & CAMEL_MESSAGE_USER) != 0 || !camel_named_flags_get_length (camel_imapx_message_info_get_server_user_flags (xinfo))) { camel_imapx_message_info_take_server_user_flags (xinfo, camel_message_info_dup_user_flags (info)); } if (changed_meanwhile) set_folder_flagged = TRUE; camel_imapx_message_info_set_server_flags (xinfo, set_server_flags); camel_message_info_set_folder_flagged (info, set_folder_flagged); camel_message_info_property_unlock (info); camel_folder_summary_touch (folder_summary); g_clear_object (&info); } camel_folder_summary_unlock (folder_summary); /* Apply the changes to server-side unread count; it won't tell * us of these changes, of course. */ unseen = camel_imapx_mailbox_get_unseen (mailbox); unseen += unread_change; camel_imapx_mailbox_set_unseen (mailbox, unseen); if ((camel_folder_summary_get_flags (folder_summary) & CAMEL_FOLDER_SUMMARY_DIRTY) != 0) { CamelStoreInfo *si; /* ... and store's summary when folder's summary is dirty */ si = camel_store_summary_path (CAMEL_IMAPX_STORE (parent_store)->summary, camel_folder_get_full_name (folder)); if (si) { if (si->total != camel_folder_summary_get_saved_count (folder_summary) || si->unread != camel_folder_summary_get_unread_count (folder_summary)) { si->total = camel_folder_summary_get_saved_count (folder_summary); si->unread = camel_folder_summary_get_unread_count (folder_summary); camel_store_summary_touch (CAMEL_IMAPX_STORE (parent_store)->summary); } camel_store_summary_info_unref (CAMEL_IMAPX_STORE (parent_store)->summary, si); } } } camel_folder_summary_save (camel_folder_get_folder_summary (folder), NULL); camel_store_summary_save (CAMEL_IMAPX_STORE (camel_folder_get_parent_store (folder))->summary); imapx_sync_free_user (on_user); imapx_sync_free_user (off_user); camel_folder_free_uids (folder, changed_uids); g_hash_table_destroy (stamps); g_object_unref (folder); return success; }
0
[ "CWE-476" ]
evolution-data-server
2cc39592b532cf0dc994fd3694b8e6bf924c9ab5
303,276,983,979,666,440,000,000,000,000,000,000,000
615
I#189 - Crash on malformed server response with minimal capabilities Closes https://gitlab.gnome.org/GNOME/evolution-data-server/issues/189
virtual Item *convert_to_basic_const_item(THD *thd) { return 0; };
0
[ "CWE-617" ]
server
2e7891080667c59ac80f788eef4d59d447595772
129,376,081,158,035,030,000,000,000,000,000,000,000
1
MDEV-25635 Assertion failure when pushing from HAVING into WHERE of view This bug could manifest itself after pushing a where condition over a mergeable derived table / view / CTE DT into a grouping view / derived table / CTE V whose item list contained set functions with constant arguments such as MIN(2), SUM(1) etc. In such cases the field references used in the condition pushed into the view V that correspond set functions are wrapped into Item_direct_view_ref wrappers. Due to a wrong implementation of the virtual method const_item() for the class Item_direct_view_ref the wrapped set functions with constant arguments could be erroneously taken for constant items. This could lead to a wrong result set returned by the main select query in 10.2. In 10.4 where a possibility of pushing condition from HAVING into WHERE had been added this could cause a crash. Approved by Sergey Petrunya <[email protected]>
static int __dcbnl_pg_getcfg(struct net_device *netdev, struct nlmsghdr *nlh, struct nlattr **tb, struct sk_buff *skb, int dir) { struct nlattr *pg_nest, *param_nest, *data; struct nlattr *pg_tb[DCB_PG_ATTR_MAX + 1]; struct nlattr *param_tb[DCB_TC_ATTR_PARAM_MAX + 1]; u8 prio, pgid, tc_pct, up_map; int ret; int getall = 0; int i; if (!tb[DCB_ATTR_PG_CFG]) return -EINVAL; if (!netdev->dcbnl_ops->getpgtccfgtx || !netdev->dcbnl_ops->getpgtccfgrx || !netdev->dcbnl_ops->getpgbwgcfgtx || !netdev->dcbnl_ops->getpgbwgcfgrx) return -EOPNOTSUPP; ret = nla_parse_nested(pg_tb, DCB_PG_ATTR_MAX, tb[DCB_ATTR_PG_CFG], dcbnl_pg_nest); if (ret) return ret; pg_nest = nla_nest_start(skb, DCB_ATTR_PG_CFG); if (!pg_nest) return -EMSGSIZE; if (pg_tb[DCB_PG_ATTR_TC_ALL]) getall = 1; for (i = DCB_PG_ATTR_TC_0; i <= DCB_PG_ATTR_TC_7; i++) { if (!getall && !pg_tb[i]) continue; if (pg_tb[DCB_PG_ATTR_TC_ALL]) data = pg_tb[DCB_PG_ATTR_TC_ALL]; else data = pg_tb[i]; ret = nla_parse_nested(param_tb, DCB_TC_ATTR_PARAM_MAX, data, dcbnl_tc_param_nest); if (ret) goto err_pg; param_nest = nla_nest_start(skb, i); if (!param_nest) goto err_pg; pgid = DCB_ATTR_VALUE_UNDEFINED; prio = DCB_ATTR_VALUE_UNDEFINED; tc_pct = DCB_ATTR_VALUE_UNDEFINED; up_map = DCB_ATTR_VALUE_UNDEFINED; if (dir) { /* Rx */ netdev->dcbnl_ops->getpgtccfgrx(netdev, i - DCB_PG_ATTR_TC_0, &prio, &pgid, &tc_pct, &up_map); } else { /* Tx */ netdev->dcbnl_ops->getpgtccfgtx(netdev, i - DCB_PG_ATTR_TC_0, &prio, &pgid, &tc_pct, &up_map); } if (param_tb[DCB_TC_ATTR_PARAM_PGID] || param_tb[DCB_TC_ATTR_PARAM_ALL]) { ret = nla_put_u8(skb, DCB_TC_ATTR_PARAM_PGID, pgid); if (ret) goto err_param; } if (param_tb[DCB_TC_ATTR_PARAM_UP_MAPPING] || param_tb[DCB_TC_ATTR_PARAM_ALL]) { ret = nla_put_u8(skb, DCB_TC_ATTR_PARAM_UP_MAPPING, up_map); if (ret) goto err_param; } if (param_tb[DCB_TC_ATTR_PARAM_STRICT_PRIO] || param_tb[DCB_TC_ATTR_PARAM_ALL]) { ret = nla_put_u8(skb, DCB_TC_ATTR_PARAM_STRICT_PRIO, prio); if (ret) goto err_param; } if (param_tb[DCB_TC_ATTR_PARAM_BW_PCT] || param_tb[DCB_TC_ATTR_PARAM_ALL]) { ret = nla_put_u8(skb, DCB_TC_ATTR_PARAM_BW_PCT, tc_pct); if (ret) goto err_param; } nla_nest_end(skb, param_nest); } if (pg_tb[DCB_PG_ATTR_BW_ID_ALL]) getall = 1; else getall = 0; for (i = DCB_PG_ATTR_BW_ID_0; i <= DCB_PG_ATTR_BW_ID_7; i++) { if (!getall && !pg_tb[i]) continue; tc_pct = DCB_ATTR_VALUE_UNDEFINED; if (dir) { /* Rx */ netdev->dcbnl_ops->getpgbwgcfgrx(netdev, i - DCB_PG_ATTR_BW_ID_0, &tc_pct); } else { /* Tx */ netdev->dcbnl_ops->getpgbwgcfgtx(netdev, i - DCB_PG_ATTR_BW_ID_0, &tc_pct); } ret = nla_put_u8(skb, i, tc_pct); if (ret) goto err_pg; } nla_nest_end(skb, pg_nest); return 0; err_param: nla_nest_cancel(skb, param_nest); err_pg: nla_nest_cancel(skb, pg_nest); return -EMSGSIZE; }
0
[ "CWE-399" ]
linux-2.6
29cd8ae0e1a39e239a3a7b67da1986add1199fc0
23,926,273,564,534,440,000,000,000,000,000,000,000
133
dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]>
void createHermesBuiltins( Runtime *runtime, llvm::MutableArrayRef<NativeFunction *> builtins) { auto defineInternMethod = [&](BuiltinMethod::Enum builtinIndex, Predefined::Str symID, NativeFunctionPtr func, uint8_t count = 0) { auto method = NativeFunction::create( runtime, Handle<JSObject>::vmcast(&runtime->functionPrototype), nullptr /* context */, func, Predefined::getSymbolID(symID), count, Runtime::makeNullHandle<JSObject>()); assert(builtins[builtinIndex] == nullptr && "builtin already defined"); builtins[builtinIndex] = *method; }; // HermesBuiltin function properties namespace P = Predefined; namespace B = BuiltinMethod; defineInternMethod( B::HermesBuiltin_silentSetPrototypeOf, P::silentSetPrototypeOf, silentObjectSetPrototypeOf, 2); defineInternMethod( B::HermesBuiltin_getTemplateObject, P::getTemplateObject, hermesBuiltinGetTemplateObject); defineInternMethod( B::HermesBuiltin_ensureObject, P::ensureObject, hermesBuiltinEnsureObject, 2); defineInternMethod( B::HermesBuiltin_throwTypeError, P::throwTypeError, hermesBuiltinThrowTypeError, 1); defineInternMethod( B::HermesBuiltin_generatorSetDelegated, P::generatorSetDelegated, hermesBuiltinGeneratorSetDelegated, 1); defineInternMethod( B::HermesBuiltin_copyDataProperties, P::copyDataProperties, hermesBuiltinCopyDataProperties, 3); defineInternMethod( B::HermesBuiltin_copyRestArgs, P::copyRestArgs, hermesBuiltinCopyRestArgs, 1); defineInternMethod( B::HermesBuiltin_arraySpread, P::arraySpread, hermesBuiltinArraySpread, 2); defineInternMethod(B::HermesBuiltin_apply, P::apply, hermesBuiltinApply, 2); defineInternMethod( B::HermesBuiltin_exportAll, P::exportAll, hermesBuiltinExportAll); defineInternMethod( B::HermesBuiltin_exponentiationOperator, P::exponentiationOperator, mathPow); // Define the 'requireFast' function, which takes a number argument. defineInternMethod( B::HermesBuiltin_requireFast, P::requireFast, requireFast, 1); }
0
[ "CWE-787" ]
hermes
86543ac47e59c522976b5632b8bf9a2a4583c7d2
317,121,141,459,774,970,000,000,000,000,000,000,000
74
Added stack overflow check for hermes::vm:: hermesBuiltinApply Summary: This adds a missing check for stack overflow. Reviewed By: tmikov Differential Revision: D20104955 fbshipit-source-id: 1f37e23d2e28ebcd3aa4176d134b8418e7059ebd
xmlValidPrintNode(xmlNodePtr cur) { if (cur == NULL) { xmlGenericError(xmlGenericErrorContext, "null"); return; } switch (cur->type) { case XML_ELEMENT_NODE: xmlGenericError(xmlGenericErrorContext, "%s ", cur->name); break; case XML_TEXT_NODE: xmlGenericError(xmlGenericErrorContext, "text "); break; case XML_CDATA_SECTION_NODE: xmlGenericError(xmlGenericErrorContext, "cdata "); break; case XML_ENTITY_REF_NODE: xmlGenericError(xmlGenericErrorContext, "&%s; ", cur->name); break; case XML_PI_NODE: xmlGenericError(xmlGenericErrorContext, "pi(%s) ", cur->name); break; case XML_COMMENT_NODE: xmlGenericError(xmlGenericErrorContext, "comment "); break; case XML_ATTRIBUTE_NODE: xmlGenericError(xmlGenericErrorContext, "?attr? "); break; case XML_ENTITY_NODE: xmlGenericError(xmlGenericErrorContext, "?ent? "); break; case XML_DOCUMENT_NODE: xmlGenericError(xmlGenericErrorContext, "?doc? "); break; case XML_DOCUMENT_TYPE_NODE: xmlGenericError(xmlGenericErrorContext, "?doctype? "); break; case XML_DOCUMENT_FRAG_NODE: xmlGenericError(xmlGenericErrorContext, "?frag? "); break; case XML_NOTATION_NODE: xmlGenericError(xmlGenericErrorContext, "?nota? "); break; case XML_HTML_DOCUMENT_NODE: xmlGenericError(xmlGenericErrorContext, "?html? "); break; #ifdef LIBXML_DOCB_ENABLED case XML_DOCB_DOCUMENT_NODE: xmlGenericError(xmlGenericErrorContext, "?docb? "); break; #endif case XML_DTD_NODE: xmlGenericError(xmlGenericErrorContext, "?dtd? "); break; case XML_ELEMENT_DECL: xmlGenericError(xmlGenericErrorContext, "?edecl? "); break; case XML_ATTRIBUTE_DECL: xmlGenericError(xmlGenericErrorContext, "?adecl? "); break; case XML_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "?entdecl? "); break; case XML_NAMESPACE_DECL: xmlGenericError(xmlGenericErrorContext, "?nsdecl? "); break; case XML_XINCLUDE_START: xmlGenericError(xmlGenericErrorContext, "incstart "); break; case XML_XINCLUDE_END: xmlGenericError(xmlGenericErrorContext, "incend "); break; } }
0
[]
libxml2
932cc9896ab41475d4aa429c27d9afd175959d74
339,632,049,567,968,300,000,000,000,000,000,000,000
73
Fix buffer size checks in xmlSnprintfElementContent xmlSnprintfElementContent failed to correctly check the available buffer space in two locations. Fixes bug 781333 (CVE-2017-9047) and bug 781701 (CVE-2017-9048). Thanks to Marcel Böhme and Thuan Pham for the report.
do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual) { int param_count, i; MonoMethodSignature *sig; ILStackDesc *value; MonoMethod *method; gboolean virt_check_this = FALSE; gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED; if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call"))) return; if (virtual) { CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED); if (method->klass->valuetype) // && !constrained ??? CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset)); if ((method->flags & METHOD_ATTRIBUTE_STATIC)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset)); } else { if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset)); if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) { virt_check_this = TRUE; ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL; } } if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context))) sig = mono_method_get_signature (method, ctx->image, method_token); if (!sig) { char *name = mono_type_get_full_name (method->klass); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset)); g_free (name); return; } param_count = sig->param_count + sig->hasthis; if (!check_underflow (ctx, param_count)) return; for (i = sig->param_count - 1; i >= 0; --i) { VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); ); value = stack_pop (ctx); if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) { char *stack_name = stack_slot_full_name (value); char *sig_name = mono_type_full_name (sig->params [i]); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset)); g_free (stack_name); g_free (sig_name); } if (stack_slot_is_managed_mutability_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset)); if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot pass a byref argument to a tail %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset)); return; } } if (sig->hasthis) { MonoType *type = &method->klass->byval_arg; ILStackDesc copy; if (mono_method_is_constructor (method) && !method->klass->valuetype) { if (!mono_method_is_constructor (ctx->method)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset)); if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor to a type diferent that this or super at 0x%04x", ctx->ip_offset)); ctx->super_ctor_called = TRUE; value = stack_pop_safe (ctx); if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset)); } else { value = stack_pop (ctx); } copy_stack_value (&copy, value); //TODO we should extract this to a 'drop_byref_argument' and use everywhere //Other parts of the code suffer from the same issue of copy.type = mono_type_get_type_byval (copy.type); copy.stype &= ~POINTER_MASK; if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset)); if (constrained && virtual) { if (!stack_slot_is_managed_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset)); if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset)); copy.stype |= BOXED_MASK; } else { if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset)); if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset)); if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset)); if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset)); } if (!verify_stack_type_compatibility (ctx, type, &copy)) { char *expected = mono_type_full_name (type); char *effective = stack_slot_full_name (&copy); char *method_name = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x", expected, effective, method_name, ctx->ip_offset)); g_free (method_name); g_free (effective); g_free (expected); } if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) { char *name = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS); g_free (name); } } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) { char *name = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS); g_free (name); } if (sig->ret->type != MONO_TYPE_VOID) { if (check_overflow (ctx)) { value = stack_push (ctx); set_stack_value (ctx, value, sig->ret, FALSE); if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) { ctx->prefix_set &= ~PREFIX_READONLY; value->stype |= CMMP_MASK; } } } if ((ctx->prefix_set & PREFIX_TAIL)) { if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset)); if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset)); } }
0
[ "CWE-20" ]
mono
65292a69c837b8a5f7a392d34db63de592153358
130,250,278,390,864,530,000,000,000,000,000,000,000
153
Handle invalid instantiation of generic methods. * verify.c: Add new function to internal verifier API to check method instantiations. * reflection.c (mono_reflection_bind_generic_method_parameters): Check the instantiation before returning it. Fixes #655847
static int tiff_closeproc(thandle_t clientdata) { (void)clientdata; /*tiff_handle *th = (tiff_handle *)clientdata; gdIOCtx *ctx = th->ctx; (ctx->gd_free)(ctx);*/ return 0; }
0
[ "CWE-125" ]
libgd
4859d69e07504d4b0a4bdf9bcb4d9e3769ca35ae
89,332,085,147,246,760,000,000,000,000,000,000,000
10
Fix invalid read in gdImageCreateFromTiffPtr() tiff_invalid_read.tiff is corrupt, and causes an invalid read in gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case, dynamicGetbuf() is called with a negative dp->pos, but also positive buffer overflows have to be handled, in which case 0 has to be returned (cf. commit 75e29a9). Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create the image, because the return value of TIFFReadRGBAImage() is not checked. We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6911
static WC_INLINE void innermul8_mulx(fp_digit *c_mulx, fp_digit *cy_mulx, fp_digit *tmpm, fp_digit mu) { fp_digit cy = *cy_mulx ; INNERMUL8_MULX ; *cy_mulx = cy ; }
0
[ "CWE-326", "CWE-203" ]
wolfssl
1de07da61f0c8e9926dcbd68119f73230dae283f
38,648,501,991,054,510,000,000,000,000,000,000,000
6
Constant time EC map to affine for private operations For fast math, use a constant time modular inverse when mapping to affine when operation involves a private key - key gen, calc shared secret, sign.
copytup_cluster(Tuplesortstate *state, SortTuple *stup, void *tup) { HeapTuple tuple = (HeapTuple) tup; Datum original; /* copy the tuple into sort storage */ tuple = heap_copytuple(tuple); stup->tuple = (void *) tuple; USEMEM(state, GetMemoryChunkSpace(tuple)); /* * set up first-column key value, and potentially abbreviate, if it's a * simple column */ if (state->indexInfo->ii_KeyAttrNumbers[0] == 0) return; original = heap_getattr(tuple, state->indexInfo->ii_KeyAttrNumbers[0], state->tupDesc, &stup->isnull1); if (!state->sortKeys->abbrev_converter || stup->isnull1) { /* * Store ordinary Datum representation, or NULL value. If there is a * converter it won't expect NULL values, and cost model is not * required to account for NULL, so in that case we avoid calling * converter and just set datum1 to "void" representation (to be * consistent). */ stup->datum1 = original; } else if (!consider_abort_common(state)) { /* Store abbreviated key representation */ stup->datum1 = state->sortKeys->abbrev_converter(original, state->sortKeys); } else { /* Abort abbreviation */ int i; stup->datum1 = original; /* * Set state to be consistent with never trying abbreviation. * * Alter datum1 representation in already-copied tuples, so as to * ensure a consistent representation (current tuple was just handled). * Note that we rely on all tuples copied so far actually being * contained within memtuples array. */ for (i = 0; i < state->memtupcount; i++) { SortTuple *mtup = &state->memtuples[i]; tuple = (HeapTuple) mtup->tuple; mtup->datum1 = heap_getattr(tuple, state->indexInfo->ii_KeyAttrNumbers[0], state->tupDesc, &stup->isnull1); } } }
0
[ "CWE-209" ]
postgres
804b6b6db4dcfc590a468e7be390738f9f7755fb
135,958,605,335,450,700,000,000,000,000,000,000,000
65
Fix column-privilege leak in error-message paths While building error messages to return to the user, BuildIndexValueDescription, ExecBuildSlotValueDescription and ri_ReportViolation would happily include the entire key or entire row in the result returned to the user, even if the user didn't have access to view all of the columns being included. Instead, include only those columns which the user is providing or which the user has select rights on. If the user does not have any rights to view the table or any of the columns involved then no detail is provided and a NULL value is returned from BuildIndexValueDescription and ExecBuildSlotValueDescription. Note that, for key cases, the user must have access to all of the columns for the key to be shown; a partial key will not be returned. Further, in master only, do not return any data for cases where row security is enabled on the relation and row security should be applied for the user. This required a bit of refactoring and moving of things around related to RLS- note the addition of utils/misc/rls.c. Back-patch all the way, as column-level privileges are now in all supported versions. This has been assigned CVE-2014-8161, but since the issue and the patch have already been publicized on pgsql-hackers, there's no point in trying to hide this commit.
void CLASS foveon_make_curves(short **curvep, float dq[3], float div[3], float filt) { double mul[3], max = 0; int c; FORC3 mul[c] = dq[c] / div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve(max, mul[c], filt); }
0
[ "CWE-476", "CWE-119" ]
LibRaw
d7c3d2cb460be10a3ea7b32e9443a83c243b2251
41,513,709,502,862,043,000,000,000,000,000,000,000
9
Secunia SA75000 advisory: several buffer overruns
GF_ISMASample *gf_isom_get_ismacryp_sample(GF_ISOFile *the_file, u32 trackNumber, const GF_ISOSample *samp, u32 sampleDescriptionIndex) { GF_TrackBox *trak; GF_ISMASampleFormatBox *fmt; GF_ProtectionSchemeInfoBox *sinf; trak = gf_isom_get_track_from_file(the_file, trackNumber); if (!trak) return NULL; sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, 0, NULL); if (!sinf) return NULL; /*ISMA*/ if (sinf->scheme_type->scheme_type == GF_ISOM_ISMACRYP_SCHEME) { fmt = sinf->info->isfm; if (!fmt) return NULL; return gf_isom_ismacryp_sample_from_data(samp->data, samp->dataLength, sinf->info->isfm->selective_encryption, sinf->info->isfm->key_indicator_length, sinf->info->isfm->IV_length); } /*OMA*/ else if (sinf->scheme_type->scheme_type == GF_ISOM_OMADRM_SCHEME ) { if (!sinf->info->odkm) return NULL; fmt = sinf->info->odkm->fmt; if (fmt) { return gf_isom_ismacryp_sample_from_data(samp->data, samp->dataLength, fmt->selective_encryption, fmt->key_indicator_length, fmt->IV_length); } /*OMA default: no selective encryption, one key, 128 bit IV*/ return gf_isom_ismacryp_sample_from_data(samp->data, samp->dataLength, GF_FALSE, 0, 128); } return NULL; }
0
[ "CWE-476" ]
gpac
3b84ffcbacf144ce35650df958432f472b6483f8
1,812,034,089,161,067,300,000,000,000,000,000,000
31
fixed #1735
int nfc_fw_download(struct nfc_dev *dev, const char *firmware_name) { int rc = 0; pr_debug("%s do firmware %s\n", dev_name(&dev->dev), firmware_name); device_lock(&dev->dev); if (dev->shutting_down) { rc = -ENODEV; goto error; } if (dev->dev_up) { rc = -EBUSY; goto error; } if (!dev->ops->fw_download) { rc = -EOPNOTSUPP; goto error; } dev->fw_download_in_progress = true; rc = dev->ops->fw_download(dev, firmware_name); if (rc) dev->fw_download_in_progress = false; error: device_unlock(&dev->dev); return rc; }
0
[ "CWE-416" ]
linux
da5c0f119203ad9728920456a0f52a6d850c01cd
150,036,504,821,052,330,000,000,000,000,000,000,000
32
nfc: replace improper check device_is_registered() in netlink related functions The device_is_registered() in nfc core is used to check whether nfc device is registered in netlink related functions such as nfc_fw_download(), nfc_dev_up() and so on. Although device_is_registered() is protected by device_lock, there is still a race condition between device_del() and device_is_registered(). The root cause is that kobject_del() in device_del() is not protected by device_lock. (cleanup task) | (netlink task) | nfc_unregister_device | nfc_fw_download device_del | device_lock ... | if (!device_is_registered)//(1) kobject_del//(2) | ... ... | device_unlock The device_is_registered() returns the value of state_in_sysfs and the state_in_sysfs is set to zero in kobject_del(). If we pass check in position (1), then set zero in position (2). As a result, the check in position (1) is useless. This patch uses bool variable instead of device_is_registered() to judge whether the nfc device is registered, which is well synchronized. Fixes: 3e256b8f8dfa ("NFC: add nfc subsystem core") Signed-off-by: Duoming Zhou <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static struct sock *vsock_dequeue_accept(struct sock *listener) { struct vsock_sock *vlistener; struct vsock_sock *vconnected; vlistener = vsock_sk(listener); if (list_empty(&vlistener->accept_queue)) return NULL; vconnected = list_entry(vlistener->accept_queue.next, struct vsock_sock, accept_queue); list_del_init(&vconnected->accept_queue); sock_put(listener); /* The caller will need a reference on the connected socket so we let * it call sock_put(). */ return sk_vsock(vconnected); }
0
[ "CWE-667" ]
linux
c518adafa39f37858697ac9309c6cf1805581446
207,743,485,761,014,880,000,000,000,000,000,000,000
21
vsock: fix the race conditions in multi-transport support There are multiple similar bugs implicitly introduced by the commit c0cfa2d8a788fcf4 ("vsock: add multi-transports support") and commit 6a2c0962105ae8ce ("vsock: prevent transport modules unloading"). The bug pattern: [1] vsock_sock.transport pointer is copied to a local variable, [2] lock_sock() is called, [3] the local variable is used. VSOCK multi-transport support introduced the race condition: vsock_sock.transport value may change between [1] and [2]. Let's copy vsock_sock.transport pointer to local variables after the lock_sock() call. Fixes: c0cfa2d8a788fcf4 ("vsock: add multi-transports support") Signed-off-by: Alexander Popov <[email protected]> Reviewed-by: Stefano Garzarella <[email protected]> Reviewed-by: Jorgen Hansen <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jakub Kicinski <[email protected]>
create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb) { MonoDynamicTable *table; MonoClass *klass; MonoType *type; guint32 *values; guint32 token; SigBuffer buf; int count, i; /* * We're creating a TypeSpec for the TypeBuilder of a generic type declaration, * ie. what we'd normally use as the generic type in a TypeSpec signature. * Because of this, we must not insert it into the `typeref' hash table. */ type = mono_reflection_type_get_handle ((MonoReflectionType*)tb); token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type)); if (token) return token; sigbuffer_init (&buf, 32); g_assert (tb->generic_params); klass = mono_class_from_mono_type (type); if (tb->generic_container) mono_reflection_create_generic_class (tb); sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST); g_assert (klass->generic_container); sigbuffer_add_value (&buf, klass->byval_arg.type); sigbuffer_add_value (&buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE)); count = mono_array_length (tb->generic_params); sigbuffer_add_value (&buf, count); for (i = 0; i < count; i++) { MonoReflectionGenericParam *gparam; gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i); encode_type (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)gparam), &buf); } table = &assembly->tables [MONO_TABLE_TYPESPEC]; if (assembly->save) { token = sigbuffer_add_to_blob_cached (assembly, &buf); alloc_table (table, table->rows + 1); values = table->values + table->next_idx * MONO_TYPESPEC_SIZE; values [MONO_TYPESPEC_SIGNATURE] = token; } sigbuffer_free (&buf); token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS); g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token)); table->next_idx ++; return token; }
0
[ "CWE-20" ]
mono
4905ef1130feb26c3150b28b97e4a96752e0d399
130,730,261,363,789,490,000,000,000,000,000,000,000
58
Handle invalid instantiation of generic methods. * verify.c: Add new function to internal verifier API to check method instantiations. * reflection.c (mono_reflection_bind_generic_method_parameters): Check the instantiation before returning it. Fixes #655847
TEST_P(CdsIntegrationTest, CdsClusterDownWithLotsOfIdleConnections) { constexpr int num_requests = 2000; // Make upstream H/1 so it creates connection for each request upstream_codec_type_ = Http::CodecType::HTTP1; // Relax default circuit breaker limits and timeouts so Envoy can accumulate a lot of idle // connections cluster_creator_ = &ConfigHelper::buildH1ClusterWithHighCircuitBreakersLimits; config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->mutable_timeout() ->set_seconds(600); hcm.mutable_route_config() ->mutable_virtual_hosts(0) ->mutable_routes(0) ->mutable_route() ->mutable_idle_timeout() ->set_seconds(600); }); initialize(); std::vector<IntegrationStreamDecoderPtr> responses; std::vector<FakeHttpConnectionPtr> upstream_connections; std::vector<FakeStreamPtr> upstream_requests; codec_client_ = makeHttpConnection(makeClientConnection((lookupPort("http")))); // The first loop establishes a lot of open connections with active requests to upstream for (int i = 0; i < num_requests; ++i) { Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/cluster1"}, {":scheme", "http"}, {":authority", "host"}, {"x-lyft-user-id", absl::StrCat(i)}}; auto response = codec_client_->makeHeaderOnlyRequest(request_headers); responses.push_back(std::move(response)); FakeHttpConnectionPtr fake_upstream_connection; waitForNextUpstreamConnection({UpstreamIndex1}, TestUtility::DefaultTimeout, fake_upstream_connection); // Wait for the next stream on the upstream connection. FakeStreamPtr upstream_request; AssertionResult result = fake_upstream_connection->waitForNewStream(*dispatcher_, upstream_request); RELEASE_ASSERT(result, result.message()); // Wait for the stream to be completely received. result = upstream_request->waitForEndStream(*dispatcher_); RELEASE_ASSERT(result, result.message()); upstream_connections.push_back(std::move(fake_upstream_connection)); upstream_requests.push_back(std::move(upstream_request)); } // This loop completes all requests making the all upstream connections idle for (int i = 0; i < num_requests; ++i) { // Send response headers, and end_stream if there is no response body. upstream_requests[i]->encodeHeaders(default_response_headers_, true); // Wait for the response to be read by the codec client. RELEASE_ASSERT(responses[i]->waitForEndStream(), "unexpected timeout"); ASSERT_TRUE(responses[i]->complete()); EXPECT_EQ("200", responses[i]->headers().getStatusValue()); } test_server_->waitForCounterGe("cluster_manager.cluster_added", 1); // Tell Envoy that cluster_1 is gone. Envoy will try to close all idle connections EXPECT_TRUE(compareDiscoveryRequest(Config::TypeUrl::get().Cluster, "55", {}, {}, {})); sendDiscoveryResponse<envoy::config::cluster::v3::Cluster>(Config::TypeUrl::get().Cluster, {}, {}, {ClusterName1}, "42"); // We can continue the test once we're sure that Envoy's ClusterManager has made use of // the DiscoveryResponse that says cluster_1 is gone. test_server_->waitForCounterGe("cluster_manager.cluster_removed", 1); // If we made it this far then everything is ok. for (int i = 0; i < num_requests; ++i) { AssertionResult result = upstream_connections[i]->close(); RELEASE_ASSERT(result, result.message()); result = upstream_connections[i]->waitForDisconnect(); RELEASE_ASSERT(result, result.message()); } upstream_connections.clear(); cleanupUpstreamAndDownstream(); ASSERT_TRUE(codec_client_->waitForDisconnect()); }
0
[ "CWE-703", "CWE-674" ]
envoy
4b6dd3b53cd5c6d4d4df378a2fc62c1707522b31
198,429,760,405,033,100,000,000,000,000,000,000,000
85
CVE-2022-23606 Avoid closing other connections to prevent deep recursion when a large number of idle connections are closed at the start of a pool drain, when a connection is closed. Signed-off-by: Yan Avlasov <[email protected]>
bool do_find_state(ctx_t &ctx) { kernels_t &kernels = ctx.dc_kernels; const closure_t &closure = ctx.state; // empty closure corresponds to default state if (closure.size() == 0) { ctx.dc_target = dfa_t::NIL; ctx.dc_actions = NULL; return false; } // resize buffer if closure is too large reserve_buffers<ctx_t, stadfa>(ctx); kernel_t *k = ctx.dc_buffers.kernel; // copy closure to buffer kernel copy_to_buffer<stadfa>(closure, ctx.newprectbl, ctx.stadfa_actions, k); // hash "static" part of the kernel const uint32_t hash = hash_kernel(k); // try to find identical kernel kernel_eq_t<ctx_t, stadfa> cmp_eq = {ctx}; ctx.dc_target = kernels.find_with(hash, k, cmp_eq); if (ctx.dc_target != kernels_t::NIL) return false; // else if not staDFA try to find mappable kernel // see note [bijective mappings] if (!stadfa) { kernel_map_t<ctx_t, regless> cmp_map = {ctx}; ctx.dc_target = kernels.find_with(hash, k, cmp_map); if (ctx.dc_target != kernels_t::NIL) return false; } // otherwise add new kernel kernel_t *kcopy = make_kernel_copy<stadfa>(k, ctx.dc_allocator); ctx.dc_target = kernels.push(hash, kcopy); return true; }
1
[ "CWE-787" ]
re2c
a3473fd7be829cb33907cb08612f955133c70a96
19,823,844,414,563,305,000,000,000,000,000,000,000
40
Limit maximum allowed NFA and DFA size. Instead of failing with an out of memory exception or crashing with a stack overflow, emit an error message and exit. This is a partial fix for bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc", where re2c hit stack overflow on a counted repetition regexp with high upper bound. The patch adds the following limits: 1. the number of NFA states 2. NFA depth (maximum length of a non-looping path from start to end) 3. the number of DFA states 3. total DFA size (sum total of all NFA substates in all DFA states) There are tests for the first three limits, but not for the DFA size as all examples that trigger this behavior take a long time to finish (a few seconds), which increases test run time almost twice.
xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst) { xmlParserCtxtPtr ctxt; xmlDocPtr newDoc; xmlNodePtr newRoot; xmlSAXHandlerPtr oldsax = NULL; int ret = 0; xmlChar start[4]; xmlCharEncoding enc; if (ctx == NULL) return(-1); if (((ctx->depth > 40) && ((ctx->options & XML_PARSE_HUGE) == 0)) || (ctx->depth > 1024)) { return(XML_ERR_ENTITY_LOOP); } if (lst != NULL) *lst = NULL; if ((URL == NULL) && (ID == NULL)) return(-1); if (ctx->myDoc == NULL) /* @@ relax but check for dereferences */ return(-1); ctxt = xmlCreateEntityParserCtxtInternal(URL, ID, NULL, ctx); if (ctxt == NULL) { return(-1); } oldsax = ctxt->sax; ctxt->sax = ctx->sax; xmlDetectSAX2(ctxt); newDoc = xmlNewDoc(BAD_CAST "1.0"); if (newDoc == NULL) { xmlFreeParserCtxt(ctxt); return(-1); } newDoc->properties = XML_DOC_INTERNAL; if (ctx->myDoc->dict) { newDoc->dict = ctx->myDoc->dict; xmlDictReference(newDoc->dict); } if (ctx->myDoc != NULL) { newDoc->intSubset = ctx->myDoc->intSubset; newDoc->extSubset = ctx->myDoc->extSubset; } if (ctx->myDoc->URL != NULL) { newDoc->URL = xmlStrdup(ctx->myDoc->URL); } newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL); if (newRoot == NULL) { ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(-1); } xmlAddChild((xmlNodePtr) newDoc, newRoot); nodePush(ctxt, newDoc->children); if (ctx->myDoc == NULL) { ctxt->myDoc = newDoc; } else { ctxt->myDoc = ctx->myDoc; newDoc->children->doc = ctx->myDoc; } /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ GROW if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } /* * Parse a possible text declaration first */ if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); /* * An XML-1.0 document can't reference an entity not XML-1.0 */ if ((xmlStrEqual(ctx->version, BAD_CAST "1.0")) && (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) { xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH, "Version mismatch between document and entity\n"); } } /* * Doing validity checking on chunk doesn't make sense */ ctxt->instate = XML_PARSER_CONTENT; ctxt->validate = ctx->validate; ctxt->valid = ctx->valid; ctxt->loadsubset = ctx->loadsubset; ctxt->depth = ctx->depth + 1; ctxt->replaceEntities = ctx->replaceEntities; if (ctxt->validate) { ctxt->vctxt.error = ctx->vctxt.error; ctxt->vctxt.warning = ctx->vctxt.warning; } else { ctxt->vctxt.error = NULL; ctxt->vctxt.warning = NULL; } ctxt->vctxt.nodeTab = NULL; ctxt->vctxt.nodeNr = 0; ctxt->vctxt.nodeMax = 0; ctxt->vctxt.node = NULL; if (ctxt->dict != NULL) xmlDictFree(ctxt->dict); ctxt->dict = ctx->dict; ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3); ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5); ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36); ctxt->dictNames = ctx->dictNames; ctxt->attsDefault = ctx->attsDefault; ctxt->attsSpecial = ctx->attsSpecial; ctxt->linenumbers = ctx->linenumbers; xmlParseContent(ctxt); ctx->validate = ctxt->validate; ctx->valid = ctxt->valid; if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if (ctxt->node != newDoc->children) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = 1; else ret = ctxt->errNo; } else { if (lst != NULL) { xmlNodePtr cur; /* * Return the newly created nodeset after unlinking it from * they pseudo parent. */ cur = newDoc->children->children; *lst = cur; while (cur != NULL) { cur->parent = NULL; cur = cur->next; } newDoc->children->children = NULL; } ret = 0; } ctxt->sax = oldsax; ctxt->dict = NULL; ctxt->attsDefault = NULL; ctxt->attsSpecial = NULL; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(ret); }
0
[ "CWE-125" ]
libxml2
77404b8b69bc122d12231807abf1a837d121b551
251,541,098,090,117,500,000,000,000,000,000,000,000
176
Make sure the parser returns when getting a Stop order patch backported from chromiun bug fixes, assuming author is Chris
bool CIRCSock::OnTextMessage(CTextMessage& Message) { bool bResult = false; CChan* pChan = nullptr; CString sTarget = Message.GetTarget(); if (sTarget.Equals(GetNick())) { IRCSOCKMODULECALL(OnPrivTextMessage(Message), &bResult); if (bResult) return true; if (!m_pNetwork->IsUserOnline() || !m_pNetwork->GetUser()->AutoClearQueryBuffer()) { const CNick& Nick = Message.GetNick(); CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick()); if (pQuery) { CTextMessage Format; Format.Clone(Message); Format.SetNick(_NAMEDFMT(Nick.GetNickMask())); Format.SetTarget("{target}"); Format.SetText("{text}"); pQuery->AddBuffer(Format, Message.GetText()); } } } else { pChan = m_pNetwork->FindChan(sTarget); if (pChan) { Message.SetChan(pChan); FixupChanNick(Message.GetNick(), pChan); IRCSOCKMODULECALL(OnChanTextMessage(Message), &bResult); if (bResult) return true; if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || pChan->IsDetached()) { CTextMessage Format; Format.Clone(Message); Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask())); Format.SetTarget(_NAMEDFMT(Message.GetTarget())); Format.SetText("{text}"); pChan->AddBuffer(Format, Message.GetText()); } } } return (pChan && pChan->IsDetached()); }
0
[ "CWE-20", "CWE-284" ]
znc
d22fef8620cdd87490754f607e7153979731c69d
422,630,610,214,911,840,000,000,000,000,000,000
44
Better cleanup lines coming from network. Thanks for Jeriko One <[email protected]> for finding and reporting this.
kill_query_thread( /*===============*/ void *arg __attribute__((unused))) { MYSQL *mysql; time_t start_time; my_thread_init(); start_time = time(NULL); os_event_set(kill_query_thread_started); msg_ts("Kill query timeout %d seconds.\n", opt_kill_long_queries_timeout); while (time(NULL) - start_time < (time_t)opt_kill_long_queries_timeout) { if (os_event_wait_time(kill_query_thread_stop, 1000) != OS_SYNC_TIME_EXCEEDED) { goto stop_thread; } } if ((mysql = xb_mysql_connect()) == NULL) { msg("Error: kill query thread failed\n"); goto stop_thread; } while (true) { kill_long_queries(mysql, time(NULL) - start_time); if (os_event_wait_time(kill_query_thread_stop, 1000) != OS_SYNC_TIME_EXCEEDED) { break; } } mysql_close(mysql); stop_thread: msg_ts("Kill query thread stopped\n"); my_thread_end(); os_event_set(kill_query_thread_stopped); os_thread_exit(); OS_THREAD_DUMMY_RETURN; }
0
[ "CWE-200" ]
percona-xtrabackup
7742f875bb289a874246fb4653b7cd9f14b588fe
237,508,858,860,223,630,000,000,000,000,000,000,000
49
PXB-2722 password is written into xtrabackup_info https://jira.percona.com/browse/PXB-2722 Analysis: password passed with -p option is written into backup tool_command in xtrabackup_info Fix: mask password before writting into xtrabackup_info
static inline __be32 try_6to4(struct in6_addr *v6dst) { __be32 dst = 0; if (v6dst->s6_addr16[0] == htons(0x2002)) { /* 6to4 v6 addr has 16 bits prefix, 32 v4addr, 16 SLA, ... */ memcpy(&dst, &v6dst->s6_addr16[1], 4); } return dst; }
0
[ "CWE-399" ]
linux-2.6
36ca34cc3b8335eb1fe8bd9a1d0a2592980c3f02
94,432,550,802,322,260,000,000,000,000,000,000,000
10
sit: Add missing kfree_skb() on pskb_may_pull() failure. Noticed by Paul Marks <[email protected]>. Signed-off-by: David S. Miller <[email protected]>
flatpak_dir_mirror_oci (FlatpakDir *self, FlatpakOciRegistry *dst_registry, FlatpakRemoteState *state, const char *ref, const char *skip_if_current_is, OstreeAsyncProgress *progress, GCancellable *cancellable, GError **error) { g_autoptr(FlatpakOciRegistry) registry = NULL; g_autofree char *registry_uri = NULL; g_autofree char *oci_digest = NULL; g_autofree char *latest_rev = NULL; g_autoptr(GVariant) summary_element = NULL; g_autoptr(GVariant) metadata = NULL; g_autofree char *oci_repository = NULL; gboolean res; /* We use the summary so that we can reuse any cached json */ flatpak_remote_state_lookup_ref (state, ref, &latest_rev, &summary_element, error); if (latest_rev == NULL) { if (error != NULL && *error == NULL) flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA, _("Couldn't find latest checksum for ref %s in remote %s"), ref, state->remote_name); return FALSE; } if (skip_if_current_is != NULL && strcmp (latest_rev, skip_if_current_is) == 0) { flatpak_fail_error (error, FLATPAK_ERROR_ALREADY_INSTALLED, _("%s commit %s already installed"), ref, latest_rev); return FALSE; } metadata = g_variant_get_child_value (summary_element, 2); g_variant_lookup (metadata, "xa.oci-repository", "s", &oci_repository); oci_digest = g_strconcat ("sha256:", latest_rev, NULL); registry_uri = lookup_oci_registry_uri_from_summary (state->summary, error); if (registry_uri == NULL) return FALSE; registry = flatpak_oci_registry_new (registry_uri, FALSE, -1, NULL, error); if (registry == NULL) return FALSE; g_assert (progress != NULL); oci_pull_init_progress (progress); g_debug ("Mirroring OCI image %s", oci_digest); res = flatpak_mirror_image_from_oci (dst_registry, registry, oci_repository, oci_digest, oci_pull_progress_cb, progress, cancellable, error); if (progress) ostree_async_progress_finish (progress); if (!res) return FALSE; return TRUE; }
0
[ "CWE-668" ]
flatpak
cd2142888fc4c199723a0dfca1f15ea8788a5483
197,633,998,554,398,300,000,000,000,000,000,000,000
64
Don't expose /proc when running apply_extra As shown by CVE-2019-5736, it is sometimes possible for the sandbox app to access outside files using /proc/self/exe. This is not typically an issue for flatpak as the sandbox runs as the user which has no permissions to e.g. modify the host files. However, when installing apps using extra-data into the system repo we *do* actually run a sandbox as root. So, in this case we disable mounting /proc in the sandbox, which will neuter attacks like this.
static int mwifiex_free_ack_frame(int id, void *p, void *data) { pr_warn("Have pending ack frames!\n"); kfree_skb(p); return 0; }
0
[ "CWE-787" ]
linux
3a9b153c5591548612c3955c9600a98150c81875
12,342,755,708,413,417,000,000,000,000,000,000,000
6
mwifiex: Fix possible buffer overflows in mwifiex_ret_wmm_get_status() mwifiex_ret_wmm_get_status() calls memcpy() without checking the destination size.Since the source is given from remote AP which contains illegal wmm elements , this may trigger a heap buffer overflow. Fix it by putting the length check before calling memcpy(). Signed-off-by: Qing Xu <[email protected]> Signed-off-by: Kalle Valo <[email protected]>
Field *Item::make_string_field(TABLE *table) { Field *field; MEM_ROOT *mem_root= table->in_use->mem_root; DBUG_ASSERT(collation.collation); /* Note: the following check is repeated in subquery_types_allow_materialization(): */ if (too_big_for_varchar()) field= new (mem_root) Field_blob(max_length, maybe_null, name, collation.collation, TRUE); /* Item_type_holder holds the exact type, do not change it */ else if (max_length > 0 && (type() != Item::TYPE_HOLDER || field_type() != MYSQL_TYPE_STRING)) field= new (mem_root) Field_varstring(max_length, maybe_null, name, table->s, collation.collation); else field= new (mem_root) Field_string(max_length, maybe_null, name, collation.collation); if (field) field->init(table); return field; }
0
[ "CWE-89" ]
server
b5e16a6e0381b28b598da80b414168ce9a5016e5
82,930,299,264,242,420,000,000,000,000,000,000,000
27
MDEV-26061 MariaDB server crash at Field::set_default * Item_default_value::fix_fields creates a copy of its argument's field. * Field::default_value is changed when its expression is prepared in unpack_vcol_info_from_frm() This means we must unpack any vcol expression that includes DEFAULT(x) strictly after unpacking x->default_value. To avoid building and solving this dependency graph on every table open, we update Item_default_value::field->default_value after all vcols are unpacked and fixed.
int intel_guc_allocate_and_map_vma(struct intel_guc *guc, u32 size, struct i915_vma **out_vma, void **out_vaddr) { struct i915_vma *vma; void *vaddr; vma = intel_guc_allocate_vma(guc, size); if (IS_ERR(vma)) return PTR_ERR(vma); vaddr = i915_gem_object_pin_map(vma->obj, I915_MAP_WB); if (IS_ERR(vaddr)) { i915_vma_unpin_and_release(&vma, 0); return PTR_ERR(vaddr); } *out_vma = vma; *out_vaddr = vaddr; return 0; }
0
[ "CWE-20", "CWE-190" ]
linux
c784e5249e773689e38d2bc1749f08b986621a26
281,548,084,053,508,750,000,000,000,000,000,000,000
21
drm/i915/guc: Update to use firmware v49.0.1 The latest GuC firmware includes a number of interface changes that require driver updates to match. * Starting from Gen11, the ID to be provided to GuC needs to contain the engine class in bits [0..2] and the instance in bits [3..6]. NOTE: this patch breaks pointer dereferences in some existing GuC functions that use the guc_id to dereference arrays but these functions are not used for now as we have GuC submission disabled and we will update these functions in follow up patch which requires new IDs. * The new GuC requires the additional data structure (ADS) and associated 'private_data' pointer to be setup. This is basically a scratch area of memory that the GuC owns. The size is read from the CSS header. * There is now a physical to logical engine mapping table in the ADS which needs to be configured in order for the firmware to load. For now, the table is initialised with a 1 to 1 mapping. * GUC_CTL_CTXINFO has been removed from the initialization params. * reg_state_buffer is maintained internally by the GuC as part of the private data. * The ADS layout has changed significantly. This patch updates the shared structure and also adds better documentation of the layout. * While i915 does not use GuC doorbells, the firmware now requires that some initialisation is done. * The number of engine classes and instances supported in the ADS has been increased. Signed-off-by: John Harrison <[email protected]> Signed-off-by: Matthew Brost <[email protected]> Signed-off-by: Daniele Ceraolo Spurio <[email protected]> Signed-off-by: Oscar Mateo <[email protected]> Signed-off-by: Michel Thierry <[email protected]> Signed-off-by: Rodrigo Vivi <[email protected]> Signed-off-by: Michal Wajdeczko <[email protected]> Cc: Michal Winiarski <[email protected]> Cc: Tomasz Lis <[email protected]> Cc: Joonas Lahtinen <[email protected]> Reviewed-by: Daniele Ceraolo Spurio <[email protected]> Signed-off-by: Joonas Lahtinen <[email protected]> Link: https://patchwork.freedesktop.org/patch/msgid/[email protected]
void Lua::setParamsTable(lua_State* vm, const char* table_name, const char* query) const { char outbuf[FILENAME_MAX]; char *where; char *tok; char *query_string = query ? strdup(query) : NULL; lua_newtable(L); if (query_string) { // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string); tok = strtok_r(query_string, "&", &where); while(tok != NULL) { char *_equal; if(strncmp(tok, "csrf", strlen("csrf")) /* Do not put csrf into the params table */ && (_equal = strchr(tok, '='))) { char *decoded_buf; int len; _equal[0] = '\0'; _equal = &_equal[1]; len = strlen(_equal); purifyHTTPParameter(tok), purifyHTTPParameter(_equal); // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal); if((decoded_buf = (char*)malloc(len+1)) != NULL) { Utils::urlDecode(_equal, decoded_buf, len+1); Utils::purifyHTTPparam(tok, true, false); Utils::purifyHTTPparam(decoded_buf, false, false); /* Now make sure that decoded_buf is not a file path */ FILE *fd; if((decoded_buf[0] == '.') && ((fd = fopen(decoded_buf, "r")) || (fd = fopen(realpath(decoded_buf, outbuf), "r")))) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path", tok, decoded_buf); decoded_buf[0] = '\0'; fclose(fd); } /* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */ /* put tok and the decoded buffer in to the table */ lua_push_str_table_entry(vm, tok, decoded_buf); free(decoded_buf); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } tok = strtok_r(NULL, "&", &where); } /* while */ } if(query_string) free(query_string); if(table_name) lua_setglobal(L, table_name); else lua_setglobal(L, (char*)"_GET"); /* Default */ }
1
[ "CWE-476" ]
ntopng
01f47e04fd7c8d54399c9e465f823f0017069f8f
220,933,882,247,283,180,000,000,000,000,000,000,000
71
Security fix: prevents empty host from being used
pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx) { #ifndef WITHOUT_PKCS11 if (ctx == NULL) return; if (ctx->p11 != NULL) { if (ctx->session) { ctx->p11->C_CloseSession(ctx->session); ctx->session = CK_INVALID_HANDLE; } ctx->p11->C_Finalize(NULL_PTR); ctx->p11 = NULL; } if (ctx->p11_module != NULL) { pkinit_C_UnloadModule(ctx->p11_module); ctx->p11_module = NULL; } free(ctx->p11_module_name); free(ctx->token_label); free(ctx->cert_id); free(ctx->cert_label); #endif }
0
[ "CWE-476" ]
krb5
f249555301940c6df3a2cdda13b56b5674eebc2e
232,091,692,134,409,200,000,000,000,000,000,000,000
24
PKINIT null pointer deref [CVE-2013-1415] Don't dereference a null pointer when cleaning up. The KDC plugin for PKINIT can dereference a null pointer when a malformed packet causes processing to terminate early, leading to a crash of the KDC process. An attacker would need to have a valid PKINIT certificate or have observed a successful PKINIT authentication, or an unauthenticated attacker could execute the attack if anonymous PKINIT is enabled. CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C This is a minimal commit for pullup; style fixes in a followup. [[email protected]: reformat and edit commit message] (cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed) ticket: 7570 version_fixed: 1.11.1 status: resolved
bool napi_complete_done(struct napi_struct *n, int work_done) { unsigned long flags, val, new; /* * 1) Don't let napi dequeue from the cpu poll list * just in case its running on a different cpu. * 2) If we are busy polling, do nothing here, we have * the guarantee we will be called later. */ if (unlikely(n->state & (NAPIF_STATE_NPSVC | NAPIF_STATE_IN_BUSY_POLL))) return false; if (n->gro_bitmask) { unsigned long timeout = 0; if (work_done) timeout = n->dev->gro_flush_timeout; /* When the NAPI instance uses a timeout and keeps postponing * it, we need to bound somehow the time packets are kept in * the GRO layer */ napi_gro_flush(n, !!timeout); if (timeout) hrtimer_start(&n->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED); } if (unlikely(!list_empty(&n->poll_list))) { /* If n->poll_list is not empty, we need to mask irqs */ local_irq_save(flags); list_del_init(&n->poll_list); local_irq_restore(flags); } do { val = READ_ONCE(n->state); WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED); /* If STATE_MISSED was set, leave STATE_SCHED set, * because we will call napi->poll() one more time. * This C code was suggested by Alexander Duyck to help gcc. */ new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * NAPIF_STATE_SCHED; } while (cmpxchg(&n->state, val, new) != val); if (unlikely(val & NAPIF_STATE_MISSED)) { __napi_schedule(n); return false; } return true;
0
[ "CWE-416" ]
linux
a4270d6795b0580287453ea55974d948393e66ef
303,388,549,387,947,600,000,000,000,000,000,000,000
58
net-gro: fix use-after-free read in napi_gro_frags() If a network driver provides to napi_gro_frags() an skb with a page fragment of exactly 14 bytes, the call to gro_pull_from_frag0() will 'consume' the fragment by calling skb_frag_unref(skb, 0), and the page might be freed and reused. Reading eth->h_proto at the end of napi_frags_skb() might read mangled data, or crash under specific debugging features. BUG: KASAN: use-after-free in napi_frags_skb net/core/dev.c:5833 [inline] BUG: KASAN: use-after-free in napi_gro_frags+0xc6f/0xd10 net/core/dev.c:5841 Read of size 2 at addr ffff88809366840c by task syz-executor599/8957 CPU: 1 PID: 8957 Comm: syz-executor599 Not tainted 5.2.0-rc1+ #32 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0x172/0x1f0 lib/dump_stack.c:113 print_address_description.cold+0x7c/0x20d mm/kasan/report.c:188 __kasan_report.cold+0x1b/0x40 mm/kasan/report.c:317 kasan_report+0x12/0x20 mm/kasan/common.c:614 __asan_report_load_n_noabort+0xf/0x20 mm/kasan/generic_report.c:142 napi_frags_skb net/core/dev.c:5833 [inline] napi_gro_frags+0xc6f/0xd10 net/core/dev.c:5841 tun_get_user+0x2f3c/0x3ff0 drivers/net/tun.c:1991 tun_chr_write_iter+0xbd/0x156 drivers/net/tun.c:2037 call_write_iter include/linux/fs.h:1872 [inline] do_iter_readv_writev+0x5f8/0x8f0 fs/read_write.c:693 do_iter_write fs/read_write.c:970 [inline] do_iter_write+0x184/0x610 fs/read_write.c:951 vfs_writev+0x1b3/0x2f0 fs/read_write.c:1015 do_writev+0x15b/0x330 fs/read_write.c:1058 Fixes: a50e233c50db ("net-gro: restore frag0 optimization") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: syzbot <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static bool torture_winbind_struct_lookup_sids_invalid( struct torture_context *torture) { struct winbindd_request req = {0}; struct winbindd_response rep = {0}; bool strict = torture_setting_bool(torture, "strict mode", false); bool ok; torture_comment(torture, "Running WINBINDD_LOOKUP_SIDS (struct based)\n"); ok = true; DO_STRUCT_REQ_REP_EXT(WINBINDD_LOOKUPSIDS, &req, &rep, NSS_STATUS_NOTFOUND, strict, ok=false, talloc_asprintf( torture, "invalid lookupsids succeeded")); return ok; }
0
[ "CWE-476" ]
samba
0b259a48a70bde4dfd482e0720e593ae5a9c414a
85,179,865,752,990,630,000,000,000,000,000,000,000
22
CVE-2020-14323 torture4: Add a simple test for invalid lookup_sids winbind call We can't add this test before the fix, add it to knownfail and have the fix remove the knownfail entry again. As this crashes winbind, many tests after this one will fail. Reported by Bas Alberts of the GitHub Security Lab Team as GHSL-2020-134 Bug: https://bugzilla.samba.org/show_bug.cgi?id=14436 Signed-off-by: Volker Lendecke <[email protected]>
void CairoOutputDev::drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, CharCode code, int nBytes, Unicode *u, int uLen) { if (currentFont) { glyphs[glyphCount].index = currentFont->getGlyph (code, u, uLen); glyphs[glyphCount].x = x - originX; glyphs[glyphCount].y = y - originY; glyphCount++; } if (!text) return; actualText->addChar (state, x, y, dx, dy, code, nBytes, u, uLen); }
0
[]
poppler
abf167af8b15e5f3b510275ce619e6fdb42edd40
337,816,582,921,032,330,000,000,000,000,000,000,000
16
Implement tiling/patterns in SplashOutputDev Fixes bug 13518
static int ff_layout_read_done_cb(struct rpc_task *task, struct nfs_pgio_header *hdr) { int err; if (task->tk_status < 0) { ff_layout_io_track_ds_error(hdr->lseg, hdr->pgio_mirror_idx, hdr->args.offset, hdr->args.count, &hdr->res.op_status, OP_READ, task->tk_status); trace_ff_layout_read_error(hdr); } err = ff_layout_async_handle_error(task, hdr->args.context->state, hdr->ds_clp, hdr->lseg, hdr->pgio_mirror_idx); trace_nfs4_pnfs_read(hdr, err); clear_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags); clear_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags); switch (err) { case -NFS4ERR_RESET_TO_PNFS: set_bit(NFS_IOHDR_RESEND_PNFS, &hdr->flags); return task->tk_status; case -NFS4ERR_RESET_TO_MDS: set_bit(NFS_IOHDR_RESEND_MDS, &hdr->flags); return task->tk_status; case -EAGAIN: goto out_eagain; } return 0; out_eagain: rpc_restart_call_prepare(task); return -EAGAIN; }
0
[ "CWE-787" ]
linux
ed34695e15aba74f45247f1ee2cf7e09d449f925
330,872,505,513,758,720,000,000,000,000,000,000,000
36
pNFS/flexfiles: fix incorrect size check in decode_nfs_fh() We (adam zabrocki, alexander matrosov, alexander tereshkin, maksym bazalii) observed the check: if (fh->size > sizeof(struct nfs_fh)) should not use the size of the nfs_fh struct which includes an extra two bytes from the size field. struct nfs_fh { unsigned short size; unsigned char data[NFS_MAXFHSIZE]; } but should determine the size from data[NFS_MAXFHSIZE] so the memcpy will not write 2 bytes beyond destination. The proposed fix is to compare against the NFS_MAXFHSIZE directly, as is done elsewhere in fs code base. Fixes: d67ae825a59d ("pnfs/flexfiles: Add the FlexFile Layout Driver") Signed-off-by: Nikola Livic <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Trond Myklebust <[email protected]>
void *ztrymalloc_usable(size_t size, size_t *usable) { void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) return NULL; #ifdef HAVE_MALLOC_SIZE size = zmalloc_size(ptr); update_zmalloc_stat_alloc(size); if (usable) *usable = size; return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); if (usable) *usable = size; return (char*)ptr+PREFIX_SIZE; #endif }
1
[ "CWE-190" ]
redis
d32f2e9999ce003bad0bd2c3bca29f64dcce4433
238,902,175,294,809,530,000,000,000,000,000,000,000
16
Fix integer overflow (CVE-2021-21309). (#8522) On 32-bit systems, setting the proto-max-bulk-len config parameter to a high value may result with integer overflow and a subsequent heap overflow when parsing an input bulk (CVE-2021-21309). This fix has two parts: Set a reasonable limit to the config parameter. Add additional checks to prevent the problem in other potential but unknown code paths.
void var_copy(VAR *dest, VAR *src) { dest->int_val= src->int_val; dest->is_int= src->is_int; dest->int_dirty= src->int_dirty; /* Alloc/realloc data for str_val in dest */ if (dest->alloced_len < src->alloced_len && !(dest->str_val= dest->str_val ? (char*)my_realloc(PSI_NOT_INSTRUMENTED, dest->str_val, src->alloced_len, MYF(MY_WME)) : (char*)my_malloc(PSI_NOT_INSTRUMENTED, src->alloced_len, MYF(MY_WME)))) die("Out of memory"); else dest->alloced_len= src->alloced_len; /* Copy str_val data to dest */ dest->str_val_len= src->str_val_len; if (src->str_val_len) memcpy(dest->str_val, src->str_val, src->str_val_len); }
0
[ "CWE-284", "CWE-295" ]
mysql-server
3bd5589e1a5a93f9c224badf983cd65c45215390
26,863,751,203,197,487,000,000,000,000,000,000,000
22
WL#6791 : Redefine client --ssl option to imply enforced encryption # Changed the meaning of the --ssl=1 option of all client binaries to mean force ssl, not try ssl and fail over to eunecrypted # Added a new MYSQL_OPT_SSL_ENFORCE mysql_options() option to specify that an ssl connection is required. # Added a new macro SSL_SET_OPTIONS() to the client SSL handling headers that sets all the relevant SSL options at once. # Revamped all of the current native clients to use the new macro # Removed some Windows line endings. # Added proper handling of the new option into the ssl helper headers. # If SSL is mandatory assume that the media is secure enough for the sha256 plugin to do unencrypted password exchange even before establishing a connection. # Set the default ssl cipher to DHE-RSA-AES256-SHA if none is specified. # updated test cases that require a non-default cipher to spawn a mysql command line tool binary since mysqltest has no support for specifying ciphers. # updated the replication slave connection code to always enforce SSL if any of the SSL config options is present. # test cases added and updated. # added a mysql_get_option() API to return mysql_options() values. Used the new API inside the sha256 plugin. # Fixed compilation warnings because of unused variables. # Fixed test failures (mysql_ssl and bug13115401) # Fixed whitespace issues. # Fully implemented the mysql_get_option() function. # Added a test case for mysql_get_option() # fixed some trailing whitespace issues # fixed some uint/int warnings in mysql_client_test.c # removed shared memory option from non-windows get_options tests # moved MYSQL_OPT_LOCAL_INFILE to the uint options
static inline size_t write_octet_sequence(unsigned char *buf, enum entity_charset charset, unsigned code) { /* code is not necessarily a unicode code point */ switch (charset) { case cs_utf_8: return php_utf32_utf8(buf, code); case cs_8859_1: case cs_cp1252: case cs_8859_15: case cs_koi8r: case cs_cp1251: case cs_8859_5: case cs_cp866: case cs_macroman: /* single byte stuff */ *buf = code; return 1; case cs_big5: case cs_big5hkscs: case cs_sjis: case cs_gb2312: /* we don't have complete unicode mappings for these yet in entity_decode, * and we opt to pass through the octet sequences for these in htmlentities * instead of converting to an int and then converting back. */ #if 0 return php_mb2_int_to_char(buf, code); #else #ifdef ZEND_DEBUG assert(code <= 0xFFU); #endif *buf = code; return 1; #endif case cs_eucjp: #if 0 /* idem */ return php_mb2_int_to_char(buf, code); #else #ifdef ZEND_DEBUG assert(code <= 0xFFU); #endif *buf = code; return 1; #endif default: assert(0); return 0; } }
0
[ "CWE-190" ]
php-src
0da8b8b801f9276359262f1ef8274c7812d3dfda
238,986,132,984,639,300,000,000,000,000,000,000,000
51
Fix bug #72135 - don't create strings with lengths outside int range
int Monitor::check_features(MonitorDBStore *store) { CompatSet required = get_supported_features(); CompatSet ondisk; read_features_off_disk(store, &ondisk); if (!required.writeable(ondisk)) { CompatSet diff = required.unsupported(ondisk); generic_derr << "ERROR: on disk data includes unsupported features: " << diff << dendl; return -EPERM; } return 0; }
0
[ "CWE-287", "CWE-284" ]
ceph
5ead97120e07054d80623dada90a5cc764c28468
43,881,108,404,497,660,000,000,000,000,000,000,000
15
auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <[email protected]> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()
static void clean_up_mutexes() { mysql_rwlock_destroy(&LOCK_grant); mysql_mutex_destroy(&LOCK_thread_count); mysql_mutex_destroy(&LOCK_thread_created); mysql_mutex_destroy(&LOCK_status); mysql_mutex_destroy(&LOCK_delayed_insert); mysql_mutex_destroy(&LOCK_delayed_status); mysql_mutex_destroy(&LOCK_delayed_create); mysql_mutex_destroy(&LOCK_manager); mysql_mutex_destroy(&LOCK_crypt); mysql_mutex_destroy(&LOCK_user_conn); mysql_mutex_destroy(&LOCK_connection_count); #ifdef HAVE_OPENSSL mysql_mutex_destroy(&LOCK_des_key_file); #ifndef HAVE_YASSL for (int i= 0; i < CRYPTO_num_locks(); ++i) mysql_rwlock_destroy(&openssl_stdlocks[i].lock); OPENSSL_free(openssl_stdlocks); #endif #endif #ifdef HAVE_REPLICATION mysql_mutex_destroy(&LOCK_rpl_status); mysql_cond_destroy(&COND_rpl_status); #endif mysql_mutex_destroy(&LOCK_active_mi); mysql_rwlock_destroy(&LOCK_sys_init_connect); mysql_rwlock_destroy(&LOCK_sys_init_slave); mysql_mutex_destroy(&LOCK_global_system_variables); mysql_rwlock_destroy(&LOCK_system_variables_hash); mysql_mutex_destroy(&LOCK_uuid_generator); mysql_mutex_destroy(&LOCK_prepared_stmt_count); mysql_mutex_destroy(&LOCK_error_messages); mysql_cond_destroy(&COND_thread_count); mysql_mutex_destroy(&LOCK_thd_remove); mysql_cond_destroy(&COND_thread_cache); mysql_cond_destroy(&COND_flush_thread_cache); mysql_cond_destroy(&COND_manager); }
0
[ "CWE-264" ]
mysql-server
48bd8b16fe382be302c6f0b45931be5aa6f29a0e
51,905,197,003,892,760,000,000,000,000,000,000,000
39
Bug#24388753: PRIVILEGE ESCALATION USING MYSQLD_SAFE [This is the 5.5/5.6 version of the bugfix]. The problem was that it was possible to write log files ending in .ini/.cnf that later could be parsed as an options file. This made it possible for users to specify startup options without the permissions to do so. This patch fixes the problem by disallowing general query log and slow query log to be written to files ending in .ini and .cnf.
static void cli_session_setup_gensec_local_next(struct tevent_req *req) { struct cli_session_setup_gensec_state *state = tevent_req_data(req, struct cli_session_setup_gensec_state); struct tevent_req *subreq = NULL; if (state->local_ready) { tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE); return; } subreq = gensec_update_send(state, state->ev, state->auth_generic->gensec_security, state->blob_in); if (tevent_req_nomem(subreq, req)) { return; } tevent_req_set_callback(subreq, cli_session_setup_gensec_local_done, req); }
0
[ "CWE-94" ]
samba
94295b7aa22d2544af5323bca70d3dcb97fd7c64
131,924,787,296,153,880,000,000,000,000,000,000,000
20
CVE-2016-2019: s3:libsmb: add comment regarding smbXcli_session_is_guest() with mandatory signing BUG: https://bugzilla.samba.org/show_bug.cgi?id=11860 Signed-off-by: Stefan Metzmacher <[email protected]>
static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid) { int i; trace_usb_xhci_slot_disable(slotid); assert(slotid >= 1 && slotid <= xhci->numslots); for (i = 1; i <= 31; i++) { if (xhci->slots[slotid-1].eps[i-1]) { xhci_disable_ep(xhci, slotid, i); } } xhci->slots[slotid-1].enabled = 0; xhci->slots[slotid-1].addressed = 0; xhci->slots[slotid-1].uport = NULL; return CC_SUCCESS; }
0
[ "CWE-835" ]
qemu
96d87bdda3919bb16f754b3d3fd1227e1f38f13c
47,844,528,077,119,330,000,000,000,000,000,000,000
18
xhci: guard xhci_kick_epctx against recursive calls Track xhci_kick_epctx processing being active in a variable. Check the variable before calling xhci_kick_epctx from xhci_kick_ep. Add an assert to make sure we don't call recursively into xhci_kick_epctx. Cc: [email protected] Fixes: 94b037f2a451b3dc855f9f2c346e5049a361bd55 Reported-by: Fabian Lesniak <[email protected]> Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected] Message-id: [email protected]
SPICE_GNUC_VISIBLE int spice_server_is_server_mouse(SpiceServer *reds) { return reds->mouse_mode == SPICE_MOUSE_MODE_SERVER; }
0
[]
spice
ca5bbc5692e052159bce1a75f55dc60b36078749
39,720,937,035,308,923,000,000,000,000,000,000,000
4
With OpenSSL 1.1: Disable client-initiated renegotiation. Fixes issue #49 Fixes BZ#1904459 Signed-off-by: Julien Ropé <[email protected]> Reported-by: BlackKD Acked-by: Frediano Ziglio <[email protected]>
xmlSchemaInternalErr2(xmlSchemaAbstractCtxtPtr actxt, const char *funcName, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *msg = NULL; if (actxt == NULL) return; msg = xmlStrdup(BAD_CAST "Internal error: %s, "); msg = xmlStrcat(msg, BAD_CAST message); msg = xmlStrcat(msg, BAD_CAST ".\n"); if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) xmlSchemaErr3(actxt, XML_SCHEMAV_INTERNAL, NULL, (const char *) msg, (const xmlChar *) funcName, str1, str2); else if (actxt->type == XML_SCHEMA_CTXT_PARSER) xmlSchemaErr3(actxt, XML_SCHEMAP_INTERNAL, NULL, (const char *) msg, (const xmlChar *) funcName, str1, str2); FREE_AND_NULL(msg) }
0
[ "CWE-134" ]
libxml2
4472c3a5a5b516aaf59b89be602fbce52756c3e9
326,093,710,680,008,600,000,000,000,000,000,000,000
23
Fix some format string warnings with possible format string vulnerability For https://bugzilla.gnome.org/show_bug.cgi?id=761029 Decorate every method in libxml2 with the appropriate LIBXML_ATTR_FORMAT(fmt,args) macro and add some cleanups following the reports.
static int v9fs_mapped_iattr_valid(int iattr_valid) { int i; int p9_iattr_valid = 0; struct dotl_iattr_map dotl_iattr_map[] = { { ATTR_MODE, P9_ATTR_MODE }, { ATTR_UID, P9_ATTR_UID }, { ATTR_GID, P9_ATTR_GID }, { ATTR_SIZE, P9_ATTR_SIZE }, { ATTR_ATIME, P9_ATTR_ATIME }, { ATTR_MTIME, P9_ATTR_MTIME }, { ATTR_CTIME, P9_ATTR_CTIME }, { ATTR_ATIME_SET, P9_ATTR_ATIME_SET }, { ATTR_MTIME_SET, P9_ATTR_MTIME_SET }, }; for (i = 0; i < ARRAY_SIZE(dotl_iattr_map); i++) { if (iattr_valid & dotl_iattr_map[i].iattr_valid) p9_iattr_valid |= dotl_iattr_map[i].p9_iattr_valid; } return p9_iattr_valid; }
0
[ "CWE-835" ]
linux
5e3cc1ee1405a7eb3487ed24f786dec01b4cbe1f
236,850,894,041,139,240,000,000,000,000,000,000,000
21
9p: use inode->i_lock to protect i_size_write() under 32-bit Use inode->i_lock to protect i_size_write(), else i_size_read() in generic_fillattr() may loop infinitely in read_seqcount_begin() when multiple processes invoke v9fs_vfs_getattr() or v9fs_vfs_getattr_dotl() simultaneously under 32-bit SMP environment, and a soft lockup will be triggered as show below: watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [stat:2217] Modules linked in: CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4 Hardware name: Generic DT based system PC is at generic_fillattr+0x104/0x108 LR is at 0xec497f00 pc : [<802b8898>] lr : [<ec497f00>] psr: 200c0013 sp : ec497e20 ip : ed608030 fp : ec497e3c r10: 00000000 r9 : ec497f00 r8 : ed608030 r7 : ec497ebc r6 : ec497f00 r5 : ee5c1550 r4 : ee005780 r3 : 0000052d r2 : 00000000 r1 : ec497f00 r0 : ed608030 Flags: nzCv IRQs on FIQs on Mode SVC_32 ISA ARM Segment none Control: 10c5387d Table: ac48006a DAC: 00000051 CPU: 5 PID: 2217 Comm: stat Not tainted 5.0.0-rc1-00005-g7f702faf5a9e #4 Hardware name: Generic DT based system Backtrace: [<8010d974>] (dump_backtrace) from [<8010dc88>] (show_stack+0x20/0x24) [<8010dc68>] (show_stack) from [<80a1d194>] (dump_stack+0xb0/0xdc) [<80a1d0e4>] (dump_stack) from [<80109f34>] (show_regs+0x1c/0x20) [<80109f18>] (show_regs) from [<801d0a80>] (watchdog_timer_fn+0x280/0x2f8) [<801d0800>] (watchdog_timer_fn) from [<80198658>] (__hrtimer_run_queues+0x18c/0x380) [<801984cc>] (__hrtimer_run_queues) from [<80198e60>] (hrtimer_run_queues+0xb8/0xf0) [<80198da8>] (hrtimer_run_queues) from [<801973e8>] (run_local_timers+0x28/0x64) [<801973c0>] (run_local_timers) from [<80197460>] (update_process_times+0x3c/0x6c) [<80197424>] (update_process_times) from [<801ab2b8>] (tick_nohz_handler+0xe0/0x1bc) [<801ab1d8>] (tick_nohz_handler) from [<80843050>] (arch_timer_handler_virt+0x38/0x48) [<80843018>] (arch_timer_handler_virt) from [<80180a64>] (handle_percpu_devid_irq+0x8c/0x240) [<801809d8>] (handle_percpu_devid_irq) from [<8017ac20>] (generic_handle_irq+0x34/0x44) [<8017abec>] (generic_handle_irq) from [<8017b344>] (__handle_domain_irq+0x6c/0xc4) [<8017b2d8>] (__handle_domain_irq) from [<801022e0>] (gic_handle_irq+0x4c/0x88) [<80102294>] (gic_handle_irq) from [<80101a30>] (__irq_svc+0x70/0x98) [<802b8794>] (generic_fillattr) from [<8056b284>] (v9fs_vfs_getattr_dotl+0x74/0xa4) [<8056b210>] (v9fs_vfs_getattr_dotl) from [<802b8904>] (vfs_getattr_nosec+0x68/0x7c) [<802b889c>] (vfs_getattr_nosec) from [<802b895c>] (vfs_getattr+0x44/0x48) [<802b8918>] (vfs_getattr) from [<802b8a74>] (vfs_statx+0x9c/0xec) [<802b89d8>] (vfs_statx) from [<802b9428>] (sys_lstat64+0x48/0x78) [<802b93e0>] (sys_lstat64) from [<80101000>] (ret_fast_syscall+0x0/0x28) [[email protected]: updated comment to not refer to a function in another subsystem] Link: http://lkml.kernel.org/r/[email protected] Cc: [email protected] Fixes: 7549ae3e81cc ("9p: Use the i_size_[read, write]() macros instead of using inode->i_size directly.") Reported-by: Xing Gaopeng <[email protected]> Signed-off-by: Hou Tao <[email protected]> Signed-off-by: Dominique Martinet <[email protected]>
GF_Err segr_Size(GF_Box *s) { u32 i; FDSessionGroupBox *ptr = (FDSessionGroupBox *)s; ptr->size += 2; for (i=0; i<ptr->num_session_groups; i++) { ptr->size += 1 + 4*ptr->session_groups[i].nb_groups; ptr->size += 2 + 4*ptr->session_groups[i].nb_channels; } return GF_OK; }
0
[ "CWE-125" ]
gpac
bceb03fd2be95097a7b409ea59914f332fb6bc86
308,925,652,887,555,150,000,000,000,000,000,000,000
13
fixed 2 possible heap overflows (inc. #1088)
static void __hw_addr_init(struct netdev_hw_addr_list *list) { INIT_LIST_HEAD(&list->list); list->count = 0; }
0
[ "CWE-399" ]
linux
6ec82562ffc6f297d0de36d65776cff8e5704867
68,193,219,985,289,940,000,000,000,000,000,000,000
5
veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static int decode_delegation(struct xdr_stream *xdr, struct nfs_openres *res) { __be32 *p; uint32_t delegation_type; READ_BUF(4); READ32(delegation_type); if (delegation_type == NFS4_OPEN_DELEGATE_NONE) { res->delegation_type = 0; return 0; } READ_BUF(NFS4_STATEID_SIZE+4); COPYMEM(res->delegation.data, NFS4_STATEID_SIZE); READ32(res->do_recall); switch (delegation_type) { case NFS4_OPEN_DELEGATE_READ: res->delegation_type = FMODE_READ; break; case NFS4_OPEN_DELEGATE_WRITE: res->delegation_type = FMODE_WRITE|FMODE_READ; if (decode_space_limit(xdr, &res->maxsize) < 0) return -EIO; } return decode_ace(xdr, NULL, res->server->nfs_client); }
0
[ "CWE-703" ]
linux
dc0b027dfadfcb8a5504f7d8052754bf8d501ab9
88,318,508,111,435,540,000,000,000,000,000,000,000
25
NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]>
int wc_CheckRsaKey(RsaKey* key) { #if defined(WOLFSSL_CRYPTOCELL) return 0; #endif #ifdef WOLFSSL_SMALL_STACK mp_int *k = NULL, *tmp = NULL; #else mp_int k[1], tmp[1]; #endif int ret = 0; #ifdef WOLFSSL_SMALL_STACK k = (mp_int*)XMALLOC(sizeof(mp_int) * 2, NULL, DYNAMIC_TYPE_RSA); if (k == NULL) return MEMORY_E; tmp = k + 1; #endif if (mp_init_multi(k, tmp, NULL, NULL, NULL, NULL) != MP_OKAY) ret = MP_INIT_E; if (ret == 0) { if (key == NULL) ret = BAD_FUNC_ARG; } if (ret == 0) { if (mp_set_int(k, 0x2342) != MP_OKAY) ret = MP_READ_E; } #ifdef WOLFSSL_HAVE_SP_RSA if (ret == 0) { switch (mp_count_bits(&key->n)) { #ifndef WOLFSSL_SP_NO_2048 case 2048: ret = sp_ModExp_2048(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_NO_2048 */ #ifndef WOLFSSL_SP_NO_3072 case 3072: ret = sp_ModExp_3072(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_NO_3072 */ #ifdef WOLFSSL_SP_4096 case 4096: ret = sp_ModExp_4096(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_4096 */ default: /* If using only single prcsision math then issue key size error, otherwise fall-back to multi-precision math calculation */ #ifdef WOLFSSL_SP_MATH ret = WC_KEY_SIZE_E; #endif break; } } #endif /* WOLFSSL_HAVE_SP_RSA */ #ifndef WOLFSSL_SP_MATH if (ret == 0) { if (mp_exptmod(k, &key->e, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; } if (ret == 0) { if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; } #endif /* !WOLFSSL_SP_MATH */ if (ret == 0) { if (mp_cmp(k, tmp) != MP_EQ) ret = RSA_KEY_PAIR_E; } /* Check d is less than n. */ if (ret == 0 ) { if (mp_cmp(&key->d, &key->n) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check p*q = n. */ if (ret == 0 ) { if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (mp_cmp(&key->n, tmp) != MP_EQ) { ret = MP_EXPTMOD_E; } } /* Check dP, dQ and u if they exist */ if (ret == 0 && !mp_iszero(&key->dP)) { if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } /* Check dP <= p-1. */ if (ret == 0) { if (mp_cmp(&key->dP, tmp) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */ if (ret == 0) { if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } if (ret == 0) { if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } /* Check dQ <= q-1. */ if (ret == 0) { if (mp_cmp(&key->dQ, tmp) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */ if (ret == 0) { if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } /* Check u <= p. */ if (ret == 0) { if (mp_cmp(&key->u, &key->p) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check u*q mod p = 1. (u = 1/q mod p) */ if (ret == 0) { if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } } mp_forcezero(tmp); mp_clear(tmp); mp_clear(k); #ifdef WOLFSSL_SMALL_STACK XFREE(k, NULL, DYNAMIC_TYPE_RSA); #endif return ret; }
0
[ "CWE-310", "CWE-787" ]
wolfssl
fb2288c46dd4c864b78f00a47a364b96a09a5c0f
154,692,935,145,047,000,000,000,000,000,000,000,000
190
RSA-PSS: Handle edge case with encoding message to hash When the key is small relative to the digest (1024-bit key, 64-byte hash, 61-byte salt length), the internal message to hash is larger than the output size. Allocate a buffer for the message when this happens.
smtp_check_rcpt_to(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (s->tx == NULL) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->tx->rcptcount >= env->sc_session_max_rcpt) { smtp_reply(s->tx->session, "451 %s %s: Too many recipients", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return 0; } if (smtp_mailaddr(&s->tx->evp.rcpt, copy, 0, &copy, s->tx->session->smtpname) == 0) { smtp_reply(s->tx->session, "501 %s Recipient address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_BAD_DESTINATION_MAILBOX_ADDRESS_SYNTAX)); return 0; } return 1; }
0
[ "CWE-78", "CWE-252" ]
src
9dcfda045474d8903224d175907bfc29761dcb45
327,340,120,332,336,170,000,000,000,000,000,000,000
33
Fix a security vulnerability discovered by Qualys which can lead to a privileges escalation on mbox deliveries and unprivileged code execution on lmtp deliveries, due to a logic issue causing a sanity check to be missed. ok eric@, millert@
const AST *ast_iter(const AST *a, uint32_t n, uint32_t m) { AST *ast = new AST(a->loc, AST::ITER); ast->iter.ast = a; ast->iter.min = n; ast->iter.max = m; return ast; }
1
[ "CWE-787" ]
re2c
039c18949190c5de5397eba504d2c75dad2ea9ca
20,856,557,274,485,214,000,000,000,000,000,000,000
8
Emit an error when repetition lower bound exceeds upper bound. Historically this was allowed and re2c swapped the bounds. However, it most likely indicates an error in user code and there is only a single occurrence in the tests (and the test in an artificial one), so although the change is backwards incompatible there is low chance of breaking real-world code. This fixes second test case in the bug #394 "Stack overflow due to recursion in src/dfa/dead_rules.cc" (the actual fix is to limit DFA size but the test also has counted repetition with swapped bounds).
int udplite_get_port(struct sock *sk, unsigned short p, int (*c)(const struct sock *, const struct sock *)) { return __udp_lib_get_port(sk, p, udplite_hash, &udplite_port_rover, c); }
1
[]
linux-2.6
32c1da70810017a98aa6c431a5494a302b6b9a30
251,875,682,803,410,300,000,000,000,000,000,000,000
5
[UDP]: Randomize port selection. This patch causes UDP port allocation to be randomized like TCP. The earlier code would always choose same port (ie first empty list). Signed-off-by: Stephen Hemminger <[email protected]> Signed-off-by: David S. Miller <[email protected]>
int register_reboot_notifier(struct notifier_block * nb) { return blocking_notifier_chain_register(&reboot_notifier_list, nb); }
0
[ "CWE-20" ]
linux-2.6
9926e4c74300c4b31dee007298c6475d33369df0
8,350,201,037,623,848,000,000,000,000,000,000,000
4
CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix As discovered here today, the change in Kernel 2.6.17 intended to inhibit users from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by "cheating" and setting it to 1 in such a case, does not make a difference, as the check is done in the wrong place (too late), and only applies to the profiling code. On all systems I checked running kernels above 2.6.17, no matter what the hard and soft CPU time limits were before, a user could escape them by issuing in the shell (sh/bash/zsh) "ulimit -t 0", and then the user's process was not ever killed. Attached is a trivial patch to fix that. Simply moving the check to a slightly earlier location (specifically, before the line that actually assigns the limit - *old_rlim = new_rlim), does the trick. Do note that at least the zsh (but not ash, dash, or bash) shell has the problem of "caching" the limits set by the ulimit command, so when running zsh the fix will not immediately be evident - after entering "ulimit -t 0", "ulimit -a" will show "-t: cpu time (seconds) 0", even though the actual limit as returned by getrlimit(...) will be 1. It can be verified by opening a subshell (which will not have the values of the parent shell in cache) and checking in it, or just by running a CPU intensive command like "echo '65536^1048576' | bc" and verifying that it dumps core after one second. Regardless of whether that is a misfeature in the shell, perhaps it would be better to return -EINVAL from setrlimit in such a case instead of cheating and setting to 1, as that does not really reflect the actual state of the process anymore. I do not however know what the ground for that decision was in the original 2.6.17 change, and whether there would be any "backward" compatibility issues, so I preferred not to touch that right now. Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
static void tcf_block_owner_del(struct tcf_block *block, struct Qdisc *q, enum flow_block_binder_type binder_type) { struct tcf_block_owner_item *item; list_for_each_entry(item, &block->owner_list, list) { if (item->q == q && item->binder_type == binder_type) { list_del(&item->list); kfree(item); return; } } WARN_ON(1); }
0
[ "CWE-416" ]
linux
04c2a47ffb13c29778e2a14e414ad4cb5a5db4b5
290,936,942,589,178,460,000,000,000,000,000,000,000
15
net: sched: fix use-after-free in tc_new_tfilter() Whenever tc_new_tfilter() jumps back to replay: label, we need to make sure @q and @chain local variables are cleared again, or risk use-after-free as in [1] For consistency, apply the same fix in tc_ctl_chain() BUG: KASAN: use-after-free in mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581 Write of size 8 at addr ffff8880985c4b08 by task syz-executor.4/1945 CPU: 0 PID: 1945 Comm: syz-executor.4 Not tainted 5.17.0-rc1-syzkaller-00495-gff58831fa02d #0 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: <TASK> __dump_stack lib/dump_stack.c:88 [inline] dump_stack_lvl+0xcd/0x134 lib/dump_stack.c:106 print_address_description.constprop.0.cold+0x8d/0x336 mm/kasan/report.c:255 __kasan_report mm/kasan/report.c:442 [inline] kasan_report.cold+0x83/0xdf mm/kasan/report.c:459 mini_qdisc_pair_swap+0x1b9/0x1f0 net/sched/sch_generic.c:1581 tcf_chain_head_change_item net/sched/cls_api.c:372 [inline] tcf_chain0_head_change.isra.0+0xb9/0x120 net/sched/cls_api.c:386 tcf_chain_tp_insert net/sched/cls_api.c:1657 [inline] tcf_chain_tp_insert_unique net/sched/cls_api.c:1707 [inline] tc_new_tfilter+0x1e67/0x2350 net/sched/cls_api.c:2086 rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae RIP: 0033:0x7f2647172059 Code: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 b8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f2645aa5168 EFLAGS: 00000246 ORIG_RAX: 0000000000000133 RAX: ffffffffffffffda RBX: 00007f2647285100 RCX: 00007f2647172059 RDX: 040000000000009f RSI: 00000000200002c0 RDI: 0000000000000006 RBP: 00007f26471cc08d R08: 0000000000000000 R09: 0000000000000000 R10: 9e00000000000000 R11: 0000000000000246 R12: 0000000000000000 R13: 00007fffb3f7f02f R14: 00007f2645aa5300 R15: 0000000000022000 </TASK> Allocated by task 1944: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 kasan_set_track mm/kasan/common.c:45 [inline] set_alloc_info mm/kasan/common.c:436 [inline] ____kasan_kmalloc mm/kasan/common.c:515 [inline] ____kasan_kmalloc mm/kasan/common.c:474 [inline] __kasan_kmalloc+0xa9/0xd0 mm/kasan/common.c:524 kmalloc_node include/linux/slab.h:604 [inline] kzalloc_node include/linux/slab.h:726 [inline] qdisc_alloc+0xac/0xa10 net/sched/sch_generic.c:941 qdisc_create.constprop.0+0xce/0x10f0 net/sched/sch_api.c:1211 tc_modify_qdisc+0x4c5/0x1980 net/sched/sch_api.c:1660 rtnetlink_rcv_msg+0x413/0xb80 net/core/rtnetlink.c:5592 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae Freed by task 3609: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 kasan_set_track+0x21/0x30 mm/kasan/common.c:45 kasan_set_free_info+0x20/0x30 mm/kasan/generic.c:370 ____kasan_slab_free mm/kasan/common.c:366 [inline] ____kasan_slab_free+0x130/0x160 mm/kasan/common.c:328 kasan_slab_free include/linux/kasan.h:236 [inline] slab_free_hook mm/slub.c:1728 [inline] slab_free_freelist_hook+0x8b/0x1c0 mm/slub.c:1754 slab_free mm/slub.c:3509 [inline] kfree+0xcb/0x280 mm/slub.c:4562 rcu_do_batch kernel/rcu/tree.c:2527 [inline] rcu_core+0x7b8/0x1540 kernel/rcu/tree.c:2778 __do_softirq+0x29b/0x9c2 kernel/softirq.c:558 Last potentially related work creation: kasan_save_stack+0x1e/0x40 mm/kasan/common.c:38 __kasan_record_aux_stack+0xbe/0xd0 mm/kasan/generic.c:348 __call_rcu kernel/rcu/tree.c:3026 [inline] call_rcu+0xb1/0x740 kernel/rcu/tree.c:3106 qdisc_put_unlocked+0x6f/0x90 net/sched/sch_generic.c:1109 tcf_block_release+0x86/0x90 net/sched/cls_api.c:1238 tc_new_tfilter+0xc0d/0x2350 net/sched/cls_api.c:2148 rtnetlink_rcv_msg+0x80d/0xb80 net/core/rtnetlink.c:5583 netlink_rcv_skb+0x153/0x420 net/netlink/af_netlink.c:2494 netlink_unicast_kernel net/netlink/af_netlink.c:1317 [inline] netlink_unicast+0x539/0x7e0 net/netlink/af_netlink.c:1343 netlink_sendmsg+0x904/0xe00 net/netlink/af_netlink.c:1919 sock_sendmsg_nosec net/socket.c:705 [inline] sock_sendmsg+0xcf/0x120 net/socket.c:725 ____sys_sendmsg+0x331/0x810 net/socket.c:2413 ___sys_sendmsg+0xf3/0x170 net/socket.c:2467 __sys_sendmmsg+0x195/0x470 net/socket.c:2553 __do_sys_sendmmsg net/socket.c:2582 [inline] __se_sys_sendmmsg net/socket.c:2579 [inline] __x64_sys_sendmmsg+0x99/0x100 net/socket.c:2579 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae The buggy address belongs to the object at ffff8880985c4800 which belongs to the cache kmalloc-1k of size 1024 The buggy address is located 776 bytes inside of 1024-byte region [ffff8880985c4800, ffff8880985c4c00) The buggy address belongs to the page: page:ffffea0002617000 refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x985c0 head:ffffea0002617000 order:3 compound_mapcount:0 compound_pincount:0 flags: 0xfff00000010200(slab|head|node=0|zone=1|lastcpupid=0x7ff) raw: 00fff00000010200 0000000000000000 dead000000000122 ffff888010c41dc0 raw: 0000000000000000 0000000000100010 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected page_owner tracks the page as allocated page last allocated via order 3, migratetype Unmovable, gfp_mask 0x1d20c0(__GFP_IO|__GFP_FS|__GFP_NOWARN|__GFP_NORETRY|__GFP_COMP|__GFP_NOMEMALLOC|__GFP_HARDWALL), pid 1941, ts 1038999441284, free_ts 1033444432829 prep_new_page mm/page_alloc.c:2434 [inline] get_page_from_freelist+0xa72/0x2f50 mm/page_alloc.c:4165 __alloc_pages+0x1b2/0x500 mm/page_alloc.c:5389 alloc_pages+0x1aa/0x310 mm/mempolicy.c:2271 alloc_slab_page mm/slub.c:1799 [inline] allocate_slab mm/slub.c:1944 [inline] new_slab+0x28a/0x3b0 mm/slub.c:2004 ___slab_alloc+0x87c/0xe90 mm/slub.c:3018 __slab_alloc.constprop.0+0x4d/0xa0 mm/slub.c:3105 slab_alloc_node mm/slub.c:3196 [inline] slab_alloc mm/slub.c:3238 [inline] __kmalloc+0x2fb/0x340 mm/slub.c:4420 kmalloc include/linux/slab.h:586 [inline] kzalloc include/linux/slab.h:715 [inline] __register_sysctl_table+0x112/0x1090 fs/proc/proc_sysctl.c:1335 neigh_sysctl_register+0x2c8/0x5e0 net/core/neighbour.c:3787 devinet_sysctl_register+0xb1/0x230 net/ipv4/devinet.c:2618 inetdev_init+0x286/0x580 net/ipv4/devinet.c:278 inetdev_event+0xa8a/0x15d0 net/ipv4/devinet.c:1532 notifier_call_chain+0xb5/0x200 kernel/notifier.c:84 call_netdevice_notifiers_info+0xb5/0x130 net/core/dev.c:1919 call_netdevice_notifiers_extack net/core/dev.c:1931 [inline] call_netdevice_notifiers net/core/dev.c:1945 [inline] register_netdevice+0x1073/0x1500 net/core/dev.c:9698 veth_newlink+0x59c/0xa90 drivers/net/veth.c:1722 page last free stack trace: reset_page_owner include/linux/page_owner.h:24 [inline] free_pages_prepare mm/page_alloc.c:1352 [inline] free_pcp_prepare+0x374/0x870 mm/page_alloc.c:1404 free_unref_page_prepare mm/page_alloc.c:3325 [inline] free_unref_page+0x19/0x690 mm/page_alloc.c:3404 release_pages+0x748/0x1220 mm/swap.c:956 tlb_batch_pages_flush mm/mmu_gather.c:50 [inline] tlb_flush_mmu_free mm/mmu_gather.c:243 [inline] tlb_flush_mmu+0xe9/0x6b0 mm/mmu_gather.c:250 zap_pte_range mm/memory.c:1441 [inline] zap_pmd_range mm/memory.c:1490 [inline] zap_pud_range mm/memory.c:1519 [inline] zap_p4d_range mm/memory.c:1540 [inline] unmap_page_range+0x1d1d/0x2a30 mm/memory.c:1561 unmap_single_vma+0x198/0x310 mm/memory.c:1606 unmap_vmas+0x16b/0x2f0 mm/memory.c:1638 exit_mmap+0x201/0x670 mm/mmap.c:3178 __mmput+0x122/0x4b0 kernel/fork.c:1114 mmput+0x56/0x60 kernel/fork.c:1135 exit_mm kernel/exit.c:507 [inline] do_exit+0xa3c/0x2a30 kernel/exit.c:793 do_group_exit+0xd2/0x2f0 kernel/exit.c:935 __do_sys_exit_group kernel/exit.c:946 [inline] __se_sys_exit_group kernel/exit.c:944 [inline] __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:944 do_syscall_x64 arch/x86/entry/common.c:50 [inline] do_syscall_64+0x35/0xb0 arch/x86/entry/common.c:80 entry_SYSCALL_64_after_hwframe+0x44/0xae Memory state around the buggy address: ffff8880985c4a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8880985c4a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8880985c4b00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8880985c4b80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8880985c4c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc Fixes: 470502de5bdb ("net: sched: unlock rules update API") Signed-off-by: Eric Dumazet <[email protected]> Cc: Vlad Buslov <[email protected]> Cc: Jiri Pirko <[email protected]> Cc: Cong Wang <[email protected]> Reported-by: syzbot <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jakub Kicinski <[email protected]>
static int MP4_ReadBox_padb( stream_t *p_stream, MP4_Box_t *p_box ) { uint32_t count; MP4_READBOX_ENTER( MP4_Box_data_padb_t ); MP4_GETVERSIONFLAGS( p_box->data.p_padb ); MP4_GET4BYTES( p_box->data.p_padb->i_sample_count ); count = (p_box->data.p_padb->i_sample_count + 1) / 2; p_box->data.p_padb->i_reserved1 = calloc( count, sizeof(uint16_t) ); p_box->data.p_padb->i_pad2 = calloc( count, sizeof(uint16_t) ); p_box->data.p_padb->i_reserved2 = calloc( count, sizeof(uint16_t) ); p_box->data.p_padb->i_pad1 = calloc( count, sizeof(uint16_t) ); if( p_box->data.p_padb->i_reserved1 == NULL || p_box->data.p_padb->i_pad2 == NULL || p_box->data.p_padb->i_reserved2 == NULL || p_box->data.p_padb->i_pad1 == NULL ) { MP4_READBOX_EXIT( 0 ); } for( unsigned int i = 0; i < i_read / 2 ; i++ ) { if( i >= count ) { MP4_READBOX_EXIT( 0 ); } p_box->data.p_padb->i_reserved1[i] = ( (*p_peek) >> 7 )&0x01; p_box->data.p_padb->i_pad2[i] = ( (*p_peek) >> 4 )&0x07; p_box->data.p_padb->i_reserved1[i] = ( (*p_peek) >> 3 )&0x01; p_box->data.p_padb->i_pad1[i] = ( (*p_peek) )&0x07; p_peek += 1; i_read -= 1; } #ifdef MP4_VERBOSE msg_Dbg( p_stream, "read box: \"stdp\" entry-count %"PRId64, i_read / 2 ); #endif MP4_READBOX_EXIT( 1 ); }
0
[ "CWE-120", "CWE-191", "CWE-787" ]
vlc
2e7c7091a61aa5d07e7997b393d821e91f593c39
2,326,422,861,790,196,300,000,000,000,000,000,000
44
demux: mp4: fix buffer overflow in parsing of string boxes. We ensure that pbox->i_size is never smaller than 8 to avoid an integer underflow in the third argument of the subsequent call to memcpy. We also make sure no truncation occurs when passing values derived from the 64 bit integer p_box->i_size to arguments of malloc and memcpy that may be 32 bit integers on 32 bit platforms. Signed-off-by: Jean-Baptiste Kempf <[email protected]>
ASN1_TIME* X509_get_notAfter(X509* x) { if (x) return x->GetAfter(); return 0; }
0
[ "CWE-254" ]
mysql-server
e7061f7e5a96c66cb2e0bf46bec7f6ff35801a69
31,677,096,498,438,415,000,000,000,000,000,000,000
5
Bug #22738607: YASSL FUNCTION X509_NAME_GET_INDEX_BY_NID IS NOT WORKING AS EXPECTED.
void __audit_seccomp(unsigned long syscall, long signr, int code) { struct audit_buffer *ab; ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_SECCOMP); if (unlikely(!ab)) return; audit_log_task(ab); audit_log_format(ab, " sig=%ld arch=%x syscall=%ld compat=%d ip=0x%lx code=0x%x", signr, syscall_get_arch(), syscall, in_compat_syscall(), KSTK_EIP(current), code); audit_log_end(ab); }
0
[ "CWE-362" ]
linux
43761473c254b45883a64441dd0bc85a42f3645c
77,096,021,968,496,240,000,000,000,000,000,000,000
13
audit: fix a double fetch in audit_log_single_execve_arg() There is a double fetch problem in audit_log_single_execve_arg() where we first check the execve(2) argumnets for any "bad" characters which would require hex encoding and then re-fetch the arguments for logging in the audit record[1]. Of course this leaves a window of opportunity for an unsavory application to munge with the data. This patch reworks things by only fetching the argument data once[2] into a buffer where it is scanned and logged into the audit records(s). In addition to fixing the double fetch, this patch improves on the original code in a few other ways: better handling of large arguments which require encoding, stricter record length checking, and some performance improvements (completely unverified, but we got rid of some strlen() calls, that's got to be a good thing). As part of the development of this patch, I've also created a basic regression test for the audit-testsuite, the test can be tracked on GitHub at the following link: * https://github.com/linux-audit/audit-testsuite/issues/25 [1] If you pay careful attention, there is actually a triple fetch problem due to a strnlen_user() call at the top of the function. [2] This is a tiny white lie, we do make a call to strnlen_user() prior to fetching the argument data. I don't like it, but due to the way the audit record is structured we really have no choice unless we copy the entire argument at once (which would require a rather wasteful allocation). The good news is that with this patch the kernel no longer relies on this strnlen_user() value for anything beyond recording it in the log, we also update it with a trustworthy value whenever possible. Reported-by: Pengfei Wang <[email protected]> Cc: <[email protected]> Signed-off-by: Paul Moore <[email protected]>
static int validate_params(uint cmd, struct dm_ioctl *param) { /* Always clear this flag */ param->flags &= ~DM_BUFFER_FULL_FLAG; param->flags &= ~DM_UEVENT_GENERATED_FLAG; param->flags &= ~DM_SECURE_DATA_FLAG; param->flags &= ~DM_DATA_OUT_FLAG; /* Ignores parameters */ if (cmd == DM_REMOVE_ALL_CMD || cmd == DM_LIST_DEVICES_CMD || cmd == DM_LIST_VERSIONS_CMD) return 0; if (cmd == DM_DEV_CREATE_CMD) { if (!*param->name) { DMWARN("name not supplied when creating device"); return -EINVAL; } } else if (*param->uuid && *param->name) { DMWARN("only supply one of name or uuid, cmd(%u)", cmd); return -EINVAL; } /* Ensure strings are terminated */ param->name[DM_NAME_LEN - 1] = '\0'; param->uuid[DM_UUID_LEN - 1] = '\0'; return 0; }
0
[ "CWE-787" ]
linux
4edbe1d7bcffcd6269f3b5eb63f710393ff2ec7a
328,007,714,444,360,000,000,000,000,000,000,000,000
30
dm ioctl: fix out of bounds array access when no devices If there are not any dm devices, we need to zero the "dev" argument in the first structure dm_name_list. However, this can cause out of bounds write, because the "needed" variable is zero and len may be less than eight. Fix this bug by reporting DM_BUFFER_FULL_FLAG if the result buffer is too small to hold the "nl->dev" value. Signed-off-by: Mikulas Patocka <[email protected]> Reported-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Mike Snitzer <[email protected]>