instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: LoadWatcher(ScriptContext* context, content::RenderFrame* frame, v8::Local<v8::Function> cb) : content::RenderFrameObserver(frame), context_(context), callback_(context->isolate(), cb) { if (ExtensionFrameHelper::Get(frame)-> did_create_current_document_element()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&LoadWatcher::CallbackAndDie, base::Unretained(this), true)); } } Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated BUG=585268,568130 Review URL: https://codereview.chromium.org/1684953002 Cr-Commit-Position: refs/heads/master@{#374758} CWE ID:
1
172,145
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: std::vector<ExtensionSyncData> ExtensionService::GetSyncDataList( ExtensionFilter filter) const { std::vector<ExtensionSyncData> sync_data_list; GetSyncDataListHelper(extensions_, filter, &sync_data_list); GetSyncDataListHelper(disabled_extensions_, filter, &sync_data_list); GetSyncDataListHelper(terminated_extensions_, filter, &sync_data_list); return sync_data_list; } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
99,924
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int set_dor(int fdc, char mask, char data) { unsigned char unit; unsigned char drive; unsigned char newdor; unsigned char olddor; if (FDCS->address == -1) return -1; olddor = FDCS->dor; newdor = (olddor & mask) | data; if (newdor != olddor) { unit = olddor & 0x3; if (is_selected(olddor, unit) && !is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); debug_dcl(UDP->flags, "calling disk change from set_dor\n"); disk_change(drive); } FDCS->dor = newdor; fd_outb(newdor, FD_DOR); unit = newdor & 0x3; if (!is_selected(olddor, unit) && is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); UDRS->select_date = jiffies; } } return olddor; } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <mattd@bugfuzz.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
0
39,432
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: RenderFrameHost* RenderFrameHost::FromAXTreeID( int ax_tree_id) { return RenderFrameHostImpl::FromAXTreeID(ax_tree_id); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
0
127,779
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static __init int rb_test(void *arg) { struct rb_test_data *data = arg; while (!kthread_should_stop()) { rb_write_something(data, false); data->cnt++; set_current_state(TASK_INTERRUPTIBLE); /* Now sleep between a min of 100-300us and a max of 1ms */ usleep_range(((data->cnt % 3) + 1) * 100, 1000); } return 0; } Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize() If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE then the DIV_ROUND_UP() will return zero. Here's the details: # echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb tracing_entries_write() processes this and converts kb to bytes. 18014398509481980 << 10 = 18446744073709547520 and this is passed to ring_buffer_resize() as unsigned long size. size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); Where DIV_ROUND_UP(a, b) is (a + b - 1)/b BUF_PAGE_SIZE is 4080 and here 18446744073709547520 + 4080 - 1 = 18446744073709551599 where 18446744073709551599 is still smaller than 2^64 2^64 - 18446744073709551599 = 17 But now 18446744073709551599 / 4080 = 4521260802379792 and size = size * 4080 = 18446744073709551360 This is checked to make sure its still greater than 2 * 4080, which it is. Then we convert to the number of buffer pages needed. nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE) but this time size is 18446744073709551360 and 2^64 - (18446744073709551360 + 4080 - 1) = -3823 Thus it overflows and the resulting number is less than 4080, which makes 3823 / 4080 = 0 an nr_pages is set to this. As we already checked against the minimum that nr_pages may be, this causes the logic to fail as well, and we crash the kernel. There's no reason to have the two DIV_ROUND_UP() (that's just result of historical code changes), clean up the code and fix this bug. Cc: stable@vger.kernel.org # 3.5+ Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic") Signed-off-by: Steven Rostedt <rostedt@goodmis.org> CWE ID: CWE-190
0
72,580
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline unsigned int iucv_accept_poll(struct sock *parent) { struct iucv_sock *isk, *n; struct sock *sk; list_for_each_entry_safe(isk, n, &iucv_sk(parent)->accept_q, accept_q) { sk = (struct sock *) isk; if (sk->sk_state == IUCV_CONNECTED) return POLLIN | POLLRDNORM; } return 0; } Commit Message: iucv: Fix missing msg_namelen update in iucv_sock_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about iucv_sock_recvmsg() not filling the msg_name in case it was set. Cc: Ursula Braun <ursula.braun@de.ibm.com> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
30,594
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { while (begin && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } else if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } else if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } } Commit Message: Fix #12239 - crash in the x86.nz assembler ##asm (#12252) CWE ID: CWE-125
1
168,970
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static u32 filter_connect(struct tipc_sock *tsock, struct sk_buff **buf) { struct socket *sock = tsock->sk.sk_socket; struct tipc_msg *msg = buf_msg(*buf); struct sock *sk = &tsock->sk; u32 retval = TIPC_ERR_NO_PORT; int res; if (msg_mcast(msg)) return retval; switch ((int)sock->state) { case SS_CONNECTED: /* Accept only connection-based messages sent by peer */ if (msg_connected(msg) && tipc_port_peer_msg(tsock->p, msg)) { if (unlikely(msg_errcode(msg))) { sock->state = SS_DISCONNECTING; __tipc_disconnect(tsock->p); } retval = TIPC_OK; } break; case SS_CONNECTING: /* Accept only ACK or NACK message */ if (unlikely(msg_errcode(msg))) { sock->state = SS_DISCONNECTING; sk->sk_err = -ECONNREFUSED; retval = TIPC_OK; break; } if (unlikely(!msg_connected(msg))) break; res = auto_connect(sock, msg); if (res) { sock->state = SS_DISCONNECTING; sk->sk_err = res; retval = TIPC_OK; break; } /* If an incoming message is an 'ACK-', it should be * discarded here because it doesn't contain useful * data. In addition, we should try to wake up * connect() routine if sleeping. */ if (msg_data_sz(msg) == 0) { kfree_skb(*buf); *buf = NULL; if (waitqueue_active(sk_sleep(sk))) wake_up_interruptible(sk_sleep(sk)); } retval = TIPC_OK; break; case SS_LISTENING: case SS_UNCONNECTED: /* Accept only SYN message */ if (!msg_connected(msg) && !(msg_errcode(msg))) retval = TIPC_OK; break; case SS_DISCONNECTING: break; default: pr_err("Unknown socket state %u\n", sock->state); } return retval; } Commit Message: tipc: fix info leaks via msg_name in recv_msg/recv_stream The code in set_orig_addr() does not initialize all of the members of struct sockaddr_tipc when filling the sockaddr info -- namely the union is only partly filled. This will make recv_msg() and recv_stream() -- the only users of this function -- leak kernel stack memory as the msg_name member is a local variable in net/socket.c. Additionally to that both recv_msg() and recv_stream() fail to update the msg_namelen member to 0 while otherwise returning with 0, i.e. "success". This is the case for, e.g., non-blocking sockets. This will lead to a 128 byte kernel stack leak in net/socket.c. Fix the first issue by initializing the memory of the union with memset(0). Fix the second one by setting msg_namelen to 0 early as it will be updated later if we're going to fill the msg_name member. Cc: Jon Maloy <jon.maloy@ericsson.com> Cc: Allan Stephens <allan.stephens@windriver.com> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
30,453
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BrowserWindowGtk::RegisterUserPrefs(PrefService* prefs) { bool custom_frame_default = false; if (ui::XDisplayExists() && !prefs->HasPrefPath(prefs::kUseCustomChromeFrame)) { custom_frame_default = GetCustomFramePrefDefault(); } prefs->RegisterBooleanPref(prefs::kUseCustomChromeFrame, custom_frame_default, PrefService::SYNCABLE_PREF); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
117,998
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GLES2DecoderImpl::DoUniformMatrix3x2fv(GLint fake_location, GLsizei count, GLboolean transpose, const volatile GLfloat* value) { GLenum type = 0; GLint real_location = -1; if (!PrepForSetUniformByLocation(fake_location, "glUniformMatrix3x2fv", Program::kUniformMatrix3x2f, &real_location, &type, &count)) { return; } api()->glUniformMatrix3x2fvFn(real_location, count, transpose, const_cast<const GLfloat*>(value)); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
0
141,402
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: char *lxc_append_paths(const char *first, const char *second) { size_t len = strlen(first) + strlen(second) + 1; const char *pattern = "%s%s"; char *result = NULL; if (second[0] != '/') { len += 1; pattern = "%s/%s"; } result = calloc(1, len); if (!result) return NULL; snprintf(result, len, pattern, first, second); return result; } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com> CWE ID: CWE-59
0
44,681
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void PrintPreviewHandler::HandleSignin(const ListValue* /*args*/) { gfx::NativeWindow modal_parent = platform_util::GetTopLevel(preview_web_contents()->GetNativeView()); print_dialog_cloud::CreateCloudPrintSigninDialog( preview_web_contents()->GetBrowserContext(), modal_parent, base::Bind(&PrintPreviewHandler::OnSigninComplete, AsWeakPtr())); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
0
105,813
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild) { InlineBidiResolver resolver; RootInlineBox* startLine = determineStartPosition(layoutState, resolver); unsigned consecutiveHyphenatedLines = 0; if (startLine) { for (RootInlineBox* line = startLine->prevRootBox(); line && line->isHyphenated(); line = line->prevRootBox()) consecutiveHyphenatedLines++; } if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) { setNeedsLayout(MarkOnlyThis); // Mark as needing a full layout to force us to repaint. RenderView* v = view(); if (v && !v->doingFullRepaint() && hasLayer()) { repaintUsingContainer(containerForRepaint(), pixelSnappedIntRect(layer()->repaintRect())); } } if (containsFloats()) layoutState.setLastFloat(m_floatingObjects->set().last()); InlineIterator cleanLineStart; BidiStatus cleanLineBidiStatus; if (!layoutState.isFullLayout() && startLine) determineEndPosition(layoutState, startLine, cleanLineStart, cleanLineBidiStatus); if (startLine) { if (!layoutState.usesRepaintBounds()) layoutState.setRepaintRange(logicalHeight()); deleteLineRange(layoutState, startLine); } if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) { if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) { RenderObject* lastObject = lastLeafChild->renderer(); if (!lastObject->isBR()) lastObject = lastRootBox()->firstLeafChild()->renderer(); if (lastObject->isBR()) { EClear clear = lastObject->style()->clear(); if (clear != CNONE) newLine(clear); } } } layoutRunsAndFloatsInRange(layoutState, resolver, cleanLineStart, cleanLineBidiStatus, consecutiveHyphenatedLines); linkToEndLineIfNeeded(layoutState); repaintDirtyFloats(layoutState.floats()); } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
111,372
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: brcmf_notify_sched_scan_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e, void *data) { struct brcmf_cfg80211_info *cfg = ifp->drvr->config; struct brcmf_pno_net_info_le *netinfo, *netinfo_start; struct cfg80211_scan_request *request = NULL; struct cfg80211_ssid *ssid = NULL; struct ieee80211_channel *channel = NULL; struct wiphy *wiphy = cfg_to_wiphy(cfg); int err = 0; int channel_req = 0; int band = 0; struct brcmf_pno_scanresults_le *pfn_result; u32 result_count; u32 status; brcmf_dbg(SCAN, "Enter\n"); if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) { brcmf_dbg(SCAN, "Event data to small. Ignore\n"); return 0; } if (e->event_code == BRCMF_E_PFN_NET_LOST) { brcmf_dbg(SCAN, "PFN NET LOST event. Do Nothing\n"); return 0; } pfn_result = (struct brcmf_pno_scanresults_le *)data; result_count = le32_to_cpu(pfn_result->count); status = le32_to_cpu(pfn_result->status); /* PFN event is limited to fit 512 bytes so we may get * multiple NET_FOUND events. For now place a warning here. */ WARN_ON(status != BRCMF_PNO_SCAN_COMPLETE); brcmf_dbg(SCAN, "PFN NET FOUND event. count: %d\n", result_count); if (result_count > 0) { int i; request = kzalloc(sizeof(*request), GFP_KERNEL); ssid = kcalloc(result_count, sizeof(*ssid), GFP_KERNEL); channel = kcalloc(result_count, sizeof(*channel), GFP_KERNEL); if (!request || !ssid || !channel) { err = -ENOMEM; goto out_err; } request->wiphy = wiphy; data += sizeof(struct brcmf_pno_scanresults_le); netinfo_start = (struct brcmf_pno_net_info_le *)data; for (i = 0; i < result_count; i++) { netinfo = &netinfo_start[i]; if (!netinfo) { brcmf_err("Invalid netinfo ptr. index: %d\n", i); err = -EINVAL; goto out_err; } brcmf_dbg(SCAN, "SSID:%s Channel:%d\n", netinfo->SSID, netinfo->channel); memcpy(ssid[i].ssid, netinfo->SSID, netinfo->SSID_len); ssid[i].ssid_len = netinfo->SSID_len; request->n_ssids++; channel_req = netinfo->channel; if (channel_req <= CH_MAX_2G_CHANNEL) band = NL80211_BAND_2GHZ; else band = NL80211_BAND_5GHZ; channel[i].center_freq = ieee80211_channel_to_frequency(channel_req, band); channel[i].band = band; channel[i].flags |= IEEE80211_CHAN_NO_HT40; request->channels[i] = &channel[i]; request->n_channels++; } /* assign parsed ssid array */ if (request->n_ssids) request->ssids = &ssid[0]; if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) { /* Abort any on-going scan */ brcmf_abort_scanning(cfg); } set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status); cfg->escan_info.run = brcmf_run_escan; err = brcmf_do_escan(cfg, wiphy, ifp, request); if (err) { clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status); goto out_err; } cfg->sched_escan = true; cfg->scan_request = request; } else { brcmf_err("FALSE PNO Event. (pfn_count == 0)\n"); goto out_err; } kfree(ssid); kfree(channel); kfree(request); return 0; out_err: kfree(ssid); kfree(channel); kfree(request); cfg80211_sched_scan_stopped(wiphy); return err; } Commit Message: brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap() User-space can choose to omit NL80211_ATTR_SSID and only provide raw IE TLV data. When doing so it can provide SSID IE with length exceeding the allowed size. The driver further processes this IE copying it into a local variable without checking the length. Hence stack can be corrupted and used as exploit. Cc: stable@vger.kernel.org # v4.7 Reported-by: Daxing Guo <freener.gdx@gmail.com> Reviewed-by: Hante Meuleman <hante.meuleman@broadcom.com> Reviewed-by: Pieter-Paul Giesberts <pieter-paul.giesberts@broadcom.com> Reviewed-by: Franky Lin <franky.lin@broadcom.com> Signed-off-by: Arend van Spriel <arend.vanspriel@broadcom.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.org> CWE ID: CWE-119
0
49,099
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs, Error **errp, const char *fmt, ...) { char msg[64]; va_list ap; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2", msg); } Commit Message: CWE ID: CWE-190
0
16,832
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xfs_attr_node_removename(xfs_da_args_t *args) { xfs_da_state_t *state; xfs_da_state_blk_t *blk; xfs_inode_t *dp; struct xfs_buf *bp; int retval, error, forkoff; trace_xfs_attr_node_removename(args); /* * Tie a string around our finger to remind us where we are. */ dp = args->dp; state = xfs_da_state_alloc(); state->args = args; state->mp = dp->i_mount; /* * Search to see if name exists, and get back a pointer to it. */ error = xfs_da3_node_lookup_int(state, &retval); if (error || (retval != -EEXIST)) { if (error == 0) error = retval; goto out; } /* * If there is an out-of-line value, de-allocate the blocks. * This is done before we remove the attribute so that we don't * overflow the maximum size of a transaction and/or hit a deadlock. */ blk = &state->path.blk[ state->path.active-1 ]; ASSERT(blk->bp != NULL); ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC); if (args->rmtblkno > 0) { /* * Fill in disk block numbers in the state structure * so that we can get the buffers back after we commit * several transactions in the following calls. */ error = xfs_attr_fillstate(state); if (error) goto out; /* * Mark the attribute as INCOMPLETE, then bunmapi() the * remote value. */ error = xfs_attr3_leaf_setflag(args); if (error) goto out; error = xfs_attr_rmtval_remove(args); if (error) goto out; /* * Refill the state structure with buffers, the prior calls * released our buffers. */ error = xfs_attr_refillstate(state); if (error) goto out; } /* * Remove the name and update the hashvals in the tree. */ blk = &state->path.blk[ state->path.active-1 ]; ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC); retval = xfs_attr3_leaf_remove(blk->bp, args); xfs_da3_fixhashpath(state, &state->path); /* * Check to see if the tree needs to be collapsed. */ if (retval && (state->path.active > 1)) { xfs_defer_init(args->dfops, args->firstblock); error = xfs_da3_join(state); if (error) goto out_defer_cancel; xfs_defer_ijoin(args->dfops, dp); error = xfs_defer_finish(&args->trans, args->dfops); if (error) goto out_defer_cancel; /* * Commit the Btree join operation and start a new trans. */ error = xfs_trans_roll_inode(&args->trans, dp); if (error) goto out; } /* * If the result is small enough, push it all into the inode. */ if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) { /* * Have to get rid of the copy of this dabuf in the state. */ ASSERT(state->path.active == 1); ASSERT(state->path.blk[0].bp); state->path.blk[0].bp = NULL; error = xfs_attr3_leaf_read(args->trans, args->dp, 0, -1, &bp); if (error) goto out; if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) { xfs_defer_init(args->dfops, args->firstblock); error = xfs_attr3_leaf_to_shortform(bp, args, forkoff); /* bp is gone due to xfs_da_shrink_inode */ if (error) goto out_defer_cancel; xfs_defer_ijoin(args->dfops, dp); error = xfs_defer_finish(&args->trans, args->dfops); if (error) goto out_defer_cancel; } else xfs_trans_brelse(args->trans, bp); } error = 0; out: xfs_da_state_free(state); return error; out_defer_cancel: xfs_defer_cancel(args->dfops); goto out; } Commit Message: xfs: don't fail when converting shortform attr to long form during ATTR_REPLACE Kanda Motohiro reported that expanding a tiny xattr into a large xattr fails on XFS because we remove the tiny xattr from a shortform fork and then try to re-add it after converting the fork to extents format having not removed the ATTR_REPLACE flag. This fails because the attr is no longer present, causing a fs shutdown. This is derived from the patch in his bug report, but we really shouldn't ignore a nonzero retval from the remove call. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199119 Reported-by: kanda.motohiro@gmail.com Reviewed-by: Dave Chinner <dchinner@redhat.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Signed-off-by: Darrick J. Wong <darrick.wong@oracle.com> CWE ID: CWE-754
0
76,323
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run) { int r; sigset_t sigsaved; if (vcpu->mmio_needed) { vcpu->mmio_needed = 0; if (!vcpu->mmio_is_write) kvmppc_complete_mmio_load(vcpu, run); #ifdef CONFIG_VSX if (vcpu->arch.mmio_vsx_copy_nums > 0) { vcpu->arch.mmio_vsx_copy_nums--; vcpu->arch.mmio_vsx_offset++; } if (vcpu->arch.mmio_vsx_copy_nums > 0) { r = kvmppc_emulate_mmio_vsx_loadstore(vcpu, run); if (r == RESUME_HOST) { vcpu->mmio_needed = 1; return r; } } #endif } else if (vcpu->arch.osi_needed) { u64 *gprs = run->osi.gprs; int i; for (i = 0; i < 32; i++) kvmppc_set_gpr(vcpu, i, gprs[i]); vcpu->arch.osi_needed = 0; } else if (vcpu->arch.hcall_needed) { int i; kvmppc_set_gpr(vcpu, 3, run->papr_hcall.ret); for (i = 0; i < 9; ++i) kvmppc_set_gpr(vcpu, 4 + i, run->papr_hcall.args[i]); vcpu->arch.hcall_needed = 0; #ifdef CONFIG_BOOKE } else if (vcpu->arch.epr_needed) { kvmppc_set_epr(vcpu, run->epr.epr); vcpu->arch.epr_needed = 0; #endif } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved); if (run->immediate_exit) r = -EINTR; else r = kvmppc_vcpu_run(run, vcpu); if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &sigsaved, NULL); return r; } Commit Message: KVM: PPC: Fix oops when checking KVM_CAP_PPC_HTM The following program causes a kernel oops: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/kvm.h> main() { int fd = open("/dev/kvm", O_RDWR); ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_PPC_HTM); } This happens because when using the global KVM fd with KVM_CHECK_EXTENSION, kvm_vm_ioctl_check_extension() gets called with a NULL kvm argument, which gets dereferenced in is_kvmppc_hv_enabled(). Spotted while reading the code. Let's use the hv_enabled fallback variable, like everywhere else in this function. Fixes: 23528bb21ee2 ("KVM: PPC: Introduce KVM_CAP_PPC_HTM") Cc: stable@vger.kernel.org # v4.7+ Signed-off-by: Greg Kurz <groug@kaod.org> Reviewed-by: David Gibson <david@gibson.dropbear.id.au> Reviewed-by: Thomas Huth <thuth@redhat.com> Signed-off-by: Paul Mackerras <paulus@ozlabs.org> CWE ID: CWE-476
0
60,521
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void php_snmp_error(zval *object, const char *docref, int type, const char *format, ...) { va_list args; php_snmp_object *snmp_object = NULL; if (object) { snmp_object = Z_SNMP_P(object); if (type == PHP_SNMP_ERRNO_NOERROR) { memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr)); } else { va_start(args, format); vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args); va_end(args); } snmp_object->snmp_errno = type; } if (type == PHP_SNMP_ERRNO_NOERROR) { return; } if (object && (snmp_object->exceptions_enabled & type)) { zend_throw_exception_ex(php_snmp_exception_ce, type, snmp_object->snmp_errstr); } else { va_start(args, format); php_verror(docref, "", E_WARNING, format, args); va_end(args); } } Commit Message: CWE ID: CWE-20
1
165,074
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: status_t MediaRecorder::setVideoSource(int vs) { ALOGV("setVideoSource(%d)", vs); if (mMediaRecorder == NULL) { ALOGE("media recorder is not initialized yet"); return INVALID_OPERATION; } if (mIsVideoSourceSet) { ALOGE("video source has already been set"); return INVALID_OPERATION; } if (mCurrentState & MEDIA_RECORDER_IDLE) { ALOGV("Call init() since the media recorder is not initialized yet"); status_t ret = init(); if (OK != ret) { return ret; } } if (!(mCurrentState & MEDIA_RECORDER_INITIALIZED)) { ALOGE("setVideoSource called in an invalid state(%d)", mCurrentState); return INVALID_OPERATION; } status_t ret = mMediaRecorder->setVideoSource(vs); if (OK != ret) { ALOGV("setVideoSource failed: %d", ret); mCurrentState = MEDIA_RECORDER_ERROR; return ret; } mIsVideoSourceSet = true; return ret; } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476
0
159,548
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void OutOfProcessInstance::DocumentHasUnsupportedFeature( const std::string& feature) { std::string metric("PDF_Unsupported_"); metric += feature; if (!unsupported_features_reported_.count(metric)) { unsupported_features_reported_.insert(metric); UserMetricsRecordAction(metric); } if (!full_) return; if (told_browser_about_unsupported_feature_) return; told_browser_about_unsupported_feature_ = true; pp::PDF::HasUnsupportedFeature(this); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20
0
129,417
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: expand_string_internal(uschar *string, BOOL ket_ends, uschar **left, BOOL skipping, BOOL honour_dollar, BOOL *resetok_p) { int ptr = 0; int size = Ustrlen(string)+ 64; int item_type; uschar *yield = store_get(size); uschar *s = string; uschar *save_expand_nstring[EXPAND_MAXN+1]; int save_expand_nlength[EXPAND_MAXN+1]; BOOL resetok = TRUE; expand_string_forcedfail = FALSE; expand_string_message = US""; while (*s != 0) { uschar *value; uschar name[256]; /* \ escapes the next character, which must exist, or else the expansion fails. There's a special escape, \N, which causes copying of the subject verbatim up to the next \N. Otherwise, the escapes are the standard set. */ if (*s == '\\') { if (s[1] == 0) { expand_string_message = US"\\ at end of string"; goto EXPAND_FAILED; } if (s[1] == 'N') { uschar *t = s + 2; for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break; yield = string_cat(yield, &size, &ptr, t, s - t); if (*s != 0) s += 2; } else { uschar ch[1]; ch[0] = string_interpret_escape(&s); s++; yield = string_cat(yield, &size, &ptr, ch, 1); } continue; } /*{*/ /* Anything other than $ is just copied verbatim, unless we are looking for a terminating } character. */ /*{*/ if (ket_ends && *s == '}') break; if (*s != '$' || !honour_dollar) { yield = string_cat(yield, &size, &ptr, s++, 1); continue; } /* No { after the $ - must be a plain name or a number for string match variable. There has to be a fudge for variables that are the names of header fields preceded by "$header_" because header field names can contain any printing characters except space and colon. For those that don't like typing this much, "$h_" is a synonym for "$header_". A non-existent header yields a NULL value; nothing is inserted. */ /*}*/ if (isalpha((*(++s)))) { int len; int newsize = 0; s = read_name(name, sizeof(name), s, US"_"); /* If this is the first thing to be expanded, release the pre-allocated buffer. */ if (ptr == 0 && yield != NULL) { if (resetok) store_reset(yield); yield = NULL; size = 0; } /* Header */ if (Ustrncmp(name, "h_", 2) == 0 || Ustrncmp(name, "rh_", 3) == 0 || Ustrncmp(name, "bh_", 3) == 0 || Ustrncmp(name, "header_", 7) == 0 || Ustrncmp(name, "rheader_", 8) == 0 || Ustrncmp(name, "bheader_", 8) == 0) { BOOL want_raw = (name[0] == 'r')? TRUE : FALSE; uschar *charset = (name[0] == 'b')? NULL : headers_charset; s = read_header_name(name, sizeof(name), s); value = find_header(name, FALSE, &newsize, want_raw, charset); /* If we didn't find the header, and the header contains a closing brace character, this may be a user error where the terminating colon has been omitted. Set a flag to adjust the error message in this case. But there is no error here - nothing gets inserted. */ if (value == NULL) { if (Ustrchr(name, '}') != NULL) malformed_header = TRUE; continue; } } /* Variable */ else { value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable name \"%s\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } } /* If the data is known to be in a new buffer, newsize will be set to the size of that buffer. If this is the first thing in an expansion string, yield will be NULL; just point it at the new store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers. */ len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } if (isdigit(*s)) { int n; s = read_number(&n, s); if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } /* Otherwise, if there's no '{' after $ it's an error. */ /*}*/ if (*s != '{') /*}*/ { expand_string_message = US"$ not followed by letter, digit, or {"; /*}*/ goto EXPAND_FAILED; } /* After { there can be various things, but they all start with an initial word, except for a number for a string match variable. */ if (isdigit((*(++s)))) { int n; s = read_number(&n, s); /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = US"} expected after number"; goto EXPAND_FAILED; } if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } if (!isalpha(*s)) { expand_string_message = US"letter or digit expected after ${"; /*}*/ goto EXPAND_FAILED; } /* Allow "-" in names to cater for substrings with negative arguments. Since we are checking for known names after { this is OK. */ s = read_name(name, sizeof(name), s, US"_-"); item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *)); switch(item_type) { /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9. If the ACL returns accept or reject we return content set by "message =" There is currently no limit on recursion; this would have us call acl_check_internal() directly and get a current level from somewhere. See also the acl expansion condition ECOND_ACL and the traditional acl modifier ACLC_ACL. Assume that the function has side-effects on the store that must be preserved. */ case EITEM_ACL: /* ${acl {name} {arg1}{arg2}...} */ { uschar *sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */ uschar *user_msg; switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US"acl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (skipping) continue; resetok = FALSE; switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg)) { case OK: case FAIL: DEBUG(D_expand) debug_printf("acl expansion yield: %s\n", user_msg); if (user_msg) yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg)); continue; case DEFER: expand_string_forcedfail = TRUE; default: expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]); goto EXPAND_FAILED; } } /* Handle conditionals - preserve the values of the numerical expansion variables in case they get changed by a regular expression match in the condition. If not, they retain their external settings. At the end of this "if" section, they get restored to their previous values. */ case EITEM_IF: { BOOL cond = FALSE; uschar *next_s; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); while (isspace(*s)) s++; next_s = eval_condition(s, &resetok, skipping? NULL : &cond); if (next_s == NULL) goto EXPAND_FAILED; /* message already set */ DEBUG(D_expand) debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s, cond? "true" : "false"); s = next_s; /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${lookup} and ${extract} and ${run}. */ switch(process_yesno( skipping, /* were previously skipping */ cond, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"if", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for continuation at this level. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle database lookups unless locked out. If "skipping" is TRUE, we are expanding an internal string that isn't actually going to be used. All we need to do is check the syntax, so don't do a lookup at all. Preserve the values of the numerical expansion variables in case they get changed by a partial lookup. If not, they retain their external settings. At the end of this "lookup" section, they get restored to their previous values. */ case EITEM_LOOKUP: { int stype, partial, affixlen, starflags; int expand_setup = 0; int nameptr = 0; uschar *key, *filename, *affix; uschar *save_lookup_value = lookup_value; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); if ((expand_forbid & RDO_LOOKUP) != 0) { expand_string_message = US"lookup expansions are not permitted"; goto EXPAND_FAILED; } /* Get the key we are to look up for single-key+file style lookups. Otherwise set the key NULL pro-tem. */ while (isspace(*s)) s++; if (*s == '{') /*}*/ { key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (key == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } else key = NULL; /* Find out the type of database */ if (!isalpha(*s)) { expand_string_message = US"missing lookup type"; goto EXPAND_FAILED; } /* The type is a string that may contain special characters of various kinds. Allow everything except space or { to appear; the actual content is checked by search_findtype_partial. */ /*}*/ while (*s != 0 && *s != '{' && !isspace(*s)) /*}*/ { if (nameptr < sizeof(name) - 1) name[nameptr++] = *s; s++; } name[nameptr] = 0; while (isspace(*s)) s++; /* Now check for the individual search type and any partial or default options. Only those types that are actually in the binary are valid. */ stype = search_findtype_partial(name, &partial, &affix, &affixlen, &starflags); if (stype < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } /* Check that a key was provided for those lookup types that need it, and was not supplied for those that use the query style. */ if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery)) { if (key == NULL) { expand_string_message = string_sprintf("missing {key} for single-" "key \"%s\" lookup", name); goto EXPAND_FAILED; } } else { if (key != NULL) { expand_string_message = string_sprintf("a single key was given for " "lookup type \"%s\", which is not a single-key lookup type", name); goto EXPAND_FAILED; } } /* Get the next string in brackets and expand it. It is the file name for single-key+file lookups, and the whole query otherwise. In the case of queries that also require a file name (e.g. sqlite), the file name comes first. */ if (*s != '{') goto EXPAND_FAILED_CURLY; filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (filename == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; /* If this isn't a single-key+file lookup, re-arrange the variables to be appropriate for the search_ functions. For query-style lookups, there is just a "key", and no file name. For the special query-style + file types, the query (i.e. "key") starts with a file name. */ if (key == NULL) { while (isspace(*filename)) filename++; key = filename; if (mac_islookup(stype, lookup_querystyle)) { filename = NULL; } else { if (*filename != '/') { expand_string_message = string_sprintf( "absolute file name expected for \"%s\" lookup", name); goto EXPAND_FAILED; } while (*key != 0 && !isspace(*key)) key++; if (*key != 0) *key++ = 0; } } /* If skipping, don't do the next bit - just lookup_value == NULL, as if the entry was not found. Note that there is no search_close() function. Files are left open in case of re-use. At suitable places in higher logic, search_tidyup() is called to tidy all open files. This can save opening the same file several times. However, files may also get closed when others are opened, if too many are open at once. The rule is that a handle should not be used after a second search_open(). Request that a partial search sets up $1 and maybe $2 by passing expand_setup containing zero. If its value changes, reset expand_nmax, since new variables will have been set. Note that at the end of this "lookup" section, the old numeric variables are restored. */ if (skipping) lookup_value = NULL; else { void *handle = search_open(filename, stype, 0, NULL, NULL); if (handle == NULL) { expand_string_message = search_error_message; goto EXPAND_FAILED; } lookup_value = search_find(handle, filename, key, partial, affix, affixlen, starflags, &expand_setup); if (search_find_defer) { expand_string_message = string_sprintf("lookup of \"%s\" gave DEFER: %s", string_printing2(key, FALSE), search_error_message); goto EXPAND_FAILED; } if (expand_setup > 0) expand_nmax = expand_setup; } /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${if} and ${extract}. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"lookup", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for carrying on at this level, and continue. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* If Perl support is configured, handle calling embedded perl subroutines, unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}} or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS arguments (defined below). */ #define EXIM_PERL_MAX_ARGS 8 case EITEM_PERL: #ifndef EXIM_PERL expand_string_message = US"\"${perl\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXIM_PERL */ { uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2]; uschar *new_yield; if ((expand_forbid & RDO_PERL) != 0) { expand_string_message = US"Perl calls are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE, US"perl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Start the interpreter if necessary */ if (!opt_perl_started) { uschar *initerror; if (opt_perl_startup == NULL) { expand_string_message = US"A setting of perl_startup is needed when " "using the Perl interpreter"; goto EXPAND_FAILED; } DEBUG(D_any) debug_printf("Starting Perl interpreter\n"); initerror = init_perl(opt_perl_startup); if (initerror != NULL) { expand_string_message = string_sprintf("error in perl_startup code: %s\n", initerror); goto EXPAND_FAILED; } opt_perl_started = TRUE; } /* Call the function */ sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL; new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message, sub_arg[0], sub_arg + 1); /* NULL yield indicates failure; if the message pointer has been set to NULL, the yield was undef, indicating a forced failure. Otherwise the message will indicate some kind of Perl error. */ if (new_yield == NULL) { if (expand_string_message == NULL) { expand_string_message = string_sprintf("Perl subroutine \"%s\" returned undef to force " "failure", sub_arg[0]); expand_string_forcedfail = TRUE; } goto EXPAND_FAILED; } /* Yield succeeded. Ensure forcedfail is unset, just in case it got set during a callback from Perl. */ expand_string_forcedfail = FALSE; yield = new_yield; continue; } #endif /* EXIM_PERL */ /* Transform email address to "prvs" scheme to use as BATV-signed return path */ case EITEM_PRVS: { uschar *sub_arg[3]; uschar *p,*domain; switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* sub_arg[0] is the address */ domain = Ustrrchr(sub_arg[0],'@'); if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) ) { expand_string_message = US"prvs first argument must be a qualified email address"; goto EXPAND_FAILED; } /* Calculate the hash. The second argument must be a single-digit key number, or unset. */ if (sub_arg[2] != NULL && (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0)) { expand_string_message = US"prvs second argument must be a single digit"; goto EXPAND_FAILED; } p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7)); if (p == NULL) { expand_string_message = US"prvs hmac-sha1 conversion failed"; goto EXPAND_FAILED; } /* Now separate the domain from the local part */ *domain++ = '\0'; yield = string_cat(yield,&size,&ptr,US"prvs=",5); string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1); string_cat(yield,&size,&ptr,prvs_daystamp(7),3); string_cat(yield,&size,&ptr,p,6); string_cat(yield,&size,&ptr,US"=",1); string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); string_cat(yield,&size,&ptr,US"@",1); string_cat(yield,&size,&ptr,domain,Ustrlen(domain)); continue; } /* Check a prvs-encoded address for validity */ case EITEM_PRVSCHECK: { uschar *sub_arg[3]; int mysize = 0, myptr = 0; const pcre *re; uschar *p; /* TF: Ugliness: We want to expand parameter 1 first, then set up expansion variables that are used in the expansion of parameter 2. So we clone the string for the first expansion, where we only expand parameter 1. PH: Actually, that isn't necessary. The read_subs() function is designed to work this way for the ${if and ${lookup expansions. I've tidied the code. */ /* Reset expansion variables */ prvscheck_result = NULL; prvscheck_address = NULL; prvscheck_keynum = NULL; switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$", TRUE,FALSE); if (regex_match_and_setup(re,sub_arg[0],0,-1)) { uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]); uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]); uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]); uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]); uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]); DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part); DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num); DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp); DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain); /* Set up expansion variables */ prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part)); string_cat(prvscheck_address,&mysize,&myptr,US"@",1); string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain)); prvscheck_address[myptr] = '\0'; prvscheck_keynum = string_copy(key_num); /* Now expand the second argument */ switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Now we have the key and can check the address. */ p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum, daystamp); if (p == NULL) { expand_string_message = US"hmac-sha1 conversion failed"; goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p); if (Ustrcmp(p,hash) == 0) { /* Success, valid BATV address. Now check the expiry date. */ uschar *now = prvs_daystamp(0); unsigned int inow = 0,iexpire = 1; (void)sscanf(CS now,"%u",&inow); (void)sscanf(CS daystamp,"%u",&iexpire); /* When "iexpire" is < 7, a "flip" has occured. Adjust "inow" accordingly. */ if ( (iexpire < 7) && (inow >= 993) ) inow = 0; if (iexpire >= inow) { prvscheck_result = US"1"; DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n"); } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n"); } } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n"); } /* Now expand the final argument. We leave this till now so that it can include $prvscheck_result. */ switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (sub_arg[0] == NULL || *sub_arg[0] == '\0') yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address)); else yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); /* Reset the "internal" variables afterwards, because they are in dynamic store that will be reclaimed if the expansion succeeded. */ prvscheck_address = NULL; prvscheck_keynum = NULL; } else { /* Does not look like a prvs encoded address, return the empty string. We need to make sure all subs are expanded first, so as to skip over the entire item. */ switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } } continue; } /* Handle "readfile" to insert an entire file */ case EITEM_READFILE: { FILE *f; uschar *sub_arg[2]; if ((expand_forbid & RDO_READFILE) != 0) { expand_string_message = US"file insertions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Open the file and read it */ f = Ufopen(sub_arg[0], "rb"); if (f == NULL) { expand_string_message = string_open_failed(errno, "%s", sub_arg[0]); goto EXPAND_FAILED; } yield = cat_file(f, yield, &size, &ptr, sub_arg[1]); (void)fclose(f); continue; } /* Handle "readsocket" to insert data from a Unix domain socket */ case EITEM_READSOCK: { int fd; int timeout = 5; int save_ptr = ptr; FILE *f; struct sockaddr_un sockun; /* don't call this "sun" ! */ uschar *arg; uschar *sub_arg[4]; if ((expand_forbid & RDO_READSOCK) != 0) { expand_string_message = US"socket insertions are not permitted"; goto EXPAND_FAILED; } /* Read up to 4 arguments, but don't do the end of item check afterwards, because there may be a string for expansion on failure. */ switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: /* Won't occur: no end check */ case 3: goto EXPAND_FAILED; } /* Sort out timeout, if given */ if (sub_arg[2] != NULL) { timeout = readconf_readtime(sub_arg[2], 0, FALSE); if (timeout < 0) { expand_string_message = string_sprintf("bad time value %s", sub_arg[2]); goto EXPAND_FAILED; } } else sub_arg[3] = NULL; /* No eol if no timeout */ /* If skipping, we don't actually do anything. Otherwise, arrange to connect to either an IP or a Unix socket. */ if (!skipping) { /* Handle an IP (internet) domain */ if (Ustrncmp(sub_arg[0], "inet:", 5) == 0) { int port; uschar *server_name = sub_arg[0] + 5; uschar *port_name = Ustrrchr(server_name, ':'); /* Sort out the port */ if (port_name == NULL) { expand_string_message = string_sprintf("missing port for readsocket %s", sub_arg[0]); goto EXPAND_FAILED; } *port_name++ = 0; /* Terminate server name */ if (isdigit(*port_name)) { uschar *end; port = Ustrtol(port_name, &end, 0); if (end != port_name + Ustrlen(port_name)) { expand_string_message = string_sprintf("invalid port number %s", port_name); goto EXPAND_FAILED; } } else { struct servent *service_info = getservbyname(CS port_name, "tcp"); if (service_info == NULL) { expand_string_message = string_sprintf("unknown port \"%s\"", port_name); goto EXPAND_FAILED; } port = ntohs(service_info->s_port); } if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port, timeout, NULL, &expand_string_message)) < 0) goto SOCK_FAIL; } /* Handle a Unix domain socket */ else { int rc; if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) { expand_string_message = string_sprintf("failed to create socket: %s", strerror(errno)); goto SOCK_FAIL; } sockun.sun_family = AF_UNIX; sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sub_arg[0]); sigalrm_seen = FALSE; alarm(timeout); rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun)); alarm(0); if (sigalrm_seen) { expand_string_message = US "socket connect timed out"; goto SOCK_FAIL; } if (rc < 0) { expand_string_message = string_sprintf("failed to connect to socket " "%s: %s", sub_arg[0], strerror(errno)); goto SOCK_FAIL; } } DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]); /* Allow sequencing of test actions */ if (running_in_test_harness) millisleep(100); /* Write the request string, if not empty */ if (sub_arg[1][0] != 0) { int len = Ustrlen(sub_arg[1]); DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n", sub_arg[1]); if (write(fd, sub_arg[1], len) != len) { expand_string_message = string_sprintf("request write to socket " "failed: %s", strerror(errno)); goto SOCK_FAIL; } } /* Shut down the sending side of the socket. This helps some servers to recognise that it is their turn to do some work. Just in case some system doesn't have this function, make it conditional. */ #ifdef SHUT_WR shutdown(fd, SHUT_WR); #endif if (running_in_test_harness) millisleep(100); /* Now we need to read from the socket, under a timeout. The function that reads a file can be used. */ f = fdopen(fd, "rb"); sigalrm_seen = FALSE; alarm(timeout); yield = cat_file(f, yield, &size, &ptr, sub_arg[3]); alarm(0); (void)fclose(f); /* After a timeout, we restore the pointer in the result, that is, make sure we add nothing from the socket. */ if (sigalrm_seen) { ptr = save_ptr; expand_string_message = US "socket read timed out"; goto SOCK_FAIL; } } /* The whole thing has worked (or we were skipping). If there is a failure string following, we need to skip it. */ if (*s == '{') { if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; /* Come here on failure to create socket, connect socket, write to the socket, or timeout on reading. If another substring follows, expand and use it. Otherwise, those conditions give expand errors. */ SOCK_FAIL: if (*s != '{') goto EXPAND_FAILED; DEBUG(D_any) debug_printf("%s\n", expand_string_message); arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg)); if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; } /* Handle "run" to execute a program. */ case EITEM_RUN: { FILE *f; uschar *arg; uschar **argv; pid_t pid; int fd_in, fd_out; int lsize = 0; int lptr = 0; if ((expand_forbid & RDO_RUN) != 0) { expand_string_message = US"running a command is not permitted"; goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s != '{') goto EXPAND_FAILED_CURLY; arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) /* Just pretend it worked when we're skipping */ { runrc = 0; } else { if (!transport_set_up_command(&argv, /* anchor for arg list */ arg, /* raw command */ FALSE, /* don't expand the arguments */ 0, /* not relevant when... */ NULL, /* no transporting address */ US"${run} expansion", /* for error messages */ &expand_string_message)) /* where to put error message */ { goto EXPAND_FAILED; } /* Create the child process, making it a group leader. */ pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE); if (pid < 0) { expand_string_message = string_sprintf("couldn't create child process: %s", strerror(errno)); goto EXPAND_FAILED; } /* Nothing is written to the standard input. */ (void)close(fd_in); /* Read the pipe to get the command's output into $value (which is kept in lookup_value). Read during execution, so that if the output exceeds the OS pipe buffer limit, we don't block forever. */ f = fdopen(fd_out, "rb"); sigalrm_seen = FALSE; alarm(60); lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL); alarm(0); (void)fclose(f); /* Wait for the process to finish, applying the timeout, and inspect its return code for serious disasters. Simple non-zero returns are passed on. */ if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0) { if (sigalrm_seen == TRUE || runrc == -256) { expand_string_message = string_sprintf("command timed out"); killpg(pid, SIGKILL); /* Kill the whole process group */ } else if (runrc == -257) expand_string_message = string_sprintf("wait() failed: %s", strerror(errno)); else expand_string_message = string_sprintf("command killed by signal %d", -runrc); goto EXPAND_FAILED; } } /* Process the yes/no strings; $value may be useful in both cases */ switch(process_yesno( skipping, /* were previously skipping */ runrc == 0, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"run", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } continue; } /* Handle character translation for "tr" */ case EITEM_TR: { int oldptr = ptr; int o2m; uschar *sub[3]; switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0])); o2m = Ustrlen(sub[2]) - 1; if (o2m >= 0) for (; oldptr < ptr; oldptr++) { uschar *m = Ustrrchr(sub[1], yield[oldptr]); if (m != NULL) { int o = m - sub[1]; yield[oldptr] = sub[2][(o < o2m)? o : o2m]; } } continue; } /* Handle "hash", "length", "nhash", and "substr" when they are given with expanded arguments. */ case EITEM_HASH: case EITEM_LENGTH: case EITEM_NHASH: case EITEM_SUBSTR: { int i; int len; uschar *ret; int val[2] = { 0, -1 }; uschar *sub[3]; /* "length" takes only 2 arguments whereas the others take 2 or 3. Ensure that sub[2] is set in the ${length } case. */ sub[2] = NULL; switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Juggle the arguments if there are only two of them: always move the string to the last position and make ${length{n}{str}} equivalent to ${substr{0}{n}{str}}. See the defaults for val[] above. */ if (sub[2] == NULL) { sub[2] = sub[1]; sub[1] = NULL; if (item_type == EITEM_LENGTH) { sub[1] = sub[0]; sub[0] = NULL; } } for (i = 0; i < 2; i++) { if (sub[i] == NULL) continue; val[i] = (int)Ustrtol(sub[i], &ret, 10); if (*ret != 0 || (i != 0 && val[i] < 0)) { expand_string_message = string_sprintf("\"%s\" is not a%s number " "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name); goto EXPAND_FAILED; } } ret = (item_type == EITEM_HASH)? compute_hash(sub[2], val[0], val[1], &len) : (item_type == EITEM_NHASH)? compute_nhash(sub[2], val[0], val[1], &len) : extract_substr(sub[2], val[0], val[1], &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}} This code originally contributed by Steve Haslam. It currently supports the use of MD5 and SHA-1 hashes. We need some workspace that is large enough to handle all the supported hash types. Use macros to set the sizes rather than be too elaborate. */ #define MAX_HASHLEN 20 #define MAX_HASHBLOCKLEN 64 case EITEM_HMAC: { uschar *sub[3]; md5 md5_base; sha1 sha1_base; void *use_base; int type, i; int hashlen; /* Number of octets for the hash algorithm's output */ int hashblocklen; /* Number of octets the hash algorithm processes */ uschar *keyptr, *p; unsigned int keylen; uschar keyhash[MAX_HASHLEN]; uschar innerhash[MAX_HASHLEN]; uschar finalhash[MAX_HASHLEN]; uschar finalhash_hex[2*MAX_HASHLEN]; uschar innerkey[MAX_HASHBLOCKLEN]; uschar outerkey[MAX_HASHBLOCKLEN]; switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (Ustrcmp(sub[0], "md5") == 0) { type = HMAC_MD5; use_base = &md5_base; hashlen = 16; hashblocklen = 64; } else if (Ustrcmp(sub[0], "sha1") == 0) { type = HMAC_SHA1; use_base = &sha1_base; hashlen = 20; hashblocklen = 64; } else { expand_string_message = string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]); goto EXPAND_FAILED; } keyptr = sub[1]; keylen = Ustrlen(keyptr); /* If the key is longer than the hash block length, then hash the key first */ if (keylen > hashblocklen) { chash_start(type, use_base); chash_end(type, use_base, keyptr, keylen, keyhash); keyptr = keyhash; keylen = hashlen; } /* Now make the inner and outer key values */ memset(innerkey, 0x36, hashblocklen); memset(outerkey, 0x5c, hashblocklen); for (i = 0; i < keylen; i++) { innerkey[i] ^= keyptr[i]; outerkey[i] ^= keyptr[i]; } /* Now do the hashes */ chash_start(type, use_base); chash_mid(type, use_base, innerkey); chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash); chash_start(type, use_base); chash_mid(type, use_base, outerkey); chash_end(type, use_base, innerhash, hashlen, finalhash); /* Encode the final hash as a hex string */ p = finalhash_hex; for (i = 0; i < hashlen; i++) { *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4]; *p++ = hex_digits[finalhash[i] & 0x0f]; } DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0], (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex); yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2); } continue; /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator. We have to save the numerical variables and restore them afterwards. */ case EITEM_SG: { const pcre *re; int moffset, moffsetextra, slen; int roffset; int emptyopt; const uschar *rerror; uschar *subject; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Compile the regular expression */ re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset, NULL); if (re == NULL) { expand_string_message = string_sprintf("regular expression error in " "\"%s\": %s at offset %d", sub[1], rerror, roffset); goto EXPAND_FAILED; } /* Now run a loop to do the substitutions as often as necessary. It ends when there are no more matches. Take care over matches of the null string; do the same thing as Perl does. */ subject = sub[0]; slen = Ustrlen(sub[0]); moffset = moffsetextra = 0; emptyopt = 0; for (;;) { int ovector[3*(EXPAND_MAXN+1)]; int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra, PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int)); int nn; uschar *insert; /* No match - if we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We want to repeat the match from one character further along, but leaving the basic offset the same (for copying below). We can't be at the end of the string - that was checked before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are finished; copy the remaining string and end the loop. */ if (n < 0) { if (emptyopt != 0) { moffsetextra = 1; emptyopt = 0; continue; } yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset); break; } /* Match - set up for expanding the replacement. */ if (n == 0) n = EXPAND_MAXN + 1; expand_nmax = 0; for (nn = 0; nn < n*2; nn += 2) { expand_nstring[expand_nmax] = subject + ovector[nn]; expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn]; } expand_nmax--; /* Copy the characters before the match, plus the expanded insertion. */ yield = string_cat(yield, &size, &ptr, subject + moffset, ovector[0] - moffset); insert = expand_string(sub[2]); if (insert == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert)); moffset = ovector[1]; moffsetextra = 0; emptyopt = 0; /* If we have matched an empty string, first check to see if we are at the end of the subject. If so, the loop is over. Otherwise, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty string at the same point. If this fails (picked up above) we advance to the next character. */ if (ovector[0] == ovector[1]) { if (ovector[0] == slen) break; emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED; } } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle keyed and numbered substring extraction. If the first argument consists entirely of digits, then a numerical extraction is assumed. */ case EITEM_EXTRACT: { int i; int j = 2; int field_number = 1; BOOL field_number_set = FALSE; uschar *save_lookup_value = lookup_value; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the arguments */ for (i = 0; i < j; i++) { while (isspace(*s)) s++; if (*s == '{') /*}*/ { sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (sub[i] == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must not be empty; if it consists entirely of digits (optionally preceded by a minus sign), this is a numerical extraction, and we expect 3 arguments. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (*p == 0 && !skipping) { expand_string_message = US"first argument of \"extract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p == 0) { field_number *= x; j = 3; /* Need 3 args */ field_number_set = TRUE; } } } else goto EXPAND_FAILED_CURLY; } /* Extract either the numbered or the keyed substring into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : field_number_set? expand_gettokened(field_number, sub[1], sub[2]) : expand_getkeyed(sub[0], sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* return the Nth item from a list */ case EITEM_LISTEXTRACT: { int i; int field_number = 1; uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field & list arguments */ for (i = 0; i < 2; i++) { while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[i]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must be numeric and nonempty. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (!*p && !skipping) { expand_string_message = US"first argument of \"listextract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p) { expand_string_message = US"first argument of \"listextract\" must " "be numeric"; goto EXPAND_FAILED; } field_number *= x; } } /* Extract the numbered element into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #ifdef SUPPORT_TLS case EITEM_CERTEXTRACT: { uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[0]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* strip spaces fore & aft */ { int len; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; } /* inspect the cert argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; if (*++s != '$') { expand_string_message = US"second argument of \"certextract\" must " "be a certificate variable"; goto EXPAND_FAILED; } sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok); if (!sub[1]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) lookup_value = NULL; else { lookup_value = expand_getcertele(sub[0], sub[1]); if (*expand_string_message) goto EXPAND_FAILED; } switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #endif /*SUPPORT_TLS*/ /* Handle list operations */ case EITEM_FILTER: case EITEM_MAP: case EITEM_REDUCE: { int sep = 0; int save_ptr = ptr; uschar outsep[2] = { '\0', '\0' }; uschar *list, *expr, *temp; uschar *save_iterate_item = iterate_item; uschar *save_lookup_value = lookup_value; while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (list == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (item_type == EITEM_REDUCE) { while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (temp == NULL) goto EXPAND_FAILED; lookup_value = temp; if (*s++ != '}') goto EXPAND_FAILED_CURLY; } while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; expr = s; /* For EITEM_FILTER, call eval_condition once, with result discarded (as if scanning a "false" part). This allows us to find the end of the condition, because if the list is empty, we won't actually evaluate the condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using the normal internal expansion function. */ if (item_type == EITEM_FILTER) { temp = eval_condition(expr, &resetok, NULL); if (temp != NULL) s = temp; } else { temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok); } if (temp == NULL) { expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of condition " "or expression inside \"%s\"", name); goto EXPAND_FAILED; } while (isspace(*s)) s++; /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of \"%s\"", name); goto EXPAND_FAILED; } /* If we are skipping, we can now just move on to the next item. When processing for real, we perform the iteration. */ if (skipping) continue; while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL) { *outsep = (uschar)sep; /* Separator as a string */ DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item); if (item_type == EITEM_FILTER) { BOOL condresult; if (eval_condition(expr, &resetok, &condresult) == NULL) { iterate_item = save_iterate_item; lookup_value = save_lookup_value; expand_string_message = string_sprintf("%s inside \"%s\" condition", expand_string_message, name); goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("%s: condition is %s\n", name, condresult? "true":"false"); if (condresult) temp = iterate_item; /* TRUE => include this item */ else continue; /* FALSE => skip this item */ } /* EITEM_MAP and EITEM_REDUCE */ else { temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok); if (temp == NULL) { iterate_item = save_iterate_item; expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } if (item_type == EITEM_REDUCE) { lookup_value = temp; /* Update the value of $value */ continue; /* and continue the iteration */ } } /* We reach here for FILTER if the condition is true, always for MAP, and never for REDUCE. The value in "temp" is to be added to the output list that is being created, ensuring that any occurrences of the separator character are doubled. Unless we are dealing with the first item of the output list, add in a space if the new item begins with the separator character, or is an empty string. */ if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0)) yield = string_cat(yield, &size, &ptr, US" ", 1); /* Add the string in "temp" to the output list that we are building, This is done in chunks by searching for the separator character. */ for (;;) { size_t seglen = Ustrcspn(temp, outsep); yield = string_cat(yield, &size, &ptr, temp, seglen + 1); /* If we got to the end of the string we output one character too many; backup and end the loop. Otherwise arrange to double the separator. */ if (temp[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); temp += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } /* End of iteration over the list loop */ /* REDUCE has generated no output above: output the final value of $value. */ if (item_type == EITEM_REDUCE) { yield = string_cat(yield, &size, &ptr, lookup_value, Ustrlen(lookup_value)); lookup_value = save_lookup_value; /* Restore $value */ } /* FILTER and MAP generate lists: if they have generated anything, remove the redundant final separator. Even though an empty item at the end of a list does not count, this is tidier. */ else if (ptr != save_ptr) ptr--; /* Restore preserved $item */ iterate_item = save_iterate_item; continue; } /* If ${dlfunc } support is configured, handle calling dynamically-loaded functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}} or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */ #define EXPAND_DLFUNC_MAX_ARGS 8 case EITEM_DLFUNC: #ifndef EXPAND_DLFUNC expand_string_message = US"\"${dlfunc\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXPAND_DLFUNC */ { tree_node *t; exim_dlfunc_t *func; uschar *result; int status, argc; uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3]; if ((expand_forbid & RDO_DLFUNC) != 0) { expand_string_message = US"dynamically-loaded functions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping, TRUE, US"dlfunc", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Look up the dynamically loaded object handle in the tree. If it isn't found, dlopen() the file and put the handle in the tree for next time. */ t = tree_search(dlobj_anchor, argv[0]); if (t == NULL) { void *handle = dlopen(CS argv[0], RTLD_LAZY); if (handle == NULL) { expand_string_message = string_sprintf("dlopen \"%s\" failed: %s", argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0])); Ustrcpy(t->name, argv[0]); t->data.ptr = handle; (void)tree_insertnode(&dlobj_anchor, t); } /* Having obtained the dynamically loaded object handle, look up the function pointer. */ func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]); if (func == NULL) { expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: " "%s", argv[1], argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } /* Call the function and work out what to do with the result. If it returns OK, we have a replacement string; if it returns DEFER then expansion has failed in a non-forced manner; if it returns FAIL then failure was forced; if it returns ERROR or any other value there's a problem, so panic slightly. In any case, assume that the function has side-effects on the store that must be preserved. */ resetok = FALSE; result = NULL; for (argc = 0; argv[argc] != NULL; argc++); status = func(&result, argc - 2, &argv[2]); if(status == OK) { if (result == NULL) result = US""; yield = string_cat(yield, &size, &ptr, result, Ustrlen(result)); continue; } else { expand_string_message = result == NULL ? US"(no message)" : result; if(status == FAIL_FORCED) expand_string_forcedfail = TRUE; else if(status != FAIL) log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s", argv[0], argv[1], status, expand_string_message); goto EXPAND_FAILED; } } #endif /* EXPAND_DLFUNC */ } /* EITEM_* switch */ /* Control reaches here if the name is not recognized as one of the more complicated expansion items. Check for the "operator" syntax (name terminated by a colon). Some of the operators have arguments, separated by _ from the name. */ if (*s == ':') { int c; uschar *arg = NULL; uschar *sub; var_entry *vp = NULL; /* Owing to an historical mis-design, an underscore may be part of the operator name, or it may introduce arguments. We therefore first scan the table of names that contain underscores. If there is no match, we cut off the arguments and then scan the main table. */ if ((c = chop_match(name, op_table_underscore, sizeof(op_table_underscore)/sizeof(uschar *))) < 0) { arg = Ustrchr(name, '_'); if (arg != NULL) *arg = 0; c = chop_match(name, op_table_main, sizeof(op_table_main)/sizeof(uschar *)); if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *); if (arg != NULL) *arg++ = '_'; /* Put back for error messages */ } /* Deal specially with operators that might take a certificate variable as we do not want to do the usual expansion. For most, expand the string.*/ switch(c) { #ifdef SUPPORT_TLS case EOP_MD5: case EOP_SHA1: case EOP_SHA256: if (s[1] == '$') { uschar * s1 = s; sub = expand_string_internal(s+2, TRUE, &s1, skipping, FALSE, &resetok); if (!sub) goto EXPAND_FAILED; /*{*/ if (*s1 != '}') goto EXPAND_FAILED_CURLY; if ((vp = find_var_ent(sub)) && vp->type == vtype_cert) { s = s1+1; break; } vp = NULL; } /*FALLTHROUGH*/ #endif default: sub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub) goto EXPAND_FAILED; s++; break; } /* If we are skipping, we don't need to perform the operation at all. This matters for operations like "mask", because the data may not be in the correct format when skipping. For example, the expression may test for the existence of $sender_host_address before trying to mask it. For other operations, doing them may not fail, but it is a waste of time. */ if (skipping && c >= 0) continue; /* Otherwise, switch on the operator type */ switch(c) { case EOP_BASE62: { uschar *t; unsigned long int n = Ustrtoul(sub, &t, 10); if (*t != 0) { expand_string_message = string_sprintf("argument for base62 " "operator is \"%s\", which is not a decimal number", sub); goto EXPAND_FAILED; } t = string_base62(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */ case EOP_BASE62D: { uschar buf[16]; uschar *tt = sub; unsigned long int n = 0; while (*tt != 0) { uschar *t = Ustrchr(base62_chars, *tt++); if (t == NULL) { expand_string_message = string_sprintf("argument for base62d " "operator is \"%s\", which is not a base %d number", sub, BASE_62); goto EXPAND_FAILED; } n = n * BASE_62 + (t - base62_chars); } (void)sprintf(CS buf, "%ld", n); yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf)); continue; } case EOP_EXPAND: { uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok); if (expanded == NULL) { expand_string_message = string_sprintf("internal expansion of \"%s\" failed: %s", sub, expand_string_message); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded)); continue; } case EOP_LC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = tolower(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_UC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = toupper(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_MD5: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_md5(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { md5 base; uschar digest[16]; int j; char st[33]; md5_start(&base); md5_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA1: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { sha1 base; uschar digest[20]; int j; char st[41]; sha1_start(&base); sha1_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA256: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp)); } else #endif expand_string_message = US"sha256 only supported for certificates"; continue; /* Convert hex encoding to base64 encoding */ case EOP_HEX2B64: { int c = 0; int b = -1; uschar *in = sub; uschar *out = sub; uschar *enc; for (enc = sub; *enc != 0; enc++) { if (!isxdigit(*enc)) { expand_string_message = string_sprintf("\"%s\" is not a hex " "string", sub); goto EXPAND_FAILED; } c++; } if ((c & 1) != 0) { expand_string_message = string_sprintf("\"%s\" contains an odd " "number of characters", sub); goto EXPAND_FAILED; } while ((c = *in++) != 0) { if (isdigit(c)) c -= '0'; else c = toupper(c) - 'A' + 10; if (b == -1) { b = c << 4; } else { *out++ = b | c; b = -1; } } enc = auth_b64encode(sub, out - sub); yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc)); continue; } /* Convert octets outside 0x21..0x7E to \xXX form */ case EOP_HEXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (*t < 0x21 || 0x7E < *t) yield = string_cat(yield, &size, &ptr, string_sprintf("\\x%02x", *t), 4); else yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* count the number of list elements */ case EOP_LISTCOUNT: { int cnt = 0; int sep = 0; uschar * cp; uschar buffer[256]; while (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++; cp = string_sprintf("%d", cnt); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); continue; } /* expand a named list given the name */ /* handles nested named lists; requotes as colon-sep list */ case EOP_LISTNAMED: { tree_node *t = NULL; uschar * list; int sep = 0; uschar * item; uschar * suffix = US""; BOOL needsep = FALSE; uschar buffer[256]; if (*sub == '+') sub++; if (arg == NULL) /* no-argument version */ { if (!(t = tree_search(addresslist_anchor, sub)) && !(t = tree_search(domainlist_anchor, sub)) && !(t = tree_search(hostlist_anchor, sub))) t = tree_search(localpartlist_anchor, sub); } else switch(*arg) /* specific list-type version */ { case 'a': t = tree_search(addresslist_anchor, sub); suffix = US"_a"; break; case 'd': t = tree_search(domainlist_anchor, sub); suffix = US"_d"; break; case 'h': t = tree_search(hostlist_anchor, sub); suffix = US"_h"; break; case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US"_l"; break; default: expand_string_message = string_sprintf("bad suffix on \"list\" operator"); goto EXPAND_FAILED; } if(!t) { expand_string_message = string_sprintf("\"%s\" is not a %snamed list", sub, !arg?"" : *arg=='a'?"address " : *arg=='d'?"domain " : *arg=='h'?"host " : *arg=='l'?"localpart " : 0); goto EXPAND_FAILED; } list = ((namedlist_block *)(t->data.ptr))->string; while ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { uschar * buf = US" : "; if (needsep) yield = string_cat(yield, &size, &ptr, buf, 3); else needsep = TRUE; if (*item == '+') /* list item is itself a named list */ { uschar * sub = string_sprintf("${listnamed%s:%s}", suffix, item); item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok); } else if (sep != ':') /* item from non-colon-sep list, re-quote for colon list-separator */ { char * cp; char tok[3]; tok[0] = sep; tok[1] = ':'; tok[2] = 0; while ((cp= strpbrk((const char *)item, tok))) { yield = string_cat(yield, &size, &ptr, item, cp-(char *)item); if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */ { yield = string_cat(yield, &size, &ptr, US"::", 2); item = (uschar *)cp; } else /* sep in item; should already be doubled; emit once */ { yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1); if (*cp == sep) cp++; item = (uschar *)cp; } } } yield = string_cat(yield, &size, &ptr, item, Ustrlen(item)); } continue; } /* mask applies a mask to an IP address; for example the result of ${mask:131.111.10.206/28} is 131.111.10.192/28. */ case EOP_MASK: { int count; uschar *endptr; int binary[4]; int mask, maskoffset; int type = string_is_ip_address(sub, &maskoffset); uschar buffer[64]; if (type == 0) { expand_string_message = string_sprintf("\"%s\" is not an IP address", sub); goto EXPAND_FAILED; } if (maskoffset == 0) { expand_string_message = string_sprintf("missing mask value in \"%s\"", sub); goto EXPAND_FAILED; } mask = Ustrtol(sub + maskoffset + 1, &endptr, 10); if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128)) { expand_string_message = string_sprintf("mask value too big in \"%s\"", sub); goto EXPAND_FAILED; } /* Convert the address to binary integer(s) and apply the mask */ sub[maskoffset] = 0; count = host_aton(sub, binary); host_mask(count, binary, mask); /* Convert to masked textual format and add to output. */ yield = string_cat(yield, &size, &ptr, buffer, host_nmtoa(count, binary, mask, buffer, '.')); continue; } case EOP_ADDRESS: case EOP_LOCAL_PART: case EOP_DOMAIN: { uschar *error; int start, end, domain; uschar *t = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); if (t != NULL) { if (c != EOP_DOMAIN) { if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1; yield = string_cat(yield, &size, &ptr, sub+start, end-start); } else if (domain != 0) { domain += start; yield = string_cat(yield, &size, &ptr, sub+domain, end-domain); } } continue; } case EOP_ADDRESSES: { uschar outsep[2] = { ':', '\0' }; uschar *address, *error; int save_ptr = ptr; int start, end, domain; /* Not really used */ while (isspace(*sub)) sub++; if (*sub == '>') { *outsep = *++sub; ++sub; } parse_allow_group = TRUE; for (;;) { uschar *p = parse_find_address_end(sub, FALSE); uschar saveend = *p; *p = '\0'; address = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); *p = saveend; /* Add the address to the output list that we are building. This is done in chunks by searching for the separator character. At the start, unless we are dealing with the first address of the output list, add in a space if the new address begins with the separator character, or is an empty string. */ if (address != NULL) { if (ptr != save_ptr && address[0] == *outsep) yield = string_cat(yield, &size, &ptr, US" ", 1); for (;;) { size_t seglen = Ustrcspn(address, outsep); yield = string_cat(yield, &size, &ptr, address, seglen + 1); /* If we got to the end of the string we output one character too many. */ if (address[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); address += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } if (saveend == '\0') break; sub = p + 1; } /* If we have generated anything, remove the redundant final separator. */ if (ptr != save_ptr) ptr--; parse_allow_group = FALSE; continue; } /* quote puts a string in quotes if it is empty or contains anything other than alphamerics, underscore, dot, or hyphen. quote_local_part puts a string in quotes if RFC 2821/2822 requires it to be quoted in order to be a valid local part. In both cases, newlines and carriage returns are converted into \n and \r respectively */ case EOP_QUOTE: case EOP_QUOTE_LOCAL_PART: if (arg == NULL) { BOOL needs_quote = (*sub == 0); /* TRUE for empty string */ uschar *t = sub - 1; if (c == EOP_QUOTE) { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && !strchr("_-.", *t); } else /* EOP_QUOTE_LOCAL_PART */ { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL && (*t != '.' || t == sub || t[1] == 0); } if (needs_quote) { yield = string_cat(yield, &size, &ptr, US"\"", 1); t = sub - 1; while (*(++t) != 0) { if (*t == '\n') yield = string_cat(yield, &size, &ptr, US"\\n", 2); else if (*t == '\r') yield = string_cat(yield, &size, &ptr, US"\\r", 2); else { if (*t == '\\' || *t == '"') yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } } yield = string_cat(yield, &size, &ptr, US"\"", 1); } else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* quote_lookuptype does lookup-specific quoting */ else { int n; uschar *opt = Ustrchr(arg, '_'); if (opt != NULL) *opt++ = 0; n = search_findtype(arg, Ustrlen(arg)); if (n < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } if (lookup_list[n]->quote != NULL) sub = (lookup_list[n]->quote)(sub, opt); else if (opt != NULL) sub = NULL; if (sub == NULL) { expand_string_message = string_sprintf( "\"%s\" unrecognized after \"${quote_%s\"", opt, arg); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* rx quote sticks in \ before any non-alphameric character so that the insertion works in a regular expression. */ case EOP_RXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (!isalnum(*t)) yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as prescribed by the RFC, if there are characters that need to be encoded */ case EOP_RFC2047: { uschar buffer[2048]; uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset, buffer, sizeof(buffer), FALSE); yield = string_cat(yield, &size, &ptr, string, Ustrlen(string)); continue; } /* RFC 2047 decode */ case EOP_RFC2047D: { int len; uschar *error; uschar *decoded = rfc2047_decode(sub, check_rfc2047_length, headers_charset, '?', &len, &error); if (error != NULL) { expand_string_message = error; goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, decoded, len); continue; } /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into underscores */ case EOP_FROM_UTF8: { while (*sub != 0) { int c; uschar buff[4]; GETUTF8INC(c, sub); if (c > 255) c = '_'; buff[0] = c; yield = string_cat(yield, &size, &ptr, buff, 1); } continue; } /* replace illegal UTF-8 sequences by replacement character */ #define UTF8_REPLACEMENT_CHAR US"?" case EOP_UTF8CLEAN: { int seq_len, index = 0; int bytes_left = 0; uschar seq_buff[4]; /* accumulate utf-8 here */ while (*sub != 0) { int complete; long codepoint; uschar c; complete = 0; c = *sub++; if (bytes_left) { if ((c & 0xc0) != 0x80) { /* wrong continuation byte; invalidate all bytes */ complete = 1; /* error */ } else { codepoint = (codepoint << 6) | (c & 0x3f); seq_buff[index++] = c; if (--bytes_left == 0) /* codepoint complete */ { if(codepoint > 0x10FFFF) /* is it too large? */ complete = -1; /* error */ else { /* finished; output utf-8 sequence */ yield = string_cat(yield, &size, &ptr, seq_buff, seq_len); index = 0; } } } } else /* no bytes left: new sequence */ { if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */ { yield = string_cat(yield, &size, &ptr, &c, 1); continue; } if((c & 0xe0) == 0xc0) /* 2-byte sequence */ { if(c == 0xc0 || c == 0xc1) /* 0xc0 and 0xc1 are illegal */ complete = -1; else { bytes_left = 1; codepoint = c & 0x1f; } } else if((c & 0xf0) == 0xe0) /* 3-byte sequence */ { bytes_left = 2; codepoint = c & 0x0f; } else if((c & 0xf8) == 0xf0) /* 4-byte sequence */ { bytes_left = 3; codepoint = c & 0x07; } else /* invalid or too long (RFC3629 allows only 4 bytes) */ complete = -1; seq_buff[index++] = c; seq_len = bytes_left + 1; } /* if(bytes_left) */ if (complete != 0) { bytes_left = index = 0; yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1); } if ((complete == 1) && ((c & 0x80) == 0)) { /* ASCII character follows incomplete sequence */ yield = string_cat(yield, &size, &ptr, &c, 1); } } continue; } /* escape turns all non-printing characters into escape sequences. */ case EOP_ESCAPE: { uschar *t = string_printing(sub); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Handle numeric expression evaluation */ case EOP_EVAL: case EOP_EVAL10: { uschar *save_sub = sub; uschar *error = NULL; int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE); if (error != NULL) { expand_string_message = string_sprintf("error in expression " "evaluation: %s (after processing \"%.*s\")", error, sub-save_sub, save_sub); goto EXPAND_FAILED; } sprintf(CS var_buffer, PR_EXIM_ARITH, n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } /* Handle time period formating */ case EOP_TIME_EVAL: { int n = readconf_readtime(sub, 0, FALSE); if (n < 0) { expand_string_message = string_sprintf("string \"%s\" is not an " "Exim time interval in \"%s\" operator", sub, name); goto EXPAND_FAILED; } sprintf(CS var_buffer, "%d", n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } case EOP_TIME_INTERVAL: { int n; uschar *t = read_number(&n, sub); if (*t != 0) /* Not A Number*/ { expand_string_message = string_sprintf("string \"%s\" is not a " "positive number in \"%s\" operator", sub, name); goto EXPAND_FAILED; } t = readconf_printtime(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Convert string to base64 encoding */ case EOP_STR2B64: { uschar *encstr = auth_b64encode(sub, Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr)); continue; } /* strlen returns the length of the string */ case EOP_STRLEN: { uschar buff[24]; (void)sprintf(CS buff, "%d", Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff)); continue; } /* length_n or l_n takes just the first n characters or the whole string, whichever is the shorter; substr_m_n, and s_m_n take n characters from offset m; negative m take from the end; l_n is synonymous with s_0_n. If n is omitted in substr it takes the rest, either to the right or to the left. hash_n or h_n makes a hash of length n from the string, yielding n characters from the set a-z; hash_n_m makes a hash of length n, but uses m characters from the set a-zA-Z0-9. nhash_n returns a single number between 0 and n-1 (in text form), while nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies between 0 and n-1 and the second between 0 and m-1. */ case EOP_LENGTH: case EOP_L: case EOP_SUBSTR: case EOP_S: case EOP_HASH: case EOP_H: case EOP_NHASH: case EOP_NH: { int sign = 1; int value1 = 0; int value2 = -1; int *pn; int len; uschar *ret; if (arg == NULL) { expand_string_message = string_sprintf("missing values after %s", name); goto EXPAND_FAILED; } /* "length" has only one argument, effectively being synonymous with substr_0_n. */ if (c == EOP_LENGTH || c == EOP_L) { pn = &value2; value2 = 0; } /* The others have one or two arguments; for "substr" the first may be negative. The second being negative means "not supplied". */ else { pn = &value1; if (name[0] == 's' && *arg == '-') { sign = -1; arg++; } } /* Read up to two numbers, separated by underscores */ ret = arg; while (*arg != 0) { if (arg != ret && *arg == '_' && pn == &value1) { pn = &value2; value2 = 0; if (arg[1] != 0) arg++; } else if (!isdigit(*arg)) { expand_string_message = string_sprintf("non-digit after underscore in \"%s\"", name); goto EXPAND_FAILED; } else *pn = (*pn)*10 + *arg++ - '0'; } value1 *= sign; /* Perform the required operation */ ret = (c == EOP_HASH || c == EOP_H)? compute_hash(sub, value1, value2, &len) : (c == EOP_NHASH || c == EOP_NH)? compute_nhash(sub, value1, value2, &len) : extract_substr(sub, value1, value2, &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Stat a path */ case EOP_STAT: { uschar *s; uschar smode[12]; uschar **modetable[3]; int i; mode_t mode; struct stat st; if ((expand_forbid & RDO_EXISTS) != 0) { expand_string_message = US"Use of the stat() expansion is not permitted"; goto EXPAND_FAILED; } if (stat(CS sub, &st) < 0) { expand_string_message = string_sprintf("stat(%s) failed: %s", sub, strerror(errno)); goto EXPAND_FAILED; } mode = st.st_mode; switch (mode & S_IFMT) { case S_IFIFO: smode[0] = 'p'; break; case S_IFCHR: smode[0] = 'c'; break; case S_IFDIR: smode[0] = 'd'; break; case S_IFBLK: smode[0] = 'b'; break; case S_IFREG: smode[0] = '-'; break; default: smode[0] = '?'; break; } modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky; modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid; modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid; for (i = 0; i < 3; i++) { memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3); mode >>= 3; } smode[10] = 0; s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld " "uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld", (long)(st.st_mode & 077777), smode, (long)st.st_ino, (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid, (long)st.st_gid, st.st_size, (long)st.st_atime, (long)st.st_mtime, (long)st.st_ctime); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* vaguely random number less than N */ case EOP_RANDINT: { int_eximarith_t max; uschar *s; max = expand_string_integer(sub, TRUE); if (expand_string_message != NULL) goto EXPAND_FAILED; s = string_sprintf("%d", vaguely_random_number((int)max)); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* Reverse IP, including IPv6 to dotted-nibble */ case EOP_REVERSE_IP: { int family, maskptr; uschar reversed[128]; family = string_is_ip_address(sub, &maskptr); if (family == 0) { expand_string_message = string_sprintf( "reverse_ip() not given an IP address [%s]", sub); goto EXPAND_FAILED; } invert_address(reversed, sub); yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed)); continue; } /* Unknown operator */ default: expand_string_message = string_sprintf("unknown expansion operator \"%s\"", name); goto EXPAND_FAILED; } } /* Handle a plain name. If this is the first thing in the expansion, release the pre-allocated buffer. If the result data is known to be in a new buffer, newsize will be set to the size of that buffer, and we can just point at that store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers ($message_headers). */ /*{*/ if (*s++ == '}') { int len; int newsize = 0; if (ptr == 0) { if (resetok) store_reset(yield); yield = NULL; size = 0; } value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable in \"${%s}\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } /* Else there's something wrong */ expand_string_message = string_sprintf("\"${%s\" is not a known operator (or a } is missing " "in a variable reference)", name); goto EXPAND_FAILED; } /* If we hit the end of the string when ket_ends is set, there is a missing terminating brace. */ if (ket_ends && *s == 0) { expand_string_message = malformed_header? US"missing } at end of string - could be header name not terminated by colon" : US"missing } at end of string"; goto EXPAND_FAILED; } /* Expansion succeeded; yield may still be NULL here if nothing was actually added to the string. If so, set up an empty string. Add a terminating zero. If left != NULL, return a pointer to the terminator. */ if (yield == NULL) yield = store_get(1); yield[ptr] = 0; if (left != NULL) *left = s; /* Any stacking store that was used above the final string is no longer needed. In many cases the final string will be the first one that was got and so there will be optimal store usage. */ if (resetok) store_reset(yield + ptr + 1); else if (resetok_p) *resetok_p = FALSE; DEBUG(D_expand) { debug_printf("expanding: %.*s\n result: %s\n", (int)(s - string), string, yield); if (skipping) debug_printf("skipping: result is not used\n"); } return yield; /* This is the failure exit: easiest to program with a goto. We still need to update the pointer to the terminator, for cases of nested calls with "fail". */ EXPAND_FAILED_CURLY: expand_string_message = malformed_header? US"missing or misplaced { or } - could be header name not terminated by colon" : US"missing or misplaced { or }"; /* At one point, Exim reset the store to yield (if yield was not NULL), but that is a bad idea, because expand_string_message is in dynamic store. */ EXPAND_FAILED: if (left != NULL) *left = s; DEBUG(D_expand) { debug_printf("failed to expand: %s\n", string); debug_printf(" error message: %s\n", expand_string_message); if (expand_string_forcedfail) debug_printf("failure was forced\n"); } if (resetok_p) *resetok_p = resetok; return NULL; } Commit Message: CWE ID: CWE-189
1
165,192
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int v9fs_xattr_set_acl(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *name, const void *value, size_t size, int flags) { int retval; struct posix_acl *acl; struct v9fs_session_info *v9ses; v9ses = v9fs_dentry2v9ses(dentry); /* * set the attribute on the remote. Without even looking at the * xattr value. We leave it to the server to validate */ if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) return v9fs_xattr_set(dentry, handler->name, value, size, flags); if (S_ISLNK(inode->i_mode)) return -EOPNOTSUPP; if (!inode_owner_or_capable(inode)) return -EPERM; if (value) { /* update the cached acl value */ acl = posix_acl_from_xattr(&init_user_ns, value, size); if (IS_ERR(acl)) return PTR_ERR(acl); else if (acl) { retval = posix_acl_valid(inode->i_sb->s_user_ns, acl); if (retval) goto err_out; } } else acl = NULL; switch (handler->flags) { case ACL_TYPE_ACCESS: if (acl) { umode_t mode = inode->i_mode; retval = posix_acl_equiv_mode(acl, &mode); if (retval < 0) goto err_out; else { struct iattr iattr; if (retval == 0) { /* * ACL can be represented * by the mode bits. So don't * update ACL. */ acl = NULL; value = NULL; size = 0; } /* Updte the mode bits */ iattr.ia_mode = ((mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO)); iattr.ia_valid = ATTR_MODE; /* FIXME should we update ctime ? * What is the following setxattr update the * mode ? */ v9fs_vfs_setattr_dotl(dentry, &iattr); } } break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) { retval = acl ? -EINVAL : 0; goto err_out; } break; default: BUG(); } retval = v9fs_xattr_set(dentry, handler->name, value, size, flags); if (!retval) set_cached_acl(inode, handler->flags, acl); err_out: posix_acl_release(acl); return retval; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
1
166,966
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void LockContentsView::SetAvatarForUser(const AccountId& account_id, const mojom::UserAvatarPtr& avatar) { auto replace = [&](const mojom::LoginUserInfoPtr& user) { auto changed = user->Clone(); changed->basic_user_info->avatar = avatar->Clone(); return changed; }; LoginBigUserView* big = TryToFindBigUser(account_id, false /*require_auth_active*/); if (big) { big->UpdateForUser(replace(big->GetCurrentUser())); return; } LoginUserView* user = users_list_ ? users_list_->GetUserView(account_id) : nullptr; if (user) { user->UpdateForUser(replace(user->current_user()), false /*animate*/); return; } } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
0
131,538
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gfx::Point Textfield::GetLastClickLocation() const { return selection_controller_.last_click_location(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <mblsha@yandex-team.ru> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
0
126,332
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int64_t RenderWidgetHostImpl::GetLatencyComponentId() const { return latency_tracker_.latency_component_id(); } Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI BUG=590284 Review URL: https://codereview.chromium.org/1747183002 Cr-Commit-Position: refs/heads/master@{#378844} CWE ID:
0
130,956
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int buffer_get(void *data) { char c; buffer_data_t *stream = data; if(stream->pos >= stream->len) return EOF; c = stream->data[stream->pos]; stream->pos++; return (unsigned char)c; } Commit Message: Fix for issue #282 The fix limits recursion depths when parsing arrays and objects. The limit is configurable via the `JSON_PARSER_MAX_DEPTH` setting within `jansson_config.h` and is set by default to 2048. Update the RFC conformance document to note the limit; the RFC allows limits to be set by the implementation so nothing has actually changed w.r.t. conformance state. Reported by Gustavo Grieco. CWE ID: CWE-20
0
53,334
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: cf2_hint_initZero( CF2_Hint hint ) { FT_ZERO( hint ); } Commit Message: CWE ID: CWE-119
0
7,145
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void xmlCleanupGlobals(void) { if (xmlThrDefMutex != NULL) { xmlFreeMutex(xmlThrDefMutex); xmlThrDefMutex = NULL; } __xmlGlobalInitMutexDestroy(); } Commit Message: Attempt to address libxml crash. BUG=129930 Review URL: https://chromiumcodereview.appspot.com/10458051 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@142822 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
0
107,318
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: status_t FLACSource::read( MediaBuffer **outBuffer, const ReadOptions *options) { MediaBuffer *buffer; int64_t seekTimeUs; ReadOptions::SeekMode mode; if ((NULL != options) && options->getSeekTo(&seekTimeUs, &mode)) { FLAC__uint64 sample; if (seekTimeUs <= 0LL) { sample = 0LL; } else { sample = (seekTimeUs * mParser->getSampleRate()) / 1000000LL; if (sample >= mParser->getTotalSamples()) { sample = mParser->getTotalSamples(); } } buffer = mParser->readBuffer(sample); } else { buffer = mParser->readBuffer(); } *outBuffer = buffer; return buffer != NULL ? (status_t) OK : (status_t) ERROR_END_OF_STREAM; } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
0
162,523
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: RendererSchedulerImpl::GetSchedulerHelperForTesting() { return &helper_; } Commit Message: [scheduler] Remove implicit fallthrough in switch Bail out early when a condition in the switch is fulfilled. This does not change behaviour due to RemoveTaskObserver being no-op when the task observer is not present in the list. R=thakis@chromium.org Bug: 177475 Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd Reviewed-on: https://chromium-review.googlesource.com/891187 Reviewed-by: Nico Weber <thakis@chromium.org> Commit-Queue: Alexander Timin <altimin@chromium.org> Cr-Commit-Position: refs/heads/master@{#532649} CWE ID: CWE-119
0
143,412
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: iasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update) { struct sc_context *ctx = card->ctx; unsigned char scb; int rv; LOG_FUNC_CALLED(ctx); if (update->sdo_prv_key) { sc_log(ctx, "encode private rsa in %p", &update->update_prv); rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv); LOG_TEST_RET(ctx, rv, "failed to encode update of RSA private key"); } if (update->sdo_pub_key) { sc_log(ctx, "encode public rsa in %p", &update->update_pub); if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { if (update->sdo_pub_key->data.pub_key.cha.value) { free(update->sdo_pub_key->data.pub_key.cha.value); memset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha)); } } rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub); LOG_TEST_RET(ctx, rv, "failed to encode update of RSA public key"); } if (update->sdo_prv_key) { sc_log(ctx, "reference of the private key to store: %X", update->sdo_prv_key->sdo_ref); if (update->sdo_prv_key->docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "extremely strange ... there are no ACLs"); scb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA]; sc_log(ctx, "'UPDATE PRIVATE RSA' scb 0x%X", scb); do { unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; if ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions) break; if (scb & IASECC_SCB_METHOD_EXT_AUTH) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); if (scb & IASECC_SCB_METHOD_SM) { #ifdef ENABLE_SM rv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update); LOG_FUNC_RETURN(ctx, rv); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "built without support of Secure-Messaging"); #endif } } while(0); rv = iasecc_sdo_put_data(card, &update->update_prv); LOG_TEST_RET(ctx, rv, "failed to update of RSA private key"); } if (update->sdo_pub_key) { sc_log(ctx, "reference of the public key to store: %X", update->sdo_pub_key->sdo_ref); rv = iasecc_sdo_put_data(card, &update->update_pub); LOG_TEST_RET(ctx, rv, "failed to update of RSA public key"); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
78,515
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool TabsDetectLanguageFunction::RunAsync() { std::unique_ptr<tabs::DetectLanguage::Params> params( tabs::DetectLanguage::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = 0; Browser* browser = NULL; WebContents* contents = NULL; if (params->tab_id.get()) { tab_id = *params->tab_id; if (!GetTabById(tab_id, browser_context(), include_incognito(), &browser, nullptr, &contents, nullptr, &error_)) { return false; } if (!browser || !contents) return false; } else { browser = ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); if (!browser) return false; contents = browser->tab_strip_model()->GetActiveWebContents(); if (!contents) return false; } if (contents->GetController().NeedsReload()) { error_ = keys::kCannotDetermineLanguageOfUnloadedTab; return false; } AddRef(); // Balanced in GotLanguage(). ChromeTranslateClient* chrome_translate_client = ChromeTranslateClient::FromWebContents(contents); if (!chrome_translate_client->GetLanguageState() .original_language() .empty()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( &TabsDetectLanguageFunction::GotLanguage, this, chrome_translate_client->GetLanguageState().original_language())); return true; } registrar_.Add(this, chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, content::Source<WebContents>(contents)); registrar_.Add( this, chrome::NOTIFICATION_TAB_CLOSING, content::Source<NavigationController>(&(contents->GetController()))); registrar_.Add( this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<NavigationController>(&(contents->GetController()))); return true; } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Karan Bhatia <karandeepb@chromium.org> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20
0
155,674
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_MostVisitedURLsObserver_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); } Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer. BUG=677672 Review-Url: https://codereview.chromium.org/2697543002 Cr-Commit-Position: refs/heads/master@{#449958} CWE ID: CWE-17
1
172,034
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static uint16_t data_stream_element(NeAACDecStruct *hDecoder, bitfile *ld) { uint8_t byte_aligned; uint16_t i, count; /* element_instance_tag = */ faad_getbits(ld, LEN_TAG DEBUGVAR(1,60,"data_stream_element(): element_instance_tag")); byte_aligned = faad_get1bit(ld DEBUGVAR(1,61,"data_stream_element(): byte_aligned")); count = (uint16_t)faad_getbits(ld, 8 DEBUGVAR(1,62,"data_stream_element(): count")); if (count == 255) { count += (uint16_t)faad_getbits(ld, 8 DEBUGVAR(1,63,"data_stream_element(): extra count")); } if (byte_aligned) faad_byte_align(ld); for (i = 0; i < count; i++) { faad_getbits(ld, LEN_BYTE DEBUGVAR(1,64,"data_stream_element(): data_stream_byte")); } return count; } Commit Message: Fix a couple buffer overflows https://hackerone.com/reports/502816 https://hackerone.com/reports/507858 https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch CWE ID: CWE-119
0
88,373
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; } Commit Message: kexec/uefi: copy secure_boot flag in boot params across kexec reboot Kexec reboot in case secure boot being enabled does not keep the secure boot mode in new kernel, so later one can load unsigned kernel via legacy kexec_load. In this state, the system is missing the protections provided by secure boot. Adding a patch to fix this by retain the secure_boot flag in original kernel. secure_boot flag in boot_params is set in EFI stub, but kexec bypasses the stub. Fixing this issue by copying secure_boot flag across kexec reboot. Signed-off-by: Dave Young <dyoung@redhat.com> CWE ID: CWE-254
1
168,868
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void V8WindowShell::updateDocument() { ASSERT(m_world->isMainWorld()); if (m_global.isEmpty()) return; if (m_context.isEmpty()) return; updateDocumentProperty(); updateSecurityOrigin(); } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
110,441
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: dpbOutPicture_t* h264bsdDpbOutputPicture(dpbStorage_t *dpb) { /* Variables */ /* Code */ ASSERT(dpb); if (dpb->outIndex < dpb->numOut) return(dpb->outBuf + dpb->outIndex++); else return(NULL); } Commit Message: Fix potential overflow Bug: 28533562 Change-Id: I798ab24caa4c81f3ba564cad7c9ee019284fb702 CWE ID: CWE-119
0
159,582
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PanoramiXRenderTriFan(ClientPtr client) { PanoramiXRes *src, *dst; int result = Success, j; REQUEST(xRenderTriFanReq); char *extra; int extra_len; REQUEST_AT_LEAST_SIZE (xRenderTriFanReq); VERIFY_XIN_PICTURE (src, stuff->src, client, DixReadAccess); VERIFY_XIN_PICTURE (dst, stuff->dst, client, DixWriteAccess); extra_len = (client->req_len << 2) - sizeof (xRenderTriFanReq); if (extra_len && (extra = (char *) malloc(extra_len))) { memcpy (extra, stuff + 1, extra_len); FOR_NSCREENS_FORWARD(j) { if (j) memcpy (stuff + 1, extra, extra_len); if (dst->u.pict.root) { int x_off = screenInfo.screens[j]->x; int y_off = screenInfo.screens[j]->y; if(x_off || y_off) { xPointFixed *fixed = (xPointFixed *) (stuff + 1); int i = extra_len / sizeof (xPointFixed); while (i--) { fixed->x -= x_off; fixed->y -= y_off; fixed++; } } } stuff->src = src->info[j].id; stuff->dst = dst->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderTriFan]) (client); if(result != Success) break; } free(extra); } return result; } Commit Message: CWE ID: CWE-20
0
14,048
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool RenderThreadImpl::EnableStreamTextureCopy() { return sync_compositor_message_filter_.get(); } Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6 https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604 BUG=778101 Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c Reviewed-on: https://chromium-review.googlesource.com/747941 Reviewed-by: Avi Drissman <avi@chromium.org> Reviewed-by: David Benjamin <davidben@chromium.org> Commit-Queue: Steven Valdez <svaldez@chromium.org> Cr-Commit-Position: refs/heads/master@{#513774} CWE ID: CWE-310
0
150,506
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: e1000e_intrmgr_on_throttling_timer(void *opaque) { E1000IntrDelayTimer *timer = opaque; assert(!msix_enabled(timer->core->owner)); timer->running = false; if (!timer->core->itr_intr_pending) { trace_e1000e_irq_throttling_no_pending_interrupts(); return; } if (msi_enabled(timer->core->owner)) { trace_e1000e_irq_msi_notify_postponed(); e1000e_set_interrupt_cause(timer->core, 0); } else { trace_e1000e_irq_legacy_notify_postponed(); e1000e_set_interrupt_cause(timer->core, 0); } } Commit Message: CWE ID: CWE-835
0
5,987
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebContentsAndroid::HideTransitionElements(JNIEnv* env, jobject jobj, jstring css_selector) { web_contents_->GetMainFrame()->Send( new FrameMsg_HideTransitionElements( web_contents_->GetMainFrame()->GetRoutingID(), ConvertJavaStringToUTF8(env, css_selector))); } Commit Message: Revert "Load web contents after tab is created." This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d. BUG=432562 TBR=tedchoc@chromium.org,jbudorick@chromium.org,sky@chromium.org Review URL: https://codereview.chromium.org/894003005 Cr-Commit-Position: refs/heads/master@{#314469} CWE ID: CWE-399
0
109,885
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool omx_venc::dev_is_video_session_supported(OMX_U32 width, OMX_U32 height) { #ifdef _MSM8974_ return handle->venc_is_video_session_supported(width,height); #else DEBUG_PRINT_LOW("Check against video capability not supported"); return true; #endif } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
0
159,225
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebContentsImpl::SendUserGestureForResourceDispatchHost() { ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get(); if (rdh) rdh->OnUserGesture(); } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <arthursonzogni@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Mustaq Ahmed <mustaq@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Reviewed-by: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254
0
145,039
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void AudioMixerAlsa::ApplyState() { DCHECK(MessageLoop::current() == thread_->message_loop()); if (!alsa_mixer_) return; bool should_mute = false; double new_volume_db = 0; { base::AutoLock lock(lock_); should_mute = is_muted_; new_volume_db = should_mute ? min_volume_db_ : volume_db_; apply_is_pending_ = false; } if (pcm_element_) { SetElementVolume(master_element_, new_volume_db, 0.9999f); double pcm_volume_db = 0.0; double master_volume_db = 0.0; if (GetElementVolume(master_element_, &master_volume_db)) pcm_volume_db = new_volume_db - master_volume_db; SetElementVolume(pcm_element_, pcm_volume_db, 0.5f); } else { SetElementVolume(master_element_, new_volume_db, 0.5f); } SetElementMuted(master_element_, should_mute); } Commit Message: chromeos: Move audio, power, and UI files into subdirs. This moves more files from chrome/browser/chromeos/ into subdirectories. BUG=chromium-os:22896 TEST=did chrome os builds both with and without aura TBR=sky Review URL: http://codereview.chromium.org/9125006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
109,256
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void efx_start_channel(struct efx_channel *channel) { struct efx_rx_queue *rx_queue; netif_dbg(channel->efx, ifup, channel->efx->net_dev, "starting chan %d\n", channel->channel); /* The interrupt handler for this channel may set work_pending * as soon as we enable it. Make sure it's cleared before * then. Similarly, make sure it sees the enabled flag set. */ channel->work_pending = false; channel->enabled = true; smp_wmb(); /* Fill the queues before enabling NAPI */ efx_for_each_channel_rx_queue(rx_queue, channel) efx_fast_push_rx_descriptors(rx_queue); napi_enable(&channel->napi_str); } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <bhutchings@solarflare.com> Signed-off-by: David S. Miller <davem@davemloft.net> Signed-off-by: Ben Hutchings <ben@decadent.org.uk> CWE ID: CWE-189
0
19,435
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int nfs4_proc_lookup(struct inode *dir, struct qstr *name, struct nfs_fh *fhandle, struct nfs_fattr *fattr) { int status; struct rpc_clnt *client = NFS_CLIENT(dir); status = nfs4_proc_lookup_common(&client, dir, name, fhandle, fattr); if (client != NFS_CLIENT(dir)) { rpc_shutdown_client(client); nfs_fixup_secinfo_attributes(fattr); } return status; } Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in __nfs4_get_acl_uncached" accidently dropped the checking for too small result buffer length. If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount supporting ACLs, the ACL has not been cached and the buffer suplied is too short, we still copy the complete ACL, resulting in kernel and user space memory corruption. Signed-off-by: Sven Wegener <sven.wegener@stealer.net> Cc: stable@kernel.org Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-119
0
29,200
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void md_update_sb(struct mddev *mddev, int force_change) { struct md_rdev *rdev; int sync_req; int nospares = 0; int any_badblocks_changed = 0; if (mddev->ro) { if (force_change) set_bit(MD_CHANGE_DEVS, &mddev->flags); return; } repeat: /* First make sure individual recovery_offsets are correct */ rdev_for_each(rdev, mddev) { if (rdev->raid_disk >= 0 && mddev->delta_disks >= 0 && !test_bit(In_sync, &rdev->flags) && mddev->curr_resync_completed > rdev->recovery_offset) rdev->recovery_offset = mddev->curr_resync_completed; } if (!mddev->persistent) { clear_bit(MD_CHANGE_CLEAN, &mddev->flags); clear_bit(MD_CHANGE_DEVS, &mddev->flags); if (!mddev->external) { clear_bit(MD_CHANGE_PENDING, &mddev->flags); rdev_for_each(rdev, mddev) { if (rdev->badblocks.changed) { rdev->badblocks.changed = 0; md_ack_all_badblocks(&rdev->badblocks); md_error(mddev, rdev); } clear_bit(Blocked, &rdev->flags); clear_bit(BlockedBadBlocks, &rdev->flags); wake_up(&rdev->blocked_wait); } } wake_up(&mddev->sb_wait); return; } spin_lock(&mddev->lock); mddev->utime = get_seconds(); if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags)) force_change = 1; if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags)) /* just a clean<-> dirty transition, possibly leave spares alone, * though if events isn't the right even/odd, we will have to do * spares after all */ nospares = 1; if (force_change) nospares = 0; if (mddev->degraded) /* If the array is degraded, then skipping spares is both * dangerous and fairly pointless. * Dangerous because a device that was removed from the array * might have a event_count that still looks up-to-date, * so it can be re-added without a resync. * Pointless because if there are any spares to skip, * then a recovery will happen and soon that array won't * be degraded any more and the spare can go back to sleep then. */ nospares = 0; sync_req = mddev->in_sync; /* If this is just a dirty<->clean transition, and the array is clean * and 'events' is odd, we can roll back to the previous clean state */ if (nospares && (mddev->in_sync && mddev->recovery_cp == MaxSector) && mddev->can_decrease_events && mddev->events != 1) { mddev->events--; mddev->can_decrease_events = 0; } else { /* otherwise we have to go forward and ... */ mddev->events ++; mddev->can_decrease_events = nospares; } /* * This 64-bit counter should never wrap. * Either we are in around ~1 trillion A.C., assuming * 1 reboot per second, or we have a bug... */ WARN_ON(mddev->events == 0); rdev_for_each(rdev, mddev) { if (rdev->badblocks.changed) any_badblocks_changed++; if (test_bit(Faulty, &rdev->flags)) set_bit(FaultRecorded, &rdev->flags); } sync_sbs(mddev, nospares); spin_unlock(&mddev->lock); pr_debug("md: updating %s RAID superblock on device (in sync %d)\n", mdname(mddev), mddev->in_sync); bitmap_update_sb(mddev->bitmap); rdev_for_each(rdev, mddev) { char b[BDEVNAME_SIZE]; if (rdev->sb_loaded != 1) continue; /* no noise on spare devices */ if (!test_bit(Faulty, &rdev->flags)) { md_super_write(mddev,rdev, rdev->sb_start, rdev->sb_size, rdev->sb_page); pr_debug("md: (write) %s's sb offset: %llu\n", bdevname(rdev->bdev, b), (unsigned long long)rdev->sb_start); rdev->sb_events = mddev->events; if (rdev->badblocks.size) { md_super_write(mddev, rdev, rdev->badblocks.sector, rdev->badblocks.size << 9, rdev->bb_page); rdev->badblocks.size = 0; } } else pr_debug("md: %s (skipping faulty)\n", bdevname(rdev->bdev, b)); if (mddev->level == LEVEL_MULTIPATH) /* only need to write one superblock... */ break; } md_super_wait(mddev); /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */ spin_lock(&mddev->lock); if (mddev->in_sync != sync_req || test_bit(MD_CHANGE_DEVS, &mddev->flags)) { /* have to write it out again */ spin_unlock(&mddev->lock); goto repeat; } clear_bit(MD_CHANGE_PENDING, &mddev->flags); spin_unlock(&mddev->lock); wake_up(&mddev->sb_wait); if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) sysfs_notify(&mddev->kobj, NULL, "sync_completed"); rdev_for_each(rdev, mddev) { if (test_and_clear_bit(FaultRecorded, &rdev->flags)) clear_bit(Blocked, &rdev->flags); if (any_badblocks_changed) md_ack_all_badblocks(&rdev->badblocks); clear_bit(BlockedBadBlocks, &rdev->flags); wake_up(&rdev->blocked_wait); } } Commit Message: md: use kzalloc() when bitmap is disabled In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a mdu_bitmap_file_t called "file". 5769 file = kmalloc(sizeof(*file), GFP_NOIO); 5770 if (!file) 5771 return -ENOMEM; This structure is copied to user space at the end of the function. 5786 if (err == 0 && 5787 copy_to_user(arg, file, sizeof(*file))) 5788 err = -EFAULT But if bitmap is disabled only the first byte of "file" is initialized with zero, so it's possible to read some bytes (up to 4095) of kernel space memory from user space. This is an information leak. 5775 /* bitmap disabled, zero the first byte and copy out */ 5776 if (!mddev->bitmap_info.file) 5777 file->pathname[0] = '\0'; Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr> Signed-off-by: NeilBrown <neilb@suse.com> CWE ID: CWE-200
0
42,480
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int SeekHead::GetVoidElementCount() const { return m_void_element_count; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
0
160,821
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: CACHE_LIMITER_FUNC(private) /* {{{ */ { ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT"); CACHE_LIMITER(private_no_expire)(TSRMLS_C); } /* }}} */ Commit Message: CWE ID: CWE-416
0
9,576
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: IW_IMPL(int) iw_is_valid_density(double density_x, double density_y, int density_code) { if(density_x<0.0001 || density_y<0.0001) return 0; if(density_x>10000000.0 || density_y>10000000.0) return 0; if(density_x/10.0>density_y) return 0; if(density_y/10.0>density_x) return 0; if(density_code!=IW_DENSITY_UNITS_UNKNOWN && density_code!=IW_DENSITY_UNITS_PER_METER) return 0; return 1; } Commit Message: Double-check that the input image's density is valid Fixes a bug that could result in division by zero, at least for a JPEG source image. Fixes issues #19, #20 CWE ID: CWE-369
0
64,974
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int dw2102_serit_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], int num) { struct dvb_usb_device *d = i2c_get_adapdata(adap); u8 buf6[] = {0, 0, 0, 0, 0, 0, 0}; if (!d) return -ENODEV; if (mutex_lock_interruptible(&d->i2c_mutex) < 0) return -EAGAIN; switch (num) { case 2: /* read si2109 register by number */ buf6[0] = msg[0].addr << 1; buf6[1] = msg[0].len; buf6[2] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xc2, 0, 0, buf6, msg[0].len + 2, DW210X_WRITE_MSG); /* read si2109 register */ dw210x_op_rw(d->udev, 0xc3, 0xd0, 0, buf6, msg[1].len + 2, DW210X_READ_MSG); memcpy(msg[1].buf, buf6 + 2, msg[1].len); break; case 1: switch (msg[0].addr) { case 0x68: /* write to si2109 register */ buf6[0] = msg[0].addr << 1; buf6[1] = msg[0].len; memcpy(buf6 + 2, msg[0].buf, msg[0].len); dw210x_op_rw(d->udev, 0xc2, 0, 0, buf6, msg[0].len + 2, DW210X_WRITE_MSG); break; case(DW2102_RC_QUERY): dw210x_op_rw(d->udev, 0xb8, 0, 0, buf6, 2, DW210X_READ_MSG); msg[0].buf[0] = buf6[0]; msg[0].buf[1] = buf6[1]; break; case(DW2102_VOLTAGE_CTRL): buf6[0] = 0x30; buf6[1] = msg[0].buf[0]; dw210x_op_rw(d->udev, 0xb2, 0, 0, buf6, 2, DW210X_WRITE_MSG); break; } break; } mutex_unlock(&d->i2c_mutex); return num; } Commit Message: [media] dw2102: don't do DMA on stack On Kernel 4.9, WARNINGs about doing DMA on stack are hit at the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach(). Both were due to the use of buffers on the stack as parameters to dvb_usb_generic_rw() and the resulting attempt to do DMA with them. The device was non-functional as a result. So, switch this driver over to use a buffer within the device state structure, as has been done with other DVB-USB drivers. Tested with TechnoTrend TT-connect S2-4600. [mchehab@osg.samsung.com: fixed a warning at su3000_i2c_transfer() that state var were dereferenced before check 'd'] Signed-off-by: Jonathan McDowell <noodles@earth.li> Cc: <stable@vger.kernel.org> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com> CWE ID: CWE-119
0
66,763
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ofputil_decode_table_miss(ovs_be32 config_, enum ofp_version version) { uint32_t config = ntohl(config_); if (version == OFP11_VERSION || version == OFP12_VERSION) { switch (config & OFPTC11_TABLE_MISS_MASK) { case OFPTC11_TABLE_MISS_CONTROLLER: return OFPUTIL_TABLE_MISS_CONTROLLER; case OFPTC11_TABLE_MISS_CONTINUE: return OFPUTIL_TABLE_MISS_CONTINUE; case OFPTC11_TABLE_MISS_DROP: return OFPUTIL_TABLE_MISS_DROP; default: VLOG_WARN_RL(&bad_ofmsg_rl, "bad table miss config %d", config); return OFPUTIL_TABLE_MISS_CONTROLLER; } } else { return OFPUTIL_TABLE_MISS_DEFAULT; } } Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <blp@ovn.org> Reviewed-by: Yifeng Sun <pkusunyifeng@gmail.com> CWE ID: CWE-617
0
77,546
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ftp_mdtm(ftpbuf_t *ftp, const char *path) { time_t stamp; struct tm *gmt, tmbuf; struct tm tm; char *ptr; int n; if (ftp == NULL) { return -1; } if (!ftp_putcmd(ftp, "MDTM", path)) { return -1; } if (!ftp_getresp(ftp) || ftp->resp != 213) { return -1; } /* parse out the timestamp */ for (ptr = ftp->inbuf; *ptr && !isdigit(*ptr); ptr++); n = sscanf(ptr, "%4u%2u%2u%2u%2u%2u", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec); if (n != 6) { return -1; } tm.tm_year -= 1900; tm.tm_mon--; tm.tm_isdst = -1; /* figure out the GMT offset */ stamp = time(NULL); gmt = php_gmtime_r(&stamp, &tmbuf); if (!gmt) { return -1; } gmt->tm_isdst = -1; /* apply the GMT offset */ tm.tm_sec += stamp - mktime(gmt); tm.tm_isdst = gmt->tm_isdst; stamp = mktime(&tm); return stamp; } Commit Message: CWE ID: CWE-119
0
14,796
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int __release_reference_state(struct bpf_func_state *state, int ptr_id) { int i, last_idx; if (!ptr_id) return -EFAULT; last_idx = state->acquired_refs - 1; for (i = 0; i < state->acquired_refs; i++) { if (state->refs[i].id == ptr_id) { if (last_idx && i != last_idx) memcpy(&state->refs[i], &state->refs[last_idx], sizeof(*state->refs)); memset(&state->refs[last_idx], 0, sizeof(*state->refs)); state->acquired_refs--; return 0; } } return -EFAULT; } Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") took care of rejecting alu op on pointer when e.g. pointer came from two different map values with different map properties such as value size, Jann reported that a case was not covered yet when a given alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from different branches where we would incorrectly try to sanitize based on the pointer's limit. Catch this corner case and reject the program instead. Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Alexei Starovoitov <ast@kernel.org> Signed-off-by: Alexei Starovoitov <ast@kernel.org> CWE ID: CWE-189
0
91,392
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: dtdCreate(const XML_Memory_Handling_Suite *ms) { DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD)); if (p == NULL) return p; poolInit(&(p->pool), ms); poolInit(&(p->entityValuePool), ms); hashTableInit(&(p->generalEntities), ms); hashTableInit(&(p->elementTypes), ms); hashTableInit(&(p->attributeIds), ms); hashTableInit(&(p->prefixes), ms); #ifdef XML_DTD p->paramEntityRead = XML_FALSE; hashTableInit(&(p->paramEntities), ms); #endif /* XML_DTD */ p->defaultPrefix.name = NULL; p->defaultPrefix.binding = NULL; p->in_eldecl = XML_FALSE; p->scaffIndex = NULL; p->scaffold = NULL; p->scaffLevel = 0; p->scaffSize = 0; p->scaffCount = 0; p->contentStringLen = 0; p->keepProcessing = XML_TRUE; p->hasParamEntityRefs = XML_FALSE; p->standalone = XML_FALSE; return p; } Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186) CWE ID: CWE-611
0
92,314
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void MetricsWebContentsObserver::HandleFailedNavigationForTrackedLoad( content::NavigationHandle* navigation_handle, std::unique_ptr<PageLoadTracker> tracker) { const base::TimeTicks now = base::TimeTicks::Now(); tracker->FailedProvisionalLoad(navigation_handle, now); const net::Error error = navigation_handle->GetNetErrorCode(); const bool is_aborted_provisional_load = error == net::OK || error == net::ERR_ABORTED; tracker->NotifyPageEnd( is_aborted_provisional_load ? END_OTHER : END_PROVISIONAL_LOAD_FAILED, UserInitiatedInfo::NotUserInitiated(), now, true); if (is_aborted_provisional_load) aborted_provisional_loads_.push_back(std::move(tracker)); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <sullivan@chromium.org> Reviewed-by: Bryan McQuade <bmcquade@chromium.org> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79
0
140,139
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SelectionEditor::DidUpdateCharacterData(CharacterData* node, unsigned offset, unsigned old_length, unsigned new_length) { if (selection_.IsNone() || !node || !node->isConnected()) { DidFinishDOMMutation(); return; } const Position& new_base = UpdatePositionAfterAdoptingTextReplacement( selection_.base_, node, offset, old_length, new_length); const Position& new_extent = UpdatePositionAfterAdoptingTextReplacement( selection_.extent_, node, offset, old_length, new_length); DidFinishTextChange(new_base, new_extent); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
0
124,960
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Document::didRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = false; styleResolverChanged(RecalcStyleDeferred, AnalyzedStyleUpdate); executeScriptsWaitingForResourcesIfNeeded(); if (m_gotoAnchorNeededAfterStylesheetsLoad && view()) view()->scrollToFragment(m_url); } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none R=haraken@chromium.org, abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
0
102,692
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) { u64 runtime, delta, now; /* Use the start of this time slice to avoid calculations. */ now = p->se.exec_start; runtime = p->se.sum_exec_runtime; if (p->last_task_numa_placement) { delta = runtime - p->last_sum_exec_runtime; *period = now - p->last_task_numa_placement; } else { delta = p->se.avg.load_sum; *period = LOAD_AVG_MAX; } p->last_sum_exec_runtime = runtime; p->last_task_numa_placement = now; return delta; } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <xiexiuqi@huawei.com> Analyzed-by: Vincent Guittot <vincent.guittot@linaro.org> Reported-by: Zhipeng Xie <xiezhipeng1@huawei.com> Reported-by: Sargun Dhillon <sargun@sargun.me> Reported-by: Xie XiuQi <xiexiuqi@huawei.com> Tested-by: Zhipeng Xie <xiezhipeng1@huawei.com> Tested-by: Sargun Dhillon <sargun@sargun.me> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Vincent Guittot <vincent.guittot@linaro.org> Cc: <stable@vger.kernel.org> # v4.13+ Cc: Bin Li <huawei.libin@huawei.com> Cc: Mike Galbraith <efault@gmx.de> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Tejun Heo <tj@kernel.org> Cc: Thomas Gleixner <tglx@linutronix.de> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/1545879866-27809-1-git-send-email-xiexiuqi@huawei.com Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-400
0
92,619
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void voidMethodAttrArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodAttrArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
122,795
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: update_fragments(vpx_codec_alg_priv_t *ctx, const uint8_t *data, unsigned int data_sz, vpx_codec_err_t *res) { *res = VPX_CODEC_OK; if (ctx->fragments.count == 0) { /* New frame, reset fragment pointers and sizes */ memset((void*)ctx->fragments.ptrs, 0, sizeof(ctx->fragments.ptrs)); memset(ctx->fragments.sizes, 0, sizeof(ctx->fragments.sizes)); } if (ctx->fragments.enabled && !(data == NULL && data_sz == 0)) { /* Store a pointer to this fragment and return. We haven't * received the complete frame yet, so we will wait with decoding. */ ctx->fragments.ptrs[ctx->fragments.count] = data; ctx->fragments.sizes[ctx->fragments.count] = data_sz; ctx->fragments.count++; if (ctx->fragments.count > (1 << EIGHT_PARTITION) + 1) { ctx->fragments.count = 0; *res = VPX_CODEC_INVALID_PARAM; return -1; } return 0; } if (!ctx->fragments.enabled && (data == NULL && data_sz == 0)) { return 0; } if (!ctx->fragments.enabled) { ctx->fragments.ptrs[0] = data; ctx->fragments.sizes[0] = data_sz; ctx->fragments.count = 1; } return 1; } Commit Message: DO NOT MERGE | libvpx: Cherry-pick 0f42d1f from upstream Description from upstream: vp8: fix decoder crash with invalid leading keyframes decoding the same invalid keyframe twice would result in a crash as the second time through the decoder would be assumed to have been initialized as there was no resolution change. in this case the resolution was itself invalid (0x6), but vp8_peek_si() was only failing in the case of 0x0. invalid-vp80-00-comprehensive-018.ivf.2kf_0x6.ivf tests this case by duplicating the first keyframe and additionally adds a valid one to ensure decoding can resume without error. Bug: 30593765 Change-Id: I0de85f5a5eb5c0a5605230faf20c042b69aea507 (cherry picked from commit fc0466b695dce03e10390101844caa374848d903) (cherry picked from commit 1114575245cb9d2f108749f916c76549524f5136) CWE ID: CWE-20
0
157,768
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int efx_init_io(struct efx_nic *efx) { struct pci_dev *pci_dev = efx->pci_dev; dma_addr_t dma_mask = efx->type->max_dma_mask; int rc; netif_dbg(efx, probe, efx->net_dev, "initialising I/O\n"); rc = pci_enable_device(pci_dev); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to enable PCI device\n"); goto fail1; } pci_set_master(pci_dev); /* Set the PCI DMA mask. Try all possibilities from our * genuine mask down to 32 bits, because some architectures * (e.g. x86_64 with iommu_sac_force set) will allow 40 bit * masks event though they reject 46 bit masks. */ while (dma_mask > 0x7fffffffUL) { if (pci_dma_supported(pci_dev, dma_mask) && ((rc = pci_set_dma_mask(pci_dev, dma_mask)) == 0)) break; dma_mask >>= 1; } if (rc) { netif_err(efx, probe, efx->net_dev, "could not find a suitable DMA mask\n"); goto fail2; } netif_dbg(efx, probe, efx->net_dev, "using DMA mask %llx\n", (unsigned long long) dma_mask); rc = pci_set_consistent_dma_mask(pci_dev, dma_mask); if (rc) { /* pci_set_consistent_dma_mask() is not *allowed* to * fail with a mask that pci_set_dma_mask() accepted, * but just in case... */ netif_err(efx, probe, efx->net_dev, "failed to set consistent DMA mask\n"); goto fail2; } efx->membase_phys = pci_resource_start(efx->pci_dev, EFX_MEM_BAR); rc = pci_request_region(pci_dev, EFX_MEM_BAR, "sfc"); if (rc) { netif_err(efx, probe, efx->net_dev, "request for memory BAR failed\n"); rc = -EIO; goto fail3; } efx->membase = ioremap_nocache(efx->membase_phys, efx->type->mem_map_size); if (!efx->membase) { netif_err(efx, probe, efx->net_dev, "could not map memory BAR at %llx+%x\n", (unsigned long long)efx->membase_phys, efx->type->mem_map_size); rc = -ENOMEM; goto fail4; } netif_dbg(efx, probe, efx->net_dev, "memory BAR at %llx+%x (virtual %p)\n", (unsigned long long)efx->membase_phys, efx->type->mem_map_size, efx->membase); return 0; fail4: pci_release_region(efx->pci_dev, EFX_MEM_BAR); fail3: efx->membase_phys = 0; fail2: pci_disable_device(efx->pci_dev); fail1: return rc; } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <bhutchings@solarflare.com> Signed-off-by: David S. Miller <davem@davemloft.net> Signed-off-by: Ben Hutchings <ben@decadent.org.uk> CWE ID: CWE-189
0
19,378
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: const BoundNetLog& HttpProxyClientSocket::NetLog() const { return net_log_; } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19
0
129,335
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PHP_FUNCTION(pg_update) { zval *pgsql_link, *values, *ids; char *table; size_t table_len; zend_ulong option = PGSQL_DML_EXEC; PGconn *pg_link; zend_string *sql = NULL; int id = -1, argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rsaa|l", &pgsql_link, &table, &table_len, &values, &ids, &option) == FAILURE) { return; } if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) { php_error_docref(NULL, E_WARNING, "Invalid option is specified"); RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pg_link, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (php_pgsql_flush_query(pg_link)) { php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection"); } if (php_pgsql_update(pg_link, table, values, ids, option, &sql) == FAILURE) { RETURN_FALSE; } if (option & PGSQL_DML_STRING) { RETURN_STR(sql); } RETURN_TRUE; } Commit Message: CWE ID:
0
5,201
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void DocumentThreadableLoader::loadFallbackRequestForServiceWorker() { clearResource(); ResourceRequest fallbackRequest(m_fallbackRequestForServiceWorker); m_fallbackRequestForServiceWorker = ResourceRequest(); dispatchInitialRequest(fallbackRequest); } Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource() In loadRequest(), setResource() can call clear() synchronously: DocumentThreadableLoader::clear() DocumentThreadableLoader::handleError() Resource::didAddClient() RawResource::didAddClient() and thus |m_client| can be null while resource() isn't null after setResource(), causing crashes (Issue 595964). This CL checks whether |*this| is destructed and whether |m_client| is null after setResource(). BUG=595964 Review-Url: https://codereview.chromium.org/1902683002 Cr-Commit-Position: refs/heads/master@{#391001} CWE ID: CWE-189
0
119,493
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (size > 0) { if (size - 1 > LONG_MAX) { goto error; } if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
1
168,693
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Layer::RemoveAnimation(int animation_id) { layer_animation_controller_->RemoveAnimation(animation_id); SetNeedsCommit(); } Commit Message: Removed pinch viewport scroll offset distribution The associated change in Blink makes the pinch viewport a proper ScrollableArea meaning the normal path for synchronizing layer scroll offsets is used. This is a 2 sided patch, the other CL: https://codereview.chromium.org/199253002/ BUG=349941 Review URL: https://codereview.chromium.org/210543002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
111,876
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static EAS_RESULT PushcdlStack (EAS_U32 *pStack, EAS_INT *pStackPtr, EAS_U32 value) { /* stack overflow, return an error */ if (*pStackPtr >= CDL_STACK_SIZE) return EAS_ERROR_FILE_FORMAT; /* push the value onto the stack */ *pStackPtr = *pStackPtr + 1; pStack[*pStackPtr] = value; return EAS_SUCCESS; } Commit Message: DLS parser: fix wave pool size check. Bug: 21132860. Change-Id: I8ae872ea2cc2e8fec5fa0b7815f0b6b31ce744ff (cherry picked from commit 2d7f8e1be2241e48458f5d3cab5e90be2b07c699) CWE ID: CWE-189
0
157,532
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void DocumentLoader::UpdateForSameDocumentNavigation( const KURL& new_url, SameDocumentNavigationSource same_document_navigation_source, scoped_refptr<SerializedScriptValue> data, HistoryScrollRestorationType scroll_restoration_type, FrameLoadType type, Document* initiating_document) { if (type == kFrameLoadTypeStandard && initiating_document && !initiating_document->CanCreateHistoryEntry()) { type = kFrameLoadTypeReplaceCurrentItem; } KURL old_url = request_.Url(); original_request_.SetURL(new_url); request_.SetURL(new_url); SetReplacesCurrentHistoryItem(type != kFrameLoadTypeStandard); if (same_document_navigation_source == kSameDocumentNavigationHistoryApi) { request_.SetHTTPMethod(HTTPNames::GET); request_.SetHTTPBody(nullptr); } ClearRedirectChain(); if (is_client_redirect_) AppendRedirect(old_url); AppendRedirect(new_url); SetHistoryItemStateForCommit( history_item_.Get(), type, same_document_navigation_source == kSameDocumentNavigationHistoryApi ? HistoryNavigationType::kHistoryApi : HistoryNavigationType::kFragment); history_item_->SetDocumentState(frame_->GetDocument()->FormElementsState()); if (same_document_navigation_source == kSameDocumentNavigationHistoryApi) { history_item_->SetStateObject(std::move(data)); history_item_->SetScrollRestorationType(scroll_restoration_type); } HistoryCommitType commit_type = LoadTypeToCommitType(type); frame_->FrameScheduler()->DidCommitProvisionalLoad( commit_type == kHistoryInertCommit, type == kFrameLoadTypeReload, frame_->IsLocalRoot()); GetLocalFrameClient().DispatchDidNavigateWithinPage( history_item_.Get(), commit_type, initiating_document); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Nate Chapin <japhet@chromium.org> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362
0
125,771
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void AddClearBrowsingDataStrings(content::WebUIDataSource* html_source, Profile* profile) { int clear_cookies_summary_msg_id = IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC; #if defined(OS_CHROMEOS) if (AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile)) { clear_cookies_summary_msg_id = IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC_WITH_EXCEPTION; } #else // !defined(OS_CHROMEOS) if (signin::IsDiceEnabledForProfile(profile->GetPrefs())) { clear_cookies_summary_msg_id = IDS_SETTINGS_CLEAR_COOKIES_AND_SITE_DATA_SUMMARY_BASIC_WITH_EXCEPTION; } #endif LocalizedString localized_strings[] = { {"clearTimeRange", IDS_SETTINGS_CLEAR_PERIOD_TITLE}, {"clearBrowsingHistory", IDS_SETTINGS_CLEAR_BROWSING_HISTORY}, {"clearBrowsingHistorySummary", IDS_SETTINGS_CLEAR_BROWSING_HISTORY_SUMMARY}, {"clearDownloadHistory", IDS_SETTINGS_CLEAR_DOWNLOAD_HISTORY}, {"clearCache", IDS_SETTINGS_CLEAR_CACHE}, {"clearCookies", IDS_SETTINGS_CLEAR_COOKIES}, {"clearCookiesSummary", clear_cookies_summary_msg_id}, {"clearCookiesCounter", IDS_DEL_COOKIES_COUNTER}, {"clearCookiesFlash", IDS_SETTINGS_CLEAR_COOKIES_FLASH}, {"clearPasswords", IDS_SETTINGS_CLEAR_PASSWORDS}, {"clearFormData", IDS_SETTINGS_CLEAR_FORM_DATA}, {"clearHostedAppData", IDS_SETTINGS_CLEAR_HOSTED_APP_DATA}, {"clearMediaLicenses", IDS_SETTINGS_CLEAR_MEDIA_LICENSES}, {"clearPeriodHour", IDS_SETTINGS_CLEAR_PERIOD_HOUR}, {"clearPeriod24Hours", IDS_SETTINGS_CLEAR_PERIOD_24_HOURS}, {"clearPeriod7Days", IDS_SETTINGS_CLEAR_PERIOD_7_DAYS}, {"clearPeriod4Weeks", IDS_SETTINGS_CLEAR_PERIOD_FOUR_WEEKS}, {"clearPeriodEverything", IDS_SETTINGS_CLEAR_PERIOD_EVERYTHING}, {"historyDeletionDialogTitle", IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_TITLE}, {"historyDeletionDialogOK", IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_OK}, {"importantSitesSubtitleCookies", IDS_SETTINGS_IMPORTANT_SITES_SUBTITLE_COOKIES}, {"importantSitesSubtitleCookiesAndCache", IDS_SETTINGS_IMPORTANT_SITES_SUBTITLE_COOKIES_AND_CACHE}, {"importantSitesConfirm", IDS_SETTINGS_IMPORTANT_SITES_CONFIRM}, {"notificationWarning", IDS_SETTINGS_NOTIFICATION_WARNING}, }; html_source->AddString( "clearBrowsingHistorySummarySignedIn", l10n_util::GetStringFUTF16( IDS_SETTINGS_CLEAR_BROWSING_HISTORY_SUMMARY_SIGNED_IN, base::ASCIIToUTF16(chrome::kMyActivityUrlInClearBrowsingData))); html_source->AddString( "clearBrowsingHistorySummarySynced", l10n_util::GetStringFUTF16( IDS_SETTINGS_CLEAR_BROWSING_HISTORY_SUMMARY_SYNCED, base::ASCIIToUTF16(chrome::kMyActivityUrlInClearBrowsingData))); html_source->AddString( "historyDeletionDialogBody", l10n_util::GetStringFUTF16( IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE, l10n_util::GetStringUTF16( IDS_SETTINGS_CLEAR_DATA_MYACTIVITY_URL_IN_DIALOG))); AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); } Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles This change clarifies the wording around the password saving and autofill toggles. Bug: 822465 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670 Reviewed-on: https://chromium-review.googlesource.com/970541 Commit-Queue: Jan Wilken Dörrie <jdoerrie@chromium.org> Reviewed-by: Vaclav Brozek <vabr@chromium.org> Reviewed-by: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#544661} CWE ID: CWE-200
0
148,757
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: LayoutUnit RenderBlockFlow::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const { LayoutUnit left = offsetFromFloats; if (applyTextIndent && style()->isLeftToRightDirection()) left += textIndentOffset(); return left; } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. R=eseidel@chromium.org, esprehn@chromium.org, jchaffraix@chromium.org Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
116,326
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icclut8_t *lut8 = &attrval->data.lut8; int i; int j; int n; lut8->clut = 0; lut8->intabs = 0; lut8->intabsbuf = 0; lut8->outtabs = 0; lut8->outtabsbuf = 0; if (jas_stream_putc(out, lut8->numinchans) == EOF || jas_stream_putc(out, lut8->numoutchans) == EOF || jas_stream_putc(out, lut8->clutlen) == EOF || jas_stream_putc(out, 0) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccputsint32(out, lut8->e[i][j])) goto error; } } if (jas_iccputuint16(out, lut8->numintabents) || jas_iccputuint16(out, lut8->numouttabents)) goto error; n = lut8->numinchans * lut8->numintabents; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->intabsbuf[i])) goto error; } n = lut8->numoutchans * lut8->numouttabents; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->outtabsbuf[i])) goto error; } n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->clut[i])) goto error; } return 0; error: return -1; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
0
72,710
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ int i; pInfo->aFunc = sqlite3ArrayAllocate( db, pInfo->aFunc, sizeof(pInfo->aFunc[0]), &pInfo->nFunc, &i ); return i; } Commit Message: sqlite: backport bugfixes for dbfuzz2 Bug: 952406 Change-Id: Icbec429742048d6674828726c96d8e265c41b595 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152 Reviewed-by: Chris Mumford <cmumford@google.com> Commit-Queue: Darwin Huang <huangdarwin@chromium.org> Cr-Commit-Position: refs/heads/master@{#651030} CWE ID: CWE-190
0
151,625
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void remove_controlq_data(struct ports_device *portdev) { struct port_buffer *buf; unsigned int len; if (!use_multiport(portdev)) return; while ((buf = virtqueue_get_buf(portdev->c_ivq, &len))) free_buf(buf, true); while ((buf = virtqueue_detach_unused_buf(portdev->c_ivq))) free_buf(buf, true); } Commit Message: 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 <osandov@fb.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Amit Shah <amit.shah@redhat.com> CWE ID: CWE-119
0
66,613
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: const LayerTreeDebugState& LayerTreeHost::GetDebugState() const { return debug_state_; } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 TBR=danakj@chromium.org, creis@chromium.org CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362
0
137,111
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int php_zip_parse_options(zval *options, long *remove_all_path, char **remove_path, int *remove_path_len, char **add_path, int *add_path_len TSRMLS_DC) /* {{{ */ { zval **option; if (zend_hash_find(HASH_OF(options), "remove_all_path", sizeof("remove_all_path"), (void **)&option) == SUCCESS) { long opt; if (Z_TYPE_PP(option) != IS_LONG) { zval tmp = **option; zval_copy_ctor(&tmp); convert_to_long(&tmp); opt = Z_LVAL(tmp); } else { opt = Z_LVAL_PP(option); } *remove_all_path = opt; } /* If I add more options, it would make sense to create a nice static struct and loop over it. */ if (zend_hash_find(HASH_OF(options), "remove_path", sizeof("remove_path"), (void **)&option) == SUCCESS) { if (Z_TYPE_PP(option) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remove_path option expected to be a string"); return -1; } if (Z_STRLEN_PP(option) < 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Empty string given as remove_path option"); return -1; } if (Z_STRLEN_PP(option) >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remove_path string is too long (max: %i, %i given)", MAXPATHLEN - 1, Z_STRLEN_PP(option)); return -1; } *remove_path_len = Z_STRLEN_PP(option); *remove_path = Z_STRVAL_PP(option); } if (zend_hash_find(HASH_OF(options), "add_path", sizeof("add_path"), (void **)&option) == SUCCESS) { if (Z_TYPE_PP(option) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_path option expected to be a string"); return -1; } if (Z_STRLEN_PP(option) < 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Empty string given as the add_path option"); return -1; } if (Z_STRLEN_PP(option) >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_path string too long (max: %i, %i given)", MAXPATHLEN - 1, Z_STRLEN_PP(option)); return -1; } *add_path_len = Z_STRLEN_PP(option); *add_path = Z_STRVAL_PP(option); } return 1; } /* }}} */ Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize CWE ID: CWE-416
0
51,302
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg) { struct btrfs_fs_info *fs_info = btrfs_sb(fdentry(file)->d_sb); struct btrfs_device *device; struct request_queue *q; struct fstrim_range range; u64 minlen = ULLONG_MAX; u64 num_devices = 0; u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy); int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; rcu_read_lock(); list_for_each_entry_rcu(device, &fs_info->fs_devices->devices, dev_list) { if (!device->bdev) continue; q = bdev_get_queue(device->bdev); if (blk_queue_discard(q)) { num_devices++; minlen = min((u64)q->limits.discard_granularity, minlen); } } rcu_read_unlock(); if (!num_devices) return -EOPNOTSUPP; if (copy_from_user(&range, arg, sizeof(range))) return -EFAULT; if (range.start > total_bytes || range.len < fs_info->sb->s_blocksize) return -EINVAL; range.len = min(range.len, total_bytes - range.start); range.minlen = max(range.minlen, minlen); ret = btrfs_trim_fs(fs_info->tree_root, &range); if (ret < 0) return ret; if (copy_to_user(arg, &range, sizeof(range))) return -EFAULT; return 0; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <chris.mason@fusionio.com> Reported-by: Pascal Junod <pascal@junod.info> CWE ID: CWE-310
0
34,410
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: n_tty_receive_buf_closing(struct tty_struct *tty, const unsigned char *cp, char *fp, int count) { char flag = TTY_NORMAL; while (count--) { if (fp) flag = *fp++; if (likely(flag == TTY_NORMAL)) n_tty_receive_char_closing(tty, *cp++); else n_tty_receive_char_flagged(tty, *cp++, flag); } } Commit Message: n_tty: Fix n_tty_write crash when echoing in raw mode The tty atomic_write_lock does not provide an exclusion guarantee for the tty driver if the termios settings are LECHO & !OPOST. And since it is unexpected and not allowed to call TTY buffer helpers like tty_insert_flip_string concurrently, this may lead to crashes when concurrect writers call pty_write. In that case the following two writers: * the ECHOing from a workqueue and * pty_write from the process race and can overflow the corresponding TTY buffer like follows. If we look into tty_insert_flip_string_fixed_flag, there is: int space = __tty_buffer_request_room(port, goal, flags); struct tty_buffer *tb = port->buf.tail; ... memcpy(char_buf_ptr(tb, tb->used), chars, space); ... tb->used += space; so the race of the two can result in something like this: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM B's memcpy is past the tty_buffer due to the previous A's tb->used increment. Since the N_TTY line discipline input processing can output concurrently with a tty write, obtain the N_TTY ldisc output_lock to serialize echo output with normal tty writes. This ensures the tty buffer helper tty_insert_flip_string is not called concurrently and everything is fine. Note that this is nicely reproducible by an ordinary user using forkpty and some setup around that (raw termios + ECHO). And it is present in kernels at least after commit d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to use the normal buffering logic) in 2.6.31-rc3. js: add more info to the commit log js: switch to bool js: lock unconditionally js: lock only the tty->ops->write call References: CVE-2014-0196 Reported-and-tested-by: Jiri Slaby <jslaby@suse.cz> Signed-off-by: Peter Hurley <peter@hurleysoftware.com> Signed-off-by: Jiri Slaby <jslaby@suse.cz> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Alan Cox <alan@lxorguk.ukuu.org.uk> Cc: <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-362
0
39,813
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: u32 NextPacket(u8 **pStrm) { u32 index; u32 maxIndex; u32 zeroCount; u8 *stream; u8 byte; static u32 prevIndex=0; /* For default stream mode all the stream is in first packet */ if (!packetize && !nalUnitStream) return 0; index = 0; stream = *pStrm + prevIndex; maxIndex = (u32)(streamStop - stream); if (maxIndex == 0) return(0); /* leading zeros of first NAL unit */ do { byte = stream[index++]; } while (byte != 1 && index < maxIndex); /* invalid start code prefix */ if (index == maxIndex || index < 3) { DEBUG(("INVALID BYTE STREAM\n")); exit(100); } /* nalUnitStream is without start code prefix */ if (nalUnitStream) { stream += index; maxIndex -= index; index = 0; } zeroCount = 0; /* Search stream for next start code prefix */ /*lint -e(716) while(1) used consciously */ while (1) { byte = stream[index++]; if (!byte) zeroCount++; if ( (byte == 0x01) && (zeroCount >= 2) ) { /* Start code prefix has two zeros * Third zero is assumed to be leading zero of next packet * Fourth and more zeros are assumed to be trailing zeros of this * packet */ if (zeroCount > 3) { index -= 4; zeroCount -= 3; } else { index -= zeroCount+1; zeroCount = 0; } break; } else if (byte) zeroCount = 0; if (index == maxIndex) { break; } } /* Store pointer to the beginning of the packet */ *pStrm = stream; prevIndex = index; /* nalUnitStream is without trailing zeros */ if (nalUnitStream) index -= zeroCount; return(index); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
0
160,873
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int drm_mode_group_init_legacy_group(struct drm_device *dev, struct drm_mode_group *group) { struct drm_crtc *crtc; struct drm_encoder *encoder; struct drm_connector *connector; int ret; if ((ret = drm_mode_group_init(dev, group))) return ret; list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) group->id_list[group->num_crtcs++] = crtc->base.id; list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) group->id_list[group->num_crtcs + group->num_encoders++] = encoder->base.id; list_for_each_entry(connector, &dev->mode_config.connector_list, head) group->id_list[group->num_crtcs + group->num_encoders + group->num_connectors++] = connector->base.id; return 0; } Commit Message: drm: integer overflow in drm_mode_dirtyfb_ioctl() There is a potential integer overflow in drm_mode_dirtyfb_ioctl() if userspace passes in a large num_clips. The call to kmalloc would allocate a small buffer, and the call to fb->funcs->dirty may result in a memory corruption. Reported-by: Haogang Chen <haogangchen@gmail.com> Signed-off-by: Xi Wang <xi.wang@gmail.com> Cc: stable@kernel.org Signed-off-by: Dave Airlie <airlied@redhat.com> CWE ID: CWE-189
0
21,910
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static char *swiftField(const char *dn, const char *cn) { char *p = strstr (dn, ".getter_"); if (!p) { p = strstr (dn, ".setter_"); if (!p) { p = strstr (dn, ".method_"); } } if (p) { char *q = strstr (dn, cn); if (q && q[strlen (cn)] == '.') { q = strdup (q + strlen (cn) + 1); char *r = strchr (q, '.'); if (r) { *r = 0; } return q; } } return NULL; } Commit Message: Fix #9902 - Fix oobread in RBin.string_scan_range CWE ID: CWE-125
0
82,822
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: has_invalid_xml_char (char *str) { gunichar c; while (*str != 0) { c = g_utf8_get_char (str); /* characters XML permits */ if (!(c == 0x9 || c == 0xA || c == 0xD || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) || (c >= 0x10000 && c <= 0x10FFFF))) { return TRUE; } str = g_utf8_next_char (str); } return FALSE; } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
0
61,079
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: choose_comp(struct sshcomp *comp, char *client, char *server) { char *name = match_list(client, server, NULL); if (name == NULL) return SSH_ERR_NO_COMPRESS_ALG_MATCH; if (strcmp(name, "zlib@openssh.com") == 0) { comp->type = COMP_DELAYED; } else if (strcmp(name, "zlib") == 0) { comp->type = COMP_ZLIB; } else if (strcmp(name, "none") == 0) { comp->type = COMP_NONE; } else { return SSH_ERR_INTERNAL_ERROR; } comp->name = name; return 0; } Commit Message: CWE ID: CWE-476
0
17,941
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: pkinit_server_plugin_init_realm(krb5_context context, const char *realmname, pkinit_kdc_context *pplgctx) { krb5_error_code retval = ENOMEM; pkinit_kdc_context plgctx = NULL; *pplgctx = NULL; plgctx = calloc(1, sizeof(*plgctx)); if (plgctx == NULL) goto errout; pkiDebug("%s: initializing context at %p for realm '%s'\n", __FUNCTION__, plgctx, realmname); memset(plgctx, 0, sizeof(*plgctx)); plgctx->magic = PKINIT_CTX_MAGIC; plgctx->realmname = strdup(realmname); if (plgctx->realmname == NULL) goto errout; plgctx->realmname_len = strlen(plgctx->realmname); retval = pkinit_init_plg_crypto(&plgctx->cryptoctx); if (retval) goto errout; retval = pkinit_init_plg_opts(&plgctx->opts); if (retval) goto errout; retval = pkinit_init_identity_crypto(&plgctx->idctx); if (retval) goto errout; retval = pkinit_init_identity_opts(&plgctx->idopts); if (retval) goto errout; retval = pkinit_init_kdc_profile(context, plgctx); if (retval) goto errout; retval = pkinit_identity_initialize(context, plgctx->cryptoctx, NULL, plgctx->idopts, plgctx->idctx, 0, NULL); if (retval) goto errout; pkiDebug("%s: returning context at %p for realm '%s'\n", __FUNCTION__, plgctx, realmname); *pplgctx = plgctx; retval = 0; errout: if (retval) pkinit_server_plugin_fini_realm(context, plgctx); return retval; } Commit Message: PKINIT (draft9) null ptr deref [CVE-2012-1016] Don't check for an agility KDF identifier in the non-draft9 reply structure when we're building a draft9 reply, because it'll be NULL. The KDC plugin for PKINIT can dereference a null pointer when handling a draft9 request, leading to a crash of the KDC process. An attacker would need to have a valid PKINIT certificate, or an unauthenticated attacker could execute the attack if anonymous PKINIT is enabled. CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:P/RL:O/RC:C [tlyu@mit.edu: reformat comment and edit log message] (back ported from commit cd5ff932c9d1439c961b0cf9ccff979356686aff) ticket: 7527 (new) version_fixed: 1.10.4 status: resolved CWE ID:
0
34,596
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebPagePrivate::notifyPopupAutofillDialog(const Vector<String>& candidates) { vector<BlackBerry::Platform::String> textItems; for (size_t i = 0; i < candidates.size(); i++) textItems.push_back(candidates[i]); m_client->notifyPopupAutofillDialog(textItems); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
104,306
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: RenderProcessHostWatcher::RenderProcessHostWatcher( RenderProcessHost* render_process_host, WatchType type) : render_process_host_(render_process_host), type_(type), did_exit_normally_(true), message_loop_runner_(new MessageLoopRunner) { render_process_host_->AddObserver(this); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Nick Carter <nick@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#553867} CWE ID: CWE-20
0
156,133
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void AppendMostVisitedURLWithRedirect(const GURL& redirect_source, const GURL& redirect_dest, std::vector<MostVisitedURL>* list) { MostVisitedURL mv; mv.url = redirect_dest; mv.redirects.push_back(redirect_source); mv.redirects.push_back(redirect_dest); list->push_back(mv); } Commit Message: TopSites: Clear thumbnails from the cache when their URLs get removed We already cleared the thumbnails from persistent storage, but they remained in the in-memory cache, so they remained accessible (until the next Chrome restart) even after all browsing data was cleared. Bug: 758169 Change-Id: Id916d22358430a82e6d5043ac04fa463a32f824f Reviewed-on: https://chromium-review.googlesource.com/758640 Commit-Queue: Marc Treib <treib@chromium.org> Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Cr-Commit-Position: refs/heads/master@{#514861} CWE ID: CWE-200
0
147,106
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static Image *ReadSCRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char zxscr[6144]; char zxattr[768]; int octetnr; int octetline; int zoneline; int zonenr; int octet_val; int attr_nr; int pix; int piy; int binar[8]; int attrbin[8]; int *pbin; int *abin; int z; int one_nr; int ink; int paper; int bright; unsigned char colour_palette[] = { 0, 0, 0, 0, 0,192, 192, 0, 0, 192, 0,192, 0,192, 0, 0,192,192, 192,192, 0, 192,192,192, 0, 0, 0, 0, 0,255, 255, 0, 0, 255, 0,255, 0,255, 0, 0,255,255, 255,255, 0, 255,255,255 }; Image *image; MagickBooleanType status; register PixelPacket *q; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns = 256; image->rows = 192; count=ReadBlob(image,6144,(unsigned char *) zxscr); (void) count; count=ReadBlob(image,768,(unsigned char *) zxattr); for(zonenr=0;zonenr<3;zonenr++) { for(zoneline=0;zoneline<8;zoneline++) { for(octetline=0;octetline<8;octetline++) { for(octetnr=(zoneline*32);octetnr<((zoneline*32)+32);octetnr++) { octet_val = zxscr[octetnr+(256*octetline)+(zonenr*2048)]; attr_nr = zxattr[octetnr+(256*zonenr)]; pix = (((8*octetnr)-(256*zoneline))); piy = ((octetline+(8*zoneline)+(zonenr*64))); pbin = binar; abin = attrbin; one_nr=1; for(z=0;z<8;z++) { if(octet_val&one_nr) { *pbin = 1; } else { *pbin = 0; } one_nr=one_nr*2; pbin++; } one_nr = 1; for(z=0;z<8;z++) { if(attr_nr&one_nr) { *abin = 1; } else { *abin = 0; } one_nr=one_nr*2; abin++; } ink = (attrbin[0]+(2*attrbin[1])+(4*attrbin[2])); paper = (attrbin[3]+(2*attrbin[4])+(4*attrbin[5])); bright = attrbin[6]; if(bright) { ink=ink+8; paper=paper+8; } for(z=7;z>-1;z--) { q=QueueAuthenticPixels(image,pix,piy,1,1,exception); if (q == (PixelPacket *) NULL) break; if(binar[z]) { SetPixelRed(q,ScaleCharToQuantum( colour_palette[3*ink])); SetPixelGreen(q,ScaleCharToQuantum( colour_palette[1+(3*ink)])); SetPixelBlue(q,ScaleCharToQuantum( colour_palette[2+(3*ink)])); } else { SetPixelRed(q,ScaleCharToQuantum( colour_palette[3*paper])); SetPixelGreen(q,ScaleCharToQuantum( colour_palette[1+(3*paper)])); SetPixelBlue(q,ScaleCharToQuantum( colour_palette[2+(3*paper)])); } pix++; } } } } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
1
168,601
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int cxusb_fmd1216me_tuner_attach(struct dvb_usb_adapter *adap) { dvb_attach(simple_tuner_attach, adap->fe_adap[0].fe, &adap->dev->i2c_adap, 0x61, TUNER_PHILIPS_FMD1216ME_MK3); return 0; } Commit Message: [media] cxusb: Use a dma capable buffer also for reading Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack") added a kmalloc'ed bounce buffer for writes, but missed to do the same for reads. As the read only happens after the write is finished, we can reuse the same buffer. As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling it using the dvb_usb_generic_read wrapper function. Signed-off-by: Stefan Brüns <stefan.bruens@rwth-aachen.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com> CWE ID: CWE-119
0
66,731
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: CloudPolicySubsystem::ObserverRegistrar::~ObserverRegistrar() { if (policy_notifier_) policy_notifier_->RemoveObserver(observer_); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
97,783
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: double HTMLMediaElement::playbackRate() const { return m_playbackRate; } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} CWE ID: CWE-119
0
128,863
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PendingConfigureDataTypesState() : deleted_type(false), reason(sync_api::CONFIGURE_REASON_UNKNOWN) {} Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed. BUG=69561 TEST=Run sync manually and run integration tests, sync should not crash. Review URL: http://codereview.chromium.org/7016007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
101,470
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->ops->get_func_proto) fn = env->ops->get_func_proto(func_id, env->prog); if (!fn) { verbose(env, "unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); return -EINVAL; } /* With LD_ABS/IND some JITs save/restore skb from r1. */ changes_data = bpf_helper_changes_pkt_data(fn->func); if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", func_id_name(func_id), func_id); return -EINVAL; } memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; err = check_func_proto(fn); if (err) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; err = record_func_map(env, &meta, func_id, insn_idx); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1, false); if (err) return err; } regs = cur_regs(env); /* check that flags argument in get_local_storage(map, flags) is 0, * this is required because get_local_storage() can't return an error. */ if (func_id == BPF_FUNC_get_local_storage && !register_is_null(&regs[BPF_REG_2])) { verbose(env, "get_local_storage() doesn't support non-zero flags\n"); return -EINVAL; } /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* update return register (already marked as written above) */ if (fn->ret_type == RET_INTEGER) { /* sets type to SCALAR_VALUE */ mark_reg_unknown(env, regs, BPF_REG_0); } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || fn->ret_type == RET_PTR_TO_MAP_VALUE) { if (fn->ret_type == RET_PTR_TO_MAP_VALUE) regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; else regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* There is no offset yet applied, variable or fixed */ mark_reg_known_zero(env, regs, BPF_REG_0); regs[BPF_REG_0].off = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose(env, "kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; } else { verbose(env, "unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } do_refine_retval_range(regs, fn->ret_type, func_id, &meta); err = check_map_func_compatibility(env, meta.map_ptr, func_id); if (err) return err; if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) { const char *err_str; #ifdef CONFIG_PERF_EVENTS err = get_callchain_buffers(sysctl_perf_event_max_stack); err_str = "cannot get callchain buffer for func %s#%d\n"; #else err = -ENOTSUPP; err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; #endif if (err) { verbose(env, err_str, func_id_name(func_id), func_id); return err; } env->prog->has_callchain_buf = true; } if (changes_data) clear_all_pkt_pointers(env); return 0; } Commit Message: bpf: 32-bit RSH verification must truncate input before the ALU op When I wrote commit 468f6eafa6c4 ("bpf: fix 32-bit ALU op verification"), I assumed that, in order to emulate 64-bit arithmetic with 32-bit logic, it is sufficient to just truncate the output to 32 bits; and so I just moved the register size coercion that used to be at the start of the function to the end of the function. That assumption is true for almost every op, but not for 32-bit right shifts, because those can propagate information towards the least significant bit. Fix it by always truncating inputs for 32-bit ops to 32 bits. Also get rid of the coerce_reg_to_size() after the ALU op, since that has no effect. Fixes: 468f6eafa6c4 ("bpf: fix 32-bit ALU op verification") Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> CWE ID: CWE-125
0
76,373
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: status_t SoftMPEG2::resetDecoder() { ivd_ctl_reset_ip_t s_ctl_ip; ivd_ctl_reset_op_t s_ctl_op; IV_API_CALL_STATUS_T status; s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL; s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_RESET; s_ctl_ip.u4_size = sizeof(ivd_ctl_reset_ip_t); s_ctl_op.u4_size = sizeof(ivd_ctl_reset_op_t); status = ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op); if (IV_SUCCESS != status) { ALOGE("Error in reset: 0x%x", s_ctl_op.u4_error_code); return UNKNOWN_ERROR; } /* Set the run-time (dynamic) parameters */ setParams(outputBufferWidth()); /* Set number of cores/threads to be used by the codec */ setNumCores(); return OK; } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20
0
163,909
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool SVGElement::InstanceUpdatesBlocked() const { return HasSVGRareData() && SvgRareData()->InstanceUpdatesBlocked(); } Commit Message: Fix SVG crash for v0 distribution into foreignObject. We require a parent element to be an SVG element for non-svg-root elements in order to create a LayoutObject for them. However, we checked the light tree parent element, not the flat tree one which is the parent for the layout tree construction. Note that this is just an issue in Shadow DOM v0 since v1 does not allow shadow roots on SVG elements. Bug: 915469 Change-Id: Id81843abad08814fae747b5bc81c09666583f130 Reviewed-on: https://chromium-review.googlesource.com/c/1382494 Reviewed-by: Fredrik Söderquist <fs@opera.com> Commit-Queue: Rune Lillesveen <futhark@chromium.org> Cr-Commit-Position: refs/heads/master@{#617487} CWE ID: CWE-704
0
152,768
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Xcalloc(unsigned long amount) { return calloc(1, amount); } Commit Message: CWE ID: CWE-362
0
13,373
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void DetectRunPostRules( ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow, DetectRunScratchpad *scratch) { /* see if we need to increment the inspect_id and reset the de_state */ if (pflow && pflow->alstate && AppLayerParserProtocolSupportsTxs(p->proto, scratch->alproto)) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_TX_UPDATE); DeStateUpdateInspectTransactionId(pflow, scratch->flow_flags, (scratch->sgh == NULL)); PACKET_PROFILING_DETECT_END(p, PROF_DETECT_TX_UPDATE); } /* so now let's iterate the alerts and remove the ones after a pass rule * matched (if any). This is done inside PacketAlertFinalize() */ /* PR: installed "tag" keywords are handled after the threshold inspection */ PACKET_PROFILING_DETECT_START(p, PROF_DETECT_ALERT); PacketAlertFinalize(de_ctx, det_ctx, p); if (p->alerts.cnt > 0) { StatsAddUI64(tv, det_ctx->counter_alerts, (uint64_t)p->alerts.cnt); } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_ALERT); } Commit Message: stream: still inspect packets dropped by stream The detect engine would bypass packets that are set as dropped. This seems sane, as these packets are going to be dropped anyway. However, it lead to the following corner case: stream events that triggered the drop could not be matched on the rules. The packet with the event wouldn't make it to the detect engine due to the bypass. This patch changes the logic to not bypass DROP packets anymore. Packets that are dropped by the stream engine will set the no payload inspection flag, so avoid needless cost. CWE ID: CWE-693
0
84,294
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PHP_FUNCTION(snmpwalk) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_1); } Commit Message: CWE ID: CWE-416
0
9,516
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: wait_for_response(struct TCP_Server_Info *server, struct mid_q_entry *midQ) { int error; error = wait_event_freezekillable(server->response_q, midQ->mid_state != MID_REQUEST_SUBMITTED); if (error < 0) return -ERESTARTSYS; return 0; } Commit Message: cifs: move check for NULL socket into smb_send_rqst Cai reported this oops: [90701.616664] BUG: unable to handle kernel NULL pointer dereference at 0000000000000028 [90701.625438] IP: [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60 [90701.632167] PGD fea319067 PUD 103fda4067 PMD 0 [90701.637255] Oops: 0000 [#1] SMP [90701.640878] Modules linked in: des_generic md4 nls_utf8 cifs dns_resolver binfmt_misc tun sg igb iTCO_wdt iTCO_vendor_support lpc_ich pcspkr i2c_i801 i2c_core i7core_edac edac_core ioatdma dca mfd_core coretemp kvm_intel kvm crc32c_intel microcode sr_mod cdrom ata_generic sd_mod pata_acpi crc_t10dif ata_piix libata megaraid_sas dm_mirror dm_region_hash dm_log dm_mod [90701.677655] CPU 10 [90701.679808] Pid: 9627, comm: ls Tainted: G W 3.7.1+ #10 QCI QSSC-S4R/QSSC-S4R [90701.688950] RIP: 0010:[<ffffffff814a343e>] [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60 [90701.698383] RSP: 0018:ffff88177b431bb8 EFLAGS: 00010206 [90701.704309] RAX: ffff88177b431fd8 RBX: 00007ffffffff000 RCX: ffff88177b431bec [90701.712271] RDX: 0000000000000003 RSI: 0000000000000006 RDI: 0000000000000000 [90701.720223] RBP: ffff88177b431bc8 R08: 0000000000000004 R09: 0000000000000000 [90701.728185] R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000001 [90701.736147] R13: ffff88184ef92000 R14: 0000000000000023 R15: ffff88177b431c88 [90701.744109] FS: 00007fd56a1a47c0(0000) GS:ffff88105fc40000(0000) knlGS:0000000000000000 [90701.753137] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b [90701.759550] CR2: 0000000000000028 CR3: 000000104f15f000 CR4: 00000000000007e0 [90701.767512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [90701.775465] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 [90701.783428] Process ls (pid: 9627, threadinfo ffff88177b430000, task ffff88185ca4cb60) [90701.792261] Stack: [90701.794505] 0000000000000023 ffff88177b431c50 ffff88177b431c38 ffffffffa014fcb1 [90701.802809] ffff88184ef921bc 0000000000000000 00000001ffffffff ffff88184ef921c0 [90701.811123] ffff88177b431c08 ffffffff815ca3d9 ffff88177b431c18 ffff880857758000 [90701.819433] Call Trace: [90701.822183] [<ffffffffa014fcb1>] smb_send_rqst+0x71/0x1f0 [cifs] [90701.828991] [<ffffffff815ca3d9>] ? schedule+0x29/0x70 [90701.834736] [<ffffffffa014fe6d>] smb_sendv+0x3d/0x40 [cifs] [90701.841062] [<ffffffffa014fe96>] smb_send+0x26/0x30 [cifs] [90701.847291] [<ffffffffa015801f>] send_nt_cancel+0x6f/0xd0 [cifs] [90701.854102] [<ffffffffa015075e>] SendReceive+0x18e/0x360 [cifs] [90701.860814] [<ffffffffa0134a78>] CIFSFindFirst+0x1a8/0x3f0 [cifs] [90701.867724] [<ffffffffa013f731>] ? build_path_from_dentry+0xf1/0x260 [cifs] [90701.875601] [<ffffffffa013f731>] ? build_path_from_dentry+0xf1/0x260 [cifs] [90701.883477] [<ffffffffa01578e6>] cifs_query_dir_first+0x26/0x30 [cifs] [90701.890869] [<ffffffffa015480d>] initiate_cifs_search+0xed/0x250 [cifs] [90701.898354] [<ffffffff81195970>] ? fillonedir+0x100/0x100 [90701.904486] [<ffffffffa01554cb>] cifs_readdir+0x45b/0x8f0 [cifs] [90701.911288] [<ffffffff81195970>] ? fillonedir+0x100/0x100 [90701.917410] [<ffffffff81195970>] ? fillonedir+0x100/0x100 [90701.923533] [<ffffffff81195970>] ? fillonedir+0x100/0x100 [90701.929657] [<ffffffff81195848>] vfs_readdir+0xb8/0xe0 [90701.935490] [<ffffffff81195b9f>] sys_getdents+0x8f/0x110 [90701.941521] [<ffffffff815d3b99>] system_call_fastpath+0x16/0x1b [90701.948222] Code: 66 90 55 65 48 8b 04 25 f0 c6 00 00 48 89 e5 53 48 83 ec 08 83 fe 01 48 8b 98 48 e0 ff ff 48 c7 80 48 e0 ff ff ff ff ff ff 74 22 <48> 8b 47 28 ff 50 68 65 48 8b 14 25 f0 c6 00 00 48 89 9a 48 e0 [90701.970313] RIP [<ffffffff814a343e>] kernel_setsockopt+0x2e/0x60 [90701.977125] RSP <ffff88177b431bb8> [90701.981018] CR2: 0000000000000028 [90701.984809] ---[ end trace 24bd602971110a43 ]--- This is likely due to a race vs. a reconnection event. The current code checks for a NULL socket in smb_send_kvec, but that's too late. By the time that check is done, the socket will already have been passed to kernel_setsockopt. Move the check into smb_send_rqst, so that it's checked earlier. In truth, this is a bit of a half-assed fix. The -ENOTSOCK error return here looks like it could bubble back up to userspace. The locking rules around the ssocket pointer are really unclear as well. There are cases where the ssocket pointer is changed without holding the srv_mutex, but I'm not clear whether there's a potential race here yet or not. This code seems like it could benefit from some fundamental re-think of how the socket handling should behave. Until then though, this patch should at least fix the above oops in most cases. Cc: <stable@vger.kernel.org> # 3.7+ Reported-and-Tested-by: CAI Qian <caiqian@redhat.com> Signed-off-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Steve French <smfrench@gmail.com> CWE ID: CWE-362
0
30,098
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void f2fs_enable_quota_files(struct f2fs_sb_info *sbi) { int i, ret; for (i = 0; i < MAXQUOTAS; i++) { if (sbi->s_qf_names[i]) { ret = f2fs_quota_on_mount(sbi, i); if (ret < 0) f2fs_msg(sbi->sb, KERN_ERR, "Cannot turn on journaled " "quota: error %d", ret); } } } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <qkrwngud825@gmail.com> Signed-off-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-20
0
86,041