CVE ID
stringlengths
13
43
CVE Page
stringlengths
45
48
CWE ID
stringclasses
90 values
codeLink
stringlengths
46
139
commit_id
stringlengths
6
81
commit_message
stringlengths
3
13.3k
func_after
stringlengths
14
241k
func_before
stringlengths
14
241k
lang
stringclasses
3 values
project
stringclasses
309 values
vul
int8
0
1
CVE-2011-1479
https://www.cvedetails.com/cve/CVE-2011-1479/
CWE-399
https://github.com/torvalds/linux/commit/d0de4dc584ec6aa3b26fffea320a8457827768fc
d0de4dc584ec6aa3b26fffea320a8457827768fc
inotify: fix double free/corruption of stuct user On an error path in inotify_init1 a normal user can trigger a double free of struct user. This is a regression introduced by a2ae4cc9a16e ("inotify: stop kernel memory leak on file creation failure"). We fix this by making sure that if a group exists the user reference is dropped when the group is cleaned up. We should not explictly drop the reference on error and also drop the reference when the group is cleaned up. The new lifetime rules are that an inotify group lives from inotify_new_group to the last fsnotify_put_group. Since the struct user and inotify_devs are directly tied to this lifetime they are only changed/updated in those two locations. We get rid of all special casing of struct user or user->inotify_devs. Signed-off-by: Eric Paris <eparis@redhat.com> Cc: stable@kernel.org (2.6.37 and up) Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
static int inotify_release(struct inode *ignored, struct file *file) { struct fsnotify_group *group = file->private_data; pr_debug("%s: group=%p\n", __func__, group); fsnotify_clear_marks_by_group(group); /* free this group, matching get was inotify_init->fsnotify_obtain_group */ fsnotify_put_group(group); return 0; }
static int inotify_release(struct inode *ignored, struct file *file) { struct fsnotify_group *group = file->private_data; struct user_struct *user = group->inotify_data.user; pr_debug("%s: group=%p\n", __func__, group); fsnotify_clear_marks_by_group(group); /* free this group, matching get was inotify_init->fsnotify_obtain_group */ fsnotify_put_group(group); atomic_dec(&user->inotify_devs); return 0; }
C
linux
1
CVE-2012-5148
https://www.cvedetails.com/cve/CVE-2012-5148/
CWE-20
https://github.com/chromium/chromium/commit/e89cfcb9090e8c98129ae9160c513f504db74599
e89cfcb9090e8c98129ae9160c513f504db74599
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
void DomOperationObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_DOM_OPERATION_RESPONSE) { content::Details<DomOperationNotificationDetails> dom_op_details(details); if (dom_op_details->automation_id == automation_id_) OnDomOperationCompleted(dom_op_details->json); } else if (type == chrome::NOTIFICATION_APP_MODAL_DIALOG_SHOWN) { OnModalDialogShown(); } else { DCHECK_EQ(chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, type); WebContents* web_contents = content::Source<WebContents>(source).ptr(); if (web_contents) { TabSpecificContentSettings* tab_content_settings = TabSpecificContentSettings::FromWebContents(web_contents); if (tab_content_settings && tab_content_settings->IsContentBlocked( CONTENT_SETTINGS_TYPE_JAVASCRIPT)) OnJavascriptBlocked(); } } }
void DomOperationObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_DOM_OPERATION_RESPONSE) { content::Details<DomOperationNotificationDetails> dom_op_details(details); if (dom_op_details->automation_id == automation_id_) OnDomOperationCompleted(dom_op_details->json); } else if (type == chrome::NOTIFICATION_APP_MODAL_DIALOG_SHOWN) { OnModalDialogShown(); } else { DCHECK_EQ(chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, type); WebContents* web_contents = content::Source<WebContents>(source).ptr(); if (web_contents) { TabSpecificContentSettings* tab_content_settings = TabSpecificContentSettings::FromWebContents(web_contents); if (tab_content_settings && tab_content_settings->IsContentBlocked( CONTENT_SETTINGS_TYPE_JAVASCRIPT)) OnJavascriptBlocked(); } } }
C
Chrome
0
CVE-2019-15920
https://www.cvedetails.com/cve/CVE-2019-15920/
CWE-416
https://github.com/torvalds/linux/commit/088aaf17aa79300cab14dbee2569c58cfafd7d6e
088aaf17aa79300cab14dbee2569c58cfafd7d6e
cifs: Fix use-after-free in SMB2_read There is a KASAN use-after-free: BUG: KASAN: use-after-free in SMB2_read+0x1136/0x1190 Read of size 8 at addr ffff8880b4e45e50 by task ln/1009 Should not release the 'req' because it will use in the trace. Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging") Signed-off-by: ZhangXiaoxu <zhangxiaoxu5@huawei.com> Signed-off-by: Steve French <stfrench@microsoft.com> CC: Stable <stable@vger.kernel.org> 4.18+ Reviewed-by: Pavel Shilovsky <pshilov@microsoft.com>
SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; struct smb2_fs_full_size_info *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION, sizeof(struct smb2_fs_full_size_info), persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (struct smb2_fs_full_size_info *)( le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp); rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, sizeof(struct smb2_fs_full_size_info)); if (!rc) smb2_copy_fs_info_to_kstatfs(info, fsdata); qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; }
SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct cifs_ses *ses = tcon->ses; struct smb2_fs_full_size_info *info = NULL; int flags = 0; rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION, sizeof(struct smb2_fs_full_size_info), persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsinf_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; info = (struct smb2_fs_full_size_info *)( le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp); rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), le32_to_cpu(rsp->OutputBufferLength), &rsp_iov, sizeof(struct smb2_fs_full_size_info)); if (!rc) smb2_copy_fs_info_to_kstatfs(info, fsdata); qfsinf_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; }
C
linux
0
CVE-2013-6432
https://www.cvedetails.com/cve/CVE-2013-6432/
null
https://github.com/torvalds/linux/commit/cf970c002d270c36202bd5b9c2804d3097a52da0
cf970c002d270c36202bd5b9c2804d3097a52da0
ping: prevent NULL pointer dereference on write to msg_name A plain read() on a socket does set msg->msg_name to NULL. So check for NULL pointer first. Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>
void ping_err(struct sk_buff *skb, int offset, u32 info) { int family; struct icmphdr *icmph; struct inet_sock *inet_sock; int type; int code; struct net *net = dev_net(skb->dev); struct sock *sk; int harderr; int err; if (skb->protocol == htons(ETH_P_IP)) { family = AF_INET; type = icmp_hdr(skb)->type; code = icmp_hdr(skb)->code; icmph = (struct icmphdr *)(skb->data + offset); } else if (skb->protocol == htons(ETH_P_IPV6)) { family = AF_INET6; type = icmp6_hdr(skb)->icmp6_type; code = icmp6_hdr(skb)->icmp6_code; icmph = (struct icmphdr *) (skb->data + offset); } else { BUG(); } /* We assume the packet has already been checked by icmp_unreach */ if (!ping_supported(family, icmph->type, icmph->code)) return; pr_debug("ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n", skb->protocol, type, code, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence)); sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id)); if (sk == NULL) { pr_debug("no socket, dropping\n"); return; /* No socket for error */ } pr_debug("err on socket %p\n", sk); err = 0; harderr = 0; inet_sock = inet_sk(sk); if (skb->protocol == htons(ETH_P_IP)) { switch (type) { default: case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; case ICMP_SOURCE_QUENCH: /* This is not a real error but ping wants to see it. * Report it with some fake errno. */ err = EREMOTEIO; break; case ICMP_PARAMETERPROB: err = EPROTO; harderr = 1; break; case ICMP_DEST_UNREACH: if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ ipv4_sk_update_pmtu(skb, sk, info); if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) { err = EMSGSIZE; harderr = 1; break; } goto out; } err = EHOSTUNREACH; if (code <= NR_ICMP_UNREACH) { harderr = icmp_err_convert[code].fatal; err = icmp_err_convert[code].errno; } break; case ICMP_REDIRECT: /* See ICMP_SOURCE_QUENCH */ ipv4_sk_redirect(skb, sk); err = EREMOTEIO; break; } #if IS_ENABLED(CONFIG_IPV6) } else if (skb->protocol == htons(ETH_P_IPV6)) { harderr = pingv6_ops.icmpv6_err_convert(type, code, &err); #endif } /* * RFC1122: OK. Passes ICMP errors back to application, as per * 4.1.3.3. */ if ((family == AF_INET && !inet_sock->recverr) || (family == AF_INET6 && !inet6_sk(sk)->recverr)) { if (!harderr || sk->sk_state != TCP_ESTABLISHED) goto out; } else { if (family == AF_INET) { ip_icmp_error(sk, skb, err, 0 /* no remote port */, info, (u8 *)icmph); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { pingv6_ops.ipv6_icmp_error(sk, skb, err, 0, info, (u8 *)icmph); #endif } } sk->sk_err = err; sk->sk_error_report(sk); out: sock_put(sk); }
void ping_err(struct sk_buff *skb, int offset, u32 info) { int family; struct icmphdr *icmph; struct inet_sock *inet_sock; int type; int code; struct net *net = dev_net(skb->dev); struct sock *sk; int harderr; int err; if (skb->protocol == htons(ETH_P_IP)) { family = AF_INET; type = icmp_hdr(skb)->type; code = icmp_hdr(skb)->code; icmph = (struct icmphdr *)(skb->data + offset); } else if (skb->protocol == htons(ETH_P_IPV6)) { family = AF_INET6; type = icmp6_hdr(skb)->icmp6_type; code = icmp6_hdr(skb)->icmp6_code; icmph = (struct icmphdr *) (skb->data + offset); } else { BUG(); } /* We assume the packet has already been checked by icmp_unreach */ if (!ping_supported(family, icmph->type, icmph->code)) return; pr_debug("ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n", skb->protocol, type, code, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence)); sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id)); if (sk == NULL) { pr_debug("no socket, dropping\n"); return; /* No socket for error */ } pr_debug("err on socket %p\n", sk); err = 0; harderr = 0; inet_sock = inet_sk(sk); if (skb->protocol == htons(ETH_P_IP)) { switch (type) { default: case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; case ICMP_SOURCE_QUENCH: /* This is not a real error but ping wants to see it. * Report it with some fake errno. */ err = EREMOTEIO; break; case ICMP_PARAMETERPROB: err = EPROTO; harderr = 1; break; case ICMP_DEST_UNREACH: if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ ipv4_sk_update_pmtu(skb, sk, info); if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) { err = EMSGSIZE; harderr = 1; break; } goto out; } err = EHOSTUNREACH; if (code <= NR_ICMP_UNREACH) { harderr = icmp_err_convert[code].fatal; err = icmp_err_convert[code].errno; } break; case ICMP_REDIRECT: /* See ICMP_SOURCE_QUENCH */ ipv4_sk_redirect(skb, sk); err = EREMOTEIO; break; } #if IS_ENABLED(CONFIG_IPV6) } else if (skb->protocol == htons(ETH_P_IPV6)) { harderr = pingv6_ops.icmpv6_err_convert(type, code, &err); #endif } /* * RFC1122: OK. Passes ICMP errors back to application, as per * 4.1.3.3. */ if ((family == AF_INET && !inet_sock->recverr) || (family == AF_INET6 && !inet6_sk(sk)->recverr)) { if (!harderr || sk->sk_state != TCP_ESTABLISHED) goto out; } else { if (family == AF_INET) { ip_icmp_error(sk, skb, err, 0 /* no remote port */, info, (u8 *)icmph); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { pingv6_ops.ipv6_icmp_error(sk, skb, err, 0, info, (u8 *)icmph); #endif } } sk->sk_err = err; sk->sk_error_report(sk); out: sock_put(sk); }
C
linux
0
CVE-2013-0842
https://www.cvedetails.com/cve/CVE-2013-0842/
null
https://github.com/chromium/chromium/commit/10cbaf017570ba6454174c55b844647aa6a9b3b4
10cbaf017570ba6454174c55b844647aa6a9b3b4
Validate that paths don't contain embedded NULLs at deserialization. BUG=166867 Review URL: https://chromiumcodereview.appspot.com/11743009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98
void ParamTraits<long long>::Log(const param_type& p, std::string* l) { l->append(base::Int64ToString(static_cast<int64>(p))); }
void ParamTraits<long long>::Log(const param_type& p, std::string* l) { l->append(base::Int64ToString(static_cast<int64>(p))); }
C
Chrome
0
CVE-2013-0924
https://www.cvedetails.com/cve/CVE-2013-0924/
CWE-264
https://github.com/chromium/chromium/commit/e21bdfb9c758ac411012ad84f83d26d3f7dd69fb
e21bdfb9c758ac411012ad84f83d26d3f7dd69fb
Check prefs before allowing extension file access in the permissions API. R=mpcomplete@chromium.org BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
StateStore* TestExtensionSystem::rules_store() { return state_store_.get(); }
StateStore* TestExtensionSystem::rules_store() { return state_store_.get(); }
C
Chrome
0
CVE-2016-3746
https://www.cvedetails.com/cve/CVE-2016-3746/
null
https://android.googlesource.com/platform/hardware/qcom/media/+/5b82f4f90c3d531313714df4b936f92fb0ff15cf
5b82f4f90c3d531313714df4b936f92fb0ff15cf
DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
void* message_thread(void *input) { omx_vdec* omx = reinterpret_cast<omx_vdec*>(input); unsigned char id; int n; DEBUG_PRINT_HIGH("omx_vdec: message thread start"); prctl(PR_SET_NAME, (unsigned long)"VideoDecMsgThread", 0, 0, 0); while (1) { n = read(omx->m_pipe_in, &id, 1); if (0 == n) { break; } if (1 == n) { omx->process_event_cb(omx, id); } if ((n < 0) && (errno != EINTR)) { DEBUG_PRINT_LOW("ERROR: read from pipe failed, ret %d errno %d", n, errno); break; } } DEBUG_PRINT_HIGH("omx_vdec: message thread stop"); return 0; }
void* message_thread(void *input) { omx_vdec* omx = reinterpret_cast<omx_vdec*>(input); unsigned char id; int n; DEBUG_PRINT_HIGH("omx_vdec: message thread start"); prctl(PR_SET_NAME, (unsigned long)"VideoDecMsgThread", 0, 0, 0); while (1) { n = read(omx->m_pipe_in, &id, 1); if (0 == n) { break; } if (1 == n) { omx->process_event_cb(omx, id); } if ((n < 0) && (errno != EINTR)) { DEBUG_PRINT_LOW("ERROR: read from pipe failed, ret %d errno %d", n, errno); break; } } DEBUG_PRINT_HIGH("omx_vdec: message thread stop"); return 0; }
C
Android
0
CVE-2011-3896
https://www.cvedetails.com/cve/CVE-2011-3896/
CWE-119
https://github.com/chromium/chromium/commit/5925dff83699508b5e2735afb0297dfb310e159d
5925dff83699508b5e2735afb0297dfb310e159d
Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
Profile* Browser::GetProfile() const { return profile(); }
Profile* Browser::GetProfile() const { return profile(); }
C
Chrome
0
CVE-2014-0182
https://www.cvedetails.com/cve/CVE-2014-0182/
CWE-119
https://git.qemu.org/?p=qemu.git;a=commitdiff;h=a890a2f9137ac3cf5b607649e66a6f3a5512d8dc
a890a2f9137ac3cf5b607649e66a6f3a5512d8dc
null
static uint16_t vring_used_idx(VirtQueue *vq) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, idx); return lduw_phys(&address_space_memory, pa); }
static uint16_t vring_used_idx(VirtQueue *vq) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, idx); return lduw_phys(&address_space_memory, pa); }
C
qemu
0
CVE-2017-5209
https://www.cvedetails.com/cve/CVE-2017-5209/
CWE-125
https://github.com/libimobiledevice/libplist/commit/3a55ddd3c4c11ce75a86afbefd085d8d397ff957
3a55ddd3c4c11ce75a86afbefd085d8d397ff957
base64: Rework base64decode to handle split encoded data correctly
unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; int wv, w1, w2, w3, w4; int tmpval[4]; int tmpcnt = 0; do { while (ptr < buf+len && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n' || *ptr == '\r')) { ptr++; } if (*ptr == '\0' || ptr >= buf+len) { break; } if ((wv = base64_table[(int)(unsigned char)*ptr++]) == -1) { continue; } tmpval[tmpcnt++] = wv; if (tmpcnt == 4) { tmpcnt = 0; w1 = tmpval[0]; w2 = tmpval[1]; w3 = tmpval[2]; w4 = tmpval[3]; if (w2 >= 0) { outbuf[p++] = (unsigned char)(((w1 << 2) + (w2 >> 4)) & 0xFF); } if (w3 >= 0) { outbuf[p++] = (unsigned char)(((w2 << 4) + (w3 >> 2)) & 0xFF); } if (w4 >= 0) { outbuf[p++] = (unsigned char)(((w3 << 6) + w4) & 0xFF); } } } while (1); outbuf[p] = 0; *size = p; return outbuf; }
unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; }
C
libplist
1
CVE-2016-3751
https://www.cvedetails.com/cve/CVE-2016-3751/
null
https://android.googlesource.com/platform/external/libpng/+/9d4853418ab2f754c2b63e091c29c5529b8b86ca
9d4853418ab2f754c2b63e091c29c5529b8b86ca
DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
main(void) { fprintf(stderr, " test ignored: no support to modify unknown chunk handling\n"); /* So the test is skipped: */ return 77; }
main(void) { fprintf(stderr, " test ignored: no support to modify unknown chunk handling\n"); /* So the test is skipped: */ return 77; }
C
Android
0
CVE-2012-5136
https://www.cvedetails.com/cve/CVE-2012-5136/
CWE-20
https://github.com/chromium/chromium/commit/401d30ef93030afbf7e81e53a11b68fc36194502
401d30ef93030afbf7e81e53a11b68fc36194502
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
bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, Document* navigatingDocument) { if (!m_domWindow) return true; if (!body()) return true; RefPtr<Document> protect(this); RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create(); m_loadEventProgress = BeforeUnloadEventInProgress; dispatchWindowEvent(beforeUnloadEvent.get(), this); m_loadEventProgress = BeforeUnloadEventCompleted; if (!beforeUnloadEvent->defaultPrevented()) defaultEventHandler(beforeUnloadEvent.get()); if (beforeUnloadEvent->returnValue().isNull()) return true; if (navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel) { addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation."); return true; } String text = beforeUnloadEvent->returnValue(); if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) { navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel = true; return true; } return false; }
bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, Document* navigatingDocument) { if (!m_domWindow) return true; if (!body()) return true; RefPtr<Document> protect(this); RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create(); m_loadEventProgress = BeforeUnloadEventInProgress; dispatchWindowEvent(beforeUnloadEvent.get(), this); m_loadEventProgress = BeforeUnloadEventCompleted; if (!beforeUnloadEvent->defaultPrevented()) defaultEventHandler(beforeUnloadEvent.get()); if (beforeUnloadEvent->returnValue().isNull()) return true; if (navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel) { addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation."); return true; } String text = beforeUnloadEvent->returnValue(); if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) { navigatingDocument->m_didAllowNavigationViaBeforeUnloadConfirmationPanel = true; return true; } return false; }
C
Chrome
0
CVE-2017-14170
https://www.cvedetails.com/cve/CVE-2017-14170/
CWE-834
https://github.com/FFmpeg/FFmpeg/commit/900f39692ca0337a98a7cf047e4e2611071810c2
900f39692ca0337a98a7cf047e4e2611071810c2
avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array() Fixes: 20170829A.mxf Co-Author: 张洪亮(望初)" <wangchu.zhl@alibaba-inc.com> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st = s->streams[stream_index]; int64_t seconds; MXFContext* mxf = s->priv_data; int64_t seekpos; int i, ret; MXFIndexTable *t; MXFTrack *source_track = st->priv_data; if(st->codecpar->codec_type == AVMEDIA_TYPE_DATA) return 0; /* if audio then truncate sample_time to EditRate */ if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) sample_time = av_rescale_q(sample_time, st->time_base, av_inv_q(source_track->edit_rate)); if (mxf->nb_index_tables <= 0) { if (!s->bit_rate) return AVERROR_INVALIDDATA; if (sample_time < 0) sample_time = 0; seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den); seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET); if (seekpos < 0) return seekpos; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; } else { t = &mxf->index_tables[0]; /* clamp above zero, else ff_index_search_timestamp() returns negative * this also means we allow seeking before the start */ sample_time = FFMAX(sample_time, 0); if (t->fake_index) { /* The first frames may not be keyframes in presentation order, so * we have to advance the target to be able to find the first * keyframe backwards... */ if (!(flags & AVSEEK_FLAG_ANY) && (flags & AVSEEK_FLAG_BACKWARD) && t->ptses[0] != AV_NOPTS_VALUE && sample_time < t->ptses[0] && (t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME)) sample_time = t->ptses[0]; /* behave as if we have a proper index */ if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0) return sample_time; /* get the stored order index from the display order index */ sample_time += t->offsets[sample_time]; } else { /* no IndexEntryArray (one or more CBR segments) * make sure we don't seek past the end */ sample_time = FFMIN(sample_time, source_track->original_duration - 1); } if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) < 0) return ret; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; avio_seek(s->pb, seekpos, SEEK_SET); } for (i = 0; i < s->nb_streams; i++) { AVStream *cur_st = s->streams[i]; MXFTrack *cur_track = cur_st->priv_data; uint64_t current_sample_count = 0; if (cur_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { ret = mxf_compute_sample_count(mxf, i, &current_sample_count); if (ret < 0) return ret; cur_track->sample_count = current_sample_count; } } return 0; }
static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st = s->streams[stream_index]; int64_t seconds; MXFContext* mxf = s->priv_data; int64_t seekpos; int i, ret; MXFIndexTable *t; MXFTrack *source_track = st->priv_data; if(st->codecpar->codec_type == AVMEDIA_TYPE_DATA) return 0; /* if audio then truncate sample_time to EditRate */ if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) sample_time = av_rescale_q(sample_time, st->time_base, av_inv_q(source_track->edit_rate)); if (mxf->nb_index_tables <= 0) { if (!s->bit_rate) return AVERROR_INVALIDDATA; if (sample_time < 0) sample_time = 0; seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den); seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET); if (seekpos < 0) return seekpos; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; } else { t = &mxf->index_tables[0]; /* clamp above zero, else ff_index_search_timestamp() returns negative * this also means we allow seeking before the start */ sample_time = FFMAX(sample_time, 0); if (t->fake_index) { /* The first frames may not be keyframes in presentation order, so * we have to advance the target to be able to find the first * keyframe backwards... */ if (!(flags & AVSEEK_FLAG_ANY) && (flags & AVSEEK_FLAG_BACKWARD) && t->ptses[0] != AV_NOPTS_VALUE && sample_time < t->ptses[0] && (t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME)) sample_time = t->ptses[0]; /* behave as if we have a proper index */ if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0) return sample_time; /* get the stored order index from the display order index */ sample_time += t->offsets[sample_time]; } else { /* no IndexEntryArray (one or more CBR segments) * make sure we don't seek past the end */ sample_time = FFMIN(sample_time, source_track->original_duration - 1); } if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) < 0) return ret; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; avio_seek(s->pb, seekpos, SEEK_SET); } for (i = 0; i < s->nb_streams; i++) { AVStream *cur_st = s->streams[i]; MXFTrack *cur_track = cur_st->priv_data; uint64_t current_sample_count = 0; if (cur_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { ret = mxf_compute_sample_count(mxf, i, &current_sample_count); if (ret < 0) return ret; cur_track->sample_count = current_sample_count; } } return 0; }
C
FFmpeg
0
CVE-2011-4112
https://www.cvedetails.com/cve/CVE-2011-4112/
CWE-264
https://github.com/torvalds/linux/commit/550fd08c2cebad61c548def135f67aba284c6162
550fd08c2cebad61c548def135f67aba284c6162
net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <nhorman@tuxdriver.com> CC: Karsten Keil <isdn@linux-pingi.de> CC: "David S. Miller" <davem@davemloft.net> CC: Jay Vosburgh <fubar@us.ibm.com> CC: Andy Gospodarek <andy@greyhouse.net> CC: Patrick McHardy <kaber@trash.net> CC: Krzysztof Halasa <khc@pm.waw.pl> CC: "John W. Linville" <linville@tuxdriver.com> CC: Greg Kroah-Hartman <gregkh@suse.de> CC: Marcel Holtmann <marcel@holtmann.org> CC: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net>
static int vlan_dev_fcoe_ddp_done(struct net_device *dev, u16 xid) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int len = 0; if (ops->ndo_fcoe_ddp_done) len = ops->ndo_fcoe_ddp_done(real_dev, xid); return len; }
static int vlan_dev_fcoe_ddp_done(struct net_device *dev, u16 xid) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int len = 0; if (ops->ndo_fcoe_ddp_done) len = ops->ndo_fcoe_ddp_done(real_dev, xid); return len; }
C
linux
0
CVE-2015-1335
https://www.cvedetails.com/cve/CVE-2015-1335/
CWE-59
https://github.com/lxc/lxc/commit/592fd47a6245508b79fe6ac819fe6d3b2c1289be
592fd47a6245508b79fe6ac819fe6d3b2c1289be
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>
int lxc_clear_cgroups(struct lxc_conf *c, const char *key) { struct lxc_list *it,*next; bool all = false; const char *k = key + 11; if (strcmp(key, "lxc.cgroup") == 0) all = true; lxc_list_for_each_safe(it, &c->cgroup, next) { struct lxc_cgroup *cg = it->elem; if (!all && strcmp(cg->subsystem, k) != 0) continue; lxc_list_del(it); free(cg->subsystem); free(cg->value); free(cg); free(it); } return 0; }
int lxc_clear_cgroups(struct lxc_conf *c, const char *key) { struct lxc_list *it,*next; bool all = false; const char *k = key + 11; if (strcmp(key, "lxc.cgroup") == 0) all = true; lxc_list_for_each_safe(it, &c->cgroup, next) { struct lxc_cgroup *cg = it->elem; if (!all && strcmp(cg->subsystem, k) != 0) continue; lxc_list_del(it); free(cg->subsystem); free(cg->value); free(cg); free(it); } return 0; }
C
lxc
0
CVE-2013-0911
https://www.cvedetails.com/cve/CVE-2013-0911/
CWE-22
https://github.com/chromium/chromium/commit/ccfb891dc0c936a8806d663fe6581bf659761819
ccfb891dc0c936a8806d663fe6581bf659761819
WebDatabase: check path traversal in origin_identifier BUG=172264 Review URL: https://chromiumcodereview.appspot.com/12212091 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98
void DatabaseMessageFilter::OnDatabaseGetFileAttributes( const string16& vfs_file_name, IPC::Message* reply_msg) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); int32 attributes = -1; base::FilePath db_file = DatabaseUtil::GetFullFilePathForVfsFile(db_tracker_, vfs_file_name); if (!db_file.empty()) attributes = VfsBackend::GetFileAttributes(db_file); DatabaseHostMsg_GetFileAttributes::WriteReplyParams( reply_msg, attributes); Send(reply_msg); }
void DatabaseMessageFilter::OnDatabaseGetFileAttributes( const string16& vfs_file_name, IPC::Message* reply_msg) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); int32 attributes = -1; base::FilePath db_file = DatabaseUtil::GetFullFilePathForVfsFile(db_tracker_, vfs_file_name); if (!db_file.empty()) attributes = VfsBackend::GetFileAttributes(db_file); DatabaseHostMsg_GetFileAttributes::WriteReplyParams( reply_msg, attributes); Send(reply_msg); }
C
Chrome
0
CVE-2013-4623
https://www.cvedetails.com/cve/CVE-2013-4623/
CWE-20
https://github.com/polarssl/polarssl/commit/1922a4e6aade7b1d685af19d4d9339ddb5c02859
1922a4e6aade7b1d685af19d4d9339ddb5c02859
ssl_parse_certificate() now calls x509parse_crt_der() directly
static void ssl_calc_finished_ssl( ssl_context *ssl, unsigned char *buf, int from ) { const char *sender; md5_context md5; sha1_context sha1; unsigned char padbuf[48]; unsigned char md5sum[16]; unsigned char sha1sum[20]; ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) ); memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) ); /* * SSLv3: * hash = * MD5( master + pad2 + * MD5( handshake + sender + master + pad1 ) ) * + SHA1( master + pad2 + * SHA1( handshake + sender + master + pad1 ) ) */ SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); sender = ( from == SSL_IS_CLIENT ) ? "CLNT" : "SRVR"; memset( padbuf, 0x36, 48 ); md5_update( &md5, (const unsigned char *) sender, 4 ); md5_update( &md5, session->master, 48 ); md5_update( &md5, padbuf, 48 ); md5_finish( &md5, md5sum ); sha1_update( &sha1, (const unsigned char *) sender, 4 ); sha1_update( &sha1, session->master, 48 ); sha1_update( &sha1, padbuf, 40 ); sha1_finish( &sha1, sha1sum ); memset( padbuf, 0x5C, 48 ); md5_starts( &md5 ); md5_update( &md5, session->master, 48 ); md5_update( &md5, padbuf, 48 ); md5_update( &md5, md5sum, 16 ); md5_finish( &md5, buf ); sha1_starts( &sha1 ); sha1_update( &sha1, session->master, 48 ); sha1_update( &sha1, padbuf , 40 ); sha1_update( &sha1, sha1sum, 20 ); sha1_finish( &sha1, buf + 16 ); SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); memset( &md5, 0, sizeof( md5_context ) ); memset( &sha1, 0, sizeof( sha1_context ) ); memset( padbuf, 0, sizeof( padbuf ) ); memset( md5sum, 0, sizeof( md5sum ) ); memset( sha1sum, 0, sizeof( sha1sum ) ); SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); }
static void ssl_calc_finished_ssl( ssl_context *ssl, unsigned char *buf, int from ) { const char *sender; md5_context md5; sha1_context sha1; unsigned char padbuf[48]; unsigned char md5sum[16]; unsigned char sha1sum[20]; ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) ); memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) ); /* * SSLv3: * hash = * MD5( master + pad2 + * MD5( handshake + sender + master + pad1 ) ) * + SHA1( master + pad2 + * SHA1( handshake + sender + master + pad1 ) ) */ SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); sender = ( from == SSL_IS_CLIENT ) ? "CLNT" : "SRVR"; memset( padbuf, 0x36, 48 ); md5_update( &md5, (const unsigned char *) sender, 4 ); md5_update( &md5, session->master, 48 ); md5_update( &md5, padbuf, 48 ); md5_finish( &md5, md5sum ); sha1_update( &sha1, (const unsigned char *) sender, 4 ); sha1_update( &sha1, session->master, 48 ); sha1_update( &sha1, padbuf, 40 ); sha1_finish( &sha1, sha1sum ); memset( padbuf, 0x5C, 48 ); md5_starts( &md5 ); md5_update( &md5, session->master, 48 ); md5_update( &md5, padbuf, 48 ); md5_update( &md5, md5sum, 16 ); md5_finish( &md5, buf ); sha1_starts( &sha1 ); sha1_update( &sha1, session->master, 48 ); sha1_update( &sha1, padbuf , 40 ); sha1_update( &sha1, sha1sum, 20 ); sha1_finish( &sha1, buf + 16 ); SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); memset( &md5, 0, sizeof( md5_context ) ); memset( &sha1, 0, sizeof( sha1_context ) ); memset( padbuf, 0, sizeof( padbuf ) ); memset( md5sum, 0, sizeof( md5sum ) ); memset( sha1sum, 0, sizeof( sha1sum ) ); SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); }
C
polarssl
0
CVE-2016-8666
https://www.cvedetails.com/cve/CVE-2016-8666/
CWE-400
https://github.com/torvalds/linux/commit/fac8e0f579695a3ecbc4d3cac369139d7f819971
fac8e0f579695a3ecbc4d3cac369139d7f819971
tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <jesse@kernel.org> Signed-off-by: David S. Miller <davem@davemloft.net>
netdev_features_t netdev_increment_features(netdev_features_t all, netdev_features_t one, netdev_features_t mask) { if (mask & NETIF_F_HW_CSUM) mask |= NETIF_F_CSUM_MASK; mask |= NETIF_F_VLAN_CHALLENGED; all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; all &= one | ~NETIF_F_ALL_FOR_ALL; /* If one device supports hw checksumming, set for all. */ if (all & NETIF_F_HW_CSUM) all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); return all; }
netdev_features_t netdev_increment_features(netdev_features_t all, netdev_features_t one, netdev_features_t mask) { if (mask & NETIF_F_HW_CSUM) mask |= NETIF_F_CSUM_MASK; mask |= NETIF_F_VLAN_CHALLENGED; all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask; all &= one | ~NETIF_F_ALL_FOR_ALL; /* If one device supports hw checksumming, set for all. */ if (all & NETIF_F_HW_CSUM) all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM); return all; }
C
linux
0
CVE-2009-3605
https://www.cvedetails.com/cve/CVE-2009-3605/
CWE-189
https://cgit.freedesktop.org/poppler/poppler/commit/?id=7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
null
void GfxDeviceRGBColorSpace::getDefaultColor(GfxColor *color) { color->c[0] = 0; color->c[1] = 0; color->c[2] = 0; }
void GfxDeviceRGBColorSpace::getDefaultColor(GfxColor *color) { color->c[0] = 0; color->c[1] = 0; color->c[2] = 0; }
CPP
poppler
0
CVE-2013-4205
https://www.cvedetails.com/cve/CVE-2013-4205/
CWE-399
https://github.com/torvalds/linux/commit/6160968cee8b90a5dd95318d716e31d7775c4ef3
6160968cee8b90a5dd95318d716e31d7775c4ef3
userns: unshare_userns(&cred) should not populate cred on failure unshare_userns(new_cred) does *new_cred = prepare_creds() before create_user_ns() which can fail. However, the caller expects that it doesn't need to take care of new_cred if unshare_userns() fails. We could change the single caller, sys_unshare(), but I think it would be more clean to avoid the side effects on failure, so with this patch unshare_userns() does put_cred() itself and initializes *new_cred only if create_user_ns() succeeeds. Cc: stable@vger.kernel.org Signed-off-by: Oleg Nesterov <oleg@redhat.com> Reviewed-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
static bool mappings_overlap(struct uid_gid_map *new_map, struct uid_gid_extent *extent) { u32 upper_first, lower_first, upper_last, lower_last; unsigned idx; upper_first = extent->first; lower_first = extent->lower_first; upper_last = upper_first + extent->count - 1; lower_last = lower_first + extent->count - 1; for (idx = 0; idx < new_map->nr_extents; idx++) { u32 prev_upper_first, prev_lower_first; u32 prev_upper_last, prev_lower_last; struct uid_gid_extent *prev; prev = &new_map->extent[idx]; prev_upper_first = prev->first; prev_lower_first = prev->lower_first; prev_upper_last = prev_upper_first + prev->count - 1; prev_lower_last = prev_lower_first + prev->count - 1; /* Does the upper range intersect a previous extent? */ if ((prev_upper_first <= upper_last) && (prev_upper_last >= upper_first)) return true; /* Does the lower range intersect a previous extent? */ if ((prev_lower_first <= lower_last) && (prev_lower_last >= lower_first)) return true; } return false; }
static bool mappings_overlap(struct uid_gid_map *new_map, struct uid_gid_extent *extent) { u32 upper_first, lower_first, upper_last, lower_last; unsigned idx; upper_first = extent->first; lower_first = extent->lower_first; upper_last = upper_first + extent->count - 1; lower_last = lower_first + extent->count - 1; for (idx = 0; idx < new_map->nr_extents; idx++) { u32 prev_upper_first, prev_lower_first; u32 prev_upper_last, prev_lower_last; struct uid_gid_extent *prev; prev = &new_map->extent[idx]; prev_upper_first = prev->first; prev_lower_first = prev->lower_first; prev_upper_last = prev_upper_first + prev->count - 1; prev_lower_last = prev_lower_first + prev->count - 1; /* Does the upper range intersect a previous extent? */ if ((prev_upper_first <= upper_last) && (prev_upper_last >= upper_first)) return true; /* Does the lower range intersect a previous extent? */ if ((prev_lower_first <= lower_last) && (prev_lower_last >= lower_first)) return true; } return false; }
C
linux
0
CVE-2016-9137
https://www.cvedetails.com/cve/CVE-2016-9137/
CWE-416
https://git.php.net/?p=php-src.git;a=commit;h=0e6fe3a4c96be2d3e88389a5776f878021b4c59f
0e6fe3a4c96be2d3e88389a5776f878021b4c59f
null
ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry **disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_find(CG(class_table), class_name, class_name_length+1, (void **)&disabled_class)==FAILURE) { return FAILURE; } INIT_CLASS_ENTRY_INIT_METHODS((**disabled_class), disabled_class_new, NULL, NULL, NULL, NULL, NULL); (*disabled_class)->create_object = display_disabled_class; zend_hash_clean(&((*disabled_class)->function_table)); return SUCCESS; } /* }}} */
ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry **disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_find(CG(class_table), class_name, class_name_length+1, (void **)&disabled_class)==FAILURE) { return FAILURE; } INIT_CLASS_ENTRY_INIT_METHODS((**disabled_class), disabled_class_new, NULL, NULL, NULL, NULL, NULL); (*disabled_class)->create_object = display_disabled_class; zend_hash_clean(&((*disabled_class)->function_table)); return SUCCESS; } /* }}} */
C
php
0
CVE-2011-2479
https://www.cvedetails.com/cve/CVE-2011-2479/
CWE-399
https://github.com/torvalds/linux/commit/78f11a255749d09025f54d4e2df4fbcb031530e2
78f11a255749d09025f54d4e2df4fbcb031530e2
mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Reported-by: Caspar Zhang <bugs@casparzhang.com> Acked-by: Mel Gorman <mel@csn.ul.ie> Acked-by: Rik van Riel <riel@redhat.com> Cc: <stable@kernel.org> [2.6.38.x] Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
static ssize_t defrag_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { return double_flag_store(kobj, attr, buf, count, TRANSPARENT_HUGEPAGE_DEFRAG_FLAG, TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG); }
static ssize_t defrag_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { return double_flag_store(kobj, attr, buf, count, TRANSPARENT_HUGEPAGE_DEFRAG_FLAG, TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG); }
C
linux
0
CVE-2019-10664
https://www.cvedetails.com/cve/CVE-2019-10664/
CWE-89
https://github.com/domoticz/domoticz/commit/ee70db46f81afa582c96b887b73bcd2a86feda00
ee70db46f81afa582c96b887b73bcd2a86feda00
Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
void CWebServer::PostSettings(WebEmSession & session, const request& req, std::string & redirect_uri) { redirect_uri = "/index.html"; if (session.rights != 2) { session.reply_status = reply::forbidden; return; //Only admin user allowed } std::string Latitude = request::findValue(&req, "Latitude"); std::string Longitude = request::findValue(&req, "Longitude"); if ((Latitude != "") && (Longitude != "")) { std::string LatLong = Latitude + ";" + Longitude; m_sql.UpdatePreferencesVar("Location", LatLong.c_str()); m_mainworker.GetSunSettings(); } m_notifications.ConfigFromGetvars(req, true); std::string DashboardType = request::findValue(&req, "DashboardType"); m_sql.UpdatePreferencesVar("DashboardType", atoi(DashboardType.c_str())); std::string MobileType = request::findValue(&req, "MobileType"); m_sql.UpdatePreferencesVar("MobileType", atoi(MobileType.c_str())); int nUnit = atoi(request::findValue(&req, "WindUnit").c_str()); m_sql.UpdatePreferencesVar("WindUnit", nUnit); m_sql.m_windunit = (_eWindUnit)nUnit; nUnit = atoi(request::findValue(&req, "TempUnit").c_str()); m_sql.UpdatePreferencesVar("TempUnit", nUnit); m_sql.m_tempunit = (_eTempUnit)nUnit; nUnit = atoi(request::findValue(&req, "WeightUnit").c_str()); m_sql.UpdatePreferencesVar("WeightUnit", nUnit); m_sql.m_weightunit = (_eWeightUnit)nUnit; m_sql.SetUnitsAndScale(); std::string AuthenticationMethod = request::findValue(&req, "AuthenticationMethod"); _eAuthenticationMethod amethod = (_eAuthenticationMethod)atoi(AuthenticationMethod.c_str()); m_sql.UpdatePreferencesVar("AuthenticationMethod", static_cast<int>(amethod)); m_pWebEm->SetAuthenticationMethod(amethod); std::string ReleaseChannel = request::findValue(&req, "ReleaseChannel"); m_sql.UpdatePreferencesVar("ReleaseChannel", atoi(ReleaseChannel.c_str())); std::string LightHistoryDays = request::findValue(&req, "LightHistoryDays"); m_sql.UpdatePreferencesVar("LightHistoryDays", atoi(LightHistoryDays.c_str())); std::string s5MinuteHistoryDays = request::findValue(&req, "ShortLogDays"); m_sql.UpdatePreferencesVar("5MinuteHistoryDays", atoi(s5MinuteHistoryDays.c_str())); int iShortLogInterval = atoi(request::findValue(&req, "ShortLogInterval").c_str()); if (iShortLogInterval < 1) iShortLogInterval = 5; m_sql.UpdatePreferencesVar("ShortLogInterval", iShortLogInterval); m_sql.m_ShortLogInterval = iShortLogInterval; std::string sElectricVoltage = request::findValue(&req, "ElectricVoltage"); m_sql.UpdatePreferencesVar("ElectricVoltage", atoi(sElectricVoltage.c_str())); std::string sCM113DisplayType = request::findValue(&req, "CM113DisplayType"); m_sql.UpdatePreferencesVar("CM113DisplayType", atoi(sCM113DisplayType.c_str())); std::string WebUserName = base64_encode(CURLEncode::URLDecode(request::findValue(&req, "WebUserName"))); std::string WebPassword = CURLEncode::URLDecode(request::findValue(&req, "WebPassword")); std::string sOldWebLogin; std::string sOldWebPassword; m_sql.GetPreferencesVar("WebUserName", sOldWebLogin); m_sql.GetPreferencesVar("WebPassword", sOldWebPassword); bool bHaveAdminUserPasswordChange = false; if ((WebUserName == sOldWebLogin) && (WebPassword.empty())) { } else if (WebUserName.empty() || WebPassword.empty()) { if ((!sOldWebLogin.empty()) || (!sOldWebPassword.empty())) bHaveAdminUserPasswordChange = true; WebUserName = ""; WebPassword = ""; } else { if ((WebUserName != sOldWebLogin) || (WebPassword != sOldWebPassword)) { bHaveAdminUserPasswordChange = true; } } if (bHaveAdminUserPasswordChange) { RemoveUsersSessions(sOldWebLogin, session); m_sql.UpdatePreferencesVar("WebUserName", WebUserName.c_str()); m_sql.UpdatePreferencesVar("WebPassword", WebPassword.c_str()); } std::string WebLocalNetworks = CURLEncode::URLDecode(request::findValue(&req, "WebLocalNetworks")); std::string WebRemoteProxyIPs = CURLEncode::URLDecode(request::findValue(&req, "WebRemoteProxyIPs")); m_sql.UpdatePreferencesVar("WebLocalNetworks", WebLocalNetworks.c_str()); m_sql.UpdatePreferencesVar("WebRemoteProxyIPs", WebRemoteProxyIPs.c_str()); LoadUsers(); m_pWebEm->ClearLocalNetworks(); std::vector<std::string> strarray; StringSplit(WebLocalNetworks, ";", strarray); for (const auto & itt : strarray) m_pWebEm->AddLocalNetworks(itt); m_pWebEm->AddLocalNetworks(""); m_pWebEm->ClearRemoteProxyIPs(); strarray.clear(); StringSplit(WebRemoteProxyIPs, ";", strarray); for (const auto & itt : strarray) m_pWebEm->AddRemoteProxyIPs(itt); if (session.username.empty()) { session.rights = -1; } std::string SecPassword = request::findValue(&req, "SecPassword"); SecPassword = CURLEncode::URLDecode(SecPassword); if (SecPassword.size() != 32) { SecPassword = GenerateMD5Hash(SecPassword); } m_sql.UpdatePreferencesVar("SecPassword", SecPassword.c_str()); std::string ProtectionPassword = request::findValue(&req, "ProtectionPassword"); ProtectionPassword = CURLEncode::URLDecode(ProtectionPassword); if (ProtectionPassword.size() != 32) { ProtectionPassword = GenerateMD5Hash(ProtectionPassword); } m_sql.UpdatePreferencesVar("ProtectionPassword", ProtectionPassword.c_str()); int EnergyDivider = atoi(request::findValue(&req, "EnergyDivider").c_str()); int GasDivider = atoi(request::findValue(&req, "GasDivider").c_str()); int WaterDivider = atoi(request::findValue(&req, "WaterDivider").c_str()); if (EnergyDivider < 1) EnergyDivider = 1000; if (GasDivider < 1) GasDivider = 100; if (WaterDivider < 1) WaterDivider = 100; m_sql.UpdatePreferencesVar("MeterDividerEnergy", EnergyDivider); m_sql.UpdatePreferencesVar("MeterDividerGas", GasDivider); m_sql.UpdatePreferencesVar("MeterDividerWater", WaterDivider); std::string scheckforupdates = request::findValue(&req, "checkforupdates"); m_sql.UpdatePreferencesVar("UseAutoUpdate", (scheckforupdates == "on" ? 1 : 0)); std::string senableautobackup = request::findValue(&req, "enableautobackup"); m_sql.UpdatePreferencesVar("UseAutoBackup", (senableautobackup == "on" ? 1 : 0)); float CostEnergy = static_cast<float>(atof(request::findValue(&req, "CostEnergy").c_str())); float CostEnergyT2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyT2").c_str())); float CostEnergyR1 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR1").c_str())); float CostEnergyR2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR2").c_str())); float CostGas = static_cast<float>(atof(request::findValue(&req, "CostGas").c_str())); float CostWater = static_cast<float>(atof(request::findValue(&req, "CostWater").c_str())); m_sql.UpdatePreferencesVar("CostEnergy", int(CostEnergy*10000.0f)); m_sql.UpdatePreferencesVar("CostEnergyT2", int(CostEnergyT2*10000.0f)); m_sql.UpdatePreferencesVar("CostEnergyR1", int(CostEnergyR1*10000.0f)); m_sql.UpdatePreferencesVar("CostEnergyR2", int(CostEnergyR2*10000.0f)); m_sql.UpdatePreferencesVar("CostGas", int(CostGas*10000.0f)); m_sql.UpdatePreferencesVar("CostWater", int(CostWater*10000.0f)); int rnOldvalue = 0; int rnvalue = 0; m_sql.GetPreferencesVar("ActiveTimerPlan", rnOldvalue); rnvalue = atoi(request::findValue(&req, "ActiveTimerPlan").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("ActiveTimerPlan", rnvalue); m_sql.m_ActiveTimerPlan = rnvalue; m_mainworker.m_scheduler.ReloadSchedules(); } m_sql.UpdatePreferencesVar("DoorbellCommand", atoi(request::findValue(&req, "DoorbellCommand").c_str())); m_sql.UpdatePreferencesVar("SmartMeterType", atoi(request::findValue(&req, "SmartMeterType").c_str())); std::string EnableTabFloorplans = request::findValue(&req, "EnableTabFloorplans"); m_sql.UpdatePreferencesVar("EnableTabFloorplans", (EnableTabFloorplans == "on" ? 1 : 0)); std::string EnableTabLights = request::findValue(&req, "EnableTabLights"); m_sql.UpdatePreferencesVar("EnableTabLights", (EnableTabLights == "on" ? 1 : 0)); std::string EnableTabTemp = request::findValue(&req, "EnableTabTemp"); m_sql.UpdatePreferencesVar("EnableTabTemp", (EnableTabTemp == "on" ? 1 : 0)); std::string EnableTabWeather = request::findValue(&req, "EnableTabWeather"); m_sql.UpdatePreferencesVar("EnableTabWeather", (EnableTabWeather == "on" ? 1 : 0)); std::string EnableTabUtility = request::findValue(&req, "EnableTabUtility"); m_sql.UpdatePreferencesVar("EnableTabUtility", (EnableTabUtility == "on" ? 1 : 0)); std::string EnableTabScenes = request::findValue(&req, "EnableTabScenes"); m_sql.UpdatePreferencesVar("EnableTabScenes", (EnableTabScenes == "on" ? 1 : 0)); std::string EnableTabCustom = request::findValue(&req, "EnableTabCustom"); m_sql.UpdatePreferencesVar("EnableTabCustom", (EnableTabCustom == "on" ? 1 : 0)); m_sql.GetPreferencesVar("NotificationSensorInterval", rnOldvalue); rnvalue = atoi(request::findValue(&req, "NotificationSensorInterval").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("NotificationSensorInterval", rnvalue); m_notifications.ReloadNotifications(); } m_sql.GetPreferencesVar("NotificationSwitchInterval", rnOldvalue); rnvalue = atoi(request::findValue(&req, "NotificationSwitchInterval").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("NotificationSwitchInterval", rnvalue); m_notifications.ReloadNotifications(); } std::string RaspCamParams = request::findValue(&req, "RaspCamParams"); if (RaspCamParams != "") { if (IsArgumentSecure(RaspCamParams)) m_sql.UpdatePreferencesVar("RaspCamParams", RaspCamParams.c_str()); } std::string UVCParams = request::findValue(&req, "UVCParams"); if (UVCParams != "") { if (IsArgumentSecure(UVCParams)) m_sql.UpdatePreferencesVar("UVCParams", UVCParams.c_str()); } std::string EnableNewHardware = request::findValue(&req, "AcceptNewHardware"); int iEnableNewHardware = (EnableNewHardware == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("AcceptNewHardware", iEnableNewHardware); m_sql.m_bAcceptNewHardware = (iEnableNewHardware == 1); std::string HideDisabledHardwareSensors = request::findValue(&req, "HideDisabledHardwareSensors"); int iHideDisabledHardwareSensors = (HideDisabledHardwareSensors == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("HideDisabledHardwareSensors", iHideDisabledHardwareSensors); std::string ShowUpdateEffect = request::findValue(&req, "ShowUpdateEffect"); int iShowUpdateEffect = (ShowUpdateEffect == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("ShowUpdateEffect", iShowUpdateEffect); std::string SendErrorsAsNotification = request::findValue(&req, "SendErrorsAsNotification"); int iSendErrorsAsNotification = (SendErrorsAsNotification == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("SendErrorsAsNotification", iSendErrorsAsNotification); _log.ForwardErrorsToNotificationSystem(iSendErrorsAsNotification != 0); std::string DegreeDaysBaseTemperature = request::findValue(&req, "DegreeDaysBaseTemperature"); m_sql.UpdatePreferencesVar("DegreeDaysBaseTemperature", DegreeDaysBaseTemperature); rnOldvalue = 0; m_sql.GetPreferencesVar("EnableEventScriptSystem", rnOldvalue); std::string EnableEventScriptSystem = request::findValue(&req, "EnableEventScriptSystem"); int iEnableEventScriptSystem = (EnableEventScriptSystem == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("EnableEventScriptSystem", iEnableEventScriptSystem); m_sql.m_bEnableEventSystem = (iEnableEventScriptSystem == 1); if (iEnableEventScriptSystem != rnOldvalue) { m_mainworker.m_eventsystem.SetEnabled(m_sql.m_bEnableEventSystem); m_mainworker.m_eventsystem.StartEventSystem(); } rnOldvalue = 0; m_sql.GetPreferencesVar("DisableDzVentsSystem", rnOldvalue); std::string DisableDzVentsSystem = request::findValue(&req, "DisableDzVentsSystem"); int iDisableDzVentsSystem = (DisableDzVentsSystem == "on" ? 0 : 1); m_sql.UpdatePreferencesVar("DisableDzVentsSystem", iDisableDzVentsSystem); m_sql.m_bDisableDzVentsSystem = (iDisableDzVentsSystem == 1); if (m_sql.m_bEnableEventSystem && !iDisableDzVentsSystem && iDisableDzVentsSystem != rnOldvalue) { m_mainworker.m_eventsystem.LoadEvents(); m_mainworker.m_eventsystem.GetCurrentStates(); } m_sql.UpdatePreferencesVar("DzVentsLogLevel", atoi(request::findValue(&req, "DzVentsLogLevel").c_str())); std::string LogEventScriptTrigger = request::findValue(&req, "LogEventScriptTrigger"); m_sql.m_bLogEventScriptTrigger = (LogEventScriptTrigger == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("LogEventScriptTrigger", m_sql.m_bLogEventScriptTrigger); std::string EnableWidgetOrdering = request::findValue(&req, "AllowWidgetOrdering"); int iEnableAllowWidgetOrdering = (EnableWidgetOrdering == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("AllowWidgetOrdering", iEnableAllowWidgetOrdering); m_sql.m_bAllowWidgetOrdering = (iEnableAllowWidgetOrdering == 1); rnOldvalue = 0; m_sql.GetPreferencesVar("RemoteSharedPort", rnOldvalue); m_sql.UpdatePreferencesVar("RemoteSharedPort", atoi(request::findValue(&req, "RemoteSharedPort").c_str())); rnvalue = 0; m_sql.GetPreferencesVar("RemoteSharedPort", rnvalue); if (rnvalue != rnOldvalue) { m_mainworker.m_sharedserver.StopServer(); if (rnvalue != 0) { char szPort[100]; sprintf(szPort, "%d", rnvalue); m_mainworker.m_sharedserver.StartServer("::", szPort); m_mainworker.LoadSharedUsers(); } } m_sql.UpdatePreferencesVar("Language", request::findValue(&req, "Language").c_str()); std::string SelectedTheme = request::findValue(&req, "Themes"); m_sql.UpdatePreferencesVar("WebTheme", SelectedTheme.c_str()); m_pWebEm->SetWebTheme(SelectedTheme); std::string Title = request::findValue(&req, "Title").c_str(); m_sql.UpdatePreferencesVar("Title", (Title.empty()) ? "Domoticz" : Title); m_sql.GetPreferencesVar("RandomTimerFrame", rnOldvalue); rnvalue = atoi(request::findValue(&req, "RandomSpread").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("RandomTimerFrame", rnvalue); m_mainworker.m_scheduler.ReloadSchedules(); } m_sql.UpdatePreferencesVar("SecOnDelay", atoi(request::findValue(&req, "SecOnDelay").c_str())); int sensortimeout = atoi(request::findValue(&req, "SensorTimeout").c_str()); if (sensortimeout < 10) sensortimeout = 10; m_sql.UpdatePreferencesVar("SensorTimeout", sensortimeout); int batterylowlevel = atoi(request::findValue(&req, "BatterLowLevel").c_str()); if (batterylowlevel > 100) batterylowlevel = 100; m_sql.GetPreferencesVar("BatteryLowNotification", rnOldvalue); m_sql.UpdatePreferencesVar("BatteryLowNotification", batterylowlevel); if ((rnOldvalue != batterylowlevel) && (batterylowlevel != 0)) m_sql.CheckBatteryLow(); int nValue = 0; nValue = atoi(request::findValue(&req, "FloorplanPopupDelay").c_str()); m_sql.UpdatePreferencesVar("FloorplanPopupDelay", nValue); std::string FloorplanFullscreenMode = request::findValue(&req, "FloorplanFullscreenMode"); m_sql.UpdatePreferencesVar("FloorplanFullscreenMode", (FloorplanFullscreenMode == "on" ? 1 : 0)); std::string FloorplanAnimateZoom = request::findValue(&req, "FloorplanAnimateZoom"); m_sql.UpdatePreferencesVar("FloorplanAnimateZoom", (FloorplanAnimateZoom == "on" ? 1 : 0)); std::string FloorplanShowSensorValues = request::findValue(&req, "FloorplanShowSensorValues"); m_sql.UpdatePreferencesVar("FloorplanShowSensorValues", (FloorplanShowSensorValues == "on" ? 1 : 0)); std::string FloorplanShowSwitchValues = request::findValue(&req, "FloorplanShowSwitchValues"); m_sql.UpdatePreferencesVar("FloorplanShowSwitchValues", (FloorplanShowSwitchValues == "on" ? 1 : 0)); std::string FloorplanShowSceneNames = request::findValue(&req, "FloorplanShowSceneNames"); m_sql.UpdatePreferencesVar("FloorplanShowSceneNames", (FloorplanShowSceneNames == "on" ? 1 : 0)); m_sql.UpdatePreferencesVar("FloorplanRoomColour", CURLEncode::URLDecode(request::findValue(&req, "FloorplanRoomColour").c_str()).c_str()); m_sql.UpdatePreferencesVar("FloorplanActiveOpacity", atoi(request::findValue(&req, "FloorplanActiveOpacity").c_str())); m_sql.UpdatePreferencesVar("FloorplanInactiveOpacity", atoi(request::findValue(&req, "FloorplanInactiveOpacity").c_str())); #ifndef NOCLOUD std::string md_userid, md_password, pf_userid, pf_password; int md_subsystems, pf_subsystems; m_sql.GetPreferencesVar("MyDomoticzUserId", pf_userid); m_sql.GetPreferencesVar("MyDomoticzPassword", pf_password); m_sql.GetPreferencesVar("MyDomoticzSubsystems", pf_subsystems); md_userid = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzUserId")); md_password = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzPassword")); md_subsystems = (request::findValue(&req, "SubsystemHttp").empty() ? 0 : 1) + (request::findValue(&req, "SubsystemShared").empty() ? 0 : 2) + (request::findValue(&req, "SubsystemApps").empty() ? 0 : 4); if (md_userid != pf_userid || md_password != pf_password || md_subsystems != pf_subsystems) { m_sql.UpdatePreferencesVar("MyDomoticzUserId", md_userid); if (md_password != pf_password) { md_password = base64_encode(md_password); m_sql.UpdatePreferencesVar("MyDomoticzPassword", md_password); } m_sql.UpdatePreferencesVar("MyDomoticzSubsystems", md_subsystems); m_webservers.RestartProxy(); } #endif m_sql.UpdatePreferencesVar("OneWireSensorPollPeriod", atoi(request::findValue(&req, "OneWireSensorPollPeriod").c_str())); m_sql.UpdatePreferencesVar("OneWireSwitchPollPeriod", atoi(request::findValue(&req, "OneWireSwitchPollPeriod").c_str())); std::string IFTTTEnabled = request::findValue(&req, "IFTTTEnabled"); int iIFTTTEnabled = (IFTTTEnabled == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("IFTTTEnabled", iIFTTTEnabled); std::string szKey = request::findValue(&req, "IFTTTAPI"); m_sql.UpdatePreferencesVar("IFTTTAPI", base64_encode(szKey)); m_notifications.LoadConfig(); #ifdef ENABLE_PYTHON PluginLoadConfig(); #endif }
void CWebServer::PostSettings(WebEmSession & session, const request& req, std::string & redirect_uri) { redirect_uri = "/index.html"; if (session.rights != 2) { session.reply_status = reply::forbidden; return; //Only admin user allowed } std::string Latitude = request::findValue(&req, "Latitude"); std::string Longitude = request::findValue(&req, "Longitude"); if ((Latitude != "") && (Longitude != "")) { std::string LatLong = Latitude + ";" + Longitude; m_sql.UpdatePreferencesVar("Location", LatLong.c_str()); m_mainworker.GetSunSettings(); } m_notifications.ConfigFromGetvars(req, true); std::string DashboardType = request::findValue(&req, "DashboardType"); m_sql.UpdatePreferencesVar("DashboardType", atoi(DashboardType.c_str())); std::string MobileType = request::findValue(&req, "MobileType"); m_sql.UpdatePreferencesVar("MobileType", atoi(MobileType.c_str())); int nUnit = atoi(request::findValue(&req, "WindUnit").c_str()); m_sql.UpdatePreferencesVar("WindUnit", nUnit); m_sql.m_windunit = (_eWindUnit)nUnit; nUnit = atoi(request::findValue(&req, "TempUnit").c_str()); m_sql.UpdatePreferencesVar("TempUnit", nUnit); m_sql.m_tempunit = (_eTempUnit)nUnit; nUnit = atoi(request::findValue(&req, "WeightUnit").c_str()); m_sql.UpdatePreferencesVar("WeightUnit", nUnit); m_sql.m_weightunit = (_eWeightUnit)nUnit; m_sql.SetUnitsAndScale(); std::string AuthenticationMethod = request::findValue(&req, "AuthenticationMethod"); _eAuthenticationMethod amethod = (_eAuthenticationMethod)atoi(AuthenticationMethod.c_str()); m_sql.UpdatePreferencesVar("AuthenticationMethod", static_cast<int>(amethod)); m_pWebEm->SetAuthenticationMethod(amethod); std::string ReleaseChannel = request::findValue(&req, "ReleaseChannel"); m_sql.UpdatePreferencesVar("ReleaseChannel", atoi(ReleaseChannel.c_str())); std::string LightHistoryDays = request::findValue(&req, "LightHistoryDays"); m_sql.UpdatePreferencesVar("LightHistoryDays", atoi(LightHistoryDays.c_str())); std::string s5MinuteHistoryDays = request::findValue(&req, "ShortLogDays"); m_sql.UpdatePreferencesVar("5MinuteHistoryDays", atoi(s5MinuteHistoryDays.c_str())); int iShortLogInterval = atoi(request::findValue(&req, "ShortLogInterval").c_str()); if (iShortLogInterval < 1) iShortLogInterval = 5; m_sql.UpdatePreferencesVar("ShortLogInterval", iShortLogInterval); m_sql.m_ShortLogInterval = iShortLogInterval; std::string sElectricVoltage = request::findValue(&req, "ElectricVoltage"); m_sql.UpdatePreferencesVar("ElectricVoltage", atoi(sElectricVoltage.c_str())); std::string sCM113DisplayType = request::findValue(&req, "CM113DisplayType"); m_sql.UpdatePreferencesVar("CM113DisplayType", atoi(sCM113DisplayType.c_str())); std::string WebUserName = base64_encode(CURLEncode::URLDecode(request::findValue(&req, "WebUserName"))); std::string WebPassword = CURLEncode::URLDecode(request::findValue(&req, "WebPassword")); std::string sOldWebLogin; std::string sOldWebPassword; m_sql.GetPreferencesVar("WebUserName", sOldWebLogin); m_sql.GetPreferencesVar("WebPassword", sOldWebPassword); bool bHaveAdminUserPasswordChange = false; if ((WebUserName == sOldWebLogin) && (WebPassword.empty())) { } else if (WebUserName.empty() || WebPassword.empty()) { if ((!sOldWebLogin.empty()) || (!sOldWebPassword.empty())) bHaveAdminUserPasswordChange = true; WebUserName = ""; WebPassword = ""; } else { if ((WebUserName != sOldWebLogin) || (WebPassword != sOldWebPassword)) { bHaveAdminUserPasswordChange = true; } } if (bHaveAdminUserPasswordChange) { RemoveUsersSessions(sOldWebLogin, session); m_sql.UpdatePreferencesVar("WebUserName", WebUserName.c_str()); m_sql.UpdatePreferencesVar("WebPassword", WebPassword.c_str()); } std::string WebLocalNetworks = CURLEncode::URLDecode(request::findValue(&req, "WebLocalNetworks")); std::string WebRemoteProxyIPs = CURLEncode::URLDecode(request::findValue(&req, "WebRemoteProxyIPs")); m_sql.UpdatePreferencesVar("WebLocalNetworks", WebLocalNetworks.c_str()); m_sql.UpdatePreferencesVar("WebRemoteProxyIPs", WebRemoteProxyIPs.c_str()); LoadUsers(); m_pWebEm->ClearLocalNetworks(); std::vector<std::string> strarray; StringSplit(WebLocalNetworks, ";", strarray); for (const auto & itt : strarray) m_pWebEm->AddLocalNetworks(itt); m_pWebEm->AddLocalNetworks(""); m_pWebEm->ClearRemoteProxyIPs(); strarray.clear(); StringSplit(WebRemoteProxyIPs, ";", strarray); for (const auto & itt : strarray) m_pWebEm->AddRemoteProxyIPs(itt); if (session.username.empty()) { session.rights = -1; } std::string SecPassword = request::findValue(&req, "SecPassword"); SecPassword = CURLEncode::URLDecode(SecPassword); if (SecPassword.size() != 32) { SecPassword = GenerateMD5Hash(SecPassword); } m_sql.UpdatePreferencesVar("SecPassword", SecPassword.c_str()); std::string ProtectionPassword = request::findValue(&req, "ProtectionPassword"); ProtectionPassword = CURLEncode::URLDecode(ProtectionPassword); if (ProtectionPassword.size() != 32) { ProtectionPassword = GenerateMD5Hash(ProtectionPassword); } m_sql.UpdatePreferencesVar("ProtectionPassword", ProtectionPassword.c_str()); int EnergyDivider = atoi(request::findValue(&req, "EnergyDivider").c_str()); int GasDivider = atoi(request::findValue(&req, "GasDivider").c_str()); int WaterDivider = atoi(request::findValue(&req, "WaterDivider").c_str()); if (EnergyDivider < 1) EnergyDivider = 1000; if (GasDivider < 1) GasDivider = 100; if (WaterDivider < 1) WaterDivider = 100; m_sql.UpdatePreferencesVar("MeterDividerEnergy", EnergyDivider); m_sql.UpdatePreferencesVar("MeterDividerGas", GasDivider); m_sql.UpdatePreferencesVar("MeterDividerWater", WaterDivider); std::string scheckforupdates = request::findValue(&req, "checkforupdates"); m_sql.UpdatePreferencesVar("UseAutoUpdate", (scheckforupdates == "on" ? 1 : 0)); std::string senableautobackup = request::findValue(&req, "enableautobackup"); m_sql.UpdatePreferencesVar("UseAutoBackup", (senableautobackup == "on" ? 1 : 0)); float CostEnergy = static_cast<float>(atof(request::findValue(&req, "CostEnergy").c_str())); float CostEnergyT2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyT2").c_str())); float CostEnergyR1 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR1").c_str())); float CostEnergyR2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR2").c_str())); float CostGas = static_cast<float>(atof(request::findValue(&req, "CostGas").c_str())); float CostWater = static_cast<float>(atof(request::findValue(&req, "CostWater").c_str())); m_sql.UpdatePreferencesVar("CostEnergy", int(CostEnergy*10000.0f)); m_sql.UpdatePreferencesVar("CostEnergyT2", int(CostEnergyT2*10000.0f)); m_sql.UpdatePreferencesVar("CostEnergyR1", int(CostEnergyR1*10000.0f)); m_sql.UpdatePreferencesVar("CostEnergyR2", int(CostEnergyR2*10000.0f)); m_sql.UpdatePreferencesVar("CostGas", int(CostGas*10000.0f)); m_sql.UpdatePreferencesVar("CostWater", int(CostWater*10000.0f)); int rnOldvalue = 0; int rnvalue = 0; m_sql.GetPreferencesVar("ActiveTimerPlan", rnOldvalue); rnvalue = atoi(request::findValue(&req, "ActiveTimerPlan").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("ActiveTimerPlan", rnvalue); m_sql.m_ActiveTimerPlan = rnvalue; m_mainworker.m_scheduler.ReloadSchedules(); } m_sql.UpdatePreferencesVar("DoorbellCommand", atoi(request::findValue(&req, "DoorbellCommand").c_str())); m_sql.UpdatePreferencesVar("SmartMeterType", atoi(request::findValue(&req, "SmartMeterType").c_str())); std::string EnableTabFloorplans = request::findValue(&req, "EnableTabFloorplans"); m_sql.UpdatePreferencesVar("EnableTabFloorplans", (EnableTabFloorplans == "on" ? 1 : 0)); std::string EnableTabLights = request::findValue(&req, "EnableTabLights"); m_sql.UpdatePreferencesVar("EnableTabLights", (EnableTabLights == "on" ? 1 : 0)); std::string EnableTabTemp = request::findValue(&req, "EnableTabTemp"); m_sql.UpdatePreferencesVar("EnableTabTemp", (EnableTabTemp == "on" ? 1 : 0)); std::string EnableTabWeather = request::findValue(&req, "EnableTabWeather"); m_sql.UpdatePreferencesVar("EnableTabWeather", (EnableTabWeather == "on" ? 1 : 0)); std::string EnableTabUtility = request::findValue(&req, "EnableTabUtility"); m_sql.UpdatePreferencesVar("EnableTabUtility", (EnableTabUtility == "on" ? 1 : 0)); std::string EnableTabScenes = request::findValue(&req, "EnableTabScenes"); m_sql.UpdatePreferencesVar("EnableTabScenes", (EnableTabScenes == "on" ? 1 : 0)); std::string EnableTabCustom = request::findValue(&req, "EnableTabCustom"); m_sql.UpdatePreferencesVar("EnableTabCustom", (EnableTabCustom == "on" ? 1 : 0)); m_sql.GetPreferencesVar("NotificationSensorInterval", rnOldvalue); rnvalue = atoi(request::findValue(&req, "NotificationSensorInterval").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("NotificationSensorInterval", rnvalue); m_notifications.ReloadNotifications(); } m_sql.GetPreferencesVar("NotificationSwitchInterval", rnOldvalue); rnvalue = atoi(request::findValue(&req, "NotificationSwitchInterval").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("NotificationSwitchInterval", rnvalue); m_notifications.ReloadNotifications(); } std::string RaspCamParams = request::findValue(&req, "RaspCamParams"); if (RaspCamParams != "") { if (IsArgumentSecure(RaspCamParams)) m_sql.UpdatePreferencesVar("RaspCamParams", RaspCamParams.c_str()); } std::string UVCParams = request::findValue(&req, "UVCParams"); if (UVCParams != "") { if (IsArgumentSecure(UVCParams)) m_sql.UpdatePreferencesVar("UVCParams", UVCParams.c_str()); } std::string EnableNewHardware = request::findValue(&req, "AcceptNewHardware"); int iEnableNewHardware = (EnableNewHardware == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("AcceptNewHardware", iEnableNewHardware); m_sql.m_bAcceptNewHardware = (iEnableNewHardware == 1); std::string HideDisabledHardwareSensors = request::findValue(&req, "HideDisabledHardwareSensors"); int iHideDisabledHardwareSensors = (HideDisabledHardwareSensors == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("HideDisabledHardwareSensors", iHideDisabledHardwareSensors); std::string ShowUpdateEffect = request::findValue(&req, "ShowUpdateEffect"); int iShowUpdateEffect = (ShowUpdateEffect == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("ShowUpdateEffect", iShowUpdateEffect); std::string SendErrorsAsNotification = request::findValue(&req, "SendErrorsAsNotification"); int iSendErrorsAsNotification = (SendErrorsAsNotification == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("SendErrorsAsNotification", iSendErrorsAsNotification); _log.ForwardErrorsToNotificationSystem(iSendErrorsAsNotification != 0); std::string DegreeDaysBaseTemperature = request::findValue(&req, "DegreeDaysBaseTemperature"); m_sql.UpdatePreferencesVar("DegreeDaysBaseTemperature", DegreeDaysBaseTemperature); rnOldvalue = 0; m_sql.GetPreferencesVar("EnableEventScriptSystem", rnOldvalue); std::string EnableEventScriptSystem = request::findValue(&req, "EnableEventScriptSystem"); int iEnableEventScriptSystem = (EnableEventScriptSystem == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("EnableEventScriptSystem", iEnableEventScriptSystem); m_sql.m_bEnableEventSystem = (iEnableEventScriptSystem == 1); if (iEnableEventScriptSystem != rnOldvalue) { m_mainworker.m_eventsystem.SetEnabled(m_sql.m_bEnableEventSystem); m_mainworker.m_eventsystem.StartEventSystem(); } rnOldvalue = 0; m_sql.GetPreferencesVar("DisableDzVentsSystem", rnOldvalue); std::string DisableDzVentsSystem = request::findValue(&req, "DisableDzVentsSystem"); int iDisableDzVentsSystem = (DisableDzVentsSystem == "on" ? 0 : 1); m_sql.UpdatePreferencesVar("DisableDzVentsSystem", iDisableDzVentsSystem); m_sql.m_bDisableDzVentsSystem = (iDisableDzVentsSystem == 1); if (m_sql.m_bEnableEventSystem && !iDisableDzVentsSystem && iDisableDzVentsSystem != rnOldvalue) { m_mainworker.m_eventsystem.LoadEvents(); m_mainworker.m_eventsystem.GetCurrentStates(); } m_sql.UpdatePreferencesVar("DzVentsLogLevel", atoi(request::findValue(&req, "DzVentsLogLevel").c_str())); std::string LogEventScriptTrigger = request::findValue(&req, "LogEventScriptTrigger"); m_sql.m_bLogEventScriptTrigger = (LogEventScriptTrigger == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("LogEventScriptTrigger", m_sql.m_bLogEventScriptTrigger); std::string EnableWidgetOrdering = request::findValue(&req, "AllowWidgetOrdering"); int iEnableAllowWidgetOrdering = (EnableWidgetOrdering == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("AllowWidgetOrdering", iEnableAllowWidgetOrdering); m_sql.m_bAllowWidgetOrdering = (iEnableAllowWidgetOrdering == 1); rnOldvalue = 0; m_sql.GetPreferencesVar("RemoteSharedPort", rnOldvalue); m_sql.UpdatePreferencesVar("RemoteSharedPort", atoi(request::findValue(&req, "RemoteSharedPort").c_str())); rnvalue = 0; m_sql.GetPreferencesVar("RemoteSharedPort", rnvalue); if (rnvalue != rnOldvalue) { m_mainworker.m_sharedserver.StopServer(); if (rnvalue != 0) { char szPort[100]; sprintf(szPort, "%d", rnvalue); m_mainworker.m_sharedserver.StartServer("::", szPort); m_mainworker.LoadSharedUsers(); } } m_sql.UpdatePreferencesVar("Language", request::findValue(&req, "Language").c_str()); std::string SelectedTheme = request::findValue(&req, "Themes"); m_sql.UpdatePreferencesVar("WebTheme", SelectedTheme.c_str()); m_pWebEm->SetWebTheme(SelectedTheme); std::string Title = request::findValue(&req, "Title").c_str(); m_sql.UpdatePreferencesVar("Title", (Title.empty()) ? "Domoticz" : Title); m_sql.GetPreferencesVar("RandomTimerFrame", rnOldvalue); rnvalue = atoi(request::findValue(&req, "RandomSpread").c_str()); if (rnOldvalue != rnvalue) { m_sql.UpdatePreferencesVar("RandomTimerFrame", rnvalue); m_mainworker.m_scheduler.ReloadSchedules(); } m_sql.UpdatePreferencesVar("SecOnDelay", atoi(request::findValue(&req, "SecOnDelay").c_str())); int sensortimeout = atoi(request::findValue(&req, "SensorTimeout").c_str()); if (sensortimeout < 10) sensortimeout = 10; m_sql.UpdatePreferencesVar("SensorTimeout", sensortimeout); int batterylowlevel = atoi(request::findValue(&req, "BatterLowLevel").c_str()); if (batterylowlevel > 100) batterylowlevel = 100; m_sql.GetPreferencesVar("BatteryLowNotification", rnOldvalue); m_sql.UpdatePreferencesVar("BatteryLowNotification", batterylowlevel); if ((rnOldvalue != batterylowlevel) && (batterylowlevel != 0)) m_sql.CheckBatteryLow(); int nValue = 0; nValue = atoi(request::findValue(&req, "FloorplanPopupDelay").c_str()); m_sql.UpdatePreferencesVar("FloorplanPopupDelay", nValue); std::string FloorplanFullscreenMode = request::findValue(&req, "FloorplanFullscreenMode"); m_sql.UpdatePreferencesVar("FloorplanFullscreenMode", (FloorplanFullscreenMode == "on" ? 1 : 0)); std::string FloorplanAnimateZoom = request::findValue(&req, "FloorplanAnimateZoom"); m_sql.UpdatePreferencesVar("FloorplanAnimateZoom", (FloorplanAnimateZoom == "on" ? 1 : 0)); std::string FloorplanShowSensorValues = request::findValue(&req, "FloorplanShowSensorValues"); m_sql.UpdatePreferencesVar("FloorplanShowSensorValues", (FloorplanShowSensorValues == "on" ? 1 : 0)); std::string FloorplanShowSwitchValues = request::findValue(&req, "FloorplanShowSwitchValues"); m_sql.UpdatePreferencesVar("FloorplanShowSwitchValues", (FloorplanShowSwitchValues == "on" ? 1 : 0)); std::string FloorplanShowSceneNames = request::findValue(&req, "FloorplanShowSceneNames"); m_sql.UpdatePreferencesVar("FloorplanShowSceneNames", (FloorplanShowSceneNames == "on" ? 1 : 0)); m_sql.UpdatePreferencesVar("FloorplanRoomColour", CURLEncode::URLDecode(request::findValue(&req, "FloorplanRoomColour").c_str()).c_str()); m_sql.UpdatePreferencesVar("FloorplanActiveOpacity", atoi(request::findValue(&req, "FloorplanActiveOpacity").c_str())); m_sql.UpdatePreferencesVar("FloorplanInactiveOpacity", atoi(request::findValue(&req, "FloorplanInactiveOpacity").c_str())); #ifndef NOCLOUD std::string md_userid, md_password, pf_userid, pf_password; int md_subsystems, pf_subsystems; m_sql.GetPreferencesVar("MyDomoticzUserId", pf_userid); m_sql.GetPreferencesVar("MyDomoticzPassword", pf_password); m_sql.GetPreferencesVar("MyDomoticzSubsystems", pf_subsystems); md_userid = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzUserId")); md_password = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzPassword")); md_subsystems = (request::findValue(&req, "SubsystemHttp").empty() ? 0 : 1) + (request::findValue(&req, "SubsystemShared").empty() ? 0 : 2) + (request::findValue(&req, "SubsystemApps").empty() ? 0 : 4); if (md_userid != pf_userid || md_password != pf_password || md_subsystems != pf_subsystems) { m_sql.UpdatePreferencesVar("MyDomoticzUserId", md_userid); if (md_password != pf_password) { md_password = base64_encode(md_password); m_sql.UpdatePreferencesVar("MyDomoticzPassword", md_password); } m_sql.UpdatePreferencesVar("MyDomoticzSubsystems", md_subsystems); m_webservers.RestartProxy(); } #endif m_sql.UpdatePreferencesVar("OneWireSensorPollPeriod", atoi(request::findValue(&req, "OneWireSensorPollPeriod").c_str())); m_sql.UpdatePreferencesVar("OneWireSwitchPollPeriod", atoi(request::findValue(&req, "OneWireSwitchPollPeriod").c_str())); std::string IFTTTEnabled = request::findValue(&req, "IFTTTEnabled"); int iIFTTTEnabled = (IFTTTEnabled == "on" ? 1 : 0); m_sql.UpdatePreferencesVar("IFTTTEnabled", iIFTTTEnabled); std::string szKey = request::findValue(&req, "IFTTTAPI"); m_sql.UpdatePreferencesVar("IFTTTAPI", base64_encode(szKey)); m_notifications.LoadConfig(); #ifdef ENABLE_PYTHON PluginLoadConfig(); #endif }
C
domoticz
0
CVE-2013-2877
https://www.cvedetails.com/cve/CVE-2013-2877/
CWE-119
https://github.com/chromium/chromium/commit/d0947db40187f4708c58e64cbd6013faf9eddeed
d0947db40187f4708c58e64cbd6013faf9eddeed
libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlBufferFree(buf); return(-1); } } NEXTL(l); c = CUR_CHAR(l); } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); }
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > 100) { count = 0; GROW; } NEXTL(l); c = CUR_CHAR(l); } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); }
C
Chrome
1
CVE-2014-9903
https://www.cvedetails.com/cve/CVE-2014-9903/
CWE-200
https://github.com/torvalds/linux/commit/4efbc454ba68def5ef285b26ebfcfdb605b52755
4efbc454ba68def5ef285b26ebfcfdb605b52755
sched: Fix information leak in sys_sched_getattr() We're copying the on-stack structure to userspace, but forgot to give the right number of bytes to copy. This allows the calling process to obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent kernel memory). This fix copies only as much as we actually have on the stack (attr->size defaults to the size of the struct) and leaves the rest of the userspace-provided buffer untouched. Found using kmemcheck + trinity. Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI") Cc: Dario Faggioli <raistlin@linux.it> Cc: Juri Lelli <juri.lelli@gmail.com> Cc: Ingo Molnar <mingo@kernel.org> Signed-off-by: Vegard Nossum <vegard.nossum@oracle.com> Signed-off-by: Peter Zijlstra <peterz@infradead.org> Link: http://lkml.kernel.org/r/1392585857-10725-1-git-send-email-vegard.nossum@oracle.com Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
void set_user_nice(struct task_struct *p, long nice) { int old_prio, delta, on_rq; unsigned long flags; struct rq *rq; if (TASK_NICE(p) == nice || nice < -20 || nice > 19) return; /* * We have to be careful, if called from sys_setpriority(), * the task might be in the middle of scheduling on another CPU. */ rq = task_rq_lock(p, &flags); /* * The RT priorities are set via sched_setscheduler(), but we still * allow the 'normal' nice value to be set - but as expected * it wont have any effect on scheduling until the task is * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR: */ if (task_has_dl_policy(p) || task_has_rt_policy(p)) { p->static_prio = NICE_TO_PRIO(nice); goto out_unlock; } on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); p->static_prio = NICE_TO_PRIO(nice); set_load_weight(p); old_prio = p->prio; p->prio = effective_prio(p); delta = p->prio - old_prio; if (on_rq) { enqueue_task(rq, p, 0); /* * If the task increased its priority or is running and * lowered its priority, then reschedule its CPU: */ if (delta < 0 || (delta > 0 && task_running(rq, p))) resched_task(rq->curr); } out_unlock: task_rq_unlock(rq, p, &flags); }
void set_user_nice(struct task_struct *p, long nice) { int old_prio, delta, on_rq; unsigned long flags; struct rq *rq; if (TASK_NICE(p) == nice || nice < -20 || nice > 19) return; /* * We have to be careful, if called from sys_setpriority(), * the task might be in the middle of scheduling on another CPU. */ rq = task_rq_lock(p, &flags); /* * The RT priorities are set via sched_setscheduler(), but we still * allow the 'normal' nice value to be set - but as expected * it wont have any effect on scheduling until the task is * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR: */ if (task_has_dl_policy(p) || task_has_rt_policy(p)) { p->static_prio = NICE_TO_PRIO(nice); goto out_unlock; } on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); p->static_prio = NICE_TO_PRIO(nice); set_load_weight(p); old_prio = p->prio; p->prio = effective_prio(p); delta = p->prio - old_prio; if (on_rq) { enqueue_task(rq, p, 0); /* * If the task increased its priority or is running and * lowered its priority, then reschedule its CPU: */ if (delta < 0 || (delta > 0 && task_running(rq, p))) resched_task(rq->curr); } out_unlock: task_rq_unlock(rq, p, &flags); }
C
linux
0
CVE-2013-0904
https://www.cvedetails.com/cve/CVE-2013-0904/
CWE-119
https://github.com/chromium/chromium/commit/b2b21468c1f7f08b30a7c1755316f6026c50eb2a
b2b21468c1f7f08b30a7c1755316f6026c50eb2a
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
void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope& layoutScope) { if (child->style()->position() != FixedPosition) return; bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode()); bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode()); if (!hasStaticBlockPosition && !hasStaticInlinePosition) return; RenderObject* o = child->parent(); while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition) o = o->parent(); if (o->style()->position() != AbsolutePosition) return; RenderBox* box = toRenderBox(child); if (hasStaticInlinePosition) { LogicalExtentComputedValues computedValues; box->computeLogicalWidth(computedValues); LayoutUnit newLeft = computedValues.m_position; if (newLeft != box->logicalLeft()) layoutScope.setChildNeedsLayout(child); } else if (hasStaticBlockPosition) { LayoutUnit oldTop = box->logicalTop(); box->updateLogicalHeight(); if (box->logicalTop() != oldTop) layoutScope.setChildNeedsLayout(child); } }
void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope& layoutScope) { if (child->style()->position() != FixedPosition) return; bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode()); bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode()); if (!hasStaticBlockPosition && !hasStaticInlinePosition) return; RenderObject* o = child->parent(); while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition) o = o->parent(); if (o->style()->position() != AbsolutePosition) return; RenderBox* box = toRenderBox(child); if (hasStaticInlinePosition) { LogicalExtentComputedValues computedValues; box->computeLogicalWidth(computedValues); LayoutUnit newLeft = computedValues.m_position; if (newLeft != box->logicalLeft()) layoutScope.setChildNeedsLayout(child); } else if (hasStaticBlockPosition) { LayoutUnit oldTop = box->logicalTop(); box->updateLogicalHeight(); if (box->logicalTop() != oldTop) layoutScope.setChildNeedsLayout(child); } }
C
Chrome
0
CVE-2014-3200
https://www.cvedetails.com/cve/CVE-2014-3200/
null
https://github.com/chromium/chromium/commit/c0947dabeaa10da67798c1bbc668dca4b280cad5
c0947dabeaa10da67798c1bbc668dca4b280cad5
[Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899}
bool TemplateURLRef::EncodeFormData(const PostParams& post_params, PostContent* post_content) const { if (post_params.empty()) return true; if (!post_content) return false; const char kUploadDataMIMEType[] = "multipart/form-data; boundary="; std::string boundary = net::GenerateMimeMultipartBoundary(); post_content->first = kUploadDataMIMEType; post_content->first += boundary; std::string* post_data = &post_content->second; post_data->clear(); for (const auto& param : post_params) { DCHECK(!param.name.empty()); net::AddMultipartValueForUpload(param.name, param.value, boundary, param.content_type, post_data); } net::AddMultipartFinalDelimiterForUpload(boundary, post_data); return true; }
bool TemplateURLRef::EncodeFormData(const PostParams& post_params, PostContent* post_content) const { if (post_params.empty()) return true; if (!post_content) return false; const char kUploadDataMIMEType[] = "multipart/form-data; boundary="; std::string boundary = net::GenerateMimeMultipartBoundary(); post_content->first = kUploadDataMIMEType; post_content->first += boundary; std::string* post_data = &post_content->second; post_data->clear(); for (const auto& param : post_params) { DCHECK(!param.name.empty()); net::AddMultipartValueForUpload(param.name, param.value, boundary, param.content_type, post_data); } net::AddMultipartFinalDelimiterForUpload(boundary, post_data); return true; }
C
Chrome
0
CVE-2018-12714
https://www.cvedetails.com/cve/CVE-2018-12714/
CWE-787
https://github.com/torvalds/linux/commit/81f9c4e4177d31ced6f52a89bb70e93bfb77ca03
81f9c4e4177d31ced6f52a89bb70e93bfb77ca03
Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters
trace_insert_eval_map_file(struct module *mod, struct trace_eval_map **start, int len) { struct trace_eval_map **stop; struct trace_eval_map **map; union trace_eval_map_item *map_array; union trace_eval_map_item *ptr; stop = start + len; /* * The trace_eval_maps contains the map plus a head and tail item, * where the head holds the module and length of array, and the * tail holds a pointer to the next list. */ map_array = kmalloc_array(len + 2, sizeof(*map_array), GFP_KERNEL); if (!map_array) { pr_warn("Unable to allocate trace eval mapping\n"); return; } mutex_lock(&trace_eval_mutex); if (!trace_eval_maps) trace_eval_maps = map_array; else { ptr = trace_eval_maps; for (;;) { ptr = trace_eval_jmp_to_tail(ptr); if (!ptr->tail.next) break; ptr = ptr->tail.next; } ptr->tail.next = map_array; } map_array->head.mod = mod; map_array->head.length = len; map_array++; for (map = start; (unsigned long)map < (unsigned long)stop; map++) { map_array->map = **map; map_array++; } memset(map_array, 0, sizeof(*map_array)); mutex_unlock(&trace_eval_mutex); }
trace_insert_eval_map_file(struct module *mod, struct trace_eval_map **start, int len) { struct trace_eval_map **stop; struct trace_eval_map **map; union trace_eval_map_item *map_array; union trace_eval_map_item *ptr; stop = start + len; /* * The trace_eval_maps contains the map plus a head and tail item, * where the head holds the module and length of array, and the * tail holds a pointer to the next list. */ map_array = kmalloc_array(len + 2, sizeof(*map_array), GFP_KERNEL); if (!map_array) { pr_warn("Unable to allocate trace eval mapping\n"); return; } mutex_lock(&trace_eval_mutex); if (!trace_eval_maps) trace_eval_maps = map_array; else { ptr = trace_eval_maps; for (;;) { ptr = trace_eval_jmp_to_tail(ptr); if (!ptr->tail.next) break; ptr = ptr->tail.next; } ptr->tail.next = map_array; } map_array->head.mod = mod; map_array->head.length = len; map_array++; for (map = start; (unsigned long)map < (unsigned long)stop; map++) { map_array->map = **map; map_array++; } memset(map_array, 0, sizeof(*map_array)); mutex_unlock(&trace_eval_mutex); }
C
linux
0
CVE-2018-6794
https://www.cvedetails.com/cve/CVE-2018-6794/
CWE-693
https://github.com/OISF/suricata/pull/3202/commits/e1ef57c848bbe4e567d5d4b66d346a742e3f77a1
e1ef57c848bbe4e567d5d4b66d346a742e3f77a1
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.
void SigMatchSignatures(ThreadVars *th_v, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { DetectRun(th_v, de_ctx, det_ctx, p); }
void SigMatchSignatures(ThreadVars *th_v, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { DetectRun(th_v, de_ctx, det_ctx, p); }
C
suricata
0
CVE-2011-2861
https://www.cvedetails.com/cve/CVE-2011-2861/
CWE-20
https://github.com/chromium/chromium/commit/8262245d384be025f13e2a5b3a03b7e5c98374ce
8262245d384be025f13e2a5b3a03b7e5c98374ce
DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
void RenderThread::OnCreateNewView(const ViewMsg_New_Params& params) { EnsureWebKitInitialized(); RenderView::Create( this, params.parent_window, MSG_ROUTING_NONE, params.renderer_preferences, params.web_preferences, new SharedRenderViewCounter(0), params.view_id, params.session_storage_namespace_id, params.frame_name); }
void RenderThread::OnCreateNewView(const ViewMsg_New_Params& params) { EnsureWebKitInitialized(); RenderView::Create( this, params.parent_window, MSG_ROUTING_NONE, params.renderer_preferences, params.web_preferences, new SharedRenderViewCounter(0), params.view_id, params.session_storage_namespace_id, params.frame_name); }
C
Chrome
0
CVE-2015-1335
https://www.cvedetails.com/cve/CVE-2015-1335/
CWE-59
https://github.com/lxc/lxc/commit/592fd47a6245508b79fe6ac819fe6d3b2c1289be
592fd47a6245508b79fe6ac819fe6d3b2c1289be
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>
extern int lxc_pclose(struct lxc_popen_FILE *fp) { FILE *f = NULL; pid_t child_pid = 0; int wstatus = 0; pid_t wait_pid; if (fp) { f = fp->f; child_pid = fp->child_pid; /* free memory (we still need to close file stream) */ free(fp); fp = NULL; } if (!f || fclose(f)) { ERROR("fclose failure"); return -1; } do { wait_pid = waitpid(child_pid, &wstatus, 0); } while (wait_pid == -1 && errno == EINTR); if (wait_pid == -1) { ERROR("waitpid failure"); return -1; } return wstatus; }
extern int lxc_pclose(struct lxc_popen_FILE *fp) { FILE *f = NULL; pid_t child_pid = 0; int wstatus = 0; pid_t wait_pid; if (fp) { f = fp->f; child_pid = fp->child_pid; /* free memory (we still need to close file stream) */ free(fp); fp = NULL; } if (!f || fclose(f)) { ERROR("fclose failure"); return -1; } do { wait_pid = waitpid(child_pid, &wstatus, 0); } while (wait_pid == -1 && errno == EINTR); if (wait_pid == -1) { ERROR("waitpid failure"); return -1; } return wstatus; }
C
lxc
0
CVE-2013-4119
https://www.cvedetails.com/cve/CVE-2013-4119/
CWE-476
https://github.com/FreeRDP/FreeRDP/commit/0773bb9303d24473fe1185d85a424dfe159aff53
0773bb9303d24473fe1185d85a424dfe159aff53
nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.
static BOOL freerdp_peer_check_fds(freerdp_peer* client) { int status; rdpRdp* rdp; rdp = client->context->rdp; status = rdp_check_fds(rdp); if (status < 0) return FALSE; return TRUE; }
static BOOL freerdp_peer_check_fds(freerdp_peer* client) { int status; rdpRdp* rdp; rdp = client->context->rdp; status = rdp_check_fds(rdp); if (status < 0) return FALSE; return TRUE; }
C
FreeRDP
0
CVE-2013-0311
https://www.cvedetails.com/cve/CVE-2013-0311/
null
https://github.com/torvalds/linux/commit/bd97120fc3d1a11f3124c7c9ba1d91f51829eb85
bd97120fc3d1a11f3124c7c9ba1d91f51829eb85
vhost: fix length for cross region descriptor If a single descriptor crosses a region, the second chunk length should be decremented by size translated so far, instead it includes the full descriptor length. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Acked-by: Jason Wang <jasowang@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net>
static long vhost_dev_set_owner(struct vhost_dev *dev) { struct task_struct *worker; int err; /* Is there an owner already? */ if (dev->mm) { err = -EBUSY; goto err_mm; } /* No owner, become one */ dev->mm = get_task_mm(current); worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid); if (IS_ERR(worker)) { err = PTR_ERR(worker); goto err_worker; } dev->worker = worker; wake_up_process(worker); /* avoid contributing to loadavg */ err = vhost_attach_cgroups(dev); if (err) goto err_cgroup; err = vhost_dev_alloc_iovecs(dev); if (err) goto err_cgroup; return 0; err_cgroup: kthread_stop(worker); dev->worker = NULL; err_worker: if (dev->mm) mmput(dev->mm); dev->mm = NULL; err_mm: return err; }
static long vhost_dev_set_owner(struct vhost_dev *dev) { struct task_struct *worker; int err; /* Is there an owner already? */ if (dev->mm) { err = -EBUSY; goto err_mm; } /* No owner, become one */ dev->mm = get_task_mm(current); worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid); if (IS_ERR(worker)) { err = PTR_ERR(worker); goto err_worker; } dev->worker = worker; wake_up_process(worker); /* avoid contributing to loadavg */ err = vhost_attach_cgroups(dev); if (err) goto err_cgroup; err = vhost_dev_alloc_iovecs(dev); if (err) goto err_cgroup; return 0; err_cgroup: kthread_stop(worker); dev->worker = NULL; err_worker: if (dev->mm) mmput(dev->mm); dev->mm = NULL; err_mm: return err; }
C
linux
0
CVE-2016-10066
https://www.cvedetails.com/cve/CVE-2016-10066/
CWE-119
https://github.com/ImageMagick/ImageMagick/commit/f6e9d0d9955e85bdd7540b251cd50d598dacc5e6
f6e9d0d9955e85bdd7540b251cd50d598dacc5e6
null
static void SetColorBalance(double red,double green,double blue, FPXColorTwistMatrix *color_twist) { FPXColorTwistMatrix blue_effect, green_effect, result, rgb_effect, rg_effect, red_effect; /* Set image color balance in color twist matrix. */ assert(color_twist != (FPXColorTwistMatrix *) NULL); red=sqrt((double) red)-1.0; green=sqrt((double) green)-1.0; blue=sqrt((double) blue)-1.0; red_effect.byy=1.0; red_effect.byc1=0.0; red_effect.byc2=0.299*red; red_effect.dummy1_zero=0.0; red_effect.bc1y=(-0.299)*red; red_effect.bc1c1=1.0-0.299*red; red_effect.bc1c2=(-0.299)*red; red_effect.dummy2_zero=0.0; red_effect.bc2y=0.701*red; red_effect.bc2c1=0.0; red_effect.bc2c2=1.0+0.402*red; red_effect.dummy3_zero=0.0; red_effect.dummy4_zero=0.0; red_effect.dummy5_zero=0.0; red_effect.dummy6_zero=0.0; red_effect.dummy7_one=1.0; green_effect.byy=1.0; green_effect.byc1=(-0.114)*green; green_effect.byc2=(-0.299)*green; green_effect.dummy1_zero=0.0; green_effect.bc1y=(-0.587)*green; green_effect.bc1c1=1.0-0.473*green; green_effect.bc1c2=0.299*green; green_effect.dummy2_zero=0.0; green_effect.bc2y=(-0.587)*green; green_effect.bc2c1=0.114*green; green_effect.bc2c2=1.0-0.288*green; green_effect.dummy3_zero=0.0; green_effect.dummy4_zero=0.0; green_effect.dummy5_zero=0.0; green_effect.dummy6_zero=0.0; green_effect.dummy7_one=1.0; blue_effect.byy=1.0; blue_effect.byc1=0.114*blue; blue_effect.byc2=0.0; blue_effect.dummy1_zero=0.0; blue_effect.bc1y=0.886*blue; blue_effect.bc1c1=1.0+0.772*blue; blue_effect.bc1c2=0.0; blue_effect.dummy2_zero=0.0; blue_effect.bc2y=(-0.114)*blue; blue_effect.bc2c1=(-0.114)*blue; blue_effect.bc2c2=1.0-0.114*blue; blue_effect.dummy3_zero=0.0; blue_effect.dummy4_zero=0.0; blue_effect.dummy5_zero=0.0; blue_effect.dummy6_zero=0.0; blue_effect.dummy7_one=1.0; ColorTwistMultiply(red_effect,green_effect,&rg_effect); ColorTwistMultiply(rg_effect,blue_effect,&rgb_effect); ColorTwistMultiply(*color_twist,rgb_effect,&result); *color_twist=result; }
static void SetColorBalance(double red,double green,double blue, FPXColorTwistMatrix *color_twist) { FPXColorTwistMatrix blue_effect, green_effect, result, rgb_effect, rg_effect, red_effect; /* Set image color balance in color twist matrix. */ assert(color_twist != (FPXColorTwistMatrix *) NULL); red=sqrt((double) red)-1.0; green=sqrt((double) green)-1.0; blue=sqrt((double) blue)-1.0; red_effect.byy=1.0; red_effect.byc1=0.0; red_effect.byc2=0.299*red; red_effect.dummy1_zero=0.0; red_effect.bc1y=(-0.299)*red; red_effect.bc1c1=1.0-0.299*red; red_effect.bc1c2=(-0.299)*red; red_effect.dummy2_zero=0.0; red_effect.bc2y=0.701*red; red_effect.bc2c1=0.0; red_effect.bc2c2=1.0+0.402*red; red_effect.dummy3_zero=0.0; red_effect.dummy4_zero=0.0; red_effect.dummy5_zero=0.0; red_effect.dummy6_zero=0.0; red_effect.dummy7_one=1.0; green_effect.byy=1.0; green_effect.byc1=(-0.114)*green; green_effect.byc2=(-0.299)*green; green_effect.dummy1_zero=0.0; green_effect.bc1y=(-0.587)*green; green_effect.bc1c1=1.0-0.473*green; green_effect.bc1c2=0.299*green; green_effect.dummy2_zero=0.0; green_effect.bc2y=(-0.587)*green; green_effect.bc2c1=0.114*green; green_effect.bc2c2=1.0-0.288*green; green_effect.dummy3_zero=0.0; green_effect.dummy4_zero=0.0; green_effect.dummy5_zero=0.0; green_effect.dummy6_zero=0.0; green_effect.dummy7_one=1.0; blue_effect.byy=1.0; blue_effect.byc1=0.114*blue; blue_effect.byc2=0.0; blue_effect.dummy1_zero=0.0; blue_effect.bc1y=0.886*blue; blue_effect.bc1c1=1.0+0.772*blue; blue_effect.bc1c2=0.0; blue_effect.dummy2_zero=0.0; blue_effect.bc2y=(-0.114)*blue; blue_effect.bc2c1=(-0.114)*blue; blue_effect.bc2c2=1.0-0.114*blue; blue_effect.dummy3_zero=0.0; blue_effect.dummy4_zero=0.0; blue_effect.dummy5_zero=0.0; blue_effect.dummy6_zero=0.0; blue_effect.dummy7_one=1.0; ColorTwistMultiply(red_effect,green_effect,&rg_effect); ColorTwistMultiply(rg_effect,blue_effect,&rgb_effect); ColorTwistMultiply(*color_twist,rgb_effect,&result); *color_twist=result; }
C
ImageMagick
0
CVE-2016-0809
https://www.cvedetails.com/cve/CVE-2016-0809/
CWE-264
https://android.googlesource.com/platform/hardware/broadcom/wlan/+/2c5a4fac8bc8198f6a2635ede776f8de40a0c3e1
2c5a4fac8bc8198f6a2635ede776f8de40a0c3e1
Fix use-after-free in wifi_cleanup() Release reference to cmd only after possibly calling getType(). BUG: 25753768 Change-Id: Id2156ce51acec04e8364706cf7eafc7d4adae9eb (cherry picked from commit d7f3cb9915d9ac514393d0ad7767662958054b8f https://googleplex-android-review.git.corp.google.com/#/c/815223)
wifi_error wifi_set_scanning_mac_oui(wifi_interface_handle handle, oui scan_oui) { SetPnoMacAddrOuiCommand command(handle, scan_oui); return (wifi_error)command.start(); }
wifi_error wifi_set_scanning_mac_oui(wifi_interface_handle handle, oui scan_oui) { SetPnoMacAddrOuiCommand command(handle, scan_oui); return (wifi_error)command.start(); }
C
Android
0
CVE-2017-12168
https://www.cvedetails.com/cve/CVE-2017-12168/
CWE-617
https://github.com/torvalds/linux/commit/9e3f7a29694049edd728e2400ab57ad7553e5aa9
9e3f7a29694049edd728e2400ab57ad7553e5aa9
arm64: KVM: pmu: Fix AArch32 cycle counter access We're missing the handling code for the cycle counter accessed from a 32bit guest, leading to unexpected results. Cc: stable@vger.kernel.org # 4.6+ Signed-off-by: Wei Huang <wei@redhat.com> Signed-off-by: Marc Zyngier <marc.zyngier@arm.com>
int kvm_handle_cp14_load_store(struct kvm_vcpu *vcpu, struct kvm_run *run) { kvm_inject_undefined(vcpu); return 1; }
int kvm_handle_cp14_load_store(struct kvm_vcpu *vcpu, struct kvm_run *run) { kvm_inject_undefined(vcpu); return 1; }
C
linux
0
CVE-2011-4324
https://www.cvedetails.com/cve/CVE-2011-4324/
null
https://github.com/torvalds/linux/commit/dc0b027dfadfcb8a5504f7d8052754bf8d501ab9
dc0b027dfadfcb8a5504f7d8052754bf8d501ab9
NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
static int encode_remove(struct xdr_stream *xdr, const struct qstr *name) { __be32 *p; RESERVE_SPACE(8 + name->len); WRITE32(OP_REMOVE); WRITE32(name->len); WRITEMEM(name->name, name->len); return 0; }
static int encode_remove(struct xdr_stream *xdr, const struct qstr *name) { __be32 *p; RESERVE_SPACE(8 + name->len); WRITE32(OP_REMOVE); WRITE32(name->len); WRITEMEM(name->name, name->len); return 0; }
C
linux
0
CVE-2011-3193
https://www.cvedetails.com/cve/CVE-2011-3193/
CWE-119
https://cgit.freedesktop.org/harfbuzz.old/commit/?id=81c8ef785b079980ad5b46be4fe7c7bf156dbf65
81c8ef785b079980ad5b46be4fe7c7bf156dbf65
null
static HB_Error Load_PairPos( HB_GPOS_SubTable* st, HB_Stream stream ) { HB_Error error; HB_PairPos* pp = &st->pair; HB_UShort format1, format2; HB_UInt cur_offset, new_offset, base_offset; base_offset = FILE_Pos(); if ( ACCESS_Frame( 8L ) ) return error; pp->PosFormat = GET_UShort(); new_offset = GET_UShort() + base_offset; format1 = pp->ValueFormat1 = GET_UShort(); format2 = pp->ValueFormat2 = GET_UShort(); FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &pp->Coverage, stream ) ) != HB_Err_Ok ) return error; (void)FILE_Seek( cur_offset ); switch ( pp->PosFormat ) { case 1: error = Load_PairPos1( &pp->ppf.ppf1, format1, format2, stream ); if ( error ) goto Fail; break; case 2: error = Load_PairPos2( &pp->ppf.ppf2, format1, format2, stream ); if ( error ) goto Fail; break; default: return ERR(HB_Err_Invalid_SubTable_Format); } return HB_Err_Ok; Fail: _HB_OPEN_Free_Coverage( &pp->Coverage ); return error; }
static HB_Error Load_PairPos( HB_GPOS_SubTable* st, HB_Stream stream ) { HB_Error error; HB_PairPos* pp = &st->pair; HB_UShort format1, format2; HB_UInt cur_offset, new_offset, base_offset; base_offset = FILE_Pos(); if ( ACCESS_Frame( 8L ) ) return error; pp->PosFormat = GET_UShort(); new_offset = GET_UShort() + base_offset; format1 = pp->ValueFormat1 = GET_UShort(); format2 = pp->ValueFormat2 = GET_UShort(); FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &pp->Coverage, stream ) ) != HB_Err_Ok ) return error; (void)FILE_Seek( cur_offset ); switch ( pp->PosFormat ) { case 1: error = Load_PairPos1( &pp->ppf.ppf1, format1, format2, stream ); if ( error ) goto Fail; break; case 2: error = Load_PairPos2( &pp->ppf.ppf2, format1, format2, stream ); if ( error ) goto Fail; break; default: return ERR(HB_Err_Invalid_SubTable_Format); } return HB_Err_Ok; Fail: _HB_OPEN_Free_Coverage( &pp->Coverage ); return error; }
C
harfbuzz
0
CVE-2017-5019
https://www.cvedetails.com/cve/CVE-2017-5019/
CWE-416
https://github.com/chromium/chromium/commit/f03ea5a5c2ff26e239dfd23e263b15da2d9cee93
f03ea5a5c2ff26e239dfd23e263b15da2d9cee93
Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137}
void RenderFrameHostImpl::DeleteRenderFrame() { if (!is_active()) return; if (render_frame_created_) { Send(new FrameMsg_Delete(routing_id_)); if (!frame_tree_node_->IsMainFrame() && IsCurrent() && GetSuddenTerminationDisablerState(blink::kUnloadHandler)) { RenderProcessHostImpl* process = static_cast<RenderProcessHostImpl*>(GetProcess()); process->DelayProcessShutdownForUnload(subframe_unload_timeout_); } } unload_state_ = GetSuddenTerminationDisablerState(blink::kUnloadHandler) ? UnloadState::InProgress : UnloadState::Completed; }
void RenderFrameHostImpl::DeleteRenderFrame() { if (!is_active()) return; if (render_frame_created_) { Send(new FrameMsg_Delete(routing_id_)); if (!frame_tree_node_->IsMainFrame() && IsCurrent() && GetSuddenTerminationDisablerState(blink::kUnloadHandler)) { RenderProcessHostImpl* process = static_cast<RenderProcessHostImpl*>(GetProcess()); process->DelayProcessShutdownForUnload(subframe_unload_timeout_); } } unload_state_ = GetSuddenTerminationDisablerState(blink::kUnloadHandler) ? UnloadState::InProgress : UnloadState::Completed; }
C
Chrome
0
CVE-2017-9242
https://www.cvedetails.com/cve/CVE-2017-9242/
CWE-20
https://github.com/torvalds/linux/commit/232cd35d0804cc241eb887bb8d4d9b3b9881c64a
232cd35d0804cc241eb887bb8d4d9b3b9881c64a
ipv6: fix out of bound writes in __ip6_append_data() Andrey Konovalov and idaifish@gmail.com reported crashes caused by one skb shared_info being overwritten from __ip6_append_data() Andrey program lead to following state : copy -4200 datalen 2000 fraglen 2040 maxfraglen 2040 alloclen 2048 transhdrlen 0 offset 0 fraggap 6200 The skb_copy_and_csum_bits(skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); is overwriting skb->head and skb_shared_info Since we apparently detect this rare condition too late, move the code earlier to even avoid allocating skb and risking crashes. Once again, many thanks to Andrey and syzkaller team. Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Andrey Konovalov <andreyknvl@google.com> Tested-by: Andrey Konovalov <andreyknvl@google.com> Reported-by: <idaifish@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); }
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); }
C
linux
0
CVE-2010-4648
https://www.cvedetails.com/cve/CVE-2010-4648/
null
https://github.com/torvalds/linux/commit/0a54917c3fc295cb61f3fb52373c173fd3b69f48
0a54917c3fc295cb61f3fb52373c173fd3b69f48
orinoco: fix TKIP countermeasure behaviour Enable the port when disabling countermeasures, and disable it on enabling countermeasures. This bug causes the response of the system to certain attacks to be ineffective. It also prevents wpa_supplicant from getting scan results, as wpa_supplicant disables countermeasures on startup - preventing the hardware from scanning. wpa_supplicant works with ap_mode=2 despite this bug because the commit handler re-enables the port. The log tends to look like: State: DISCONNECTED -> SCANNING Starting AP scan for wildcard SSID Scan requested (ret=0) - scan timeout 5 seconds EAPOL: disable timer tick EAPOL: Supplicant port status: Unauthorized Scan timeout - try to get results Failed to get scan results Failed to get scan results - try scanning again Setting scan request: 1 sec 0 usec Starting AP scan for wildcard SSID Scan requested (ret=-1) - scan timeout 5 seconds Failed to initiate AP scan. Reported by: Giacomo Comes <comes@naic.edu> Signed-off by: David Kilroy <kilroyd@googlemail.com> Cc: stable@kernel.org Signed-off-by: John W. Linville <linville@tuxdriver.com>
static int orinoco_ioctl_setibssport(struct net_device *dev, struct iw_request_info *info, void *wrqu, char *extra) { struct orinoco_private *priv = ndev_priv(dev); int val = *((int *) extra); unsigned long flags; if (orinoco_lock(priv, &flags) != 0) return -EBUSY; priv->ibss_port = val; /* Actually update the mode we are using */ set_port_type(priv); orinoco_unlock(priv, &flags); return -EINPROGRESS; /* Call commit handler */ }
static int orinoco_ioctl_setibssport(struct net_device *dev, struct iw_request_info *info, void *wrqu, char *extra) { struct orinoco_private *priv = ndev_priv(dev); int val = *((int *) extra); unsigned long flags; if (orinoco_lock(priv, &flags) != 0) return -EBUSY; priv->ibss_port = val; /* Actually update the mode we are using */ set_port_type(priv); orinoco_unlock(priv, &flags); return -EINPROGRESS; /* Call commit handler */ }
C
linux
0
CVE-2013-7271
https://www.cvedetails.com/cve/CVE-2013-7271/
CWE-20
https://github.com/torvalds/linux/commit/f3d3342602f8bcbf37d7c46641cb9bca7618eb1c
f3d3342602f8bcbf37d7c46641cb9bca7618eb1c
net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>
static inline int cmp_2_addr(struct pppoe_addr *a, struct pppoe_addr *b) { return a->sid == b->sid && !memcmp(a->remote, b->remote, ETH_ALEN); }
static inline int cmp_2_addr(struct pppoe_addr *a, struct pppoe_addr *b) { return a->sid == b->sid && !memcmp(a->remote, b->remote, ETH_ALEN); }
C
linux
0
CVE-2017-7541
https://www.cvedetails.com/cve/CVE-2017-7541/
CWE-119
https://github.com/torvalds/linux/commit/8f44c9a41386729fea410e688959ddaa9d51be7c
8f44c9a41386729fea410e688959ddaa9d51be7c
brcmfmac: fix possible buffer overflow in brcmf_cfg80211_mgmt_tx() The lower level nl80211 code in cfg80211 ensures that "len" is between 25 and NL80211_ATTR_FRAME (2304). We subtract DOT11_MGMT_HDR_LEN (24) from "len" so thats's max of 2280. However, the action_frame->data[] buffer is only BRCMF_FIL_ACTION_FRAME_SIZE (1800) bytes long so this memcpy() can overflow. memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN], le16_to_cpu(action_frame->len)); Cc: stable@vger.kernel.org # 3.9.x Fixes: 18e2f61db3b70 ("brcmfmac: P2P action frame tx.") Reported-by: "freenerguo(郭大兴)" <freenerguo@tencent.com> Signed-off-by: Arend van Spriel <arend.vanspriel@broadcom.com> Signed-off-by: David S. Miller <davem@davemloft.net>
static int brcmf_cfg80211_set_pmk(struct wiphy *wiphy, struct net_device *dev, const struct cfg80211_pmk_conf *conf) { struct brcmf_if *ifp; brcmf_dbg(TRACE, "enter\n"); /* expect using firmware supplicant for 1X */ ifp = netdev_priv(dev); if (WARN_ON(ifp->vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_1X)) return -EINVAL; return brcmf_set_pmk(ifp, conf->pmk, conf->pmk_len); }
static int brcmf_cfg80211_set_pmk(struct wiphy *wiphy, struct net_device *dev, const struct cfg80211_pmk_conf *conf) { struct brcmf_if *ifp; brcmf_dbg(TRACE, "enter\n"); /* expect using firmware supplicant for 1X */ ifp = netdev_priv(dev); if (WARN_ON(ifp->vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_1X)) return -EINVAL; return brcmf_set_pmk(ifp, conf->pmk, conf->pmk_len); }
C
linux
0
CVE-2016-9317
https://www.cvedetails.com/cve/CVE-2016-9317/
CWE-20
https://github.com/libgd/libgd/commit/1846f48e5fcdde996e7c27a4bbac5d0aef183e4b
1846f48e5fcdde996e7c27a4bbac5d0aef183e4b
Fix #340: System frozen gdImageCreate() doesn't check for oversized images and as such is prone to DoS vulnerabilities. We fix that by applying the same overflow check that is already in place for gdImageCreateTrueColor(). CVE-2016-9317
BGD_DECLARE(void) gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg) { im->saveAlphaFlag = saveAlphaArg; }
BGD_DECLARE(void) gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg) { im->saveAlphaFlag = saveAlphaArg; }
C
libgd
0
CVE-2013-4125
https://www.cvedetails.com/cve/CVE-2013-4125/
CWE-399
https://github.com/torvalds/linux/commit/307f2fb95e9b96b3577916e73d92e104f8f26494
307f2fb95e9b96b3577916e73d92e104f8f26494
ipv6: only static routes qualify for equal cost multipathing Static routes in this case are non-expiring routes which did not get configured by autoconf or by icmpv6 redirects. To make sure we actually get an ecmp route while searching for the first one in this fib6_node's leafs, also make sure it matches the ecmp route assumptions. v2: a) Removed RTF_EXPIRE check in dst.from chain. The check of RTF_ADDRCONF already ensures that this route, even if added again without RTF_EXPIRES (in case of a RA announcement with infinite timeout), does not cause the rt6i_nsiblings logic to go wrong if a later RA updates the expiration time later. v3: a) Allow RTF_EXPIRES routes to enter the ecmp route set. We have to do so, because an pmtu event could update the RTF_EXPIRES flag and we would not count this route, if another route joins this set. We now filter only for RTF_GATEWAY|RTF_ADDRCONF|RTF_DYNAMIC, which are flags that don't get changed after rt6_info construction. Cc: Nicolas Dichtel <nicolas.dichtel@6wind.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>
static int fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt, struct nl_info *info) { struct rt6_info *iter = NULL; struct rt6_info **ins; int replace = (info->nlh && (info->nlh->nlmsg_flags & NLM_F_REPLACE)); int add = (!info->nlh || (info->nlh->nlmsg_flags & NLM_F_CREATE)); int found = 0; bool rt_can_ecmp = rt6_qualify_for_ecmp(rt); ins = &fn->leaf; for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) { /* * Search for duplicates */ if (iter->rt6i_metric == rt->rt6i_metric) { /* * Same priority level */ if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_EXCL)) return -EEXIST; if (replace) { found++; break; } if (iter->dst.dev == rt->dst.dev && iter->rt6i_idev == rt->rt6i_idev && ipv6_addr_equal(&iter->rt6i_gateway, &rt->rt6i_gateway)) { if (rt->rt6i_nsiblings) rt->rt6i_nsiblings = 0; if (!(iter->rt6i_flags & RTF_EXPIRES)) return -EEXIST; if (!(rt->rt6i_flags & RTF_EXPIRES)) rt6_clean_expires(iter); else rt6_set_expires(iter, rt->dst.expires); return -EEXIST; } /* If we have the same destination and the same metric, * but not the same gateway, then the route we try to * add is sibling to this route, increment our counter * of siblings, and later we will add our route to the * list. * Only static routes (which don't have flag * RTF_EXPIRES) are used for ECMPv6. * * To avoid long list, we only had siblings if the * route have a gateway. */ if (rt_can_ecmp && rt6_qualify_for_ecmp(iter)) rt->rt6i_nsiblings++; } if (iter->rt6i_metric > rt->rt6i_metric) break; ins = &iter->dst.rt6_next; } /* Reset round-robin state, if necessary */ if (ins == &fn->leaf) fn->rr_ptr = NULL; /* Link this route to others same route. */ if (rt->rt6i_nsiblings) { unsigned int rt6i_nsiblings; struct rt6_info *sibling, *temp_sibling; /* Find the first route that have the same metric */ sibling = fn->leaf; while (sibling) { if (sibling->rt6i_metric == rt->rt6i_metric && rt6_qualify_for_ecmp(sibling)) { list_add_tail(&rt->rt6i_siblings, &sibling->rt6i_siblings); break; } sibling = sibling->dst.rt6_next; } /* For each sibling in the list, increment the counter of * siblings. BUG() if counters does not match, list of siblings * is broken! */ rt6i_nsiblings = 0; list_for_each_entry_safe(sibling, temp_sibling, &rt->rt6i_siblings, rt6i_siblings) { sibling->rt6i_nsiblings++; BUG_ON(sibling->rt6i_nsiblings != rt->rt6i_nsiblings); rt6i_nsiblings++; } BUG_ON(rt6i_nsiblings != rt->rt6i_nsiblings); } /* * insert node */ if (!replace) { if (!add) pr_warn("NLM_F_CREATE should be set when creating new route\n"); add: rt->dst.rt6_next = iter; *ins = rt; rt->rt6i_node = fn; atomic_inc(&rt->rt6i_ref); inet6_rt_notify(RTM_NEWROUTE, rt, info); info->nl_net->ipv6.rt6_stats->fib_rt_entries++; if (!(fn->fn_flags & RTN_RTINFO)) { info->nl_net->ipv6.rt6_stats->fib_route_nodes++; fn->fn_flags |= RTN_RTINFO; } } else { if (!found) { if (add) goto add; pr_warn("NLM_F_REPLACE set, but no existing node found!\n"); return -ENOENT; } *ins = rt; rt->rt6i_node = fn; rt->dst.rt6_next = iter->dst.rt6_next; atomic_inc(&rt->rt6i_ref); inet6_rt_notify(RTM_NEWROUTE, rt, info); rt6_release(iter); if (!(fn->fn_flags & RTN_RTINFO)) { info->nl_net->ipv6.rt6_stats->fib_route_nodes++; fn->fn_flags |= RTN_RTINFO; } } return 0; }
static int fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt, struct nl_info *info) { struct rt6_info *iter = NULL; struct rt6_info **ins; int replace = (info->nlh && (info->nlh->nlmsg_flags & NLM_F_REPLACE)); int add = (!info->nlh || (info->nlh->nlmsg_flags & NLM_F_CREATE)); int found = 0; ins = &fn->leaf; for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) { /* * Search for duplicates */ if (iter->rt6i_metric == rt->rt6i_metric) { /* * Same priority level */ if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_EXCL)) return -EEXIST; if (replace) { found++; break; } if (iter->dst.dev == rt->dst.dev && iter->rt6i_idev == rt->rt6i_idev && ipv6_addr_equal(&iter->rt6i_gateway, &rt->rt6i_gateway)) { if (rt->rt6i_nsiblings) rt->rt6i_nsiblings = 0; if (!(iter->rt6i_flags & RTF_EXPIRES)) return -EEXIST; if (!(rt->rt6i_flags & RTF_EXPIRES)) rt6_clean_expires(iter); else rt6_set_expires(iter, rt->dst.expires); return -EEXIST; } /* If we have the same destination and the same metric, * but not the same gateway, then the route we try to * add is sibling to this route, increment our counter * of siblings, and later we will add our route to the * list. * Only static routes (which don't have flag * RTF_EXPIRES) are used for ECMPv6. * * To avoid long list, we only had siblings if the * route have a gateway. */ if (rt->rt6i_flags & RTF_GATEWAY && !(rt->rt6i_flags & RTF_EXPIRES) && !(iter->rt6i_flags & RTF_EXPIRES)) rt->rt6i_nsiblings++; } if (iter->rt6i_metric > rt->rt6i_metric) break; ins = &iter->dst.rt6_next; } /* Reset round-robin state, if necessary */ if (ins == &fn->leaf) fn->rr_ptr = NULL; /* Link this route to others same route. */ if (rt->rt6i_nsiblings) { unsigned int rt6i_nsiblings; struct rt6_info *sibling, *temp_sibling; /* Find the first route that have the same metric */ sibling = fn->leaf; while (sibling) { if (sibling->rt6i_metric == rt->rt6i_metric) { list_add_tail(&rt->rt6i_siblings, &sibling->rt6i_siblings); break; } sibling = sibling->dst.rt6_next; } /* For each sibling in the list, increment the counter of * siblings. BUG() if counters does not match, list of siblings * is broken! */ rt6i_nsiblings = 0; list_for_each_entry_safe(sibling, temp_sibling, &rt->rt6i_siblings, rt6i_siblings) { sibling->rt6i_nsiblings++; BUG_ON(sibling->rt6i_nsiblings != rt->rt6i_nsiblings); rt6i_nsiblings++; } BUG_ON(rt6i_nsiblings != rt->rt6i_nsiblings); } /* * insert node */ if (!replace) { if (!add) pr_warn("NLM_F_CREATE should be set when creating new route\n"); add: rt->dst.rt6_next = iter; *ins = rt; rt->rt6i_node = fn; atomic_inc(&rt->rt6i_ref); inet6_rt_notify(RTM_NEWROUTE, rt, info); info->nl_net->ipv6.rt6_stats->fib_rt_entries++; if (!(fn->fn_flags & RTN_RTINFO)) { info->nl_net->ipv6.rt6_stats->fib_route_nodes++; fn->fn_flags |= RTN_RTINFO; } } else { if (!found) { if (add) goto add; pr_warn("NLM_F_REPLACE set, but no existing node found!\n"); return -ENOENT; } *ins = rt; rt->rt6i_node = fn; rt->dst.rt6_next = iter->dst.rt6_next; atomic_inc(&rt->rt6i_ref); inet6_rt_notify(RTM_NEWROUTE, rt, info); rt6_release(iter); if (!(fn->fn_flags & RTN_RTINFO)) { info->nl_net->ipv6.rt6_stats->fib_route_nodes++; fn->fn_flags |= RTN_RTINFO; } } return 0; }
C
linux
1
CVE-2016-4558
https://www.cvedetails.com/cve/CVE-2016-4558/
null
https://github.com/torvalds/linux/commit/92117d8443bc5afacc8d5ba82e541946310f106e
92117d8443bc5afacc8d5ba82e541946310f106e
bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net>
static void bpf_map_put_uref(struct bpf_map *map) { if (atomic_dec_and_test(&map->usercnt)) { if (map->map_type == BPF_MAP_TYPE_PROG_ARRAY) bpf_fd_array_map_clear(map); } }
static void bpf_map_put_uref(struct bpf_map *map) { if (atomic_dec_and_test(&map->usercnt)) { if (map->map_type == BPF_MAP_TYPE_PROG_ARRAY) bpf_fd_array_map_clear(map); } }
C
linux
0
null
null
null
https://github.com/chromium/chromium/commit/ea3d1d84be3d6f97bf50e76511c9e26af6895533
ea3d1d84be3d6f97bf50e76511c9e26af6895533
Fix passing pointers between processes. BUG=31880 Review URL: http://codereview.chromium.org/558036 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@37555 0039d316-1c4b-4281-b951-d872f2087c98
void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& paint_rect) { if (!delegate_) return; delegate_->Paint(canvas, paint_rect); }
void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& paint_rect) { if (!delegate_) return; delegate_->Paint(canvas, paint_rect); }
C
Chrome
0
CVE-2013-1790
https://www.cvedetails.com/cve/CVE-2013-1790/
CWE-119
https://cgit.freedesktop.org/poppler/poppler/commit/?h=poppler-0.22&id=b1026b5978c385328f2a15a2185c599a563edf91
b1026b5978c385328f2a15a2185c599a563edf91
null
EmbedStream::EmbedStream(Stream *strA, Object *dictA, GBool limitedA, Guint lengthA): BaseStream(dictA, lengthA) { str = strA; limited = limitedA; length = lengthA; }
EmbedStream::EmbedStream(Stream *strA, Object *dictA, GBool limitedA, Guint lengthA): BaseStream(dictA, lengthA) { str = strA; limited = limitedA; length = lengthA; }
CPP
poppler
0
CVE-2013-0843
https://www.cvedetails.com/cve/CVE-2013-0843/
CWE-119
https://github.com/chromium/chromium/commit/f96f1f27d9bc16b1a045c4fb5c8a8a82f73ece59
f96f1f27d9bc16b1a045c4fb5c8a8a82f73ece59
Avoids crash in WebRTC audio clients for 96kHz render rate on Mac OSX. TBR=xians BUG=166523 TEST=Misc set of WebRTC audio clients on Mac. Review URL: https://codereview.chromium.org/11773017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175323 0039d316-1c4b-4281-b951-d872f2087c98
AudioFramesPerBuffer AsAudioFramesPerBuffer(int frames_per_buffer) { switch (frames_per_buffer) { case 160: return k160; case 320: return k320; case 440: return k440; case 480: return k480; case 640: return k640; case 880: return k880; case 960: return k960; case 1440: return k1440; case 1920: return k1920; } return kUnexpectedAudioBufferSize; }
AudioFramesPerBuffer AsAudioFramesPerBuffer(int frames_per_buffer) { switch (frames_per_buffer) { case 160: return k160; case 320: return k320; case 440: return k440; case 480: return k480; case 640: return k640; case 880: return k880; case 960: return k960; case 1440: return k1440; case 1920: return k1920; } return kUnexpectedAudioBufferSize; }
C
Chrome
0
CVE-2018-16427
https://www.cvedetails.com/cve/CVE-2018-16427/
CWE-125
https://github.com/OpenSC/OpenSC/pull/1447/commits/8fe377e93b4b56060e5bbfb6f3142ceaeca744fa
8fe377e93b4b56060e5bbfb6f3142ceaeca744fa
fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes.
static int entersafe_preinstall_keys(sc_card_t *card,int (*install_rsa)(sc_card_t *,u8)) { int r; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); {/* RSA */ u8 rsa_index; for(rsa_index=ENTERSAFE_MIN_KEY_ID; rsa_index<=ENTERSAFE_MAX_KEY_ID; ++rsa_index) { r=install_rsa(card,rsa_index); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall rsa key failed"); } } {/* key maintain */ /* create key maintain*/ sbuf[0] = 0; /* key len extern */ sbuf[1] = sizeof(key_maintain); /* key len */ sbuf[2] = 0x03; /* USAGE */ sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */ sbuf[4] = ENTERSAFE_AC_ALWAYS; /* CHANGE AC */ sbuf[5] = ENTERSAFE_AC_NEVER; /* UPDATE AC */ sbuf[6] = 0x01; /* ALGO */ sbuf[7] = 0x00; /* EC */ sbuf[8] = 0x00; /* VER */ memcpy(&sbuf[9], key_maintain, sizeof(key_maintain)); sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,0x00); apdu.cla=0x84; apdu.data=sbuf; apdu.lc=apdu.datalen=0x19; r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall key maintain failed"); } {/* user PIN */ memset(sbuf,0,sizeof(sbuf)); sbuf[0] = 0; /* key len extern */ sbuf[1] = 16; /* key len */ sbuf[2] = 0x0B; /* USAGE */ sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */ sbuf[4] = 0X04; /* CHANGE AC */ sbuf[5] = 0x38; /* UPDATE AC */ sbuf[6] = 0x01; /* ALGO */ sbuf[7] = 0xFF; /* EC */ sbuf[8] = 0x00; /* VER */ sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,ENTERSAFE_USER_PIN_ID); apdu.cla=0x84; apdu.data=sbuf; apdu.lc=apdu.datalen=0x19; r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall user PIN failed"); } {/* user PUK */ memset(sbuf,0,sizeof(sbuf)); sbuf[0] = 0; /* key len extern */ sbuf[1] = 16; /* key len */ sbuf[2] = 0x0B; /* USAGE */ sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */ sbuf[4] = 0X08; /* CHANGE AC */ sbuf[5] = 0xC0; /* UPDATE AC */ sbuf[6] = 0x01; /* ALGO */ sbuf[7] = 0xFF; /* EC */ sbuf[8] = 0x00; /* VER */ sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,ENTERSAFE_USER_PIN_ID+1); apdu.cla=0x84; apdu.data=sbuf; apdu.lc=apdu.datalen=0x19; r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall user PUK failed"); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS); }
static int entersafe_preinstall_keys(sc_card_t *card,int (*install_rsa)(sc_card_t *,u8)) { int r; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); {/* RSA */ u8 rsa_index; for(rsa_index=ENTERSAFE_MIN_KEY_ID; rsa_index<=ENTERSAFE_MAX_KEY_ID; ++rsa_index) { r=install_rsa(card,rsa_index); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall rsa key failed"); } } {/* key maintain */ /* create key maintain*/ sbuf[0] = 0; /* key len extern */ sbuf[1] = sizeof(key_maintain); /* key len */ sbuf[2] = 0x03; /* USAGE */ sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */ sbuf[4] = ENTERSAFE_AC_ALWAYS; /* CHANGE AC */ sbuf[5] = ENTERSAFE_AC_NEVER; /* UPDATE AC */ sbuf[6] = 0x01; /* ALGO */ sbuf[7] = 0x00; /* EC */ sbuf[8] = 0x00; /* VER */ memcpy(&sbuf[9], key_maintain, sizeof(key_maintain)); sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,0x00); apdu.cla=0x84; apdu.data=sbuf; apdu.lc=apdu.datalen=0x19; r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall key maintain failed"); } {/* user PIN */ memset(sbuf,0,sizeof(sbuf)); sbuf[0] = 0; /* key len extern */ sbuf[1] = 16; /* key len */ sbuf[2] = 0x0B; /* USAGE */ sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */ sbuf[4] = 0X04; /* CHANGE AC */ sbuf[5] = 0x38; /* UPDATE AC */ sbuf[6] = 0x01; /* ALGO */ sbuf[7] = 0xFF; /* EC */ sbuf[8] = 0x00; /* VER */ sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,ENTERSAFE_USER_PIN_ID); apdu.cla=0x84; apdu.data=sbuf; apdu.lc=apdu.datalen=0x19; r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall user PIN failed"); } {/* user PUK */ memset(sbuf,0,sizeof(sbuf)); sbuf[0] = 0; /* key len extern */ sbuf[1] = 16; /* key len */ sbuf[2] = 0x0B; /* USAGE */ sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */ sbuf[4] = 0X08; /* CHANGE AC */ sbuf[5] = 0xC0; /* UPDATE AC */ sbuf[6] = 0x01; /* ALGO */ sbuf[7] = 0xFF; /* EC */ sbuf[8] = 0x00; /* VER */ sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,ENTERSAFE_USER_PIN_ID+1); apdu.cla=0x84; apdu.data=sbuf; apdu.lc=apdu.datalen=0x19; r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall user PUK failed"); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS); }
C
OpenSC
0
CVE-2018-6035
https://www.cvedetails.com/cve/CVE-2018-6035/
CWE-200
https://github.com/chromium/chromium/commit/2649de11c562aa96d336c06136a1a20c01711be0
2649de11c562aa96d336c06136a1a20c01711be0
Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <rob@robwu.nl> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#528187}
bool ExtensionApiTest::RunExtensionTestWithArg( const std::string& extension_name, const char* custom_arg) { return RunExtensionTestImpl(extension_name, std::string(), custom_arg, kFlagEnableFileAccess); }
bool ExtensionApiTest::RunExtensionTestWithArg( const std::string& extension_name, const char* custom_arg) { return RunExtensionTestImpl(extension_name, std::string(), custom_arg, kFlagEnableFileAccess); }
C
Chrome
0
CVE-2016-6187
https://www.cvedetails.com/cve/CVE-2016-6187/
CWE-119
https://github.com/torvalds/linux/commit/30a46a4647fd1df9cf52e43bf467f0d9265096ca
30a46a4647fd1df9cf52e43bf467f0d9265096ca
apparmor: fix oops, validate buffer size in apparmor_setprocattr() When proc_pid_attr_write() was changed to use memdup_user apparmor's (interface violating) assumption that the setprocattr buffer was always a single page was violated. The size test is not strictly speaking needed as proc_pid_attr_write() will reject anything larger, but for the sake of robustness we can keep it in. SMACK and SELinux look safe to me, but somebody else should probably have a look just in case. Based on original patch from Vegard Nossum <vegard.nossum@oracle.com> modified for the case that apparmor provides null termination. Fixes: bb646cdb12e75d82258c2f2e7746d5952d3e321a Reported-by: Vegard Nossum <vegard.nossum@oracle.com> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: John Johansen <john.johansen@canonical.com> Cc: Paul Moore <paul@paul-moore.com> Cc: Stephen Smalley <sds@tycho.nsa.gov> Cc: Eric Paris <eparis@parisplace.org> Cc: Casey Schaufler <casey@schaufler-ca.com> Cc: stable@kernel.org Signed-off-by: John Johansen <john.johansen@canonical.com> Reviewed-by: Tyler Hicks <tyhicks@canonical.com> Signed-off-by: James Morris <james.l.morris@oracle.com>
static int common_file_perm(int op, struct file *file, u32 mask) { struct aa_file_cxt *fcxt = file->f_security; struct aa_profile *profile, *fprofile = aa_cred_profile(file->f_cred); int error = 0; BUG_ON(!fprofile); if (!file->f_path.mnt || !mediated_filesystem(file->f_path.dentry)) return 0; profile = __aa_current_profile(); /* revalidate access, if task is unconfined, or the cached cred * doesn't match or if the request is for more permissions than * was granted. * * Note: the test for !unconfined(fprofile) is to handle file * delegation from unconfined tasks */ if (!unconfined(profile) && !unconfined(fprofile) && ((fprofile != profile) || (mask & ~fcxt->allow))) error = aa_file_perm(op, profile, file, mask); return error; }
static int common_file_perm(int op, struct file *file, u32 mask) { struct aa_file_cxt *fcxt = file->f_security; struct aa_profile *profile, *fprofile = aa_cred_profile(file->f_cred); int error = 0; BUG_ON(!fprofile); if (!file->f_path.mnt || !mediated_filesystem(file->f_path.dentry)) return 0; profile = __aa_current_profile(); /* revalidate access, if task is unconfined, or the cached cred * doesn't match or if the request is for more permissions than * was granted. * * Note: the test for !unconfined(fprofile) is to handle file * delegation from unconfined tasks */ if (!unconfined(profile) && !unconfined(fprofile) && ((fprofile != profile) || (mask & ~fcxt->allow))) error = aa_file_perm(op, profile, file, mask); return error; }
C
linux
0
CVE-2010-1149
https://www.cvedetails.com/cve/CVE-2010-1149/
CWE-200
https://cgit.freedesktop.org/udisks/commit/?id=0fcc7cb3b66f23fac53ae08647aa0007a2bd56c4
0fcc7cb3b66f23fac53ae08647aa0007a2bd56c4
null
throw_error (DBusGMethodInvocation *context, int error_code, const char *format, ...) { GError *error; va_list args; char *message; if (context == NULL) return TRUE; va_start (args, format); message = g_strdup_vprintf (format, args); va_end (args); error = g_error_new (ERROR, error_code, "%s", message); dbus_g_method_return_error (context, error); g_error_free (error); g_free (message); return TRUE; }
throw_error (DBusGMethodInvocation *context, int error_code, const char *format, ...) { GError *error; va_list args; char *message; if (context == NULL) return TRUE; va_start (args, format); message = g_strdup_vprintf (format, args); va_end (args); error = g_error_new (ERROR, error_code, "%s", message); dbus_g_method_return_error (context, error); g_error_free (error); g_free (message); return TRUE; }
C
udisks
0
CVE-2011-2790
https://www.cvedetails.com/cve/CVE-2011-2790/
CWE-399
https://github.com/chromium/chromium/commit/adb3498ca0b69561d8c6b60bab641de4b0e37dbf
adb3498ca0b69561d8c6b60bab641de4b0e37dbf
Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
void GraphicsContext::scale(const FloatSize& scale) { #if USE(WXGC) if (m_data->context) { wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); gc->Scale(scale.width(), scale.height()); } #endif }
void GraphicsContext::scale(const FloatSize& scale) { #if USE(WXGC) if (m_data->context) { wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); gc->Scale(scale.width(), scale.height()); } #endif }
C
Chrome
0
CVE-2018-8787
https://www.cvedetails.com/cve/CVE-2018-8787/
CWE-190
https://github.com/FreeRDP/FreeRDP/commit/09b9d4f1994a674c4ec85b4947aa656eda1aed8a
09b9d4f1994a674c4ec85b4947aa656eda1aed8a
Fixed CVE-2018-8787 Thanks to Eyal Itkin from Check Point Software Technologies.
static BOOL gdi_Glyph_BeginDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor, BOOL fOpRedundant) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; if (!fOpRedundant) { if (!gdi_decode_color(gdi, bgcolor, &bgcolor, NULL)) return FALSE; if (!gdi_decode_color(gdi, fgcolor, &fgcolor, NULL)) return FALSE; gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); gdi_SetTextColor(gdi->drawing->hdc, bgcolor); gdi_SetBkColor(gdi->drawing->hdc, fgcolor); if (1) { GDI_RECT rect = { 0 }; HGDI_BRUSH brush = gdi_CreateSolidBrush(fgcolor); if (!brush) return FALSE; if (x > 0) rect.left = x; if (y > 0) rect.top = y; rect.right = x + width - 1; rect.bottom = y + height - 1; if ((x + width > rect.left) && (y + height > rect.top)) gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } return gdi_SetNullClipRgn(gdi->drawing->hdc); } return TRUE; }
static BOOL gdi_Glyph_BeginDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor, BOOL fOpRedundant) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; if (!fOpRedundant) { if (!gdi_decode_color(gdi, bgcolor, &bgcolor, NULL)) return FALSE; if (!gdi_decode_color(gdi, fgcolor, &fgcolor, NULL)) return FALSE; gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); gdi_SetTextColor(gdi->drawing->hdc, bgcolor); gdi_SetBkColor(gdi->drawing->hdc, fgcolor); if (1) { GDI_RECT rect = { 0 }; HGDI_BRUSH brush = gdi_CreateSolidBrush(fgcolor); if (!brush) return FALSE; if (x > 0) rect.left = x; if (y > 0) rect.top = y; rect.right = x + width - 1; rect.bottom = y + height - 1; if ((x + width > rect.left) && (y + height > rect.top)) gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } return gdi_SetNullClipRgn(gdi->drawing->hdc); } return TRUE; }
C
FreeRDP
0
CVE-2018-6111
https://www.cvedetails.com/cve/CVE-2018-6111/
CWE-20
https://github.com/chromium/chromium/commit/3c8e4852477d5b1e2da877808c998dc57db9460f
3c8e4852477d5b1e2da877808c998dc57db9460f
DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157}
void SendSynthesizePinchGestureResponse( std::unique_ptr<Input::Backend::SynthesizePinchGestureCallback> callback, SyntheticGesture::Result result) { if (result == SyntheticGesture::Result::GESTURE_FINISHED) { callback->sendSuccess(); } else { callback->sendFailure(Response::Error( base::StringPrintf("Synthetic pinch failed, result was %d", result))); } }
void SendSynthesizePinchGestureResponse( std::unique_ptr<Input::Backend::SynthesizePinchGestureCallback> callback, SyntheticGesture::Result result) { if (result == SyntheticGesture::Result::GESTURE_FINISHED) { callback->sendSuccess(); } else { callback->sendFailure(Response::Error( base::StringPrintf("Synthetic pinch failed, result was %d", result))); } }
C
Chrome
0
CVE-2017-18241
https://www.cvedetails.com/cve/CVE-2017-18241/
CWE-476
https://github.com/torvalds/linux/commit/d4fdf8ba0e5808ba9ad6b44337783bd9935e0982
d4fdf8ba0e5808ba9ad6b44337783bd9935e0982
f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <heyunlei@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>
static int __commit_inmem_pages(struct inode *inode, struct list_head *revoke_list) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct f2fs_inode_info *fi = F2FS_I(inode); struct inmem_pages *cur, *tmp; struct f2fs_io_info fio = { .sbi = sbi, .type = DATA, .op = REQ_OP_WRITE, .op_flags = REQ_SYNC | REQ_PRIO, }; pgoff_t last_idx = ULONG_MAX; int err = 0; list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) { struct page *page = cur->page; lock_page(page); if (page->mapping == inode->i_mapping) { trace_f2fs_commit_inmem_page(page, INMEM); set_page_dirty(page); f2fs_wait_on_page_writeback(page, DATA, true); if (clear_page_dirty_for_io(page)) { inode_dec_dirty_pages(inode); remove_dirty_inode(inode); } fio.page = page; fio.old_blkaddr = NULL_ADDR; fio.encrypted_page = NULL; fio.need_lock = LOCK_DONE; err = do_write_data_page(&fio); if (err) { unlock_page(page); break; } /* record old blkaddr for revoking */ cur->old_addr = fio.old_blkaddr; last_idx = page->index; } unlock_page(page); list_move_tail(&cur->list, revoke_list); } if (last_idx != ULONG_MAX) f2fs_submit_merged_write_cond(sbi, inode, 0, last_idx, DATA); if (!err) __revoke_inmem_pages(inode, revoke_list, false, false); return err; }
static int __commit_inmem_pages(struct inode *inode, struct list_head *revoke_list) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct f2fs_inode_info *fi = F2FS_I(inode); struct inmem_pages *cur, *tmp; struct f2fs_io_info fio = { .sbi = sbi, .type = DATA, .op = REQ_OP_WRITE, .op_flags = REQ_SYNC | REQ_PRIO, }; pgoff_t last_idx = ULONG_MAX; int err = 0; list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) { struct page *page = cur->page; lock_page(page); if (page->mapping == inode->i_mapping) { trace_f2fs_commit_inmem_page(page, INMEM); set_page_dirty(page); f2fs_wait_on_page_writeback(page, DATA, true); if (clear_page_dirty_for_io(page)) { inode_dec_dirty_pages(inode); remove_dirty_inode(inode); } fio.page = page; fio.old_blkaddr = NULL_ADDR; fio.encrypted_page = NULL; fio.need_lock = LOCK_DONE; err = do_write_data_page(&fio); if (err) { unlock_page(page); break; } /* record old blkaddr for revoking */ cur->old_addr = fio.old_blkaddr; last_idx = page->index; } unlock_page(page); list_move_tail(&cur->list, revoke_list); } if (last_idx != ULONG_MAX) f2fs_submit_merged_write_cond(sbi, inode, 0, last_idx, DATA); if (!err) __revoke_inmem_pages(inode, revoke_list, false, false); return err; }
C
linux
0
CVE-2010-2527
https://www.cvedetails.com/cve/CVE-2010-2527/
CWE-119
https://git.savannah.gnu.org/cgit/freetype/freetype2-demos.git/commit/?id=b995299b73ba4cd259f221f500d4e63095508bec
b995299b73ba4cd259f221f500d4e63095508bec
null
adisplay_draw_glyph( void* _display, DisplayMode mode, int x, int y, int width, int height, int pitch, void* buffer ) { ADisplay display = (ADisplay)_display; grBitmap glyph; glyph.width = width; glyph.rows = height; glyph.pitch = pitch; glyph.buffer = (unsigned char*)buffer; glyph.grays = 256; glyph.mode = gr_pixel_mode_mono; if ( mode == DISPLAY_MODE_GRAY ) glyph.mode = gr_pixel_mode_gray; else if ( mode == DISPLAY_MODE_LCD ) glyph.mode = gr_pixel_mode_lcd; grBlitGlyphToBitmap( display->bitmap, &glyph, x, y, display->fore_color ); }
adisplay_draw_glyph( void* _display, DisplayMode mode, int x, int y, int width, int height, int pitch, void* buffer ) { ADisplay display = (ADisplay)_display; grBitmap glyph; glyph.width = width; glyph.rows = height; glyph.pitch = pitch; glyph.buffer = (unsigned char*)buffer; glyph.grays = 256; glyph.mode = gr_pixel_mode_mono; if ( mode == DISPLAY_MODE_GRAY ) glyph.mode = gr_pixel_mode_gray; else if ( mode == DISPLAY_MODE_LCD ) glyph.mode = gr_pixel_mode_lcd; grBlitGlyphToBitmap( display->bitmap, &glyph, x, y, display->fore_color ); }
C
savannah
0
CVE-2015-6787
https://www.cvedetails.com/cve/CVE-2015-6787/
null
https://github.com/chromium/chromium/commit/f911e11e7f6b5c0d6f5ee694a9871de6619889f7
f911e11e7f6b5c0d6f5ee694a9871de6619889f7
Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <trchen@chromium.org> > > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > > Cr-Commit-Position: refs/heads/master@{#554626} > > TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > Cr-Commit-Position: refs/heads/master@{#554653} TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> Cr-Commit-Position: refs/heads/master@{#563930}
void FragmentPaintPropertyTreeBuilder::UpdateClipPathCache() { if (fragment_data_.IsClipPathCacheValid()) return; if (!object_.StyleRef().ClipPath()) return; base::Optional<FloatRect> bounding_box = ClipPathClipper::LocalClipPathBoundingBox(object_); if (!bounding_box) { fragment_data_.SetClipPathCache(base::nullopt, nullptr); return; } bounding_box->MoveBy(FloatPoint(fragment_data_.PaintOffset())); bool is_valid = false; base::Optional<Path> path = ClipPathClipper::PathBasedClip( object_, object_.IsSVGChild(), ClipPathClipper::LocalReferenceBox(object_), is_valid); DCHECK(is_valid); if (path) path->Translate(ToFloatSize(FloatPoint(fragment_data_.PaintOffset()))); fragment_data_.SetClipPathCache( EnclosingIntRect(*bounding_box), path ? AdoptRef(new RefCountedPath(std::move(*path))) : nullptr); }
void FragmentPaintPropertyTreeBuilder::UpdateClipPathCache() { if (fragment_data_.IsClipPathCacheValid()) return; if (!object_.StyleRef().ClipPath()) return; base::Optional<FloatRect> bounding_box = ClipPathClipper::LocalClipPathBoundingBox(object_); if (!bounding_box) { fragment_data_.SetClipPathCache(base::nullopt, nullptr); return; } bounding_box->MoveBy(FloatPoint(fragment_data_.PaintOffset())); bool is_valid = false; base::Optional<Path> path = ClipPathClipper::PathBasedClip( object_, object_.IsSVGChild(), ClipPathClipper::LocalReferenceBox(object_), is_valid); DCHECK(is_valid); if (path) path->Translate(ToFloatSize(FloatPoint(fragment_data_.PaintOffset()))); fragment_data_.SetClipPathCache( EnclosingIntRect(*bounding_box), path ? AdoptRef(new RefCountedPath(std::move(*path))) : nullptr); }
C
Chrome
0
CVE-2012-3552
https://www.cvedetails.com/cve/CVE-2012-3552/
CWE-362
https://github.com/torvalds/linux/commit/f6d8bd051c391c1c0458a30b2a7abcd939329259
f6d8bd051c391c1c0458a30b2a7abcd939329259
inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net>
void __init tcp_v4_init(void) { inet_hashinfo_init(&tcp_hashinfo); if (register_pernet_subsys(&tcp_sk_ops)) panic("Failed to create the TCP control socket.\n"); }
void __init tcp_v4_init(void) { inet_hashinfo_init(&tcp_hashinfo); if (register_pernet_subsys(&tcp_sk_ops)) panic("Failed to create the TCP control socket.\n"); }
C
linux
0
CVE-2011-2803
https://www.cvedetails.com/cve/CVE-2011-2803/
CWE-119
https://github.com/chromium/chromium/commit/48f2ec5c24570c9b96bb2798a9ffe956117c5066
48f2ec5c24570c9b96bb2798a9ffe956117c5066
Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None R=sky@chromium.org Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98
TreeModelNode* TreeView::GetEditingNode() { return editing_node_; }
TreeModelNode* TreeView::GetEditingNode() { return editing_node_; }
C
Chrome
0
CVE-2018-20482
https://www.cvedetails.com/cve/CVE-2018-20482/
CWE-835
https://git.savannah.gnu.org/cgit/tar.git/commit/?id=c15c42ccd1e2377945fd0414eca1a49294bff454
c15c42ccd1e2377945fd0414eca1a49294bff454
null
sparse_scan_file_raw (struct tar_sparse_file *file) { struct tar_stat_info *st = file->stat_info; int fd = file->fd; char buffer[BLOCKSIZE]; size_t count = 0; off_t offset = 0; struct sp_array sp = {0, 0}; st->archive_file_size = 0; if (!tar_sparse_scan (file, scan_begin, NULL)) return false; while ((count = blocking_read (fd, buffer, sizeof buffer)) != 0 && count != SAFE_READ_ERROR) { /* Analyze the block. */ if (zero_block_p (buffer, count)) { if (sp.numbytes) { sparse_add_map (st, &sp); sp.numbytes = 0; if (!tar_sparse_scan (file, scan_block, NULL)) return false; } } else { if (sp.numbytes == 0) sp.offset = offset; sp.numbytes += count; st->archive_file_size += count; if (!tar_sparse_scan (file, scan_block, buffer)) return false; } offset += count; } /* save one more sparse segment of length 0 to indicate that the file ends with a hole */ if (sp.numbytes == 0) sp.offset = offset; sparse_add_map (st, &sp); st->archive_file_size += count; return tar_sparse_scan (file, scan_end, NULL); }
sparse_scan_file_raw (struct tar_sparse_file *file) { struct tar_stat_info *st = file->stat_info; int fd = file->fd; char buffer[BLOCKSIZE]; size_t count = 0; off_t offset = 0; struct sp_array sp = {0, 0}; st->archive_file_size = 0; if (!tar_sparse_scan (file, scan_begin, NULL)) return false; while ((count = blocking_read (fd, buffer, sizeof buffer)) != 0 && count != SAFE_READ_ERROR) { /* Analyze the block. */ if (zero_block_p (buffer, count)) { if (sp.numbytes) { sparse_add_map (st, &sp); sp.numbytes = 0; if (!tar_sparse_scan (file, scan_block, NULL)) return false; } } else { if (sp.numbytes == 0) sp.offset = offset; sp.numbytes += count; st->archive_file_size += count; if (!tar_sparse_scan (file, scan_block, buffer)) return false; } offset += count; } /* save one more sparse segment of length 0 to indicate that the file ends with a hole */ if (sp.numbytes == 0) sp.offset = offset; sparse_add_map (st, &sp); st->archive_file_size += count; return tar_sparse_scan (file, scan_end, NULL); }
C
savannah
0
CVE-2018-16075
https://www.cvedetails.com/cve/CVE-2018-16075/
CWE-254
https://github.com/chromium/chromium/commit/d913f72b4875cf0814fc3f03ad7c00642097c4a4
d913f72b4875cf0814fc3f03ad7c00642097c4a4
Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <mkwst@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Dave Tapuska <dtapuska@chromium.org> Cr-Commit-Position: refs/heads/master@{#607329}
CSSStyleSheetResource::CSSStyleSheetResource( const ResourceRequest& resource_request, const ResourceLoaderOptions& options, const TextResourceDecoderOptions& decoder_options) : TextResource(resource_request, ResourceType::kCSSStyleSheet, options, decoder_options) {}
CSSStyleSheetResource::CSSStyleSheetResource( const ResourceRequest& resource_request, const ResourceLoaderOptions& options, const TextResourceDecoderOptions& decoder_options) : TextResource(resource_request, ResourceType::kCSSStyleSheet, options, decoder_options) {}
C
Chrome
0
null
null
null
https://github.com/chromium/chromium/commit/327585cb0eab0859518643a2d00917081f7e7645
327585cb0eab0859518643a2d00917081f7e7645
2010-10-26 Kenneth Russell <kbr@google.com> Reviewed by Andreas Kling. Valgrind failure in GraphicsContext3DInternal::reshape https://bugs.webkit.org/show_bug.cgi?id=48284 * src/WebGraphicsContext3DDefaultImpl.cpp: (WebKit::WebGraphicsContext3DDefaultImpl::WebGraphicsContext3DDefaultImpl): git-svn-id: svn://svn.chromium.org/blink/trunk@70534 bbb929c8-8fbe-4397-9dbb-9b2b20218538
void WebGraphicsContext3DDefaultImpl::deleteTexture(unsigned texture) { makeContextCurrent(); glDeleteTextures(1, &texture); }
void WebGraphicsContext3DDefaultImpl::deleteTexture(unsigned texture) { makeContextCurrent(); glDeleteTextures(1, &texture); }
C
Chrome
0
CVE-2018-1000040
https://www.cvedetails.com/cve/CVE-2018-1000040/
CWE-20
http://git.ghostscript.com/?p=mupdf.git;a=commitdiff;h=83d4dae44c71816c084a635550acc1a51529b881;hp=f597300439e62f5e921f0d7b1e880b5c1a1f1607
83d4dae44c71816c084a635550acc1a51529b881
null
int fz_colorspace_is_icc(fz_context *ctx, const fz_colorspace *cs) { return cs && (cs->flags & FZ_COLORSPACE_IS_ICC); }
int fz_colorspace_is_icc(fz_context *ctx, const fz_colorspace *cs) { return cs && (cs->flags & FZ_COLORSPACE_IS_ICC); }
C
ghostscript
0
CVE-2016-9754
https://www.cvedetails.com/cve/CVE-2016-9754/
CWE-190
https://github.com/torvalds/linux/commit/59643d1535eb220668692a5359de22545af579f6
59643d1535eb220668692a5359de22545af579f6
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>
static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer) { struct list_head *head = cpu_buffer->pages; struct buffer_page *bpage, *tmp; /* Reset the head page if it exists */ if (cpu_buffer->head_page) rb_set_head_page(cpu_buffer); rb_head_page_deactivate(cpu_buffer); if (RB_WARN_ON(cpu_buffer, head->next->prev != head)) return -1; if (RB_WARN_ON(cpu_buffer, head->prev->next != head)) return -1; if (rb_check_list(cpu_buffer, head)) return -1; list_for_each_entry_safe(bpage, tmp, head, list) { if (RB_WARN_ON(cpu_buffer, bpage->list.next->prev != &bpage->list)) return -1; if (RB_WARN_ON(cpu_buffer, bpage->list.prev->next != &bpage->list)) return -1; if (rb_check_list(cpu_buffer, &bpage->list)) return -1; } rb_head_page_activate(cpu_buffer); return 0; }
static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer) { struct list_head *head = cpu_buffer->pages; struct buffer_page *bpage, *tmp; /* Reset the head page if it exists */ if (cpu_buffer->head_page) rb_set_head_page(cpu_buffer); rb_head_page_deactivate(cpu_buffer); if (RB_WARN_ON(cpu_buffer, head->next->prev != head)) return -1; if (RB_WARN_ON(cpu_buffer, head->prev->next != head)) return -1; if (rb_check_list(cpu_buffer, head)) return -1; list_for_each_entry_safe(bpage, tmp, head, list) { if (RB_WARN_ON(cpu_buffer, bpage->list.next->prev != &bpage->list)) return -1; if (RB_WARN_ON(cpu_buffer, bpage->list.prev->next != &bpage->list)) return -1; if (rb_check_list(cpu_buffer, &bpage->list)) return -1; } rb_head_page_activate(cpu_buffer); return 0; }
C
linux
0
CVE-2012-3552
https://www.cvedetails.com/cve/CVE-2012-3552/
CWE-362
https://github.com/torvalds/linux/commit/f6d8bd051c391c1c0458a30b2a7abcd939329259
f6d8bd051c391c1c0458a30b2a7abcd939329259
inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net>
static struct sock *raw_get_idx(struct seq_file *seq, loff_t pos) { struct sock *sk = raw_get_first(seq); if (sk) while (pos && (sk = raw_get_next(seq, sk)) != NULL) --pos; return pos ? NULL : sk; }
static struct sock *raw_get_idx(struct seq_file *seq, loff_t pos) { struct sock *sk = raw_get_first(seq); if (sk) while (pos && (sk = raw_get_next(seq, sk)) != NULL) --pos; return pos ? NULL : sk; }
C
linux
0
CVE-2015-1265
https://www.cvedetails.com/cve/CVE-2015-1265/
null
https://github.com/chromium/chromium/commit/8ea5693d5cf304e56174bb6b65412f04209904db
8ea5693d5cf304e56174bb6b65412f04209904db
Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Cr-Commit-Position: refs/heads/master@{#489518}
static bool ExecuteMoveToEndOfLineAndModifySelection(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.Selection().Modify( SelectionModifyAlteration::kExtend, SelectionModifyDirection::kForward, TextGranularity::kLineBoundary, SetSelectionBy::kUser); return true; }
static bool ExecuteMoveToEndOfLineAndModifySelection(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.Selection().Modify( SelectionModifyAlteration::kExtend, SelectionModifyDirection::kForward, TextGranularity::kLineBoundary, SetSelectionBy::kUser); return true; }
C
Chrome
0
CVE-2018-6085
https://www.cvedetails.com/cve/CVE-2018-6085/
CWE-20
https://github.com/chromium/chromium/commit/df5b1e1f88e013bc96107cc52c4a4f33a8238444
df5b1e1f88e013bc96107cc52c4a4f33a8238444
Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <mmenke@chromium.org> Commit-Queue: Maks Orlovich <morlovich@chromium.org> Cr-Commit-Position: refs/heads/master@{#547103}
void BackendImpl::UpgradeTo2_1() { DCHECK(0x20000 == data_->header.version); data_->header.version = 0x20001; data_->header.lru.sizes[Rankings::NO_USE] = data_->header.num_entries; }
void BackendImpl::UpgradeTo2_1() { DCHECK(0x20000 == data_->header.version); data_->header.version = 0x20001; data_->header.lru.sizes[Rankings::NO_USE] = data_->header.num_entries; }
C
Chrome
0
CVE-2014-1444
https://www.cvedetails.com/cve/CVE-2014-1444/
CWE-399
https://github.com/torvalds/linux/commit/96b340406724d87e4621284ebac5e059d67b2194
96b340406724d87e4621284ebac5e059d67b2194
farsync: fix info leak in ioctl The fst_get_iface() code fails to initialize the two padding bytes of struct sync_serial_settings after the ->loopback member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: David S. Miller <davem@davemloft.net>
fst_disable_intr(struct fst_card_info *card) { if (card->family == FST_FAMILY_TXU) { outl(0x00000000, card->pci_conf + INTCSR_9054); } else { outw(0x0000, card->pci_conf + INTCSR_9052); } }
fst_disable_intr(struct fst_card_info *card) { if (card->family == FST_FAMILY_TXU) { outl(0x00000000, card->pci_conf + INTCSR_9054); } else { outw(0x0000, card->pci_conf + INTCSR_9052); } }
C
linux
0
CVE-2018-20763
https://www.cvedetails.com/cve/CVE-2018-20763/
CWE-787
https://github.com/gpac/gpac/commit/1c449a34fe0b50aaffb881bfb9d7c5ab0bb18cdd
1c449a34fe0b50aaffb881bfb9d7c5ab0bb18cdd
add some boundary checks on gf_text_get_utf8_line (#1188)
void PrintUsage() { fprintf(stderr, "Usage MP4Client [options] [filename]\n" "\t-c fileName: user-defined configuration file. Also works with -cfg\n" #ifdef GPAC_MEMORY_TRACKING "\t-mem-track: enables memory tracker\n" "\t-mem-track-stack: enables memory tracker with stack dumping\n" #endif "\t-rti fileName: logs run-time info (FPS, CPU, Mem usage) to file\n" "\t-rtix fileName: same as -rti but driven by GPAC logs\n" "\t-quiet: removes script message, buffering and downloading status\n" "\t-strict-error: exit when the player reports its first error\n" "\t-opt option: Overrides an option in the configuration file. String format is section:key=value. \n" "\t \"section:key=null\" removes the key\n" "\t \"section:*=null\" removes the section\n" "\t-conf option: Same as -opt but does not start player.\n" "\t-log-file file: sets output log file. Also works with -lf\n" "\t-logs log_args: sets log tools and levels, formatted as a ':'-separated list of toolX[:toolZ]@levelX\n" "\t levelX can be one of:\n" "\t \"quiet\" : skip logs\n" "\t \"error\" : logs only error messages\n" "\t \"warning\" : logs error+warning messages\n" "\t \"info\" : logs error+warning+info messages\n" "\t \"debug\" : logs all messages\n" "\t toolX can be one of:\n" "\t \"core\" : libgpac core\n" "\t \"coding\" : bitstream formats (audio, video, scene)\n" "\t \"container\" : container formats (ISO File, MPEG-2 TS, AVI, ...)\n" "\t \"network\" : network data exept RTP trafic\n" "\t \"rtp\" : rtp trafic\n" "\t \"author\" : authoring tools (hint, import, export)\n" "\t \"sync\" : terminal sync layer\n" "\t \"codec\" : terminal codec messages\n" "\t \"parser\" : scene parsers (svg, xmt, bt) and other\n" "\t \"media\" : terminal media object management\n" "\t \"scene\" : scene graph and scene manager\n" "\t \"script\" : scripting engine messages\n" "\t \"interact\" : interaction engine (events, scripts, etc)\n" "\t \"smil\" : SMIL timing engine\n" "\t \"compose\" : composition engine (2D, 3D, etc)\n" "\t \"mmio\" : Audio/Video HW I/O management\n" "\t \"rti\" : various run-time stats\n" "\t \"cache\" : HTTP cache subsystem\n" "\t \"audio\" : Audio renderer and mixers\n" #ifdef GPAC_MEMORY_TRACKING "\t \"mem\" : GPAC memory tracker\n" #endif #ifndef GPAC_DISABLE_DASH_CLIENT "\t \"dash\" : HTTP streaming logs\n" #endif "\t \"module\" : GPAC modules debugging\n" "\t \"mutex\" : mutex\n" "\t \"all\" : all tools logged - other tools can be specified afterwards.\n" "\tThe special value \"ncl\" disables color logs.\n" "\n" "\t-log-clock or -lc : logs time in micro sec since start time of GPAC before each log line.\n" "\t-log-utc or -lu : logs UTC time in ms before each log line.\n" "\t-ifce IPIFCE : Sets default Multicast interface\n" "\t-size WxH: specifies visual size (default: scene size)\n" #if defined(__DARWIN__) || defined(__APPLE__) "\t-thread: enables thread usage for terminal and compositor \n" #else "\t-no-thread: disables thread usage (except for audio)\n" #endif "\t-no-cthread: disables compositor thread (iOS and Android mode)\n" "\t-no-audio: disables audio \n" "\t-no-wnd: uses windowless mode (Win32 only)\n" "\t-no-back: uses transparent background for output window when no background is specified (Win32 only)\n" "\t-align vh: specifies v and h alignment for windowless mode\n" "\t possible v values: t(op), m(iddle), b(ottom)\n" "\t possible h values: l(eft), m(iddle), r(ight)\n" "\t default alignment is top-left\n" "\t default alignment is top-left\n" "\t-pause: pauses at first frame\n" "\t-play-from T: starts from T seconds in media\n" "\t-speed S: starts with speed S\n" "\t-loop: loops presentation\n" "\t-no-regulation: disables framerate regulation\n" "\t-bench: disable a/v output and bench source decoding (as fast as possible)\n" "\t-vbench: disable audio output, video sync bench source decoding/display (as fast as possible)\n" "\t-sbench: disable all decoders and bench systems layer (as fast as possible)\n" "\t-fs: starts in fullscreen mode\n" "\t-views v1:.:vN: creates an auto-stereo scene of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored, GUI as well.\n" "\t this is equivalent as using views://v1:.:N as an URL.\n" "\t-mosaic v1:.:vN: creates a mosaic of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored.\n" "\t this is equivalent as using mosaic://v1:.:N as an URL.\n" "\n" "\t-exit: automatically exits when presentation is over\n" "\t-run-for TIME: runs for TIME seconds and exits\n" "\t-service ID: auto-tune to given service ID in a multiplex\n" "\t-noprog: disable progress report\n" "\t-no-save: disable saving config file on exit\n" "\t-no-addon: disable automatic loading of media addons declared in source URL\n" "\t-gui: starts in GUI mode. The GUI is indicated in GPAC config, section General, by the key [StartupFile]\n" "\t-ntp-shift T: shifts NTP clock of T (signed int) milliseconds\n" "\n" "Dumper Options (times is a formated as start-end, with start being sec, h:m:s:f/fps or h:m:s:ms):\n" "\t-bmp [times]: dumps given frames to bmp\n" "\t-png [times]: dumps given frames to png\n" "\t-raw [times]: dumps given frames to raw\n" "\t-avi [times]: dumps given file to raw avi\n" "\t-sha [times]: dumps given file to raw SHA-1 (1 hash per frame)\n" "\r-out filename: name of the output file\n" "\t-rgbds: dumps the RGBDS pixel format texture\n" "\t with -avi [times]: dumps an rgbds-format .avi\n" "\t-rgbd: dumps the RGBD pixel format texture\n" "\t with -avi [times]: dumps an rgbd-format .avi\n" "\t-depth: dumps depthmap (z-buffer) frames\n" "\t with -avi [times]: dumps depthmap in grayscale .avi\n" "\t with -bmp: dumps depthmap in grayscale .bmp\n" "\t with -png: dumps depthmap in grayscale .png\n" "\t-fps FPS: specifies frame rate for AVI dumping (default: %f)\n" "\t-scale s: scales the visual size (default: 1)\n" "\t-fill: uses fill aspect ratio for dumping (default: none)\n" "\t-show: shows window while dumping (default: no)\n" "\n" "\t-uncache: Revert all cached items to their original name and location. Does not start player.\n" "\n" "\t-help: shows this screen\n" "\n" "MP4Client - GPAC command line player and dumper - version "GPAC_FULL_VERSION"\n" "(c) Telecom ParisTech 2000-2018 - Licence LGPL v2\n" "GPAC Configuration: " GPAC_CONFIGURATION "\n" "Features: %s\n", GF_IMPORT_DEFAULT_FPS, gpac_features() ); }
void PrintUsage() { fprintf(stderr, "Usage MP4Client [options] [filename]\n" "\t-c fileName: user-defined configuration file. Also works with -cfg\n" #ifdef GPAC_MEMORY_TRACKING "\t-mem-track: enables memory tracker\n" "\t-mem-track-stack: enables memory tracker with stack dumping\n" #endif "\t-rti fileName: logs run-time info (FPS, CPU, Mem usage) to file\n" "\t-rtix fileName: same as -rti but driven by GPAC logs\n" "\t-quiet: removes script message, buffering and downloading status\n" "\t-strict-error: exit when the player reports its first error\n" "\t-opt option: Overrides an option in the configuration file. String format is section:key=value. \n" "\t \"section:key=null\" removes the key\n" "\t \"section:*=null\" removes the section\n" "\t-conf option: Same as -opt but does not start player.\n" "\t-log-file file: sets output log file. Also works with -lf\n" "\t-logs log_args: sets log tools and levels, formatted as a ':'-separated list of toolX[:toolZ]@levelX\n" "\t levelX can be one of:\n" "\t \"quiet\" : skip logs\n" "\t \"error\" : logs only error messages\n" "\t \"warning\" : logs error+warning messages\n" "\t \"info\" : logs error+warning+info messages\n" "\t \"debug\" : logs all messages\n" "\t toolX can be one of:\n" "\t \"core\" : libgpac core\n" "\t \"coding\" : bitstream formats (audio, video, scene)\n" "\t \"container\" : container formats (ISO File, MPEG-2 TS, AVI, ...)\n" "\t \"network\" : network data exept RTP trafic\n" "\t \"rtp\" : rtp trafic\n" "\t \"author\" : authoring tools (hint, import, export)\n" "\t \"sync\" : terminal sync layer\n" "\t \"codec\" : terminal codec messages\n" "\t \"parser\" : scene parsers (svg, xmt, bt) and other\n" "\t \"media\" : terminal media object management\n" "\t \"scene\" : scene graph and scene manager\n" "\t \"script\" : scripting engine messages\n" "\t \"interact\" : interaction engine (events, scripts, etc)\n" "\t \"smil\" : SMIL timing engine\n" "\t \"compose\" : composition engine (2D, 3D, etc)\n" "\t \"mmio\" : Audio/Video HW I/O management\n" "\t \"rti\" : various run-time stats\n" "\t \"cache\" : HTTP cache subsystem\n" "\t \"audio\" : Audio renderer and mixers\n" #ifdef GPAC_MEMORY_TRACKING "\t \"mem\" : GPAC memory tracker\n" #endif #ifndef GPAC_DISABLE_DASH_CLIENT "\t \"dash\" : HTTP streaming logs\n" #endif "\t \"module\" : GPAC modules debugging\n" "\t \"mutex\" : mutex\n" "\t \"all\" : all tools logged - other tools can be specified afterwards.\n" "\tThe special value \"ncl\" disables color logs.\n" "\n" "\t-log-clock or -lc : logs time in micro sec since start time of GPAC before each log line.\n" "\t-log-utc or -lu : logs UTC time in ms before each log line.\n" "\t-ifce IPIFCE : Sets default Multicast interface\n" "\t-size WxH: specifies visual size (default: scene size)\n" #if defined(__DARWIN__) || defined(__APPLE__) "\t-thread: enables thread usage for terminal and compositor \n" #else "\t-no-thread: disables thread usage (except for audio)\n" #endif "\t-no-cthread: disables compositor thread (iOS and Android mode)\n" "\t-no-audio: disables audio \n" "\t-no-wnd: uses windowless mode (Win32 only)\n" "\t-no-back: uses transparent background for output window when no background is specified (Win32 only)\n" "\t-align vh: specifies v and h alignment for windowless mode\n" "\t possible v values: t(op), m(iddle), b(ottom)\n" "\t possible h values: l(eft), m(iddle), r(ight)\n" "\t default alignment is top-left\n" "\t default alignment is top-left\n" "\t-pause: pauses at first frame\n" "\t-play-from T: starts from T seconds in media\n" "\t-speed S: starts with speed S\n" "\t-loop: loops presentation\n" "\t-no-regulation: disables framerate regulation\n" "\t-bench: disable a/v output and bench source decoding (as fast as possible)\n" "\t-vbench: disable audio output, video sync bench source decoding/display (as fast as possible)\n" "\t-sbench: disable all decoders and bench systems layer (as fast as possible)\n" "\t-fs: starts in fullscreen mode\n" "\t-views v1:.:vN: creates an auto-stereo scene of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored, GUI as well.\n" "\t this is equivalent as using views://v1:.:N as an URL.\n" "\t-mosaic v1:.:vN: creates a mosaic of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored.\n" "\t this is equivalent as using mosaic://v1:.:N as an URL.\n" "\n" "\t-exit: automatically exits when presentation is over\n" "\t-run-for TIME: runs for TIME seconds and exits\n" "\t-service ID: auto-tune to given service ID in a multiplex\n" "\t-noprog: disable progress report\n" "\t-no-save: disable saving config file on exit\n" "\t-no-addon: disable automatic loading of media addons declared in source URL\n" "\t-gui: starts in GUI mode. The GUI is indicated in GPAC config, section General, by the key [StartupFile]\n" "\t-ntp-shift T: shifts NTP clock of T (signed int) milliseconds\n" "\n" "Dumper Options (times is a formated as start-end, with start being sec, h:m:s:f/fps or h:m:s:ms):\n" "\t-bmp [times]: dumps given frames to bmp\n" "\t-png [times]: dumps given frames to png\n" "\t-raw [times]: dumps given frames to raw\n" "\t-avi [times]: dumps given file to raw avi\n" "\t-sha [times]: dumps given file to raw SHA-1 (1 hash per frame)\n" "\r-out filename: name of the output file\n" "\t-rgbds: dumps the RGBDS pixel format texture\n" "\t with -avi [times]: dumps an rgbds-format .avi\n" "\t-rgbd: dumps the RGBD pixel format texture\n" "\t with -avi [times]: dumps an rgbd-format .avi\n" "\t-depth: dumps depthmap (z-buffer) frames\n" "\t with -avi [times]: dumps depthmap in grayscale .avi\n" "\t with -bmp: dumps depthmap in grayscale .bmp\n" "\t with -png: dumps depthmap in grayscale .png\n" "\t-fps FPS: specifies frame rate for AVI dumping (default: %f)\n" "\t-scale s: scales the visual size (default: 1)\n" "\t-fill: uses fill aspect ratio for dumping (default: none)\n" "\t-show: shows window while dumping (default: no)\n" "\n" "\t-uncache: Revert all cached items to their original name and location. Does not start player.\n" "\n" "\t-help: shows this screen\n" "\n" "MP4Client - GPAC command line player and dumper - version "GPAC_FULL_VERSION"\n" "(c) Telecom ParisTech 2000-2018 - Licence LGPL v2\n" "GPAC Configuration: " GPAC_CONFIGURATION "\n" "Features: %s\n", GF_IMPORT_DEFAULT_FPS, gpac_features() ); }
C
gpac
0
CVE-2015-6787
https://www.cvedetails.com/cve/CVE-2015-6787/
null
https://github.com/chromium/chromium/commit/f911e11e7f6b5c0d6f5ee694a9871de6619889f7
f911e11e7f6b5c0d6f5ee694a9871de6619889f7
Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <trchen@chromium.org> > > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > > Cr-Commit-Position: refs/heads/master@{#554626} > > TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > Cr-Commit-Position: refs/heads/master@{#554653} TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> Cr-Commit-Position: refs/heads/master@{#563930}
void TestInvalidationInSubsequence() { FakeDisplayItemClient container("container"); FakeDisplayItemClient content("content"); GraphicsContext context(GetPaintController()); InitRootChunk(); { SubsequenceRecorder r(context, container); DrawRect(context, content, kBackgroundType, FloatRect(100, 100, 300, 300)); } GetPaintController().CommitNewDisplayItems(); content.SetDisplayItemsUncached(); InitRootChunk(); { EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( context, container)); SubsequenceRecorder r(context, container); DrawRect(context, content, kBackgroundType, FloatRect(100, 100, 300, 300)); } GetPaintController().CommitNewDisplayItems(); }
void TestInvalidationInSubsequence() { FakeDisplayItemClient container("container"); FakeDisplayItemClient content("content"); GraphicsContext context(GetPaintController()); InitRootChunk(); { SubsequenceRecorder r(context, container); DrawRect(context, content, kBackgroundType, FloatRect(100, 100, 300, 300)); } GetPaintController().CommitNewDisplayItems(); content.SetDisplayItemsUncached(); InitRootChunk(); { EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible( context, container)); SubsequenceRecorder r(context, container); DrawRect(context, content, kBackgroundType, FloatRect(100, 100, 300, 300)); } GetPaintController().CommitNewDisplayItems(); }
C
Chrome
0
CVE-2012-2880
https://www.cvedetails.com/cve/CVE-2012-2880/
CWE-362
https://github.com/chromium/chromium/commit/fcd3a7a671ecf2d5f46ea34787d27507a914d2f5
fcd3a7a671ecf2d5f46ea34787d27507a914d2f5
[Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
void SyncManager::SyncInternal::HandleTransactionCompleteChangeEvent( ModelTypeSet models_with_changes) { if (!change_delegate_) return; for (ModelTypeSet::Iterator it = models_with_changes.First(); it.Good(); it.Inc()) { change_delegate_->OnChangesComplete(it.Get()); change_observer_.Call( FROM_HERE, &SyncManager::ChangeObserver::OnChangesComplete, it.Get()); } }
void SyncManager::SyncInternal::HandleTransactionCompleteChangeEvent( ModelTypeSet models_with_changes) { if (!change_delegate_) return; for (ModelTypeSet::Iterator it = models_with_changes.First(); it.Good(); it.Inc()) { change_delegate_->OnChangesComplete(it.Get()); change_observer_.Call( FROM_HERE, &SyncManager::ChangeObserver::OnChangesComplete, it.Get()); } }
C
Chrome
0
CVE-2019-11487
https://www.cvedetails.com/cve/CVE-2019-11487/
CWE-416
https://github.com/torvalds/linux/commit/6b3a707736301c2128ca85ce85fb13f60b5e350a
6b3a707736301c2128ca85ce85fb13f60b5e350a
Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit
void tracing_snapshot_instance(struct trace_array *tr) { tracing_snapshot_instance_cond(tr, NULL); }
void tracing_snapshot_instance(struct trace_array *tr) { tracing_snapshot_instance_cond(tr, NULL); }
C
linux
0
CVE-2011-4930
https://www.cvedetails.com/cve/CVE-2011-4930/
CWE-134
https://htcondor-git.cs.wisc.edu/?p=condor.git;a=commitdiff;h=5e5571d1a431eb3c61977b6dd6ec90186ef79867
5e5571d1a431eb3c61977b6dd6ec90186ef79867
null
static int use_special_access( const char *file ) { return !strcmp(file,"/dev/tcp") || !strcmp(file,"/dev/udp") || !strcmp(file,"/dev/icmp") || !strcmp(file,"/dev/ip"); }
static int use_special_access( const char *file ) { return !strcmp(file,"/dev/tcp") || !strcmp(file,"/dev/udp") || !strcmp(file,"/dev/icmp") || !strcmp(file,"/dev/ip"); }
CPP
htcondor
0
CVE-2016-3839
https://www.cvedetails.com/cve/CVE-2016-3839/
CWE-284
https://android.googlesource.com/platform/system/bt/+/472271b153c5dc53c28beac55480a8d8434b2d5c
472271b153c5dc53c28beac55480a8d8434b2d5c
DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release
bt_status_t btif_hh_virtual_unplug(bt_bdaddr_t *bd_addr) { BTIF_TRACE_DEBUG("%s", __FUNCTION__); btif_hh_device_t *p_dev; char bd_str[18]; sprintf(bd_str, "%02X:%02X:%02X:%02X:%02X:%02X", bd_addr->address[0], bd_addr->address[1], bd_addr->address[2], bd_addr->address[3], bd_addr->address[4], bd_addr->address[5]); p_dev = btif_hh_find_dev_by_bda(bd_addr); if ((p_dev != NULL) && (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED) && (p_dev->attr_mask & HID_VIRTUAL_CABLE)) { BTIF_TRACE_DEBUG("%s Sending BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG", __FUNCTION__); /* start the timer */ btif_hh_start_vup_timer(bd_addr); p_dev->local_vup = TRUE; BTA_HhSendCtrl(p_dev->dev_handle, BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG); return BT_STATUS_SUCCESS; } else { BTIF_TRACE_ERROR("%s: Error, device %s not opened.", __FUNCTION__, bd_str); return BT_STATUS_FAIL; } }
bt_status_t btif_hh_virtual_unplug(bt_bdaddr_t *bd_addr) { BTIF_TRACE_DEBUG("%s", __FUNCTION__); btif_hh_device_t *p_dev; char bd_str[18]; sprintf(bd_str, "%02X:%02X:%02X:%02X:%02X:%02X", bd_addr->address[0], bd_addr->address[1], bd_addr->address[2], bd_addr->address[3], bd_addr->address[4], bd_addr->address[5]); p_dev = btif_hh_find_dev_by_bda(bd_addr); if ((p_dev != NULL) && (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED) && (p_dev->attr_mask & HID_VIRTUAL_CABLE)) { BTIF_TRACE_DEBUG("%s Sending BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG", __FUNCTION__); /* start the timer */ btif_hh_start_vup_timer(bd_addr); p_dev->local_vup = TRUE; BTA_HhSendCtrl(p_dev->dev_handle, BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG); return BT_STATUS_SUCCESS; } else { BTIF_TRACE_ERROR("%s: Error, device %s not opened.", __FUNCTION__, bd_str); return BT_STATUS_FAIL; } }
C
Android
0
CVE-2015-8877
https://www.cvedetails.com/cve/CVE-2015-8877/
CWE-399
https://github.com/libgd/libgd/commit/4751b606fa38edc456d627140898a7ec679fcc24
4751b606fa38edc456d627140898a7ec679fcc24
gdImageScaleTwoPass memory leak fix Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and confirmed by @vapier. This bug actually bit me in production and I'm very thankful that it was reported with an easy fix. Fixes #173.
static double filter_quadratic(const double x1) { const double x = x1 < 0.0 ? -x1 : x1; if (x <= 0.5) return (- 2.0 * x * x + 1); if (x <= 1.5) return (x * x - 2.5* x + 1.5); return 0.0; }
static double filter_quadratic(const double x1) { const double x = x1 < 0.0 ? -x1 : x1; if (x <= 0.5) return (- 2.0 * x * x + 1); if (x <= 1.5) return (x * x - 2.5* x + 1.5); return 0.0; }
C
libgd
0
CVE-2013-1790
https://www.cvedetails.com/cve/CVE-2013-1790/
CWE-119
https://cgit.freedesktop.org/poppler/poppler/commit/?h=poppler-0.22&id=b1026b5978c385328f2a15a2185c599a563edf91
b1026b5978c385328f2a15a2185c599a563edf91
null
void FileOutStream::close () { }
void FileOutStream::close () { }
CPP
poppler
0
CVE-2016-10746
https://www.cvedetails.com/cve/CVE-2016-10746/
CWE-254
https://github.com/libvirt/libvirt/commit/506e9d6c2d4baaf580d489fff0690c0ff2ff588f
506e9d6c2d4baaf580d489fff0690c0ff2ff588f
virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
virDomainMigrateSetCompressionCache(virDomainPtr domain, unsigned long long cacheSize, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cacheSize=%llu, flags=%x", cacheSize, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetCompressionCache) { if (conn->driver->domainMigrateSetCompressionCache(domain, cacheSize, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; }
virDomainMigrateSetCompressionCache(virDomainPtr domain, unsigned long long cacheSize, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cacheSize=%llu, flags=%x", cacheSize, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetCompressionCache) { if (conn->driver->domainMigrateSetCompressionCache(domain, cacheSize, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; }
C
libvirt
0
CVE-2017-5118
https://www.cvedetails.com/cve/CVE-2017-5118/
CWE-732
https://github.com/chromium/chromium/commit/0ab2412a104d2f235d7b9fe19d30ef605a410832
0ab2412a104d2f235d7b9fe19d30ef605a410832
Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#492333}
void WebLocalFrameImpl::RequestExecuteScriptInIsolatedWorld( int world_id, const WebScriptSource* sources_in, unsigned num_sources, bool user_gesture, ScriptExecutionType option, WebScriptExecutionCallback* callback) { DCHECK(GetFrame()); CHECK_GT(world_id, 0); CHECK_LT(world_id, DOMWrapperWorld::kEmbedderWorldIdLimit); RefPtr<DOMWrapperWorld> isolated_world = DOMWrapperWorld::EnsureIsolatedWorld(ToIsolate(GetFrame()), world_id); SuspendableScriptExecutor* executor = SuspendableScriptExecutor::Create( GetFrame(), std::move(isolated_world), CreateSourcesVector(sources_in, num_sources), user_gesture, callback); switch (option) { case kAsynchronousBlockingOnload: executor->RunAsync(SuspendableScriptExecutor::kOnloadBlocking); break; case kAsynchronous: executor->RunAsync(SuspendableScriptExecutor::kNonBlocking); break; case kSynchronous: executor->Run(); break; } }
void WebLocalFrameImpl::RequestExecuteScriptInIsolatedWorld( int world_id, const WebScriptSource* sources_in, unsigned num_sources, bool user_gesture, ScriptExecutionType option, WebScriptExecutionCallback* callback) { DCHECK(GetFrame()); CHECK_GT(world_id, 0); CHECK_LT(world_id, DOMWrapperWorld::kEmbedderWorldIdLimit); RefPtr<DOMWrapperWorld> isolated_world = DOMWrapperWorld::EnsureIsolatedWorld(ToIsolate(GetFrame()), world_id); SuspendableScriptExecutor* executor = SuspendableScriptExecutor::Create( GetFrame(), std::move(isolated_world), CreateSourcesVector(sources_in, num_sources), user_gesture, callback); switch (option) { case kAsynchronousBlockingOnload: executor->RunAsync(SuspendableScriptExecutor::kOnloadBlocking); break; case kAsynchronous: executor->RunAsync(SuspendableScriptExecutor::kNonBlocking); break; case kSynchronous: executor->Run(); break; } }
C
Chrome
0
CVE-2011-2789
https://www.cvedetails.com/cve/CVE-2011-2789/
CWE-399
https://github.com/chromium/chromium/commit/55ef04e135edaa9abfbf3647634b11ed57dc49e9
55ef04e135edaa9abfbf3647634b11ed57dc49e9
Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
PPB_URLLoader_Impl::PPB_URLLoader_Impl(PluginInstance* instance, bool main_document_loader) : Resource(instance), main_document_loader_(main_document_loader), pending_callback_(), bytes_sent_(0), total_bytes_to_be_sent_(-1), bytes_received_(0), total_bytes_to_be_received_(-1), user_buffer_(NULL), user_buffer_size_(0), done_status_(PP_OK_COMPLETIONPENDING), is_streaming_to_file_(false), is_asynchronous_load_suspended_(false), has_universal_access_(false), status_callback_(NULL) { }
PPB_URLLoader_Impl::PPB_URLLoader_Impl(PluginInstance* instance, bool main_document_loader) : Resource(instance), main_document_loader_(main_document_loader), pending_callback_(), bytes_sent_(0), total_bytes_to_be_sent_(-1), bytes_received_(0), total_bytes_to_be_received_(-1), user_buffer_(NULL), user_buffer_size_(0), done_status_(PP_OK_COMPLETIONPENDING), is_streaming_to_file_(false), is_asynchronous_load_suspended_(false), has_universal_access_(false), status_callback_(NULL) { }
C
Chrome
0
CVE-2019-12980
https://www.cvedetails.com/cve/CVE-2019-12980/
CWE-190
https://github.com/libming/libming/pull/179/commits/2223f7a1e431455a1411bee77c90db94a6f8e8fe
2223f7a1e431455a1411bee77c90db94a6f8e8fe
Fix left shift of a negative value in SWFInput_readSBits. Check for number before before left-shifting by (number-1).
SWFInput_getUInt16(SWFInput input) { int num = SWFInput_getChar(input); num += SWFInput_getChar(input) << 8; return num; }
SWFInput_getUInt16(SWFInput input) { int num = SWFInput_getChar(input); num += SWFInput_getChar(input) << 8; return num; }
C
libming
0
CVE-2019-1010239
https://www.cvedetails.com/cve/CVE-2019-1010239/
CWE-754
https://github.com/DaveGamble/cJSON/commit/be749d7efa7c9021da746e685bd6dec79f9dd99b
be749d7efa7c9021da746e685bd6dec79f9dd99b
Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) { cJSON_Delete(cJSON_DetachItemFromArray(array, which)); }
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) { cJSON_Delete(cJSON_DetachItemFromArray(array, which)); }
C
cJSON
0
CVE-2017-9310
https://www.cvedetails.com/cve/CVE-2017-9310/
CWE-835
https://git.qemu.org/?p=qemu.git;a=commitdiff;h=4154c7e03fa55b4cf52509a83d50d6c09d743b7
4154c7e03fa55b4cf52509a83d50d6c09d743b77
null
e1000e_set_rxdctl(E1000ECore *core, int index, uint32_t val) { core->mac[RXDCTL] = core->mac[RXDCTL1] = val; }
e1000e_set_rxdctl(E1000ECore *core, int index, uint32_t val) { core->mac[RXDCTL] = core->mac[RXDCTL1] = val; }
C
qemu
0
CVE-2016-10507
https://www.cvedetails.com/cve/CVE-2016-10507/
CWE-190
https://github.com/uclouvain/openjpeg/commit/da940424816e11d624362ce080bc026adffa26e8
da940424816e11d624362ce080bc026adffa26e8
Merge pull request #834 from trylab/issue833 Fix issue 833.
static void bmp24toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; width = image->comps[0].w; height = image->comps[0].h; index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { image->comps[0].data[index] = (OPJ_INT32)pSrc[3*x+2]; /* R */ image->comps[1].data[index] = (OPJ_INT32)pSrc[3*x+1]; /* G */ image->comps[2].data[index] = (OPJ_INT32)pSrc[3*x+0]; /* B */ index++; } pSrc -= stride; } }
static void bmp24toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; width = image->comps[0].w; height = image->comps[0].h; index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { image->comps[0].data[index] = (OPJ_INT32)pSrc[3*x+2]; /* R */ image->comps[1].data[index] = (OPJ_INT32)pSrc[3*x+1]; /* G */ image->comps[2].data[index] = (OPJ_INT32)pSrc[3*x+0]; /* B */ index++; } pSrc -= stride; } }
C
openjpeg
0
CVE-2012-5139
https://www.cvedetails.com/cve/CVE-2012-5139/
CWE-416
https://github.com/chromium/chromium/commit/9e417dae2833230a651989bb4e56b835355dda39
9e417dae2833230a651989bb4e56b835355dda39
Tests were marked as Flaky. BUG=151811,151810 TBR=droger@chromium.org,shalev@chromium.org NOTRY=true Review URL: https://chromiumcodereview.appspot.com/10968052 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158204 0039d316-1c4b-4281-b951-d872f2087c98
BlockingNetworkDelegateWithManualCallback() : block_on_(0), state_(NOT_BLOCKED) { }
BlockingNetworkDelegateWithManualCallback() : block_on_(0), state_(NOT_BLOCKED) { }
C
Chrome
0
CVE-2013-0886
https://www.cvedetails.com/cve/CVE-2013-0886/
null
https://github.com/chromium/chromium/commit/18d67244984a574ba2dd8779faabc0e3e34f4b76
18d67244984a574ba2dd8779faabc0e3e34f4b76
Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const { return reinterpret_cast<gfx::NativeViewId>( const_cast<RenderWidgetHostViewAndroid*>(this)); }
gfx::NativeViewId RenderWidgetHostViewAndroid::GetNativeViewId() const { return reinterpret_cast<gfx::NativeViewId>( const_cast<RenderWidgetHostViewAndroid*>(this)); }
C
Chrome
0
CVE-2015-6768
https://www.cvedetails.com/cve/CVE-2015-6768/
CWE-264
https://github.com/chromium/chromium/commit/4c8b008f055f79e622344627fed7f820375a4f01
4c8b008f055f79e622344627fed7f820375a4f01
Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642}
bool Document::hasPendingForcedStyleRecalc() const { return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange; }
bool Document::hasPendingForcedStyleRecalc() const { return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange; }
C
Chrome
0
CVE-2017-18379
https://www.cvedetails.com/cve/CVE-2017-18379/
CWE-119
https://github.com/torvalds/linux/commit/0c319d3a144d4b8f1ea2047fd614d2149b68f889
0c319d3a144d4b8f1ea2047fd614d2149b68f889
nvmet-fc: ensure target queue id within range. When searching for queue id's ensure they are within the expected range. Signed-off-by: James Smart <james.smart@broadcom.com> Signed-off-by: Christoph Hellwig <hch@lst.de> Signed-off-by: Jens Axboe <axboe@kernel.dk>
nvmet_fc_free_tgtport(struct kref *ref) { struct nvmet_fc_tgtport *tgtport = container_of(ref, struct nvmet_fc_tgtport, ref); struct device *dev = tgtport->dev; unsigned long flags; spin_lock_irqsave(&nvmet_fc_tgtlock, flags); list_del(&tgtport->tgt_list); spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); nvmet_fc_free_ls_iodlist(tgtport); /* let the LLDD know we've finished tearing it down */ tgtport->ops->targetport_delete(&tgtport->fc_target_port); ida_simple_remove(&nvmet_fc_tgtport_cnt, tgtport->fc_target_port.port_num); ida_destroy(&tgtport->assoc_cnt); kfree(tgtport); put_device(dev); }
nvmet_fc_free_tgtport(struct kref *ref) { struct nvmet_fc_tgtport *tgtport = container_of(ref, struct nvmet_fc_tgtport, ref); struct device *dev = tgtport->dev; unsigned long flags; spin_lock_irqsave(&nvmet_fc_tgtlock, flags); list_del(&tgtport->tgt_list); spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); nvmet_fc_free_ls_iodlist(tgtport); /* let the LLDD know we've finished tearing it down */ tgtport->ops->targetport_delete(&tgtport->fc_target_port); ida_simple_remove(&nvmet_fc_tgtport_cnt, tgtport->fc_target_port.port_num); ida_destroy(&tgtport->assoc_cnt); kfree(tgtport); put_device(dev); }
C
linux
0
null
null
null
https://github.com/chromium/chromium/commit/df831400bcb63db4259b5858281b1727ba972a2a
df831400bcb63db4259b5858281b1727ba972a2a
WebKit2: Support window bounce when panning. https://bugs.webkit.org/show_bug.cgi?id=58065 <rdar://problem/9244367> Reviewed by Adam Roben. Make gestureDidScroll synchronous, as once we scroll, we need to know whether or not we are at the beginning or end of the scrollable document. If we are at either end of the scrollable document, we call the Windows 7 API to bounce the window to give an indication that you are past an end of the document. * UIProcess/WebPageProxy.cpp: (WebKit::WebPageProxy::gestureDidScroll): Pass a boolean for the reply, and return it. * UIProcess/WebPageProxy.h: * UIProcess/win/WebView.cpp: (WebKit::WebView::WebView): Inititalize a new variable. (WebKit::WebView::onGesture): Once we send the message to scroll, check if have gone to an end of the document, and if we have, bounce the window. * UIProcess/win/WebView.h: * WebProcess/WebPage/WebPage.h: * WebProcess/WebPage/WebPage.messages.in: GestureDidScroll is now sync. * WebProcess/WebPage/win/WebPageWin.cpp: (WebKit::WebPage::gestureDidScroll): When we are done scrolling, check if we have a vertical scrollbar and if we are at the beginning or the end of the scrollable document. git-svn-id: svn://svn.chromium.org/blink/trunk@83197 bbb929c8-8fbe-4397-9dbb-9b2b20218538
void WebPageProxy::clearAllEditCommands() { m_pageClient->clearAllEditCommands(); }
void WebPageProxy::clearAllEditCommands() { m_pageClient->clearAllEditCommands(); }
C
Chrome
0
CVE-2013-2884
https://www.cvedetails.com/cve/CVE-2013-2884/
CWE-399
https://github.com/chromium/chromium/commit/4ac8bc08e3306f38a5ab3e551aef6ad43753579c
4ac8bc08e3306f38a5ab3e551aef6ad43753579c
Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538
void Element::scrollByUnits(int units, ScrollGranularity granularity) { document()->updateLayoutIgnorePendingStylesheets(); if (!renderer()) return; if (!renderer()->hasOverflowClip()) return; ScrollDirection direction = ScrollDown; if (units < 0) { direction = ScrollUp; units = -units; } Node* stopNode = this; toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode); }
void Element::scrollByUnits(int units, ScrollGranularity granularity) { document()->updateLayoutIgnorePendingStylesheets(); if (!renderer()) return; if (!renderer()->hasOverflowClip()) return; ScrollDirection direction = ScrollDown; if (units < 0) { direction = ScrollUp; units = -units; } Node* stopNode = this; toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode); }
C
Chrome
0
CVE-2016-7141
https://www.cvedetails.com/cve/CVE-2016-7141/
CWE-287
https://github.com/curl/curl/commit/curl-7_50_2~32
curl-7_50_2~32
nss: refuse previously loaded certificate from file ... when we are not asked to use a certificate from file
static int is_file(const char *filename) { struct_stat st; if(filename == NULL) return 0; if(stat(filename, &st) == 0) if(S_ISREG(st.st_mode)) return 1; return 0; }
static int is_file(const char *filename) { struct_stat st; if(filename == NULL) return 0; if(stat(filename, &st) == 0) if(S_ISREG(st.st_mode)) return 1; return 0; }
C
curl
0
CVE-2017-18200
https://www.cvedetails.com/cve/CVE-2017-18200/
CWE-20
https://github.com/torvalds/linux/commit/638164a2718f337ea224b747cf5977ef143166a4
638164a2718f337ea224b747cf5977ef143166a4
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>
static void change_curseg(struct f2fs_sb_info *sbi, int type) { struct dirty_seglist_info *dirty_i = DIRTY_I(sbi); struct curseg_info *curseg = CURSEG_I(sbi, type); unsigned int new_segno = curseg->next_segno; struct f2fs_summary_block *sum_node; struct page *sum_page; write_sum_page(sbi, curseg->sum_blk, GET_SUM_BLOCK(sbi, curseg->segno)); __set_test_and_inuse(sbi, new_segno); mutex_lock(&dirty_i->seglist_lock); __remove_dirty_segment(sbi, new_segno, PRE); __remove_dirty_segment(sbi, new_segno, DIRTY); mutex_unlock(&dirty_i->seglist_lock); reset_curseg(sbi, type, 1); curseg->alloc_type = SSR; __next_free_blkoff(sbi, curseg, 0); sum_page = get_sum_page(sbi, new_segno); sum_node = (struct f2fs_summary_block *)page_address(sum_page); memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE); f2fs_put_page(sum_page, 1); }
static void change_curseg(struct f2fs_sb_info *sbi, int type) { struct dirty_seglist_info *dirty_i = DIRTY_I(sbi); struct curseg_info *curseg = CURSEG_I(sbi, type); unsigned int new_segno = curseg->next_segno; struct f2fs_summary_block *sum_node; struct page *sum_page; write_sum_page(sbi, curseg->sum_blk, GET_SUM_BLOCK(sbi, curseg->segno)); __set_test_and_inuse(sbi, new_segno); mutex_lock(&dirty_i->seglist_lock); __remove_dirty_segment(sbi, new_segno, PRE); __remove_dirty_segment(sbi, new_segno, DIRTY); mutex_unlock(&dirty_i->seglist_lock); reset_curseg(sbi, type, 1); curseg->alloc_type = SSR; __next_free_blkoff(sbi, curseg, 0); sum_page = get_sum_page(sbi, new_segno); sum_node = (struct f2fs_summary_block *)page_address(sum_page); memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE); f2fs_put_page(sum_page, 1); }
C
linux
0
CVE-2017-8064
https://www.cvedetails.com/cve/CVE-2017-8064/
CWE-119
https://github.com/torvalds/linux/commit/005145378c9ad7575a01b6ce1ba118fb427f583a
005145378c9ad7575a01b6ce1ba118fb427f583a
[media] dvb-usb-v2: avoid use-after-free I ran into a stack frame size warning because of the on-stack copy of the USB device structure: drivers/media/usb/dvb-usb-v2/dvb_usb_core.c: In function 'dvb_usbv2_disconnect': drivers/media/usb/dvb-usb-v2/dvb_usb_core.c:1029:1: error: the frame size of 1104 bytes is larger than 1024 bytes [-Werror=frame-larger-than=] Copying a device structure like this is wrong for a number of other reasons too aside from the possible stack overflow. One of them is that the dev_info() call will print the name of the device later, but AFAICT we have only copied a pointer to the name earlier and the actual name has been freed by the time it gets printed. This removes the on-stack copy of the device and instead copies the device name using kstrdup(). I'm ignoring the possible failure here as both printk() and kfree() are able to deal with NULL pointers. Signed-off-by: Arnd Bergmann <arnd@arndb.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com>
static void dvb_usb_read_remote_control(struct work_struct *work) { struct dvb_usb_device *d = container_of(work, struct dvb_usb_device, rc_query_work.work); int ret; /* * When the parameter has been set to 1 via sysfs while the * driver was running, or when bulk mode is enabled after IR init. */ if (dvb_usbv2_disable_rc_polling || d->rc.bulk_mode) { d->rc_polling_active = false; return; } ret = d->rc.query(d); if (ret < 0) { dev_err(&d->udev->dev, "%s: rc.query() failed=%d\n", KBUILD_MODNAME, ret); d->rc_polling_active = false; return; /* stop polling */ } schedule_delayed_work(&d->rc_query_work, msecs_to_jiffies(d->rc.interval)); }
static void dvb_usb_read_remote_control(struct work_struct *work) { struct dvb_usb_device *d = container_of(work, struct dvb_usb_device, rc_query_work.work); int ret; /* * When the parameter has been set to 1 via sysfs while the * driver was running, or when bulk mode is enabled after IR init. */ if (dvb_usbv2_disable_rc_polling || d->rc.bulk_mode) { d->rc_polling_active = false; return; } ret = d->rc.query(d); if (ret < 0) { dev_err(&d->udev->dev, "%s: rc.query() failed=%d\n", KBUILD_MODNAME, ret); d->rc_polling_active = false; return; /* stop polling */ } schedule_delayed_work(&d->rc_query_work, msecs_to_jiffies(d->rc.interval)); }
C
linux
0
CVE-2011-2830
https://www.cvedetails.com/cve/CVE-2011-2830/
CWE-399
https://github.com/chromium/chromium/commit/08b630e66e042af3fe80015509b3238c2679ea40
08b630e66e042af3fe80015509b3238c2679ea40
PopupMenuClient::multiple() should be const https://bugs.webkit.org/show_bug.cgi?id=76771 Patch by Benjamin Poulain <bpoulain@apple.com> on 2012-01-21 Reviewed by Kent Tamura. * platform/PopupMenuClient.h: (WebCore::PopupMenuClient::multiple): * rendering/RenderMenuList.cpp: (WebCore::RenderMenuList::multiple): * rendering/RenderMenuList.h: git-svn-id: svn://svn.chromium.org/blink/trunk@105570 bbb929c8-8fbe-4397-9dbb-9b2b20218538
void RenderMenuList::hidePopup() { if (m_popup) m_popup->hide(); }
void RenderMenuList::hidePopup() { if (m_popup) m_popup->hide(); }
C
Chrome
0
CVE-2012-2862
https://www.cvedetails.com/cve/CVE-2012-2862/
CWE-399
https://github.com/chromium/chromium/commit/c4f40933f2cd7f975af63e56ea4cdcdc6c636f73
c4f40933f2cd7f975af63e56ea4cdcdc6c636f73
accelerators: Remove deprecated Accelerator ctor that takes booleans. BUG=128242 R=ben@chromium.org Review URL: https://chromiumcodereview.appspot.com/10399085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
void TaskManagerView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (child == this) { if (is_add) { parent->AddChildView(about_memory_link_); if (purge_memory_button_) parent->AddChildView(purge_memory_button_); parent->AddChildView(kill_button_); AddChildView(tab_table_); } else { parent->RemoveChildView(kill_button_); if (purge_memory_button_) parent->RemoveChildView(purge_memory_button_); parent->RemoveChildView(about_memory_link_); } } }
void TaskManagerView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (child == this) { if (is_add) { parent->AddChildView(about_memory_link_); if (purge_memory_button_) parent->AddChildView(purge_memory_button_); parent->AddChildView(kill_button_); AddChildView(tab_table_); } else { parent->RemoveChildView(kill_button_); if (purge_memory_button_) parent->RemoveChildView(purge_memory_button_); parent->RemoveChildView(about_memory_link_); } } }
C
Chrome
0
CVE-2018-18073
https://www.cvedetails.com/cve/CVE-2018-18073/
CWE-200
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=34cc326eb2c5695833361887fe0b32e8d987741c
34cc326eb2c5695833361887fe0b32e8d987741c
null
estack_underflow(i_ctx_t *i_ctx_p) { return gs_error_ExecStackUnderflow; }
estack_underflow(i_ctx_t *i_ctx_p) { return gs_error_ExecStackUnderflow; }
C
ghostscript
0
CVE-2014-1713
https://www.cvedetails.com/cve/CVE-2014-1713/
CWE-399
https://github.com/chromium/chromium/commit/f85a87ec670ad0fce9d98d90c9a705b72a288154
f85a87ec670ad0fce9d98d90c9a705b72a288154
document.location bindings fix BUG=352374 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
static void stringAttrWithSetterExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { ExceptionState exceptionState(ExceptionState::SetterContext, "stringAttrWithSetterException", "TestObject", info.Holder(), info.GetIsolate()); TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setStringAttrWithSetterException(cppValue, exceptionState); exceptionState.throwIfNeeded(); }
static void stringAttrWithSetterExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { ExceptionState exceptionState(ExceptionState::SetterContext, "stringAttrWithSetterException", "TestObject", info.Holder(), info.GetIsolate()); TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setStringAttrWithSetterException(cppValue, exceptionState); exceptionState.throwIfNeeded(); }
C
Chrome
0
CVE-2015-0272
https://www.cvedetails.com/cve/CVE-2015-0272/
CWE-20
https://cgit.freedesktop.org/NetworkManager/NetworkManager/commit/?id=d5fc88e573fa58b93034b04d35a2454f5d28cad9
d5fc88e573fa58b93034b04d35a2454f5d28cad9
null
device_has_capability (NMDevice *self, NMDeviceCapabilities caps) { { static guint32 devcount = 0; NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->path == NULL); priv->path = g_strdup_printf ("/org/freedesktop/NetworkManager/Devices/%d", devcount++); _LOGI (LOGD_DEVICE, "exported as %s", priv->path); nm_dbus_manager_register_object (nm_dbus_manager_get (), priv->path, self); } const char * nm_device_get_path (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->path; } const char * nm_device_get_udi (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->udi; } const char * nm_device_get_iface (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 0); return NM_DEVICE_GET_PRIVATE (self)->iface; } int nm_device_get_ifindex (NMDevice *self) { g_return_val_if_fail (self != NULL, 0); return NM_DEVICE_GET_PRIVATE (self)->ifindex; } gboolean nm_device_is_software (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->is_software; } const char * nm_device_get_ip_iface (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, NULL); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_iface : priv->iface; } int nm_device_get_ip_ifindex (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, 0); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_ifindex : priv->ifindex; } void nm_device_set_ip_iface (NMDevice *self, const char *iface) { NMDevicePrivate *priv; char *old_ip_iface; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (!g_strcmp0 (iface, priv->ip_iface)) return; old_ip_iface = priv->ip_iface; priv->ip_ifindex = 0; priv->ip_iface = g_strdup (iface); if (priv->ip_iface) { priv->ip_ifindex = nm_platform_link_get_ifindex (priv->ip_iface); if (priv->ip_ifindex > 0) { if (nm_platform_check_support_user_ipv6ll ()) nm_platform_link_set_user_ipv6ll_enabled (priv->ip_ifindex, TRUE); if (!nm_platform_link_is_up (priv->ip_ifindex)) nm_platform_link_set_up (priv->ip_ifindex); } else { /* Device IP interface must always be a kernel network interface */ _LOGW (LOGD_HW, "failed to look up interface index"); } } /* We don't care about any saved values from the old iface */ g_hash_table_remove_all (priv->ip6_saved_properties); /* Emit change notification */ if (g_strcmp0 (old_ip_iface, priv->ip_iface)) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); g_free (old_ip_iface); } static gboolean get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid) { NMLinkType link_type; const guint8 *hwaddr = NULL; size_t hwaddr_len = 0; int ifindex; gboolean success; /* If we get here, we *must* have a kernel netdev, which implies an ifindex */ ifindex = nm_device_get_ip_ifindex (self); g_assert (ifindex); link_type = nm_platform_link_get_type (ifindex); g_return_val_if_fail (link_type > NM_LINK_TYPE_UNKNOWN, 0); hwaddr = nm_platform_link_get_address (ifindex, &hwaddr_len); if (!hwaddr_len) return FALSE; success = nm_utils_get_ipv6_interface_identifier (link_type, hwaddr, hwaddr_len, out_iid); if (!success) { _LOGW (LOGD_HW, "failed to generate interface identifier " "for link type %u hwaddr_len %zu", link_type, hwaddr_len); } return success; } static gboolean nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid) { return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid); } const char * nm_device_get_driver (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver; } const char * nm_device_get_driver_version (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver_version; } NMDeviceType nm_device_get_device_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN); return NM_DEVICE_GET_PRIVATE (self)->type; } /** * nm_device_get_priority(): * @self: the #NMDevice * * Returns: the device's routing priority. Lower numbers means a "better" * device, eg higher priority. */ int nm_device_get_priority (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 1000); /* Device 'priority' is used for the default route-metric and is based on * the device type. The settings ipv4.route-metric and ipv6.route-metric * can overwrite this default. * * Currently for both IPv4 and IPv6 we use the same default values. * * The route-metric is used for the metric of the routes of device. * This also applies to the default route. Therefore it affects also * which device is the "best". * * For comparison, note that iproute2 by default adds IPv4 routes with * metric 0, and IPv6 routes with metric 1024. The latter is the IPv6 * "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6). * In kernel, the full uint32_t range is available for route * metrics (except for IPv6, where 0 means 1024). */ switch (nm_device_get_device_type (self)) { /* 50 is reserved for VPN (NM_VPN_ROUTE_METRIC_DEFAULT) */ case NM_DEVICE_TYPE_ETHERNET: return 100; case NM_DEVICE_TYPE_INFINIBAND: return 150; case NM_DEVICE_TYPE_ADSL: return 200; case NM_DEVICE_TYPE_WIMAX: return 250; case NM_DEVICE_TYPE_BOND: return 300; case NM_DEVICE_TYPE_TEAM: return 350; case NM_DEVICE_TYPE_VLAN: return 400; case NM_DEVICE_TYPE_BRIDGE: return 425; case NM_DEVICE_TYPE_MODEM: return 450; case NM_DEVICE_TYPE_BT: return 550; case NM_DEVICE_TYPE_WIFI: return 600; case NM_DEVICE_TYPE_OLPC_MESH: return 650; case NM_DEVICE_TYPE_GENERIC: return 950; case NM_DEVICE_TYPE_UNKNOWN: return 10000; case NM_DEVICE_TYPE_UNUSED1: case NM_DEVICE_TYPE_UNUSED2: /* omit default: to get compiler warning about missing switch cases */ break; } return 11000; } guint32 nm_device_get_ip4_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip4_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } guint32 nm_device_get_ip6_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip6_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } const NMPlatformIP4Route * nm_device_get_ip4_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v4_is_assumed; return priv->default_route.v4_has ? &priv->default_route.v4 : NULL; } const NMPlatformIP6Route * nm_device_get_ip6_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v6_is_assumed; return priv->default_route.v6_has ? &priv->default_route.v6 : NULL; } const char * nm_device_get_type_desc (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->type_desc; } gboolean nm_device_has_carrier (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->carrier; } NMActRequest * nm_device_get_act_request (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->act_request; } NMConnection * nm_device_get_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->act_request ? nm_act_request_get_connection (priv->act_request) : NULL; } RfKillType nm_device_get_rfkill_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->rfkill_type; } static const char * nm_device_get_physical_port_id (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->physical_port_id; } /***********************************************************/ static gboolean nm_device_uses_generated_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) { connection = nm_act_request_get_connection (priv->act_request); if ( connection && nm_settings_connection_get_nm_generated_assumed (NM_SETTINGS_CONNECTION (connection))) return TRUE; } return FALSE; } gboolean nm_device_uses_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) return TRUE; return FALSE; } static SlaveInfo * find_slave_info (NMDevice *self, NMDevice *slave) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; GSList *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { info = iter->data; if (info->slave == slave) return info; } return NULL; } static void free_slave_info (SlaveInfo *info) { g_signal_handler_disconnect (info->slave, info->watch_id); g_clear_object (&info->slave); memset (info, 0, sizeof (*info)); g_free (info); } /** * nm_device_enslave_slave: * @self: the master device * @slave: the slave device to enslave * @connection: (allow-none): the slave device's connection * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function enslaves @slave. * * Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave * other devices. */ static gboolean nm_device_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection) { SlaveInfo *info; gboolean success = FALSE; gboolean configure; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; if (info->enslaved) success = TRUE; else { configure = (info->configure && connection != NULL); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure); info->enslaved = success; } nm_device_slave_notify_enslave (info->slave, success); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); /* Restart IP configuration if we're waiting for slaves. Do this * after updating the hardware address as IP config may need the * new address. */ if (success) { if (NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT) nm_device_activate_stage3_ip4_start (self); if (NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT) nm_device_activate_stage3_ip6_start (self); } return success; } /** * nm_device_release_one_slave: * @self: the master device * @slave: the slave device to release * @configure: whether @self needs to actually release @slave * @reason: the state change reason for the @slave * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function releases the previously enslaved @slave and/or * updates the state of @self and @slave to reflect its release. * * Returns: %TRUE on success, %FALSE on failure, if this device cannot enslave * other devices, or if @slave was never enslaved. */ static gboolean nm_device_release_one_slave (NMDevice *self, NMDevice *slave, gboolean configure, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; gboolean success = FALSE; g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; priv->slaves = g_slist_remove (priv->slaves, info); if (info->enslaved) { success = NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure); /* The release_slave() implementation logs success/failure (in the * correct device-specific log domain), so we don't have to do anything. */ } if (!configure) { g_warn_if_fail (reason == NM_DEVICE_STATE_REASON_NONE || reason == NM_DEVICE_STATE_REASON_REMOVED); reason = NM_DEVICE_STATE_REASON_NONE; } else if (reason == NM_DEVICE_STATE_REASON_NONE) { g_warn_if_reached (); reason = NM_DEVICE_STATE_REASON_UNKNOWN; } nm_device_slave_notify_release (info->slave, reason); free_slave_info (info); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); return success; } static gboolean is_software_external (NMDevice *self) { return nm_device_is_software (self) && !nm_device_get_is_nm_owned (self); } /** * nm_device_finish_init: * @self: the master device * * Whatever needs to be done post-initialization, when the device has a DBus * object name. */ void nm_device_finish_init (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_assert (priv->initialized == FALSE); /* Do not manage externally created software devices until they are IFF_UP */ if ( is_software_external (self) && !nm_platform_link_is_up (priv->ifindex) && priv->ifindex > 0) nm_device_set_initial_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); priv->initialized = TRUE; } static void carrier_changed (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (!nm_device_get_managed (self)) return; nm_device_recheck_available_connections (self); /* ignore-carrier devices ignore all carrier-down events */ if (priv->ignore_carrier && !carrier) return; if (priv->is_master) { /* Bridge/bond/team carrier does not affect its own activation, * but when carrier comes on, if there are slaves waiting, * it will restart them. */ if (!carrier) return; if (nm_device_activate_ip4_state_in_wait (self)) nm_device_activate_stage3_ip4_start (self); if (nm_device_activate_ip6_state_in_wait (self)) nm_device_activate_stage3_ip6_start (self); return; } else if (nm_device_get_enslaved (self) && !carrier) { /* Slaves don't deactivate when they lose carrier; for * bonds/teams in particular that would be actively * counterproductive. */ return; } if (carrier) { g_warn_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_CARRIER); } else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already in DISCONNECTED state without a carrier * (probably because it is tagged for carrier ignore) ensure that * when the carrier appears, auto connections are rechecked for * the device. */ nm_device_emit_recheck_auto_activate (self); } } else { g_return_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { if (nm_device_queued_state_peek (self) >= NM_DEVICE_STATE_DISCONNECTED) nm_device_queued_state_clear (self); } else { nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE, NM_DEVICE_STATE_REASON_CARRIER); } } } #define LINK_DISCONNECT_DELAY 4 static gboolean link_disconnect_action_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); _LOGD (LOGD_DEVICE, "link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; _LOGI (LOGD_DEVICE, "link disconnected (calling deferred action)"); NM_DEVICE_GET_CLASS (self)->carrier_changed (self, FALSE); return FALSE; } static void link_disconnect_action_cancel (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier_defer_id) { g_source_remove (priv->carrier_defer_id); _LOGD (LOGD_DEVICE, "link disconnected (canceling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; } } void nm_device_set_carrier (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDeviceState state = nm_device_get_state (self); if (priv->carrier == carrier) return; priv->carrier = carrier; g_object_notify (G_OBJECT (self), NM_DEVICE_CARRIER); if (priv->carrier) { _LOGI (LOGD_DEVICE, "link connected"); link_disconnect_action_cancel (self); klass->carrier_changed (self, TRUE); if (priv->carrier_wait_id) { g_source_remove (priv->carrier_wait_id); priv->carrier_wait_id = 0; nm_device_remove_pending_action (self, "carrier wait", TRUE); _carrier_wait_check_queued_act_request (self); } } else if (state <= NM_DEVICE_STATE_DISCONNECTED) { _LOGI (LOGD_DEVICE, "link disconnected"); klass->carrier_changed (self, FALSE); } else { _LOGI (LOGD_DEVICE, "link disconnected (deferring action for %d seconds)", LINK_DISCONNECT_DELAY); priv->carrier_defer_id = g_timeout_add_seconds (LINK_DISCONNECT_DELAY, link_disconnect_action_cb, self); _LOGD (LOGD_DEVICE, "link disconnected (deferring action for %d seconds) (id=%u)", LINK_DISCONNECT_DELAY, priv->carrier_defer_id); } } static void update_for_ip_ifname_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_hash_table_remove_all (priv->ip6_saved_properties); if (priv->dhcp4_client) { if (!nm_device_dhcp4_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->dhcp6_client) { if (!nm_device_dhcp6_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->rdisc) { /* FIXME: todo */ } if (priv->dnsmasq_manager) { /* FIXME: todo */ } } static void device_set_master (NMDevice *self, int ifindex) { NMDevice *master; NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); master = nm_manager_get_device_by_ifindex (nm_manager_get (), ifindex); if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave) { g_clear_object (&priv->master); priv->master = g_object_ref (master); nm_device_master_add_slave (master, self, FALSE); } else if (master) { _LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring", nm_device_get_iface (master)); } else { _LOGW (LOGD_DEVICE, "enslaved to unknown device %d %s", ifindex, nm_platform_link_get_name (ifindex)); } } static void device_link_changed (NMDevice *self, NMPlatformLink *info) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMUtilsIPv6IfaceId token_iid; gboolean ip_ifname_changed = FALSE; if (info->udi && g_strcmp0 (info->udi, priv->udi)) { /* Update UDI to what udev gives us */ g_free (priv->udi); priv->udi = g_strdup (info->udi); g_object_notify (G_OBJECT (self), NM_DEVICE_UDI); } /* Update MTU if it has changed. */ if (priv->mtu != info->mtu) { priv->mtu = info->mtu; g_object_notify (G_OBJECT (self), NM_DEVICE_MTU); } if (info->name[0] && strcmp (priv->iface, info->name) != 0) { _LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'", priv->ifindex, priv->iface, info->name); g_free (priv->iface); priv->iface = g_strdup (info->name); /* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */ ip_ifname_changed = !priv->ip_iface; g_object_notify (G_OBJECT (self), NM_DEVICE_IFACE); if (ip_ifname_changed) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); /* Re-match available connections against the new interface name */ nm_device_recheck_available_connections (self); /* Let any connections that use the new interface name have a chance * to auto-activate on the device. */ nm_device_emit_recheck_auto_activate (self); } /* Update slave status for external changes */ if (priv->enslaved && info->master != nm_device_get_ifindex (priv->master)) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_NONE); if (info->master && !priv->enslaved) { device_set_master (self, info->master); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); } if (priv->rdisc && nm_platform_link_get_ipv6_token (priv->ifindex, &token_iid)) { _LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface); if (nm_rdisc_set_iid (priv->rdisc, token_iid)) nm_rdisc_start (priv->rdisc); } if (klass->link_changed) klass->link_changed (self, info); /* Update DHCP, etc, if needed */ if (ip_ifname_changed) update_for_ip_ifname_change (self); if (priv->up != info->up) { priv->up = info->up; /* Manage externally-created software interfaces only when they are IFF_UP */ g_assert (priv->ifindex > 0); if (is_software_external (self)) { gboolean external_down = nm_device_get_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN); if (external_down && info->up) { if (nm_device_get_state (self) < NM_DEVICE_STATE_DISCONNECTED) { /* Ensure the assume check is queued before any queued state changes * from the transition to UNAVAILABLE. */ nm_device_queue_recheck_assume (self); /* Resetting the EXTERNAL_DOWN flag may change the device's state * to UNAVAILABLE. To ensure that the state change doesn't touch * the device before assumption occurs, pass * NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED as the reason. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED); } else { /* Don't trigger a state change; if the device is in a * state higher than UNAVAILABLE, it is already IFF_UP * or an explicit activation request was received. */ priv->unmanaged_flags &= ~NM_UNMANAGED_EXTERNAL_DOWN; } } else if (!external_down && !info->up && nm_device_get_state (self) <= NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already disconnected and is set !IFF_UP, * unmanage it. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE, NM_DEVICE_STATE_REASON_USER_REQUESTED); } } } } static void device_ip_link_changed (NMDevice *self, NMPlatformLink *info) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (info->name[0] && g_strcmp0 (priv->ip_iface, info->name)) { _LOGI (LOGD_DEVICE, "interface index %d renamed ip_iface (%d) from '%s' to '%s'", priv->ifindex, nm_device_get_ip_ifindex (self), priv->ip_iface, info->name); g_free (priv->ip_iface); priv->ip_iface = g_strdup (info->name); g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); update_for_ip_ifname_change (self); } } static void link_changed_cb (NMPlatform *platform, int ifindex, NMPlatformLink *info, NMPlatformSignalChangeType change_type, NMPlatformReason reason, NMDevice *self) { if (change_type != NM_PLATFORM_SIGNAL_CHANGED) return; /* We don't filter by 'reason' because we are interested in *all* link * changes. For example a call to nm_platform_link_set_up() may result * in an internal carrier change (i.e. we ask the kernel to set IFF_UP * and it results in also setting IFF_LOWER_UP. */ if (ifindex == nm_device_get_ifindex (self)) device_link_changed (self, info); else if (ifindex == nm_device_get_ip_ifindex (self)) device_ip_link_changed (self, info); } static void link_changed (NMDevice *self, NMPlatformLink *info) { /* Update carrier from link event if applicable. */ if ( device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT) && !device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER)) nm_device_set_carrier (self, info->connected); } /** * nm_device_notify_component_added(): * @self: the #NMDevice * @component: the component being added by a plugin * * Called by the manager to notify the device that a new component has * been found. The device implementation should return %TRUE if it * wishes to claim the component, or %FALSE if it cannot. * * Returns: %TRUE to claim the component, %FALSE if the component cannot be * claimed. */ gboolean nm_device_notify_component_added (NMDevice *self, GObject *component) { if (NM_DEVICE_GET_CLASS (self)->component_added) return NM_DEVICE_GET_CLASS (self)->component_added (self, component); return FALSE; } /** * nm_device_owns_iface(): * @self: the #NMDevice * @iface: an interface name * * Called by the manager to ask if the device or any of its components owns * @iface. For example, a WWAN implementation would return %TRUE for an * ethernet interface name that was owned by the WWAN device's modem component, * because that ethernet interface is controlled by the WWAN device and cannot * be used independently of the WWAN device. * * Returns: %TRUE if @self or it's components owns the interface name, * %FALSE if not */ gboolean nm_device_owns_iface (NMDevice *self, const char *iface) { if (NM_DEVICE_GET_CLASS (self)->owns_iface) return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface); return FALSE; } NMConnection * nm_device_new_default_connection (NMDevice *self) { if (NM_DEVICE_GET_CLASS (self)->new_default_connection) return NM_DEVICE_GET_CLASS (self)->new_default_connection (self); return NULL; } static void slave_state_changed (NMDevice *slave, NMDeviceState slave_new_state, NMDeviceState slave_old_state, NMDeviceStateReason reason, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); gboolean release = FALSE; _LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)", nm_device_get_iface (slave), slave_old_state, state_to_string (slave_old_state), slave_new_state, state_to_string (slave_new_state)); /* Don't try to enslave slaves until the master is ready */ if (priv->state < NM_DEVICE_STATE_CONFIG) return; if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, slave, nm_device_get_connection (slave)); else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED) release = TRUE; else if ( slave_new_state <= NM_DEVICE_STATE_DISCONNECTED && slave_old_state > NM_DEVICE_STATE_DISCONNECTED) { /* Catch failures due to unavailable or unmanaged */ release = TRUE; } if (release) { nm_device_release_one_slave (self, slave, TRUE, reason); /* Bridge/bond/team interfaces are left up until manually deactivated */ if (priv->slaves == NULL && priv->state == NM_DEVICE_STATE_ACTIVATED) _LOGD (LOGD_DEVICE, "last slave removed; remaining activated"); } } /** * nm_device_master_add_slave: * @self: the master device * @slave: the slave device to enslave * @configure: pass %TRUE if the slave should be configured by the master, or * %FALSE if it is already configured outside NetworkManager * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function adds @slave to the slave list for later enslavement. * * Returns: %TRUE on success, %FALSE on failure */ static gboolean nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); if (!find_slave_info (self, slave)) { info = g_malloc0 (sizeof (SlaveInfo)); info->slave = g_object_ref (slave); info->configure = configure; info->watch_id = g_signal_connect (slave, "state-changed", G_CALLBACK (slave_state_changed), self); priv->slaves = g_slist_append (priv->slaves, info); } nm_device_queue_recheck_assume (self); return TRUE; } /** * nm_device_master_get_slaves: * @self: the master device * * Returns: any slaves of which @self is the master. Caller owns returned list. */ GSList * nm_device_master_get_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GSList *slaves = NULL, *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) slaves = g_slist_prepend (slaves, ((SlaveInfo *) iter->data)->slave); return slaves; } /** * nm_device_master_get_slave_by_ifindex: * @self: the master device * @ifindex: the slave's interface index * * Returns: the slave with the given @ifindex of which @self is the master, * or %NULL if no device with @ifindex is a slave of @self. */ NMDevice * nm_device_master_get_slave_by_ifindex (NMDevice *self, int ifindex) { GSList *iter; for (iter = NM_DEVICE_GET_PRIVATE (self)->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; if (nm_device_get_ip_ifindex (info->slave) == ifindex) return info->slave; } return NULL; } /** * nm_device_master_check_slave_physical_port: * @self: the master device * @slave: a slave device * @log_domain: domain to log a warning in * * Checks if @self already has a slave with the same #NMDevice:physical-port-id * as @slave, and logs a warning if so. */ void nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave, guint64 log_domain) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *slave_physical_port_id, *existing_physical_port_id; SlaveInfo *info; GSList *iter; slave_physical_port_id = nm_device_get_physical_port_id (slave); if (!slave_physical_port_id) return; for (iter = priv->slaves; iter; iter = iter->next) { info = iter->data; if (info->slave == slave) continue; existing_physical_port_id = nm_device_get_physical_port_id (info->slave); if (!g_strcmp0 (slave_physical_port_id, existing_physical_port_id)) { _LOGW (log_domain, "slave %s shares a physical port with existing slave %s", nm_device_get_ip_iface (slave), nm_device_get_ip_iface (info->slave)); /* Since this function will get called for every slave, we only have * to warn about the first match we find; if there are other matches * later in the list, we will have already warned about them matching * @existing earlier. */ return; } } } /* release all slaves */ static void nm_device_master_release_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceStateReason reason; /* Don't release the slaves if this connection doesn't belong to NM. */ if (nm_device_uses_generated_assumed_connection (self)) return; reason = priv->state_reason; if (priv->state == NM_DEVICE_STATE_FAILED) reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED; while (priv->slaves) { SlaveInfo *info = priv->slaves->data; nm_device_release_one_slave (self, info->slave, TRUE, reason); } } /** * nm_device_get_master: * @self: the device * * If @self has been enslaved by another device, this returns that * device. Otherwise it returns %NULL. (In particular, note that if * @self is in the process of activating as a slave, but has not yet * been enslaved by its master, this will return %NULL.) * * Returns: (transfer none): @self's master, or %NULL */ NMDevice * nm_device_get_master (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) return priv->master; else return NULL; } /** * nm_device_slave_notify_enslave: * @self: the slave device * @success: whether the enslaving operation succeeded * * Notifies a slave that either it has been enslaved, or else its master tried * to enslave it and failed. */ static void nm_device_slave_notify_enslave (NMDevice *self, gboolean success) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG); g_assert (priv->master); if (!priv->enslaved) { if (success) { if (activating) { _LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation", nm_connection_get_id (connection)); } else _LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master)); priv->enslaved = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } else if (activating) { _LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved", nm_connection_get_id (connection)); } } if (activating) { priv->ip4_state = IP_DONE; priv->ip6_state = IP_DONE; nm_device_queue_state (self, success ? NM_DEVICE_STATE_SECONDARIES : NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NONE); } else nm_device_queue_recheck_assume (self); } /** * nm_device_slave_notify_release: * @self: the slave device * @reason: the reason associated with the state change * * Notifies a slave that it has been released, and why. */ static void nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); NMDeviceState new_state; const char *master_status; if ( reason != NM_DEVICE_STATE_REASON_NONE && priv->state > NM_DEVICE_STATE_DISCONNECTED && priv->state <= NM_DEVICE_STATE_ACTIVATED) { if (reason == NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED) { new_state = NM_DEVICE_STATE_FAILED; master_status = "failed"; } else if (reason == NM_DEVICE_STATE_REASON_USER_REQUESTED) { new_state = NM_DEVICE_STATE_DEACTIVATING; master_status = "deactivated by user request"; } else { new_state = NM_DEVICE_STATE_DISCONNECTED; master_status = "deactivated"; } _LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s", nm_connection_get_id (connection), master_status); nm_device_queue_state (self, new_state, reason); } else if (priv->master) _LOGI (LOGD_DEVICE, "released from master %s", nm_device_get_iface (priv->master)); else _LOGD (LOGD_DEVICE, "released from master%s", priv->enslaved ? "" : " (was not enslaved)"); if (priv->enslaved) { priv->enslaved = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } } /** * nm_device_get_enslaved: * @self: the #NMDevice * * Returns: %TRUE if the device is enslaved to a master device (eg bridge or * bond or team), %FALSE if not */ gboolean nm_device_get_enslaved (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->enslaved; } /** * nm_device_removed: * @self: the #NMDevice * * Called by the manager when the device was removed. Releases the device from * the master in case it's enslaved. */ void nm_device_removed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_REMOVED); } static gboolean is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier || priv->ignore_carrier) return TRUE; if (NM_FLAGS_HAS (flags, NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER)) return TRUE; return FALSE; } /** * nm_device_is_available: * @self: the #NMDevice * @flags: additional flags to influence the check. Flags have the * meaning to increase the availability of a device. * * Checks if @self would currently be capable of activating a * connection. In particular, it checks that the device is ready (eg, * is not missing firmware), that it has carrier (if necessary), and * that any necessary external software (eg, ModemManager, * wpa_supplicant) is available. * * @self can only be in a state higher than * %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns * %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED * when it is available.) * * Returns: %TRUE or %FALSE */ gboolean nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->firmware_missing) return FALSE; return NM_DEVICE_GET_CLASS (self)->is_available (self, flags); } gboolean nm_device_get_enabled (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); if (NM_DEVICE_GET_CLASS (self)->get_enabled) return NM_DEVICE_GET_CLASS (self)->get_enabled (self); return TRUE; } void nm_device_set_enabled (NMDevice *self, gboolean enabled) { g_return_if_fail (NM_IS_DEVICE (self)); if (NM_DEVICE_GET_CLASS (self)->set_enabled) NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled); } /** * nm_device_get_autoconnect: * @self: the #NMDevice * * Returns: %TRUE if the device allows autoconnect connections, or %FALSE if the * device is explicitly blocking all autoconnect connections. Does not take * into account transient conditions like companion devices that may wish to * block the device. */ gboolean nm_device_get_autoconnect (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->autoconnect; } static void nm_device_set_autoconnect (NMDevice *self, gboolean autoconnect) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (priv->autoconnect == autoconnect) return; if (autoconnect) { /* Default-unmanaged devices never autoconnect */ if (!nm_device_get_default_unmanaged (self)) { priv->autoconnect = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } else { priv->autoconnect = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } static gboolean autoconnect_allowed_accumulator (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return, gpointer data) { if (!g_value_get_boolean (handler_return)) g_value_set_boolean (return_accu, FALSE); return TRUE; } /** * nm_device_autoconnect_allowed: * @self: the #NMDevice * * Returns: %TRUE if the device can be auto-connected immediately, taking * transient conditions into account (like companion devices that may wish to * block autoconnect for a time). */ gboolean nm_device_autoconnect_allowed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GValue instance = G_VALUE_INIT; GValue retval = G_VALUE_INIT; if (priv->state < NM_DEVICE_STATE_DISCONNECTED || !priv->autoconnect) return FALSE; /* The 'autoconnect-allowed' signal is emitted on a device to allow * other listeners to block autoconnect on the device if they wish. * This is mainly used by the OLPC Mesh devices to block autoconnect * on their companion WiFi device as they share radio resources and * cannot be connected at the same time. */ g_value_init (&instance, G_TYPE_OBJECT); g_value_set_object (&instance, self); g_value_init (&retval, G_TYPE_BOOLEAN); if (priv->autoconnect) g_value_set_boolean (&retval, TRUE); else g_value_set_boolean (&retval, FALSE); /* Use g_signal_emitv() rather than g_signal_emit() to avoid the return * value being changed if no handlers are connected */ g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval); g_value_unset (&instance); return g_value_get_boolean (&retval); } static gboolean can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { NMSettingConnection *s_con; s_con = nm_connection_get_setting_connection (connection); if (!nm_setting_connection_get_autoconnect (s_con)) return FALSE; return nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_NONE, NULL); } /** * nm_device_can_auto_connect: * @self: an #NMDevice * @connection: a #NMConnection * @specific_object: (out) (transfer full): on output, the path of an * object associated with the returned connection, to be passed to * nm_manager_activate_connection(), or %NULL. * * Checks if @connection can be auto-activated on @self right now. * This requires, at a minimum, that the connection be compatible with * @self, and that it have the #NMSettingConnection:autoconnect property * set, and that the device allow auto connections. Some devices impose * additional requirements. (Eg, a Wi-Fi connection can only be activated * if its SSID was seen in the last scan.) * * Returns: %TRUE, if the @connection can be auto-activated. **/ gboolean nm_device_can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); g_return_val_if_fail (specific_object && !*specific_object, FALSE); if (nm_device_autoconnect_allowed (self)) return NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, connection, specific_object); return FALSE; } static gboolean device_has_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); /* Check for IP configuration. */ if (priv->ip4_config && nm_ip4_config_get_num_addresses (priv->ip4_config)) return TRUE; if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config)) return TRUE; /* The existence of a software device is good enough. */ if (nm_device_is_software (self)) return TRUE; /* Slaves are also configured by definition */ if (nm_platform_link_get_master (priv->ifindex) > 0) return TRUE; return FALSE; } /** * nm_device_master_update_slave_connection: * @self: the master #NMDevice * @slave: the slave #NMDevice * @connection: the #NMConnection to update with the slave settings * @GError: (out): error description * * Reads the slave configuration for @slave and updates @connection with those * properties. This invokes a virtual function on the master device @self. * * Returns: %TRUE if the configuration was read and @connection updated, * %FALSE on failure. */ gboolean nm_device_master_update_slave_connection (NMDevice *self, NMDevice *slave, NMConnection *connection, GError **error) { NMDeviceClass *klass; gboolean success; g_return_val_if_fail (self, FALSE); g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (slave, FALSE); g_return_val_if_fail (connection, FALSE); g_return_val_if_fail (!error || !*error, FALSE); g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE); g_return_val_if_fail (nm_device_get_iface (self), FALSE); klass = NM_DEVICE_GET_CLASS (self); if (klass->master_update_slave_connection) { success = klass->master_update_slave_connection (self, slave, connection, error); g_return_val_if_fail (!error || (success && !*error) || *error, success); return success; } g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED, "master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)", nm_device_get_iface (self), nm_device_get_iface (slave)); return FALSE; } NMConnection * nm_device_generate_connection (NMDevice *self, NMDevice *master) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *ifname = nm_device_get_iface (self); NMConnection *connection; NMSetting *s_con; NMSetting *s_ip4; NMSetting *s_ip6; gs_free char *uuid = NULL; const char *ip4_method, *ip6_method; GError *error = NULL; /* If update_connection() is not implemented, just fail. */ if (!klass->update_connection) return NULL; /* Return NULL if device is unconfigured. */ if (!device_has_config (self)) { _LOGD (LOGD_DEVICE, "device has no existing configuration"); return NULL; } connection = nm_simple_connection_new (); s_con = nm_setting_connection_new (); uuid = nm_utils_uuid_generate (); g_object_set (s_con, NM_SETTING_CONNECTION_UUID, uuid, NM_SETTING_CONNECTION_ID, ifname, NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NM_SETTING_CONNECTION_INTERFACE_NAME, ifname, NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL), NULL); if (klass->connection_type) g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type, NULL); nm_connection_add_setting (connection, s_con); /* If the device is a slave, update various slave settings */ if (master) { if (!nm_device_master_update_slave_connection (master, self, connection, &error)) { _LOGE (LOGD_DEVICE, "master device '%s' failed to update slave connection: %s", nm_device_get_iface (master), error ? error->message : "(unknown error)"); g_error_free (error); g_object_unref (connection); return NULL; } } else { /* Only regular and master devices get IP configuration; slaves do not */ s_ip4 = nm_ip4_config_create_setting (priv->ip4_config); nm_connection_add_setting (connection, s_ip4); s_ip6 = nm_ip6_config_create_setting (priv->ip6_config); nm_connection_add_setting (connection, s_ip6); } klass->update_connection (self, connection); /* Check the connection in case of update_connection() bug. */ if (!nm_connection_verify (connection, &error)) { _LOGE (LOGD_DEVICE, "Generated connection does not verify: %s", error->message); g_clear_error (&error); g_object_unref (connection); return NULL; } /* Ignore the connection if it has no IP configuration, * no slave configuration, and is not a master interface. */ ip4_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); ip6_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if ( g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0 && g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0 && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con)) && !priv->slaves) { _LOGD (LOGD_DEVICE, "ignoring generated connection (no IP and not in master-slave relationship)"); g_object_unref (connection); connection = NULL; } return connection; } gboolean nm_device_complete_connection (NMDevice *self, NMConnection *connection, const char *specific_object, const GSList *existing_connections, GError **error) { gboolean success = FALSE; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (connection != NULL, FALSE); if (!NM_DEVICE_GET_CLASS (self)->complete_connection) { g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION, "Device class %s had no complete_connection method", G_OBJECT_TYPE_NAME (self)); return FALSE; } success = NM_DEVICE_GET_CLASS (self)->complete_connection (self, connection, specific_object, existing_connections, error); if (success) success = nm_connection_verify (connection, error); return success; } static gboolean check_connection_compatible (NMDevice *self, NMConnection *connection) { NMSettingConnection *s_con; const char *config_iface, *device_iface; s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); config_iface = nm_setting_connection_get_interface_name (s_con); device_iface = nm_device_get_iface (self); if (config_iface && strcmp (config_iface, device_iface) != 0) return FALSE; return TRUE; } /** * nm_device_check_connection_compatible: * @self: an #NMDevice * @connection: an #NMConnection * * Checks if @connection could potentially be activated on @self. * This means only that @self has the proper capabilities, and that * @connection is not locked to some other device. It does not * necessarily mean that @connection could be activated on @self * right now. (Eg, it might refer to a Wi-Fi network that is not * currently available.) * * Returns: #TRUE if @connection could potentially be activated on * @self. */ gboolean nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection); } /** * nm_device_can_assume_connections: * @self: #NMDevice instance * * This is a convenience function to determine whether connection assumption * is available for this device. * * Returns: %TRUE if the device is capable of assuming connections, %FALSE if not */ static gboolean nm_device_can_assume_connections (NMDevice *self) { return !!NM_DEVICE_GET_CLASS (self)->update_connection; } /** * nm_device_can_assume_active_connection: * @self: #NMDevice instance * * This is a convenience function to determine whether the device's active * connection can be assumed if NetworkManager restarts. This method returns * %TRUE if and only if the device can assume connections, and the device has * an active connection, and that active connection can be assumed. * * Returns: %TRUE if the device's active connection can be assumed, or %FALSE * if there is no active connection or the active connection cannot be * assumed. */ gboolean nm_device_can_assume_active_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; const char *assumable_ip6_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_IGNORE, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; const char *assumable_ip4_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_DISABLED, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; if (!nm_device_can_assume_connections (self)) return FALSE; connection = nm_device_get_connection (self); if (!connection) return FALSE; /* Can't assume connections that aren't yet configured * FIXME: what about bridges/bonds waiting for slaves? */ if (priv->state < NM_DEVICE_STATE_IP_CONFIG) return FALSE; if (priv->ip4_state != IP_DONE && priv->ip6_state != IP_DONE) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip6_methods)) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip4_methods)) return FALSE; return TRUE; } static gboolean nm_device_emit_recheck_assume (gpointer self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->recheck_assume_id = 0; if (!nm_device_get_act_request (self)) { _LOGD (LOGD_DEVICE, "emit RECHECK_ASSUME signal"); g_signal_emit (self, signals[RECHECK_ASSUME], 0); } return G_SOURCE_REMOVE; } void nm_device_queue_recheck_assume (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (nm_device_can_assume_connections (self) && !priv->recheck_assume_id) priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self); } void nm_device_emit_recheck_auto_activate (NMDevice *self) { g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0); } static void dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); switch (status) { case NM_DNSMASQ_STATUS_DEAD: nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED); break; default: break; } } static void activation_source_clear (NMDevice *self, gboolean remove_source, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) { if (remove_source) g_source_remove (*act_source_id); *act_source_id = 0; *act_source_func = NULL; } } static void activation_source_schedule (NMDevice *self, GSourceFunc func, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) _LOGE (LOGD_DEVICE, "activation stage already scheduled"); /* Don't bother rescheduling the same function that's about to * run anyway. Fixes issues with crappy wireless drivers sending * streams of associate events before NM has had a chance to process * the first one. */ if (!*act_source_id || (*act_source_func != func)) { activation_source_clear (self, TRUE, family); *act_source_id = g_idle_add (func, self); *act_source_func = func; } } static gboolean get_ip_config_may_fail (NMDevice *self, int family) { NMConnection *connection; NMSettingIPConfig *s_ip = NULL; g_return_val_if_fail (self != NULL, TRUE); connection = nm_device_get_connection (self); g_assert (connection); /* Fail the connection if the failed IP method is required to complete */ switch (family) { case AF_INET: s_ip = nm_connection_get_setting_ip4_config (connection); break; case AF_INET6: s_ip = nm_connection_get_setting_ip6_config (connection); break; default: g_assert_not_reached (); } return nm_setting_ip_config_get_may_fail (s_ip); } static void master_ready_cb (NMActiveConnection *active, GParamSpec *pspec, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActiveConnection *master; g_assert (priv->state == NM_DEVICE_STATE_PREPARE); /* Notify a master device that it has a new slave */ g_assert (nm_active_connection_get_master_ready (active)); master = nm_active_connection_get_master (active); priv->master = g_object_ref (nm_active_connection_get_device (master)); nm_device_master_add_slave (priv->master, self, nm_active_connection_get_assumed (active) ? FALSE : TRUE); _LOGD (LOGD_DEVICE, "master connection ready; master device %s", nm_device_get_iface (priv->master)); if (priv->master_ready_id) { g_signal_handler_disconnect (active, priv->master_ready_id); priv->master_ready_id = 0; } nm_device_activate_schedule_stage2_device_config (self); } static NMActStageReturn act_stage1_prepare (NMDevice *self, NMDeviceStateReason *reason) { return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage1_device_prepare * * Prepare for device activation * */ static gboolean nm_device_activate_stage1_device_prepare (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); priv->ip4_state = priv->ip6_state = IP_NONE; /* Notify the new ActiveConnection along with the state change */ g_object_notify (G_OBJECT (self), NM_DEVICE_ACTIVE_CONNECTION); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) started..."); nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { ret = NM_DEVICE_GET_CLASS (self)->act_stage1_prepare (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { goto out; } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (nm_active_connection_get_master (active)) { /* If the master connection is ready for slaves, attach ourselves */ if (nm_active_connection_get_master_ready (active)) master_ready_cb (active, NULL, self); else { _LOGD (LOGD_DEVICE, "waiting for master connection to become ready"); /* Attach a signal handler and wait for the master connection to begin activating */ g_assert (priv->master_ready_id == 0); priv->master_ready_id = g_signal_connect (active, "notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY, (GCallback) master_ready_cb, self); /* Postpone */ } } else nm_device_activate_schedule_stage2_device_config (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) complete."); return FALSE; } /* * nm_device_activate_schedule_stage1_device_prepare * * Prepare a device for activation * */ void nm_device_activate_schedule_stage1_device_prepare (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage1_device_prepare, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) scheduled..."); } static NMActStageReturn act_stage2_config (NMDevice *self, NMDeviceStateReason *reason) { /* Nothing to do */ return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage2_device_config * * Determine device parameters and set those on the device, ie * for wireless devices, set SSID, keys, etc. * */ static gboolean nm_device_activate_stage2_device_config (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; gboolean no_firmware = FALSE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); GSList *iter; /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) starting..."); nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { if (!nm_device_bring_up (self, FALSE, &no_firmware)) { if (no_firmware) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_FIRMWARE_MISSING); else nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED); goto out; } ret = NM_DEVICE_GET_CLASS (self)->act_stage2_config (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) goto out; else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } /* If we have slaves that aren't yet enslaved, do that now */ for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; NMDeviceState slave_state = nm_device_get_state (info->slave); if (slave_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, info->slave, nm_device_get_connection (info->slave)); else if ( nm_device_uses_generated_assumed_connection (self) && slave_state <= NM_DEVICE_STATE_DISCONNECTED) nm_device_queue_recheck_assume (info->slave); } _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) successful."); nm_device_activate_schedule_stage3_ip_config_start (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) complete."); return FALSE; } /* * nm_device_activate_schedule_stage2_device_config * * Schedule setup of the hardware device * */ void nm_device_activate_schedule_stage2_device_config (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage2_device_config, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) scheduled..."); } /*********************************************/ /* avahi-autoipd stuff */ static void aipd_timeout_remove (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { g_source_remove (priv->aipd_timeout); priv->aipd_timeout = 0; } } static void aipd_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_watch) { g_source_remove (priv->aipd_watch); priv->aipd_watch = 0; } if (priv->aipd_pid > 0) { nm_utils_kill_child_sync (priv->aipd_pid, SIGKILL, LOGD_AUTOIP4, "avahi-autoipd", NULL, 0, 0); priv->aipd_pid = -1; } aipd_timeout_remove (self); } static NMIP4Config * aipd_get_ip4_config (NMDevice *self, guint32 lla) { NMIP4Config *config = NULL; NMPlatformIP4Address address; NMPlatformIP4Route route; config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (config); memset (&address, 0, sizeof (address)); address.address = lla; address.plen = 16; address.source = NM_IP_CONFIG_SOURCE_IP4LL; nm_ip4_config_add_address (config, &address); /* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */ memset (&route, 0, sizeof (route)); route.network = htonl (0xE0000000L); route.plen = 4; route.source = NM_IP_CONFIG_SOURCE_IP4LL; route.metric = nm_device_get_ip4_route_metric (self); nm_ip4_config_add_route (config, &route); return config; } #define IPV4LL_NETWORK (htonl (0xA9FE0000L)) #define IPV4LL_NETMASK (htonl (0xFFFF0000L)) void nm_device_handle_autoip4_event (NMDevice *self, const char *event, const char *address) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = NULL; const char *method; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (event != NULL); if (priv->act_request == NULL) return; connection = nm_act_request_get_connection (priv->act_request); g_assert (connection); /* Ignore if the connection isn't an AutoIP connection */ method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) != 0) return; if (strcmp (event, "BIND") == 0) { guint32 lla; NMIP4Config *config; if (inet_pton (AF_INET, address, &lla) <= 0) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd.", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } if ((lla & IPV4LL_NETMASK) != IPV4LL_NETWORK) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd (not link-local).", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } config = aipd_get_ip4_config (self, lla); if (config == NULL) { _LOGE (LOGD_AUTOIP4, "failed to get autoip config"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); return; } if (priv->ip4_state == IP_CONF) { aipd_timeout_remove (self); nm_device_activate_schedule_ip4_config_result (self, config); } else if (priv->ip4_state == IP_DONE) { if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } } else g_assert_not_reached (); g_object_unref (config); } else { _LOGW (LOGD_AUTOIP4, "autoip address %s no longer valid because '%s'.", address, event); /* The address is gone; terminate the connection or fail activation */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); } } static void aipd_watch_cb (GPid pid, gint status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceState state; if (!priv->aipd_watch) return; priv->aipd_watch = 0; if (WIFEXITED (status)) _LOGD (LOGD_AUTOIP4, "avahi-autoipd exited with error code %d", WEXITSTATUS (status)); else if (WIFSTOPPED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd stopped unexpectedly with signal %d", WSTOPSIG (status)); else if (WIFSIGNALED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd died with signal %d", WTERMSIG (status)); else _LOGW (LOGD_AUTOIP4, "avahi-autoipd died from an unknown cause"); aipd_cleanup (self); state = nm_device_get_state (self); if (nm_device_is_activating (self) || (state == NM_DEVICE_STATE_ACTIVATED)) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_FAILED); } static gboolean aipd_timeout_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { _LOGI (LOGD_AUTOIP4, "avahi-autoipd timed out."); priv->aipd_timeout = 0; aipd_cleanup (self); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_timeout (self); } return FALSE; } /* default to installed helper, but can be modified for testing */ const char *nm_device_autoipd_helper_path = LIBEXECDIR "/nm-avahi-autoipd.action"; static NMActStageReturn aipd_start (NMDevice *self, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *argv[6]; char *cmdline; const char *aipd_binary; int i = 0; GError *error = NULL; aipd_cleanup (self); /* Find avahi-autoipd */ aipd_binary = nm_utils_find_helper ("avahi-autoipd", NULL, NULL); if (!aipd_binary) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: not found"); *reason = NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } argv[i++] = aipd_binary; argv[i++] = "--script"; argv[i++] = nm_device_autoipd_helper_path; if (nm_logging_enabled (LOGL_DEBUG, LOGD_AUTOIP4)) argv[i++] = "--debug"; argv[i++] = nm_device_get_ip_iface (self); argv[i++] = NULL; cmdline = g_strjoinv (" ", (char **) argv); _LOGD (LOGD_AUTOIP4, "running: %s", cmdline); g_free (cmdline); if (!g_spawn_async ("/", (char **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, nm_utils_setpgid, NULL, &(priv->aipd_pid), &error)) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: %s", error && error->message ? error->message : "(unknown)"); g_clear_error (&error); aipd_cleanup (self); return NM_ACT_STAGE_RETURN_FAILURE; } _LOGI (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) started" " avahi-autoipd..."); /* Monitor the child process so we know when it dies */ priv->aipd_watch = g_child_watch_add (priv->aipd_pid, aipd_watch_cb, self); /* Start a timeout to bound the address attempt */ priv->aipd_timeout = g_timeout_add_seconds (20, aipd_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /*********************************************/ static gboolean _device_get_default_route_from_platform (NMDevice *self, int addr_family, NMPlatformIPRoute *out_route) { gboolean success = FALSE; int ifindex = nm_device_get_ip_ifindex (self); GArray *routes; if (addr_family == AF_INET) routes = nm_platform_ip4_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); else routes = nm_platform_ip6_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); if (routes) { guint route_metric = G_MAXUINT32, m; const NMPlatformIPRoute *route = NULL, *r; guint i; /* if there are several default routes, find the one with the best metric */ for (i = 0; i < routes->len; i++) { if (addr_family == AF_INET) { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i); m = r->metric; } else { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i); m = nm_utils_ip6_route_metric_normalize (r->metric); } if (!route || m < route_metric) { route = r; route_metric = m; } } if (route) { if (addr_family == AF_INET) *((NMPlatformIP4Route *) out_route) = *((NMPlatformIP4Route *) route); else *((NMPlatformIP6Route *) out_route) = *((NMPlatformIP6Route *) route); success = TRUE; } g_array_free (routes, TRUE); } return success; } /*********************************************/ static void ensure_con_ipx_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMConnection *connection; g_assert (!!priv->con_ip4_config == !!priv->con_ip6_config); if (priv->con_ip4_config) return; connection = nm_device_get_connection (self); if (!connection) return; priv->con_ip4_config = nm_ip4_config_new (ip_ifindex); priv->con_ip6_config = nm_ip6_config_new (ip_ifindex); nm_ip4_config_merge_setting (priv->con_ip4_config, nm_connection_get_setting_ip4_config (connection), nm_device_get_ip4_route_metric (self)); nm_ip6_config_merge_setting (priv->con_ip6_config, nm_connection_get_setting_ip6_config (connection), nm_device_get_ip6_route_metric (self)); if (nm_device_uses_assumed_connection (self)) { /* For assumed connections ignore all addresses and routes. */ nm_ip4_config_reset_addresses (priv->con_ip4_config); nm_ip4_config_reset_routes (priv->con_ip4_config); nm_ip6_config_reset_addresses (priv->con_ip6_config); nm_ip6_config_reset_routes (priv->con_ip6_config); } } /*********************************************/ /* DHCPv4 stuff */ static void dhcp4_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp4_client) { /* Stop any ongoing DHCP transaction on this device */ if (priv->dhcp4_state_sigid) { g_signal_handler_disconnect (priv->dhcp4_client, priv->dhcp4_state_sigid); priv->dhcp4_state_sigid = 0; } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE); if (stop) nm_dhcp_client_stop (priv->dhcp4_client, release); g_clear_object (&priv->dhcp4_client); } if (priv->dhcp4_config) { g_clear_object (&priv->dhcp4_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } } static gboolean ip4_config_merge_and_apply (NMDevice *self, NMIP4Config *config, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP4Config *composite; gboolean has_direct_route; const guint32 default_route_metric = nm_device_get_ip4_route_metric (self); guint32 gateway; /* Merge all the configs into the composite config */ if (config) { g_clear_object (&priv->dev_ip4_config); priv->dev_ip4_config = g_object_ref (config); } composite = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); if (priv->dev_ip4_config) nm_ip4_config_merge (composite, priv->dev_ip4_config); if (priv->vpn4_config) nm_ip4_config_merge (composite, priv->vpn4_config); if (priv->ext_ip4_config) nm_ip4_config_merge (composite, priv->ext_ip4_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip4_config) nm_ip4_config_merge (composite, priv->wwan_ip4_config); /* Merge user overrides into the composite config. For assumed connection, * con_ip4_config is empty. */ if (priv->con_ip4_config) nm_ip4_config_merge (composite, priv->con_ip4_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip4_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v4_has = FALSE; priv->default_route.v4_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v4_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip4_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip4_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip4_config_get_gateway (composite); if ( !gateway && nm_device_get_device_type (self) != NM_DEVICE_TYPE_MODEM) goto END_ADD_DEFAULT_ROUTE; has_direct_route = ( gateway == 0 || nm_ip4_config_get_subnet_for_host (composite, gateway) || nm_ip4_config_get_direct_route_for_host (composite, gateway)); priv->default_route.v4_has = TRUE; memset (&priv->default_route.v4, 0, sizeof (priv->default_route.v4)); priv->default_route.v4.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v4.gateway = gateway; priv->default_route.v4.metric = default_route_metric; priv->default_route.v4.mss = nm_ip4_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP4Route r = priv->default_route.v4; /* add a direct route to the gateway */ r.network = gateway; r.plen = 32; r.gateway = 0; nm_ip4_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v4_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v4_has = _device_get_default_route_from_platform (self, AF_INET, (NMPlatformIPRoute *) &priv->default_route.v4); } /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, composite); } success = nm_device_set_ip4_config (self, composite, default_route_metric, commit, out_reason); g_object_unref (composite); return success; } static void dhcp4_lease_change (NMDevice *self, NMIP4Config *config) { NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (config != NULL); if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCP4 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE, nm_device_get_connection (self), self, NULL, NULL, NULL); } } static void dhcp4_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp4_cleanup (self, TRUE, FALSE); if (timeout || (priv->ip4_state == IP_CONF)) nm_device_activate_schedule_ip4_config_timeout (self); else if (priv->ip4_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } static void dhcp4_update_config (NMDevice *self, NMDhcp4Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP4 config object with new DHCP options */ nm_dhcp4_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp4_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } static void dhcp4_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP4Config *ip4_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == FALSE); g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config)); _LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: if (!ip4_config) { _LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); break; } dhcp4_update_config (self, priv->dhcp4_config, options); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_result (self, ip4_config); else if (priv->ip4_state == IP_DONE) dhcp4_lease_change (self, ip4_config); break; case NM_DHCP_STATE_TIMEOUT: dhcp4_fail (self, TRUE); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip4_state == IP_CONF) break; /* Fall through */ case NM_DHCP_STATE_DONE: case NM_DHCP_STATE_FAIL: dhcp4_fail (self, FALSE); break; default: break; } } static NMActStageReturn dhcp4_start (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip4; const guint8 *hw_addr; size_t hw_addr_len = 0; GByteArray *tmp = NULL; s_ip4 = nm_connection_get_setting_ip4_config (connection); /* Clear old exported DHCP options */ if (priv->dhcp4_config) g_object_unref (priv->dhcp4_config); priv->dhcp4_config = nm_dhcp4_config_new (); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } /* Begin DHCP on the interface */ g_warn_if_fail (priv->dhcp4_client == NULL); priv->dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip4_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip4), nm_setting_ip_config_get_dhcp_hostname (s_ip4), nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4)), priv->dhcp_timeout, priv->dhcp_anycast_address, NULL); if (tmp) g_byte_array_free (tmp, TRUE); if (!priv->dhcp4_client) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } priv->dhcp4_state_sigid = g_signal_connect (priv->dhcp4_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp4_state_changed), self); nm_device_add_pending_action (self, PENDING_ACTION_DHCP4, TRUE); /* DHCP devices will be notified by the DHCP manager when stuff happens */ return NM_ACT_STAGE_RETURN_POSTPONE; } gboolean nm_device_dhcp4_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason; NMConnection *connection; g_return_val_if_fail (priv->dhcp4_client != NULL, FALSE); _LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp4_cleanup (self, TRUE, release); connection = nm_device_get_connection (self); g_assert (connection); /* Start DHCP again on the interface */ ret = dhcp4_start (self, connection, &reason); return (ret != NM_ACT_STAGE_RETURN_FAILURE); } /*********************************************/ static GHashTable *shared_ips = NULL; static void release_shared_ip (gpointer data) { g_hash_table_remove (shared_ips, data); } static gboolean reserve_shared_ip (NMDevice *self, NMSettingIPConfig *s_ip4, NMPlatformIP4Address *address) { if (G_UNLIKELY (shared_ips == NULL)) shared_ips = g_hash_table_new (g_direct_hash, g_direct_equal); memset (address, 0, sizeof (*address)); if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) { /* Use the first user-supplied address */ NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0); g_assert (user); nm_ip_address_get_address_binary (user, &address->address); address->plen = nm_ip_address_get_prefix (user); } else { /* Find an unused address in the 10.42.x.x range */ guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */ guint32 count = 0; while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) { count += ntohl (0x100); if (count > ntohl (0xFE00)) { _LOGE (LOGD_SHARING, "ran out of shared IP addresses!"); return FALSE; } } address->address = start + count; address->plen = 24; g_hash_table_insert (shared_ips, GUINT_TO_POINTER (address->address), GUINT_TO_POINTER (TRUE)); } return TRUE; } static NMIP4Config * shared4_new_config (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMIP4Config *config = NULL; NMPlatformIP4Address address; g_return_val_if_fail (self != NULL, NULL); if (!reserve_shared_ip (self, nm_connection_get_setting_ip4_config (connection), &address)) { *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE; return NULL; } config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); address.source = NM_IP_CONFIG_SOURCE_SHARED; nm_ip4_config_add_address (config, &address); /* Remove the address lock when the object gets disposed */ g_object_set_data_full (G_OBJECT (config), "shared-ip", GUINT_TO_POINTER (address.address), release_shared_ip); return config; } /*********************************************/ static gboolean connection_ip4_method_requires_carrier (NMConnection *connection, gboolean *out_ip4_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); static const char *ip4_carrier_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_AUTO, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip4_enabled) *out_ip4_enabled = !!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED); return _nm_utils_string_in_list (method, ip4_carrier_methods); } static gboolean connection_ip6_method_requires_carrier (NMConnection *connection, gboolean *out_ip6_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); static const char *ip6_carrier_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip6_enabled) *out_ip6_enabled = !!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE); return _nm_utils_string_in_list (method, ip6_carrier_methods); } static gboolean connection_requires_carrier (NMConnection *connection) { NMSettingIPConfig *s_ip4, *s_ip6; gboolean ip4_carrier_wanted, ip6_carrier_wanted; gboolean ip4_used = FALSE, ip6_used = FALSE; ip4_carrier_wanted = connection_ip4_method_requires_carrier (connection, &ip4_used); if (ip4_carrier_wanted) { /* If IPv4 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv6 method. */ s_ip4 = nm_connection_get_setting_ip4_config (connection); if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4)) return TRUE; } ip6_carrier_wanted = connection_ip6_method_requires_carrier (connection, &ip6_used); if (ip6_carrier_wanted) { /* If IPv6 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv4 method. */ s_ip6 = nm_connection_get_setting_ip6_config (connection); if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6)) return TRUE; } /* If an IP version wants a carrier and and the other IP version isn't * used, the connection requires carrier since it will just fail without one. */ if (ip4_carrier_wanted && !ip6_used) return TRUE; if (ip6_carrier_wanted && !ip4_used) return TRUE; /* If both want a carrier, the whole connection wants a carrier */ return ip4_carrier_wanted && ip6_carrier_wanted; } static gboolean have_any_ready_slaves (NMDevice *self, const GSList *slaves) { const GSList *iter; /* Any enslaved slave is "ready" in the generic case as it's * at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2 * properties set up. */ for (iter = slaves; iter; iter = g_slist_next (iter)) { if (nm_device_get_enslaved (iter->data)) return TRUE; } return FALSE; } static gboolean ip4_requires_slaves (NMConnection *connection) { const char *method; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); return strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0; } static NMActStageReturn act_stage3_ip4_config_start (NMDevice *self, NMIP4Config **out_config, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE; const char *method; GSList *slaves; gboolean ready_slaves; g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE); connection = nm_device_get_connection (self); g_assert (connection); if ( connection_ip4_method_requires_carrier (connection, NULL) && priv->is_master && !priv->carrier) { _LOGI (LOGD_IP4 | LOGD_DEVICE, "IPv4 config waiting until carrier is on"); return NM_ACT_STAGE_RETURN_WAIT; } if (priv->is_master && ip4_requires_slaves (connection)) { /* If the master has no ready slaves, and depends on slaves for * a successful IPv4 attempt, then postpone IPv4 addressing. */ slaves = nm_device_master_get_slaves (self); ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves); g_slist_free (slaves); if (ready_slaves == FALSE) { _LOGI (LOGD_DEVICE | LOGD_IP4, "IPv4 config waiting until slaves are ready"); return NM_ACT_STAGE_RETURN_WAIT; } } method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); /* Start IPv4 addressing based on the method requested */ if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0) ret = dhcp4_start (self, connection, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) == 0) ret = aipd_start (self, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL) == 0) { /* Use only IPv4 config from the connection data */ *out_config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (*out_config); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) { *out_config = shared4_new_config (self, connection, reason); if (*out_config) { priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self)); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else ret = NM_ACT_STAGE_RETURN_FAILURE; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0) { /* Nothing to do... */ ret = NM_ACT_STAGE_RETURN_STOP; } else _LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method); return ret; } /*********************************************/ /* DHCPv6 stuff */ static void dhcp6_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE; g_clear_object (&priv->dhcp6_ip6_config); if (priv->dhcp6_client) { if (priv->dhcp6_state_sigid) { g_signal_handler_disconnect (priv->dhcp6_client, priv->dhcp6_state_sigid); priv->dhcp6_state_sigid = 0; } if (stop) nm_dhcp_client_stop (priv->dhcp6_client, release); g_clear_object (&priv->dhcp6_client); } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE); if (priv->dhcp6_config) { g_clear_object (&priv->dhcp6_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } } static gboolean ip6_config_merge_and_apply (NMDevice *self, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP6Config *composite; gboolean has_direct_route; const struct in6_addr *gateway; /* If no config was passed in, create a new one */ composite = nm_ip6_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); g_assert (composite); /* Merge all the IP configs into the composite config */ if (priv->ac_ip6_config) nm_ip6_config_merge (composite, priv->ac_ip6_config); if (priv->dhcp6_ip6_config) nm_ip6_config_merge (composite, priv->dhcp6_ip6_config); if (priv->vpn6_config) nm_ip6_config_merge (composite, priv->vpn6_config); if (priv->ext_ip6_config) nm_ip6_config_merge (composite, priv->ext_ip6_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip6_config) nm_ip6_config_merge (composite, priv->wwan_ip6_config); /* Merge user overrides into the composite config. For assumed connections, * con_ip6_config is empty. */ if (priv->con_ip6_config) nm_ip6_config_merge (composite, priv->con_ip6_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip6_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v6_has = FALSE; priv->default_route.v6_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v6_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip6_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip6_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip6_config_get_gateway (composite); if (!gateway) goto END_ADD_DEFAULT_ROUTE; has_direct_route = nm_ip6_config_get_direct_route_for_host (composite, gateway) != NULL; priv->default_route.v6_has = TRUE; memset (&priv->default_route.v6, 0, sizeof (priv->default_route.v6)); priv->default_route.v6.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v6.gateway = *gateway; priv->default_route.v6.metric = nm_device_get_ip6_route_metric (self); priv->default_route.v6.mss = nm_ip6_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP6Route r = priv->default_route.v6; /* add a direct route to the gateway */ r.network = *gateway; r.plen = 128; r.gateway = in6addr_any; nm_ip6_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v6_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v6_has = _device_get_default_route_from_platform (self, AF_INET6, (NMPlatformIPRoute *) &priv->default_route.v6); } nm_ip6_config_addresses_sort (composite, priv->rdisc ? priv->rdisc_use_tempaddr : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN); /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit (self, composite); } success = nm_device_set_ip6_config (self, composite, commit, out_reason); g_object_unref (composite); return success; } static void dhcp6_lease_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; if (priv->dhcp6_ip6_config == NULL) { _LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); return; } g_assert (priv->dhcp6_client); /* sanity check */ connection = nm_device_get_connection (self); g_assert (connection); /* Apply the updated config */ if (ip6_config_merge_and_apply (self, TRUE, &reason) == FALSE) { _LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCPv6 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE, connection, self, NULL, NULL, NULL); } } static void dhcp6_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp6_cleanup (self, TRUE, FALSE); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) { if (timeout || (priv->ip6_state == IP_CONF)) nm_device_activate_schedule_ip6_config_timeout (self); else if (priv->ip6_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } else { /* not a hard failure; just live with the RA info */ if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_timeout (NMDevice *self, NMDhcpClient *client) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) dhcp6_fail (self, TRUE); else { /* not a hard failure; just live with the RA info */ dhcp6_cleanup (self, TRUE, FALSE); if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_update_config (NMDevice *self, NMDhcp6Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP6 config object with new DHCP options */ nm_dhcp6_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp6_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } static void dhcp6_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP6Config *ip6_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == TRUE); g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config)); _LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: g_clear_object (&priv->dhcp6_ip6_config); if (ip6_config) { priv->dhcp6_ip6_config = g_object_ref (ip6_config); dhcp6_update_config (self, priv->dhcp6_config, options); } if (priv->ip6_state == IP_CONF) { if (priv->dhcp6_ip6_config == NULL) { /* FIXME: Initial DHCP failed; should we fail IPv6 entirely then? */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); break; } nm_device_activate_schedule_ip6_config_result (self); } else if (priv->ip6_state == IP_DONE) dhcp6_lease_change (self); break; case NM_DHCP_STATE_TIMEOUT: dhcp6_timeout (self, client); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip6_state != IP_CONF) dhcp6_fail (self, FALSE); break; case NM_DHCP_STATE_DONE: /* In IPv6 info-only mode, the client doesn't handle leases so it * may exit right after getting a response from the server. That's * normal. In that case we just ignore the exit. */ if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) break; /* Otherwise, fall through */ case NM_DHCP_STATE_FAIL: dhcp6_fail (self, FALSE); break; default: break; } } static gboolean dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip6; GByteArray *tmp = NULL; const guint8 *hw_addr; size_t hw_addr_len = 0; g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); g_assert (s_ip6); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } priv->dhcp6_client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip6_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip6), nm_setting_ip_config_get_dhcp_hostname (s_ip6), priv->dhcp_timeout, priv->dhcp_anycast_address, (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE, nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6))); if (tmp) g_byte_array_free (tmp, TRUE); if (priv->dhcp6_client) { priv->dhcp6_state_sigid = g_signal_connect (priv->dhcp6_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp6_state_changed), self); } return !!priv->dhcp6_client; } static gboolean dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMSettingIPConfig *s_ip6; g_clear_object (&priv->dhcp6_config); priv->dhcp6_config = nm_dhcp6_config_new (); g_warn_if_fail (priv->dhcp6_ip6_config == NULL); g_clear_object (&priv->dhcp6_ip6_config); connection = nm_device_get_connection (self); g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); if (!nm_setting_ip_config_get_may_fail (s_ip6) || !strcmp (nm_setting_ip_config_get_method (s_ip6), NM_SETTING_IP6_CONFIG_METHOD_DHCP)) nm_device_add_pending_action (self, PENDING_ACTION_DHCP6, TRUE); if (wait_for_ll) { NMActStageReturn ret; /* ensure link local is ready... */ ret = linklocal6_start (self); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { /* success; wait for the LL address to show up */ return TRUE; } /* success; already have the LL address; kick off DHCP */ g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (!dhcp6_start_with_link_ready (self, connection)) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return FALSE; } return TRUE; } gboolean nm_device_dhcp6_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_val_if_fail (priv->dhcp6_client != NULL, FALSE); _LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp6_cleanup (self, TRUE, release); /* Start DHCP again on the interface */ return dhcp6_start (self, FALSE, NULL); } /******************************************/ static gboolean have_ip6_address (const NMIP6Config *ip6_config, gboolean linklocal) { guint i; if (!ip6_config) return FALSE; linklocal = !!linklocal; for (i = 0; i < nm_ip6_config_get_num_addresses (ip6_config); i++) { const NMPlatformIP6Address *addr = nm_ip6_config_get_address (ip6_config, i); if ((IN6_IS_ADDR_LINKLOCAL (&addr->address) == linklocal) && !(addr->flags & IFA_F_TENTATIVE)) return TRUE; } return FALSE; } static void linklocal6_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->linklocal6_timeout_id) { g_source_remove (priv->linklocal6_timeout_id); priv->linklocal6_timeout_id = 0; } } static gboolean linklocal6_timeout_cb (gpointer user_data) { NMDevice *self = user_data; linklocal6_cleanup (self); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout"); nm_device_activate_schedule_ip6_config_timeout (self); return G_SOURCE_REMOVE; } static void linklocal6_complete (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; g_assert (priv->linklocal6_timeout_id); g_assert (have_ip6_address (priv->ip6_config, TRUE)); linklocal6_cleanup (self); connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method); if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) { if (!addrconf6_start_with_link_ready (self)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) { if (!dhcp6_start_with_link_ready (self, connection)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0) nm_device_activate_schedule_ip6_config_result (self); else g_return_if_fail (FALSE); } static void check_and_add_ipv6ll_addr (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMUtilsIPv6IfaceId iid; struct in6_addr lladdr; guint i, n; if (priv->nm_ipv6ll == FALSE) return; if (priv->ip6_config) { n = nm_ip6_config_get_num_addresses (priv->ip6_config); for (i = 0; i < n; i++) { const NMPlatformIP6Address *addr; addr = nm_ip6_config_get_address (priv->ip6_config, i); if (IN6_IS_ADDR_LINKLOCAL (&addr->address)) { /* Already have an LL address, nothing to do */ return; } } } if (!nm_device_get_ip_iface_identifier (self, &iid)) { _LOGW (LOGD_IP6, "failed to get interface identifier; IPv6 may be broken"); return; } memset (&lladdr, 0, sizeof (lladdr)); lladdr.s6_addr16[0] = htons (0xfe80); nm_utils_ipv6_addr_set_interface_identfier (&lladdr, iid); _LOGD (LOGD_IP6, "adding IPv6LL address %s", nm_utils_inet6_ntop (&lladdr, NULL)); if (!nm_platform_ip6_address_add (ip_ifindex, lladdr, in6addr_any, 64, NM_PLATFORM_LIFETIME_PERMANENT, NM_PLATFORM_LIFETIME_PERMANENT, 0)) { _LOGW (LOGD_IP6, "failed to add IPv6 link-local address %s", nm_utils_inet6_ntop (&lladdr, NULL)); } } static NMActStageReturn linklocal6_start (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; linklocal6_cleanup (self); if (have_ip6_address (priv->ip6_config, TRUE)) return NM_ACT_STAGE_RETURN_SUCCESS; connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.", method); check_and_add_ipv6ll_addr (self); priv->linklocal6_timeout_id = g_timeout_add_seconds (5, linklocal6_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /******************************************/ static void print_support_extended_ifa_flags (NMSettingIP6ConfigPrivacy use_tempaddr) { static gint8 warn = 0; static gint8 s_libnl = -1, s_kernel; if (warn >= 2) return; if (s_libnl == -1) { s_libnl = !!nm_platform_check_support_libnl_extended_ifa_flags (); s_kernel = !!nm_platform_check_support_kernel_extended_ifa_flags (); if (s_libnl && s_kernel) { nm_log_dbg (LOGD_IP6, "kernel and libnl support extended IFA_FLAGS (needed by NM for IPv6 private addresses)"); warn = 2; return; } } if ( use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR && use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR) { if (warn == 0) { nm_log_dbg (LOGD_IP6, "%s%s%s %s not support extended IFA_FLAGS (needed by NM for IPv6 private addresses)", !s_kernel ? "kernel" : "", !s_kernel && !s_libnl ? " and " : "", !s_libnl ? "libnl" : "", !s_kernel && !s_libnl ? "do" : "does"); warn = 1; } return; } if (!s_libnl && !s_kernel) { nm_log_warn (LOGD_IP6, "libnl and the kernel do not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_libnl) { nm_log_warn (LOGD_IP6, "libnl does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_kernel) { nm_log_warn (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); warn = 2; } static void nm_device_ipv6_set_mtu (NMDevice *self, guint32 mtu); static void nm_device_set_mtu (NMDevice *self, guint32 mtu) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ifindex = nm_device_get_ifindex (self); if (mtu) priv->mtu = mtu; /* Ensure the IPv6 MTU is still alright. */ if (priv->ip6_mtu) nm_device_ipv6_set_mtu (self, priv->ip6_mtu); if (priv->mtu != nm_platform_link_get_mtu (ifindex)) nm_platform_link_set_mtu (ifindex, priv->mtu); } static void nm_device_ipv6_set_mtu (NMDevice *self, guint32 mtu) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint32 plat_mtu = nm_device_ipv6_sysctl_get_int32 (self, "mtu", priv->mtu); char val[16]; priv->ip6_mtu = mtu ?: plat_mtu; if (priv->ip6_mtu && priv->mtu < priv->ip6_mtu) { _LOGW (LOGD_DEVICE | LOGD_IP6, "Lowering IPv6 MTU (%d) to match device MTU (%d)", priv->ip6_mtu, priv->mtu); priv->ip6_mtu = priv->mtu; } if (priv->ip6_mtu < 1280) { _LOGW (LOGD_DEVICE | LOGD_IP6, "IPv6 MTU (%d) smaller than 1280, adjusting", priv->ip6_mtu); priv->ip6_mtu = 1280; } if (priv->mtu < priv->ip6_mtu) { _LOGW (LOGD_DEVICE | LOGD_IP6, "Raising device MTU (%d) to match IPv6 MTU (%d)", priv->mtu, priv->ip6_mtu); nm_device_set_mtu (self, priv->ip6_mtu); } if (priv->ip6_mtu != plat_mtu) { g_snprintf (val, sizeof (val), "%d", mtu); nm_device_ipv6_sysctl_set (self, "mtu", val); } } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { address.preferred = discovered_address->preferred; if (address.preferred > address.lifetime) address.preferred = address.lifetime; address.source = NM_IP_CONFIG_SOURCE_RDISC; address.flags = ifa_flags; nm_ip6_config_add_address (priv->ac_ip6_config, &address); } }
device_has_capability (NMDevice *self, NMDeviceCapabilities caps) { { static guint32 devcount = 0; NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->path == NULL); priv->path = g_strdup_printf ("/org/freedesktop/NetworkManager/Devices/%d", devcount++); _LOGI (LOGD_DEVICE, "exported as %s", priv->path); nm_dbus_manager_register_object (nm_dbus_manager_get (), priv->path, self); } const char * nm_device_get_path (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->path; } const char * nm_device_get_udi (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->udi; } const char * nm_device_get_iface (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 0); return NM_DEVICE_GET_PRIVATE (self)->iface; } int nm_device_get_ifindex (NMDevice *self) { g_return_val_if_fail (self != NULL, 0); return NM_DEVICE_GET_PRIVATE (self)->ifindex; } gboolean nm_device_is_software (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->is_software; } const char * nm_device_get_ip_iface (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, NULL); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_iface : priv->iface; } int nm_device_get_ip_ifindex (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, 0); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_ifindex : priv->ifindex; } void nm_device_set_ip_iface (NMDevice *self, const char *iface) { NMDevicePrivate *priv; char *old_ip_iface; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (!g_strcmp0 (iface, priv->ip_iface)) return; old_ip_iface = priv->ip_iface; priv->ip_ifindex = 0; priv->ip_iface = g_strdup (iface); if (priv->ip_iface) { priv->ip_ifindex = nm_platform_link_get_ifindex (priv->ip_iface); if (priv->ip_ifindex > 0) { if (nm_platform_check_support_user_ipv6ll ()) nm_platform_link_set_user_ipv6ll_enabled (priv->ip_ifindex, TRUE); if (!nm_platform_link_is_up (priv->ip_ifindex)) nm_platform_link_set_up (priv->ip_ifindex); } else { /* Device IP interface must always be a kernel network interface */ _LOGW (LOGD_HW, "failed to look up interface index"); } } /* We don't care about any saved values from the old iface */ g_hash_table_remove_all (priv->ip6_saved_properties); /* Emit change notification */ if (g_strcmp0 (old_ip_iface, priv->ip_iface)) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); g_free (old_ip_iface); } static gboolean get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid) { NMLinkType link_type; const guint8 *hwaddr = NULL; size_t hwaddr_len = 0; int ifindex; gboolean success; /* If we get here, we *must* have a kernel netdev, which implies an ifindex */ ifindex = nm_device_get_ip_ifindex (self); g_assert (ifindex); link_type = nm_platform_link_get_type (ifindex); g_return_val_if_fail (link_type > NM_LINK_TYPE_UNKNOWN, 0); hwaddr = nm_platform_link_get_address (ifindex, &hwaddr_len); if (!hwaddr_len) return FALSE; success = nm_utils_get_ipv6_interface_identifier (link_type, hwaddr, hwaddr_len, out_iid); if (!success) { _LOGW (LOGD_HW, "failed to generate interface identifier " "for link type %u hwaddr_len %zu", link_type, hwaddr_len); } return success; } static gboolean nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid) { return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid); } const char * nm_device_get_driver (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver; } const char * nm_device_get_driver_version (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver_version; } NMDeviceType nm_device_get_device_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN); return NM_DEVICE_GET_PRIVATE (self)->type; } /** * nm_device_get_priority(): * @self: the #NMDevice * * Returns: the device's routing priority. Lower numbers means a "better" * device, eg higher priority. */ int nm_device_get_priority (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 1000); /* Device 'priority' is used for the default route-metric and is based on * the device type. The settings ipv4.route-metric and ipv6.route-metric * can overwrite this default. * * Currently for both IPv4 and IPv6 we use the same default values. * * The route-metric is used for the metric of the routes of device. * This also applies to the default route. Therefore it affects also * which device is the "best". * * For comparison, note that iproute2 by default adds IPv4 routes with * metric 0, and IPv6 routes with metric 1024. The latter is the IPv6 * "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6). * In kernel, the full uint32_t range is available for route * metrics (except for IPv6, where 0 means 1024). */ switch (nm_device_get_device_type (self)) { /* 50 is reserved for VPN (NM_VPN_ROUTE_METRIC_DEFAULT) */ case NM_DEVICE_TYPE_ETHERNET: return 100; case NM_DEVICE_TYPE_INFINIBAND: return 150; case NM_DEVICE_TYPE_ADSL: return 200; case NM_DEVICE_TYPE_WIMAX: return 250; case NM_DEVICE_TYPE_BOND: return 300; case NM_DEVICE_TYPE_TEAM: return 350; case NM_DEVICE_TYPE_VLAN: return 400; case NM_DEVICE_TYPE_BRIDGE: return 425; case NM_DEVICE_TYPE_MODEM: return 450; case NM_DEVICE_TYPE_BT: return 550; case NM_DEVICE_TYPE_WIFI: return 600; case NM_DEVICE_TYPE_OLPC_MESH: return 650; case NM_DEVICE_TYPE_GENERIC: return 950; case NM_DEVICE_TYPE_UNKNOWN: return 10000; case NM_DEVICE_TYPE_UNUSED1: case NM_DEVICE_TYPE_UNUSED2: /* omit default: to get compiler warning about missing switch cases */ break; } return 11000; } guint32 nm_device_get_ip4_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip4_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } guint32 nm_device_get_ip6_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip6_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } const NMPlatformIP4Route * nm_device_get_ip4_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v4_is_assumed; return priv->default_route.v4_has ? &priv->default_route.v4 : NULL; } const NMPlatformIP6Route * nm_device_get_ip6_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v6_is_assumed; return priv->default_route.v6_has ? &priv->default_route.v6 : NULL; } const char * nm_device_get_type_desc (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->type_desc; } gboolean nm_device_has_carrier (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->carrier; } NMActRequest * nm_device_get_act_request (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->act_request; } NMConnection * nm_device_get_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->act_request ? nm_act_request_get_connection (priv->act_request) : NULL; } RfKillType nm_device_get_rfkill_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->rfkill_type; } static const char * nm_device_get_physical_port_id (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->physical_port_id; } /***********************************************************/ static gboolean nm_device_uses_generated_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) { connection = nm_act_request_get_connection (priv->act_request); if ( connection && nm_settings_connection_get_nm_generated_assumed (NM_SETTINGS_CONNECTION (connection))) return TRUE; } return FALSE; } gboolean nm_device_uses_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) return TRUE; return FALSE; } static SlaveInfo * find_slave_info (NMDevice *self, NMDevice *slave) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; GSList *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { info = iter->data; if (info->slave == slave) return info; } return NULL; } static void free_slave_info (SlaveInfo *info) { g_signal_handler_disconnect (info->slave, info->watch_id); g_clear_object (&info->slave); memset (info, 0, sizeof (*info)); g_free (info); } /** * nm_device_enslave_slave: * @self: the master device * @slave: the slave device to enslave * @connection: (allow-none): the slave device's connection * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function enslaves @slave. * * Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave * other devices. */ static gboolean nm_device_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection) { SlaveInfo *info; gboolean success = FALSE; gboolean configure; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; if (info->enslaved) success = TRUE; else { configure = (info->configure && connection != NULL); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure); info->enslaved = success; } nm_device_slave_notify_enslave (info->slave, success); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); /* Restart IP configuration if we're waiting for slaves. Do this * after updating the hardware address as IP config may need the * new address. */ if (success) { if (NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT) nm_device_activate_stage3_ip4_start (self); if (NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT) nm_device_activate_stage3_ip6_start (self); } return success; } /** * nm_device_release_one_slave: * @self: the master device * @slave: the slave device to release * @configure: whether @self needs to actually release @slave * @reason: the state change reason for the @slave * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function releases the previously enslaved @slave and/or * updates the state of @self and @slave to reflect its release. * * Returns: %TRUE on success, %FALSE on failure, if this device cannot enslave * other devices, or if @slave was never enslaved. */ static gboolean nm_device_release_one_slave (NMDevice *self, NMDevice *slave, gboolean configure, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; gboolean success = FALSE; g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; priv->slaves = g_slist_remove (priv->slaves, info); if (info->enslaved) { success = NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure); /* The release_slave() implementation logs success/failure (in the * correct device-specific log domain), so we don't have to do anything. */ } if (!configure) { g_warn_if_fail (reason == NM_DEVICE_STATE_REASON_NONE || reason == NM_DEVICE_STATE_REASON_REMOVED); reason = NM_DEVICE_STATE_REASON_NONE; } else if (reason == NM_DEVICE_STATE_REASON_NONE) { g_warn_if_reached (); reason = NM_DEVICE_STATE_REASON_UNKNOWN; } nm_device_slave_notify_release (info->slave, reason); free_slave_info (info); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); return success; } static gboolean is_software_external (NMDevice *self) { return nm_device_is_software (self) && !nm_device_get_is_nm_owned (self); } /** * nm_device_finish_init: * @self: the master device * * Whatever needs to be done post-initialization, when the device has a DBus * object name. */ void nm_device_finish_init (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_assert (priv->initialized == FALSE); /* Do not manage externally created software devices until they are IFF_UP */ if ( is_software_external (self) && !nm_platform_link_is_up (priv->ifindex) && priv->ifindex > 0) nm_device_set_initial_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); priv->initialized = TRUE; } static void carrier_changed (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (!nm_device_get_managed (self)) return; nm_device_recheck_available_connections (self); /* ignore-carrier devices ignore all carrier-down events */ if (priv->ignore_carrier && !carrier) return; if (priv->is_master) { /* Bridge/bond/team carrier does not affect its own activation, * but when carrier comes on, if there are slaves waiting, * it will restart them. */ if (!carrier) return; if (nm_device_activate_ip4_state_in_wait (self)) nm_device_activate_stage3_ip4_start (self); if (nm_device_activate_ip6_state_in_wait (self)) nm_device_activate_stage3_ip6_start (self); return; } else if (nm_device_get_enslaved (self) && !carrier) { /* Slaves don't deactivate when they lose carrier; for * bonds/teams in particular that would be actively * counterproductive. */ return; } if (carrier) { g_warn_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_CARRIER); } else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already in DISCONNECTED state without a carrier * (probably because it is tagged for carrier ignore) ensure that * when the carrier appears, auto connections are rechecked for * the device. */ nm_device_emit_recheck_auto_activate (self); } } else { g_return_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { if (nm_device_queued_state_peek (self) >= NM_DEVICE_STATE_DISCONNECTED) nm_device_queued_state_clear (self); } else { nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE, NM_DEVICE_STATE_REASON_CARRIER); } } } #define LINK_DISCONNECT_DELAY 4 static gboolean link_disconnect_action_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); _LOGD (LOGD_DEVICE, "link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; _LOGI (LOGD_DEVICE, "link disconnected (calling deferred action)"); NM_DEVICE_GET_CLASS (self)->carrier_changed (self, FALSE); return FALSE; } static void link_disconnect_action_cancel (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier_defer_id) { g_source_remove (priv->carrier_defer_id); _LOGD (LOGD_DEVICE, "link disconnected (canceling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; } } void nm_device_set_carrier (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDeviceState state = nm_device_get_state (self); if (priv->carrier == carrier) return; priv->carrier = carrier; g_object_notify (G_OBJECT (self), NM_DEVICE_CARRIER); if (priv->carrier) { _LOGI (LOGD_DEVICE, "link connected"); link_disconnect_action_cancel (self); klass->carrier_changed (self, TRUE); if (priv->carrier_wait_id) { g_source_remove (priv->carrier_wait_id); priv->carrier_wait_id = 0; nm_device_remove_pending_action (self, "carrier wait", TRUE); _carrier_wait_check_queued_act_request (self); } } else if (state <= NM_DEVICE_STATE_DISCONNECTED) { _LOGI (LOGD_DEVICE, "link disconnected"); klass->carrier_changed (self, FALSE); } else { _LOGI (LOGD_DEVICE, "link disconnected (deferring action for %d seconds)", LINK_DISCONNECT_DELAY); priv->carrier_defer_id = g_timeout_add_seconds (LINK_DISCONNECT_DELAY, link_disconnect_action_cb, self); _LOGD (LOGD_DEVICE, "link disconnected (deferring action for %d seconds) (id=%u)", LINK_DISCONNECT_DELAY, priv->carrier_defer_id); } } static void update_for_ip_ifname_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_hash_table_remove_all (priv->ip6_saved_properties); if (priv->dhcp4_client) { if (!nm_device_dhcp4_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->dhcp6_client) { if (!nm_device_dhcp6_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->rdisc) { /* FIXME: todo */ } if (priv->dnsmasq_manager) { /* FIXME: todo */ } } static void device_set_master (NMDevice *self, int ifindex) { NMDevice *master; NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); master = nm_manager_get_device_by_ifindex (nm_manager_get (), ifindex); if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave) { g_clear_object (&priv->master); priv->master = g_object_ref (master); nm_device_master_add_slave (master, self, FALSE); } else if (master) { _LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring", nm_device_get_iface (master)); } else { _LOGW (LOGD_DEVICE, "enslaved to unknown device %d %s", ifindex, nm_platform_link_get_name (ifindex)); } } static void device_link_changed (NMDevice *self, NMPlatformLink *info) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMUtilsIPv6IfaceId token_iid; gboolean ip_ifname_changed = FALSE; if (info->udi && g_strcmp0 (info->udi, priv->udi)) { /* Update UDI to what udev gives us */ g_free (priv->udi); priv->udi = g_strdup (info->udi); g_object_notify (G_OBJECT (self), NM_DEVICE_UDI); } /* Update MTU if it has changed. */ if (priv->mtu != info->mtu) { priv->mtu = info->mtu; g_object_notify (G_OBJECT (self), NM_DEVICE_MTU); } if (info->name[0] && strcmp (priv->iface, info->name) != 0) { _LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'", priv->ifindex, priv->iface, info->name); g_free (priv->iface); priv->iface = g_strdup (info->name); /* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */ ip_ifname_changed = !priv->ip_iface; g_object_notify (G_OBJECT (self), NM_DEVICE_IFACE); if (ip_ifname_changed) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); /* Re-match available connections against the new interface name */ nm_device_recheck_available_connections (self); /* Let any connections that use the new interface name have a chance * to auto-activate on the device. */ nm_device_emit_recheck_auto_activate (self); } /* Update slave status for external changes */ if (priv->enslaved && info->master != nm_device_get_ifindex (priv->master)) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_NONE); if (info->master && !priv->enslaved) { device_set_master (self, info->master); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); } if (priv->rdisc && nm_platform_link_get_ipv6_token (priv->ifindex, &token_iid)) { _LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface); if (nm_rdisc_set_iid (priv->rdisc, token_iid)) nm_rdisc_start (priv->rdisc); } if (klass->link_changed) klass->link_changed (self, info); /* Update DHCP, etc, if needed */ if (ip_ifname_changed) update_for_ip_ifname_change (self); if (priv->up != info->up) { priv->up = info->up; /* Manage externally-created software interfaces only when they are IFF_UP */ g_assert (priv->ifindex > 0); if (is_software_external (self)) { gboolean external_down = nm_device_get_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN); if (external_down && info->up) { if (nm_device_get_state (self) < NM_DEVICE_STATE_DISCONNECTED) { /* Ensure the assume check is queued before any queued state changes * from the transition to UNAVAILABLE. */ nm_device_queue_recheck_assume (self); /* Resetting the EXTERNAL_DOWN flag may change the device's state * to UNAVAILABLE. To ensure that the state change doesn't touch * the device before assumption occurs, pass * NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED as the reason. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED); } else { /* Don't trigger a state change; if the device is in a * state higher than UNAVAILABLE, it is already IFF_UP * or an explicit activation request was received. */ priv->unmanaged_flags &= ~NM_UNMANAGED_EXTERNAL_DOWN; } } else if (!external_down && !info->up && nm_device_get_state (self) <= NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already disconnected and is set !IFF_UP, * unmanage it. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE, NM_DEVICE_STATE_REASON_USER_REQUESTED); } } } } static void device_ip_link_changed (NMDevice *self, NMPlatformLink *info) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (info->name[0] && g_strcmp0 (priv->ip_iface, info->name)) { _LOGI (LOGD_DEVICE, "interface index %d renamed ip_iface (%d) from '%s' to '%s'", priv->ifindex, nm_device_get_ip_ifindex (self), priv->ip_iface, info->name); g_free (priv->ip_iface); priv->ip_iface = g_strdup (info->name); g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); update_for_ip_ifname_change (self); } } static void link_changed_cb (NMPlatform *platform, int ifindex, NMPlatformLink *info, NMPlatformSignalChangeType change_type, NMPlatformReason reason, NMDevice *self) { if (change_type != NM_PLATFORM_SIGNAL_CHANGED) return; /* We don't filter by 'reason' because we are interested in *all* link * changes. For example a call to nm_platform_link_set_up() may result * in an internal carrier change (i.e. we ask the kernel to set IFF_UP * and it results in also setting IFF_LOWER_UP. */ if (ifindex == nm_device_get_ifindex (self)) device_link_changed (self, info); else if (ifindex == nm_device_get_ip_ifindex (self)) device_ip_link_changed (self, info); } static void link_changed (NMDevice *self, NMPlatformLink *info) { /* Update carrier from link event if applicable. */ if ( device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT) && !device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER)) nm_device_set_carrier (self, info->connected); } /** * nm_device_notify_component_added(): * @self: the #NMDevice * @component: the component being added by a plugin * * Called by the manager to notify the device that a new component has * been found. The device implementation should return %TRUE if it * wishes to claim the component, or %FALSE if it cannot. * * Returns: %TRUE to claim the component, %FALSE if the component cannot be * claimed. */ gboolean nm_device_notify_component_added (NMDevice *self, GObject *component) { if (NM_DEVICE_GET_CLASS (self)->component_added) return NM_DEVICE_GET_CLASS (self)->component_added (self, component); return FALSE; } /** * nm_device_owns_iface(): * @self: the #NMDevice * @iface: an interface name * * Called by the manager to ask if the device or any of its components owns * @iface. For example, a WWAN implementation would return %TRUE for an * ethernet interface name that was owned by the WWAN device's modem component, * because that ethernet interface is controlled by the WWAN device and cannot * be used independently of the WWAN device. * * Returns: %TRUE if @self or it's components owns the interface name, * %FALSE if not */ gboolean nm_device_owns_iface (NMDevice *self, const char *iface) { if (NM_DEVICE_GET_CLASS (self)->owns_iface) return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface); return FALSE; } NMConnection * nm_device_new_default_connection (NMDevice *self) { if (NM_DEVICE_GET_CLASS (self)->new_default_connection) return NM_DEVICE_GET_CLASS (self)->new_default_connection (self); return NULL; } static void slave_state_changed (NMDevice *slave, NMDeviceState slave_new_state, NMDeviceState slave_old_state, NMDeviceStateReason reason, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); gboolean release = FALSE; _LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)", nm_device_get_iface (slave), slave_old_state, state_to_string (slave_old_state), slave_new_state, state_to_string (slave_new_state)); /* Don't try to enslave slaves until the master is ready */ if (priv->state < NM_DEVICE_STATE_CONFIG) return; if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, slave, nm_device_get_connection (slave)); else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED) release = TRUE; else if ( slave_new_state <= NM_DEVICE_STATE_DISCONNECTED && slave_old_state > NM_DEVICE_STATE_DISCONNECTED) { /* Catch failures due to unavailable or unmanaged */ release = TRUE; } if (release) { nm_device_release_one_slave (self, slave, TRUE, reason); /* Bridge/bond/team interfaces are left up until manually deactivated */ if (priv->slaves == NULL && priv->state == NM_DEVICE_STATE_ACTIVATED) _LOGD (LOGD_DEVICE, "last slave removed; remaining activated"); } } /** * nm_device_master_add_slave: * @self: the master device * @slave: the slave device to enslave * @configure: pass %TRUE if the slave should be configured by the master, or * %FALSE if it is already configured outside NetworkManager * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function adds @slave to the slave list for later enslavement. * * Returns: %TRUE on success, %FALSE on failure */ static gboolean nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); if (!find_slave_info (self, slave)) { info = g_malloc0 (sizeof (SlaveInfo)); info->slave = g_object_ref (slave); info->configure = configure; info->watch_id = g_signal_connect (slave, "state-changed", G_CALLBACK (slave_state_changed), self); priv->slaves = g_slist_append (priv->slaves, info); } nm_device_queue_recheck_assume (self); return TRUE; } /** * nm_device_master_get_slaves: * @self: the master device * * Returns: any slaves of which @self is the master. Caller owns returned list. */ GSList * nm_device_master_get_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GSList *slaves = NULL, *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) slaves = g_slist_prepend (slaves, ((SlaveInfo *) iter->data)->slave); return slaves; } /** * nm_device_master_get_slave_by_ifindex: * @self: the master device * @ifindex: the slave's interface index * * Returns: the slave with the given @ifindex of which @self is the master, * or %NULL if no device with @ifindex is a slave of @self. */ NMDevice * nm_device_master_get_slave_by_ifindex (NMDevice *self, int ifindex) { GSList *iter; for (iter = NM_DEVICE_GET_PRIVATE (self)->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; if (nm_device_get_ip_ifindex (info->slave) == ifindex) return info->slave; } return NULL; } /** * nm_device_master_check_slave_physical_port: * @self: the master device * @slave: a slave device * @log_domain: domain to log a warning in * * Checks if @self already has a slave with the same #NMDevice:physical-port-id * as @slave, and logs a warning if so. */ void nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave, guint64 log_domain) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *slave_physical_port_id, *existing_physical_port_id; SlaveInfo *info; GSList *iter; slave_physical_port_id = nm_device_get_physical_port_id (slave); if (!slave_physical_port_id) return; for (iter = priv->slaves; iter; iter = iter->next) { info = iter->data; if (info->slave == slave) continue; existing_physical_port_id = nm_device_get_physical_port_id (info->slave); if (!g_strcmp0 (slave_physical_port_id, existing_physical_port_id)) { _LOGW (log_domain, "slave %s shares a physical port with existing slave %s", nm_device_get_ip_iface (slave), nm_device_get_ip_iface (info->slave)); /* Since this function will get called for every slave, we only have * to warn about the first match we find; if there are other matches * later in the list, we will have already warned about them matching * @existing earlier. */ return; } } } /* release all slaves */ static void nm_device_master_release_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceStateReason reason; /* Don't release the slaves if this connection doesn't belong to NM. */ if (nm_device_uses_generated_assumed_connection (self)) return; reason = priv->state_reason; if (priv->state == NM_DEVICE_STATE_FAILED) reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED; while (priv->slaves) { SlaveInfo *info = priv->slaves->data; nm_device_release_one_slave (self, info->slave, TRUE, reason); } } /** * nm_device_get_master: * @self: the device * * If @self has been enslaved by another device, this returns that * device. Otherwise it returns %NULL. (In particular, note that if * @self is in the process of activating as a slave, but has not yet * been enslaved by its master, this will return %NULL.) * * Returns: (transfer none): @self's master, or %NULL */ NMDevice * nm_device_get_master (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) return priv->master; else return NULL; } /** * nm_device_slave_notify_enslave: * @self: the slave device * @success: whether the enslaving operation succeeded * * Notifies a slave that either it has been enslaved, or else its master tried * to enslave it and failed. */ static void nm_device_slave_notify_enslave (NMDevice *self, gboolean success) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG); g_assert (priv->master); if (!priv->enslaved) { if (success) { if (activating) { _LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation", nm_connection_get_id (connection)); } else _LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master)); priv->enslaved = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } else if (activating) { _LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved", nm_connection_get_id (connection)); } } if (activating) { priv->ip4_state = IP_DONE; priv->ip6_state = IP_DONE; nm_device_queue_state (self, success ? NM_DEVICE_STATE_SECONDARIES : NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NONE); } else nm_device_queue_recheck_assume (self); } /** * nm_device_slave_notify_release: * @self: the slave device * @reason: the reason associated with the state change * * Notifies a slave that it has been released, and why. */ static void nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); NMDeviceState new_state; const char *master_status; if ( reason != NM_DEVICE_STATE_REASON_NONE && priv->state > NM_DEVICE_STATE_DISCONNECTED && priv->state <= NM_DEVICE_STATE_ACTIVATED) { if (reason == NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED) { new_state = NM_DEVICE_STATE_FAILED; master_status = "failed"; } else if (reason == NM_DEVICE_STATE_REASON_USER_REQUESTED) { new_state = NM_DEVICE_STATE_DEACTIVATING; master_status = "deactivated by user request"; } else { new_state = NM_DEVICE_STATE_DISCONNECTED; master_status = "deactivated"; } _LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s", nm_connection_get_id (connection), master_status); nm_device_queue_state (self, new_state, reason); } else if (priv->master) _LOGI (LOGD_DEVICE, "released from master %s", nm_device_get_iface (priv->master)); else _LOGD (LOGD_DEVICE, "released from master%s", priv->enslaved ? "" : " (was not enslaved)"); if (priv->enslaved) { priv->enslaved = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } } /** * nm_device_get_enslaved: * @self: the #NMDevice * * Returns: %TRUE if the device is enslaved to a master device (eg bridge or * bond or team), %FALSE if not */ gboolean nm_device_get_enslaved (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->enslaved; } /** * nm_device_removed: * @self: the #NMDevice * * Called by the manager when the device was removed. Releases the device from * the master in case it's enslaved. */ void nm_device_removed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_REMOVED); } static gboolean is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier || priv->ignore_carrier) return TRUE; if (NM_FLAGS_HAS (flags, NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER)) return TRUE; return FALSE; } /** * nm_device_is_available: * @self: the #NMDevice * @flags: additional flags to influence the check. Flags have the * meaning to increase the availability of a device. * * Checks if @self would currently be capable of activating a * connection. In particular, it checks that the device is ready (eg, * is not missing firmware), that it has carrier (if necessary), and * that any necessary external software (eg, ModemManager, * wpa_supplicant) is available. * * @self can only be in a state higher than * %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns * %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED * when it is available.) * * Returns: %TRUE or %FALSE */ gboolean nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->firmware_missing) return FALSE; return NM_DEVICE_GET_CLASS (self)->is_available (self, flags); } gboolean nm_device_get_enabled (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); if (NM_DEVICE_GET_CLASS (self)->get_enabled) return NM_DEVICE_GET_CLASS (self)->get_enabled (self); return TRUE; } void nm_device_set_enabled (NMDevice *self, gboolean enabled) { g_return_if_fail (NM_IS_DEVICE (self)); if (NM_DEVICE_GET_CLASS (self)->set_enabled) NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled); } /** * nm_device_get_autoconnect: * @self: the #NMDevice * * Returns: %TRUE if the device allows autoconnect connections, or %FALSE if the * device is explicitly blocking all autoconnect connections. Does not take * into account transient conditions like companion devices that may wish to * block the device. */ gboolean nm_device_get_autoconnect (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->autoconnect; } static void nm_device_set_autoconnect (NMDevice *self, gboolean autoconnect) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (priv->autoconnect == autoconnect) return; if (autoconnect) { /* Default-unmanaged devices never autoconnect */ if (!nm_device_get_default_unmanaged (self)) { priv->autoconnect = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } else { priv->autoconnect = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } static gboolean autoconnect_allowed_accumulator (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return, gpointer data) { if (!g_value_get_boolean (handler_return)) g_value_set_boolean (return_accu, FALSE); return TRUE; } /** * nm_device_autoconnect_allowed: * @self: the #NMDevice * * Returns: %TRUE if the device can be auto-connected immediately, taking * transient conditions into account (like companion devices that may wish to * block autoconnect for a time). */ gboolean nm_device_autoconnect_allowed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GValue instance = G_VALUE_INIT; GValue retval = G_VALUE_INIT; if (priv->state < NM_DEVICE_STATE_DISCONNECTED || !priv->autoconnect) return FALSE; /* The 'autoconnect-allowed' signal is emitted on a device to allow * other listeners to block autoconnect on the device if they wish. * This is mainly used by the OLPC Mesh devices to block autoconnect * on their companion WiFi device as they share radio resources and * cannot be connected at the same time. */ g_value_init (&instance, G_TYPE_OBJECT); g_value_set_object (&instance, self); g_value_init (&retval, G_TYPE_BOOLEAN); if (priv->autoconnect) g_value_set_boolean (&retval, TRUE); else g_value_set_boolean (&retval, FALSE); /* Use g_signal_emitv() rather than g_signal_emit() to avoid the return * value being changed if no handlers are connected */ g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval); g_value_unset (&instance); return g_value_get_boolean (&retval); } static gboolean can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { NMSettingConnection *s_con; s_con = nm_connection_get_setting_connection (connection); if (!nm_setting_connection_get_autoconnect (s_con)) return FALSE; return nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_NONE, NULL); } /** * nm_device_can_auto_connect: * @self: an #NMDevice * @connection: a #NMConnection * @specific_object: (out) (transfer full): on output, the path of an * object associated with the returned connection, to be passed to * nm_manager_activate_connection(), or %NULL. * * Checks if @connection can be auto-activated on @self right now. * This requires, at a minimum, that the connection be compatible with * @self, and that it have the #NMSettingConnection:autoconnect property * set, and that the device allow auto connections. Some devices impose * additional requirements. (Eg, a Wi-Fi connection can only be activated * if its SSID was seen in the last scan.) * * Returns: %TRUE, if the @connection can be auto-activated. **/ gboolean nm_device_can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); g_return_val_if_fail (specific_object && !*specific_object, FALSE); if (nm_device_autoconnect_allowed (self)) return NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, connection, specific_object); return FALSE; } static gboolean device_has_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); /* Check for IP configuration. */ if (priv->ip4_config && nm_ip4_config_get_num_addresses (priv->ip4_config)) return TRUE; if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config)) return TRUE; /* The existence of a software device is good enough. */ if (nm_device_is_software (self)) return TRUE; /* Slaves are also configured by definition */ if (nm_platform_link_get_master (priv->ifindex) > 0) return TRUE; return FALSE; } /** * nm_device_master_update_slave_connection: * @self: the master #NMDevice * @slave: the slave #NMDevice * @connection: the #NMConnection to update with the slave settings * @GError: (out): error description * * Reads the slave configuration for @slave and updates @connection with those * properties. This invokes a virtual function on the master device @self. * * Returns: %TRUE if the configuration was read and @connection updated, * %FALSE on failure. */ gboolean nm_device_master_update_slave_connection (NMDevice *self, NMDevice *slave, NMConnection *connection, GError **error) { NMDeviceClass *klass; gboolean success; g_return_val_if_fail (self, FALSE); g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (slave, FALSE); g_return_val_if_fail (connection, FALSE); g_return_val_if_fail (!error || !*error, FALSE); g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE); g_return_val_if_fail (nm_device_get_iface (self), FALSE); klass = NM_DEVICE_GET_CLASS (self); if (klass->master_update_slave_connection) { success = klass->master_update_slave_connection (self, slave, connection, error); g_return_val_if_fail (!error || (success && !*error) || *error, success); return success; } g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED, "master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)", nm_device_get_iface (self), nm_device_get_iface (slave)); return FALSE; } NMConnection * nm_device_generate_connection (NMDevice *self, NMDevice *master) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *ifname = nm_device_get_iface (self); NMConnection *connection; NMSetting *s_con; NMSetting *s_ip4; NMSetting *s_ip6; gs_free char *uuid = NULL; const char *ip4_method, *ip6_method; GError *error = NULL; /* If update_connection() is not implemented, just fail. */ if (!klass->update_connection) return NULL; /* Return NULL if device is unconfigured. */ if (!device_has_config (self)) { _LOGD (LOGD_DEVICE, "device has no existing configuration"); return NULL; } connection = nm_simple_connection_new (); s_con = nm_setting_connection_new (); uuid = nm_utils_uuid_generate (); g_object_set (s_con, NM_SETTING_CONNECTION_UUID, uuid, NM_SETTING_CONNECTION_ID, ifname, NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NM_SETTING_CONNECTION_INTERFACE_NAME, ifname, NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL), NULL); if (klass->connection_type) g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type, NULL); nm_connection_add_setting (connection, s_con); /* If the device is a slave, update various slave settings */ if (master) { if (!nm_device_master_update_slave_connection (master, self, connection, &error)) { _LOGE (LOGD_DEVICE, "master device '%s' failed to update slave connection: %s", nm_device_get_iface (master), error ? error->message : "(unknown error)"); g_error_free (error); g_object_unref (connection); return NULL; } } else { /* Only regular and master devices get IP configuration; slaves do not */ s_ip4 = nm_ip4_config_create_setting (priv->ip4_config); nm_connection_add_setting (connection, s_ip4); s_ip6 = nm_ip6_config_create_setting (priv->ip6_config); nm_connection_add_setting (connection, s_ip6); } klass->update_connection (self, connection); /* Check the connection in case of update_connection() bug. */ if (!nm_connection_verify (connection, &error)) { _LOGE (LOGD_DEVICE, "Generated connection does not verify: %s", error->message); g_clear_error (&error); g_object_unref (connection); return NULL; } /* Ignore the connection if it has no IP configuration, * no slave configuration, and is not a master interface. */ ip4_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); ip6_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if ( g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0 && g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0 && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con)) && !priv->slaves) { _LOGD (LOGD_DEVICE, "ignoring generated connection (no IP and not in master-slave relationship)"); g_object_unref (connection); connection = NULL; } return connection; } gboolean nm_device_complete_connection (NMDevice *self, NMConnection *connection, const char *specific_object, const GSList *existing_connections, GError **error) { gboolean success = FALSE; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (connection != NULL, FALSE); if (!NM_DEVICE_GET_CLASS (self)->complete_connection) { g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION, "Device class %s had no complete_connection method", G_OBJECT_TYPE_NAME (self)); return FALSE; } success = NM_DEVICE_GET_CLASS (self)->complete_connection (self, connection, specific_object, existing_connections, error); if (success) success = nm_connection_verify (connection, error); return success; } static gboolean check_connection_compatible (NMDevice *self, NMConnection *connection) { NMSettingConnection *s_con; const char *config_iface, *device_iface; s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); config_iface = nm_setting_connection_get_interface_name (s_con); device_iface = nm_device_get_iface (self); if (config_iface && strcmp (config_iface, device_iface) != 0) return FALSE; return TRUE; } /** * nm_device_check_connection_compatible: * @self: an #NMDevice * @connection: an #NMConnection * * Checks if @connection could potentially be activated on @self. * This means only that @self has the proper capabilities, and that * @connection is not locked to some other device. It does not * necessarily mean that @connection could be activated on @self * right now. (Eg, it might refer to a Wi-Fi network that is not * currently available.) * * Returns: #TRUE if @connection could potentially be activated on * @self. */ gboolean nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection); } /** * nm_device_can_assume_connections: * @self: #NMDevice instance * * This is a convenience function to determine whether connection assumption * is available for this device. * * Returns: %TRUE if the device is capable of assuming connections, %FALSE if not */ static gboolean nm_device_can_assume_connections (NMDevice *self) { return !!NM_DEVICE_GET_CLASS (self)->update_connection; } /** * nm_device_can_assume_active_connection: * @self: #NMDevice instance * * This is a convenience function to determine whether the device's active * connection can be assumed if NetworkManager restarts. This method returns * %TRUE if and only if the device can assume connections, and the device has * an active connection, and that active connection can be assumed. * * Returns: %TRUE if the device's active connection can be assumed, or %FALSE * if there is no active connection or the active connection cannot be * assumed. */ gboolean nm_device_can_assume_active_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; const char *assumable_ip6_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_IGNORE, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; const char *assumable_ip4_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_DISABLED, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; if (!nm_device_can_assume_connections (self)) return FALSE; connection = nm_device_get_connection (self); if (!connection) return FALSE; /* Can't assume connections that aren't yet configured * FIXME: what about bridges/bonds waiting for slaves? */ if (priv->state < NM_DEVICE_STATE_IP_CONFIG) return FALSE; if (priv->ip4_state != IP_DONE && priv->ip6_state != IP_DONE) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip6_methods)) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip4_methods)) return FALSE; return TRUE; } static gboolean nm_device_emit_recheck_assume (gpointer self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->recheck_assume_id = 0; if (!nm_device_get_act_request (self)) { _LOGD (LOGD_DEVICE, "emit RECHECK_ASSUME signal"); g_signal_emit (self, signals[RECHECK_ASSUME], 0); } return G_SOURCE_REMOVE; } void nm_device_queue_recheck_assume (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (nm_device_can_assume_connections (self) && !priv->recheck_assume_id) priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self); } void nm_device_emit_recheck_auto_activate (NMDevice *self) { g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0); } static void dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); switch (status) { case NM_DNSMASQ_STATUS_DEAD: nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED); break; default: break; } } static void activation_source_clear (NMDevice *self, gboolean remove_source, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) { if (remove_source) g_source_remove (*act_source_id); *act_source_id = 0; *act_source_func = NULL; } } static void activation_source_schedule (NMDevice *self, GSourceFunc func, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) _LOGE (LOGD_DEVICE, "activation stage already scheduled"); /* Don't bother rescheduling the same function that's about to * run anyway. Fixes issues with crappy wireless drivers sending * streams of associate events before NM has had a chance to process * the first one. */ if (!*act_source_id || (*act_source_func != func)) { activation_source_clear (self, TRUE, family); *act_source_id = g_idle_add (func, self); *act_source_func = func; } } static gboolean get_ip_config_may_fail (NMDevice *self, int family) { NMConnection *connection; NMSettingIPConfig *s_ip = NULL; g_return_val_if_fail (self != NULL, TRUE); connection = nm_device_get_connection (self); g_assert (connection); /* Fail the connection if the failed IP method is required to complete */ switch (family) { case AF_INET: s_ip = nm_connection_get_setting_ip4_config (connection); break; case AF_INET6: s_ip = nm_connection_get_setting_ip6_config (connection); break; default: g_assert_not_reached (); } return nm_setting_ip_config_get_may_fail (s_ip); } static void master_ready_cb (NMActiveConnection *active, GParamSpec *pspec, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActiveConnection *master; g_assert (priv->state == NM_DEVICE_STATE_PREPARE); /* Notify a master device that it has a new slave */ g_assert (nm_active_connection_get_master_ready (active)); master = nm_active_connection_get_master (active); priv->master = g_object_ref (nm_active_connection_get_device (master)); nm_device_master_add_slave (priv->master, self, nm_active_connection_get_assumed (active) ? FALSE : TRUE); _LOGD (LOGD_DEVICE, "master connection ready; master device %s", nm_device_get_iface (priv->master)); if (priv->master_ready_id) { g_signal_handler_disconnect (active, priv->master_ready_id); priv->master_ready_id = 0; } nm_device_activate_schedule_stage2_device_config (self); } static NMActStageReturn act_stage1_prepare (NMDevice *self, NMDeviceStateReason *reason) { return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage1_device_prepare * * Prepare for device activation * */ static gboolean nm_device_activate_stage1_device_prepare (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); priv->ip4_state = priv->ip6_state = IP_NONE; /* Notify the new ActiveConnection along with the state change */ g_object_notify (G_OBJECT (self), NM_DEVICE_ACTIVE_CONNECTION); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) started..."); nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { ret = NM_DEVICE_GET_CLASS (self)->act_stage1_prepare (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { goto out; } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (nm_active_connection_get_master (active)) { /* If the master connection is ready for slaves, attach ourselves */ if (nm_active_connection_get_master_ready (active)) master_ready_cb (active, NULL, self); else { _LOGD (LOGD_DEVICE, "waiting for master connection to become ready"); /* Attach a signal handler and wait for the master connection to begin activating */ g_assert (priv->master_ready_id == 0); priv->master_ready_id = g_signal_connect (active, "notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY, (GCallback) master_ready_cb, self); /* Postpone */ } } else nm_device_activate_schedule_stage2_device_config (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) complete."); return FALSE; } /* * nm_device_activate_schedule_stage1_device_prepare * * Prepare a device for activation * */ void nm_device_activate_schedule_stage1_device_prepare (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage1_device_prepare, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) scheduled..."); } static NMActStageReturn act_stage2_config (NMDevice *self, NMDeviceStateReason *reason) { /* Nothing to do */ return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage2_device_config * * Determine device parameters and set those on the device, ie * for wireless devices, set SSID, keys, etc. * */ static gboolean nm_device_activate_stage2_device_config (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; gboolean no_firmware = FALSE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); GSList *iter; /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) starting..."); nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { if (!nm_device_bring_up (self, FALSE, &no_firmware)) { if (no_firmware) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_FIRMWARE_MISSING); else nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED); goto out; } ret = NM_DEVICE_GET_CLASS (self)->act_stage2_config (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) goto out; else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } /* If we have slaves that aren't yet enslaved, do that now */ for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; NMDeviceState slave_state = nm_device_get_state (info->slave); if (slave_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, info->slave, nm_device_get_connection (info->slave)); else if ( nm_device_uses_generated_assumed_connection (self) && slave_state <= NM_DEVICE_STATE_DISCONNECTED) nm_device_queue_recheck_assume (info->slave); } _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) successful."); nm_device_activate_schedule_stage3_ip_config_start (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) complete."); return FALSE; } /* * nm_device_activate_schedule_stage2_device_config * * Schedule setup of the hardware device * */ void nm_device_activate_schedule_stage2_device_config (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage2_device_config, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) scheduled..."); } /*********************************************/ /* avahi-autoipd stuff */ static void aipd_timeout_remove (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { g_source_remove (priv->aipd_timeout); priv->aipd_timeout = 0; } } static void aipd_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_watch) { g_source_remove (priv->aipd_watch); priv->aipd_watch = 0; } if (priv->aipd_pid > 0) { nm_utils_kill_child_sync (priv->aipd_pid, SIGKILL, LOGD_AUTOIP4, "avahi-autoipd", NULL, 0, 0); priv->aipd_pid = -1; } aipd_timeout_remove (self); } static NMIP4Config * aipd_get_ip4_config (NMDevice *self, guint32 lla) { NMIP4Config *config = NULL; NMPlatformIP4Address address; NMPlatformIP4Route route; config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (config); memset (&address, 0, sizeof (address)); address.address = lla; address.plen = 16; address.source = NM_IP_CONFIG_SOURCE_IP4LL; nm_ip4_config_add_address (config, &address); /* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */ memset (&route, 0, sizeof (route)); route.network = htonl (0xE0000000L); route.plen = 4; route.source = NM_IP_CONFIG_SOURCE_IP4LL; route.metric = nm_device_get_ip4_route_metric (self); nm_ip4_config_add_route (config, &route); return config; } #define IPV4LL_NETWORK (htonl (0xA9FE0000L)) #define IPV4LL_NETMASK (htonl (0xFFFF0000L)) void nm_device_handle_autoip4_event (NMDevice *self, const char *event, const char *address) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = NULL; const char *method; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (event != NULL); if (priv->act_request == NULL) return; connection = nm_act_request_get_connection (priv->act_request); g_assert (connection); /* Ignore if the connection isn't an AutoIP connection */ method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) != 0) return; if (strcmp (event, "BIND") == 0) { guint32 lla; NMIP4Config *config; if (inet_pton (AF_INET, address, &lla) <= 0) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd.", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } if ((lla & IPV4LL_NETMASK) != IPV4LL_NETWORK) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd (not link-local).", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } config = aipd_get_ip4_config (self, lla); if (config == NULL) { _LOGE (LOGD_AUTOIP4, "failed to get autoip config"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); return; } if (priv->ip4_state == IP_CONF) { aipd_timeout_remove (self); nm_device_activate_schedule_ip4_config_result (self, config); } else if (priv->ip4_state == IP_DONE) { if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } } else g_assert_not_reached (); g_object_unref (config); } else { _LOGW (LOGD_AUTOIP4, "autoip address %s no longer valid because '%s'.", address, event); /* The address is gone; terminate the connection or fail activation */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); } } static void aipd_watch_cb (GPid pid, gint status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceState state; if (!priv->aipd_watch) return; priv->aipd_watch = 0; if (WIFEXITED (status)) _LOGD (LOGD_AUTOIP4, "avahi-autoipd exited with error code %d", WEXITSTATUS (status)); else if (WIFSTOPPED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd stopped unexpectedly with signal %d", WSTOPSIG (status)); else if (WIFSIGNALED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd died with signal %d", WTERMSIG (status)); else _LOGW (LOGD_AUTOIP4, "avahi-autoipd died from an unknown cause"); aipd_cleanup (self); state = nm_device_get_state (self); if (nm_device_is_activating (self) || (state == NM_DEVICE_STATE_ACTIVATED)) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_FAILED); } static gboolean aipd_timeout_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { _LOGI (LOGD_AUTOIP4, "avahi-autoipd timed out."); priv->aipd_timeout = 0; aipd_cleanup (self); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_timeout (self); } return FALSE; } /* default to installed helper, but can be modified for testing */ const char *nm_device_autoipd_helper_path = LIBEXECDIR "/nm-avahi-autoipd.action"; static NMActStageReturn aipd_start (NMDevice *self, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *argv[6]; char *cmdline; const char *aipd_binary; int i = 0; GError *error = NULL; aipd_cleanup (self); /* Find avahi-autoipd */ aipd_binary = nm_utils_find_helper ("avahi-autoipd", NULL, NULL); if (!aipd_binary) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: not found"); *reason = NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } argv[i++] = aipd_binary; argv[i++] = "--script"; argv[i++] = nm_device_autoipd_helper_path; if (nm_logging_enabled (LOGL_DEBUG, LOGD_AUTOIP4)) argv[i++] = "--debug"; argv[i++] = nm_device_get_ip_iface (self); argv[i++] = NULL; cmdline = g_strjoinv (" ", (char **) argv); _LOGD (LOGD_AUTOIP4, "running: %s", cmdline); g_free (cmdline); if (!g_spawn_async ("/", (char **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, nm_utils_setpgid, NULL, &(priv->aipd_pid), &error)) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: %s", error && error->message ? error->message : "(unknown)"); g_clear_error (&error); aipd_cleanup (self); return NM_ACT_STAGE_RETURN_FAILURE; } _LOGI (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) started" " avahi-autoipd..."); /* Monitor the child process so we know when it dies */ priv->aipd_watch = g_child_watch_add (priv->aipd_pid, aipd_watch_cb, self); /* Start a timeout to bound the address attempt */ priv->aipd_timeout = g_timeout_add_seconds (20, aipd_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /*********************************************/ static gboolean _device_get_default_route_from_platform (NMDevice *self, int addr_family, NMPlatformIPRoute *out_route) { gboolean success = FALSE; int ifindex = nm_device_get_ip_ifindex (self); GArray *routes; if (addr_family == AF_INET) routes = nm_platform_ip4_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); else routes = nm_platform_ip6_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); if (routes) { guint route_metric = G_MAXUINT32, m; const NMPlatformIPRoute *route = NULL, *r; guint i; /* if there are several default routes, find the one with the best metric */ for (i = 0; i < routes->len; i++) { if (addr_family == AF_INET) { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i); m = r->metric; } else { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i); m = nm_utils_ip6_route_metric_normalize (r->metric); } if (!route || m < route_metric) { route = r; route_metric = m; } } if (route) { if (addr_family == AF_INET) *((NMPlatformIP4Route *) out_route) = *((NMPlatformIP4Route *) route); else *((NMPlatformIP6Route *) out_route) = *((NMPlatformIP6Route *) route); success = TRUE; } g_array_free (routes, TRUE); } return success; } /*********************************************/ static void ensure_con_ipx_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMConnection *connection; g_assert (!!priv->con_ip4_config == !!priv->con_ip6_config); if (priv->con_ip4_config) return; connection = nm_device_get_connection (self); if (!connection) return; priv->con_ip4_config = nm_ip4_config_new (ip_ifindex); priv->con_ip6_config = nm_ip6_config_new (ip_ifindex); nm_ip4_config_merge_setting (priv->con_ip4_config, nm_connection_get_setting_ip4_config (connection), nm_device_get_ip4_route_metric (self)); nm_ip6_config_merge_setting (priv->con_ip6_config, nm_connection_get_setting_ip6_config (connection), nm_device_get_ip6_route_metric (self)); if (nm_device_uses_assumed_connection (self)) { /* For assumed connections ignore all addresses and routes. */ nm_ip4_config_reset_addresses (priv->con_ip4_config); nm_ip4_config_reset_routes (priv->con_ip4_config); nm_ip6_config_reset_addresses (priv->con_ip6_config); nm_ip6_config_reset_routes (priv->con_ip6_config); } } /*********************************************/ /* DHCPv4 stuff */ static void dhcp4_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp4_client) { /* Stop any ongoing DHCP transaction on this device */ if (priv->dhcp4_state_sigid) { g_signal_handler_disconnect (priv->dhcp4_client, priv->dhcp4_state_sigid); priv->dhcp4_state_sigid = 0; } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE); if (stop) nm_dhcp_client_stop (priv->dhcp4_client, release); g_clear_object (&priv->dhcp4_client); } if (priv->dhcp4_config) { g_clear_object (&priv->dhcp4_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } } static gboolean ip4_config_merge_and_apply (NMDevice *self, NMIP4Config *config, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP4Config *composite; gboolean has_direct_route; const guint32 default_route_metric = nm_device_get_ip4_route_metric (self); guint32 gateway; /* Merge all the configs into the composite config */ if (config) { g_clear_object (&priv->dev_ip4_config); priv->dev_ip4_config = g_object_ref (config); } composite = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); if (priv->dev_ip4_config) nm_ip4_config_merge (composite, priv->dev_ip4_config); if (priv->vpn4_config) nm_ip4_config_merge (composite, priv->vpn4_config); if (priv->ext_ip4_config) nm_ip4_config_merge (composite, priv->ext_ip4_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip4_config) nm_ip4_config_merge (composite, priv->wwan_ip4_config); /* Merge user overrides into the composite config. For assumed connection, * con_ip4_config is empty. */ if (priv->con_ip4_config) nm_ip4_config_merge (composite, priv->con_ip4_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip4_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v4_has = FALSE; priv->default_route.v4_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v4_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip4_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip4_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip4_config_get_gateway (composite); if ( !gateway && nm_device_get_device_type (self) != NM_DEVICE_TYPE_MODEM) goto END_ADD_DEFAULT_ROUTE; has_direct_route = ( gateway == 0 || nm_ip4_config_get_subnet_for_host (composite, gateway) || nm_ip4_config_get_direct_route_for_host (composite, gateway)); priv->default_route.v4_has = TRUE; memset (&priv->default_route.v4, 0, sizeof (priv->default_route.v4)); priv->default_route.v4.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v4.gateway = gateway; priv->default_route.v4.metric = default_route_metric; priv->default_route.v4.mss = nm_ip4_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP4Route r = priv->default_route.v4; /* add a direct route to the gateway */ r.network = gateway; r.plen = 32; r.gateway = 0; nm_ip4_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v4_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v4_has = _device_get_default_route_from_platform (self, AF_INET, (NMPlatformIPRoute *) &priv->default_route.v4); } /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, composite); } success = nm_device_set_ip4_config (self, composite, default_route_metric, commit, out_reason); g_object_unref (composite); return success; } static void dhcp4_lease_change (NMDevice *self, NMIP4Config *config) { NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (config != NULL); if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCP4 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE, nm_device_get_connection (self), self, NULL, NULL, NULL); } } static void dhcp4_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp4_cleanup (self, TRUE, FALSE); if (timeout || (priv->ip4_state == IP_CONF)) nm_device_activate_schedule_ip4_config_timeout (self); else if (priv->ip4_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } static void dhcp4_update_config (NMDevice *self, NMDhcp4Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP4 config object with new DHCP options */ nm_dhcp4_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp4_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } static void dhcp4_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP4Config *ip4_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == FALSE); g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config)); _LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: if (!ip4_config) { _LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); break; } dhcp4_update_config (self, priv->dhcp4_config, options); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_result (self, ip4_config); else if (priv->ip4_state == IP_DONE) dhcp4_lease_change (self, ip4_config); break; case NM_DHCP_STATE_TIMEOUT: dhcp4_fail (self, TRUE); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip4_state == IP_CONF) break; /* Fall through */ case NM_DHCP_STATE_DONE: case NM_DHCP_STATE_FAIL: dhcp4_fail (self, FALSE); break; default: break; } } static NMActStageReturn dhcp4_start (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip4; const guint8 *hw_addr; size_t hw_addr_len = 0; GByteArray *tmp = NULL; s_ip4 = nm_connection_get_setting_ip4_config (connection); /* Clear old exported DHCP options */ if (priv->dhcp4_config) g_object_unref (priv->dhcp4_config); priv->dhcp4_config = nm_dhcp4_config_new (); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } /* Begin DHCP on the interface */ g_warn_if_fail (priv->dhcp4_client == NULL); priv->dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip4_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip4), nm_setting_ip_config_get_dhcp_hostname (s_ip4), nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4)), priv->dhcp_timeout, priv->dhcp_anycast_address, NULL); if (tmp) g_byte_array_free (tmp, TRUE); if (!priv->dhcp4_client) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } priv->dhcp4_state_sigid = g_signal_connect (priv->dhcp4_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp4_state_changed), self); nm_device_add_pending_action (self, PENDING_ACTION_DHCP4, TRUE); /* DHCP devices will be notified by the DHCP manager when stuff happens */ return NM_ACT_STAGE_RETURN_POSTPONE; } gboolean nm_device_dhcp4_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason; NMConnection *connection; g_return_val_if_fail (priv->dhcp4_client != NULL, FALSE); _LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp4_cleanup (self, TRUE, release); connection = nm_device_get_connection (self); g_assert (connection); /* Start DHCP again on the interface */ ret = dhcp4_start (self, connection, &reason); return (ret != NM_ACT_STAGE_RETURN_FAILURE); } /*********************************************/ static GHashTable *shared_ips = NULL; static void release_shared_ip (gpointer data) { g_hash_table_remove (shared_ips, data); } static gboolean reserve_shared_ip (NMDevice *self, NMSettingIPConfig *s_ip4, NMPlatformIP4Address *address) { if (G_UNLIKELY (shared_ips == NULL)) shared_ips = g_hash_table_new (g_direct_hash, g_direct_equal); memset (address, 0, sizeof (*address)); if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) { /* Use the first user-supplied address */ NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0); g_assert (user); nm_ip_address_get_address_binary (user, &address->address); address->plen = nm_ip_address_get_prefix (user); } else { /* Find an unused address in the 10.42.x.x range */ guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */ guint32 count = 0; while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) { count += ntohl (0x100); if (count > ntohl (0xFE00)) { _LOGE (LOGD_SHARING, "ran out of shared IP addresses!"); return FALSE; } } address->address = start + count; address->plen = 24; g_hash_table_insert (shared_ips, GUINT_TO_POINTER (address->address), GUINT_TO_POINTER (TRUE)); } return TRUE; } static NMIP4Config * shared4_new_config (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMIP4Config *config = NULL; NMPlatformIP4Address address; g_return_val_if_fail (self != NULL, NULL); if (!reserve_shared_ip (self, nm_connection_get_setting_ip4_config (connection), &address)) { *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE; return NULL; } config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); address.source = NM_IP_CONFIG_SOURCE_SHARED; nm_ip4_config_add_address (config, &address); /* Remove the address lock when the object gets disposed */ g_object_set_data_full (G_OBJECT (config), "shared-ip", GUINT_TO_POINTER (address.address), release_shared_ip); return config; } /*********************************************/ static gboolean connection_ip4_method_requires_carrier (NMConnection *connection, gboolean *out_ip4_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); static const char *ip4_carrier_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_AUTO, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip4_enabled) *out_ip4_enabled = !!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED); return _nm_utils_string_in_list (method, ip4_carrier_methods); } static gboolean connection_ip6_method_requires_carrier (NMConnection *connection, gboolean *out_ip6_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); static const char *ip6_carrier_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip6_enabled) *out_ip6_enabled = !!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE); return _nm_utils_string_in_list (method, ip6_carrier_methods); } static gboolean connection_requires_carrier (NMConnection *connection) { NMSettingIPConfig *s_ip4, *s_ip6; gboolean ip4_carrier_wanted, ip6_carrier_wanted; gboolean ip4_used = FALSE, ip6_used = FALSE; ip4_carrier_wanted = connection_ip4_method_requires_carrier (connection, &ip4_used); if (ip4_carrier_wanted) { /* If IPv4 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv6 method. */ s_ip4 = nm_connection_get_setting_ip4_config (connection); if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4)) return TRUE; } ip6_carrier_wanted = connection_ip6_method_requires_carrier (connection, &ip6_used); if (ip6_carrier_wanted) { /* If IPv6 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv4 method. */ s_ip6 = nm_connection_get_setting_ip6_config (connection); if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6)) return TRUE; } /* If an IP version wants a carrier and and the other IP version isn't * used, the connection requires carrier since it will just fail without one. */ if (ip4_carrier_wanted && !ip6_used) return TRUE; if (ip6_carrier_wanted && !ip4_used) return TRUE; /* If both want a carrier, the whole connection wants a carrier */ return ip4_carrier_wanted && ip6_carrier_wanted; } static gboolean have_any_ready_slaves (NMDevice *self, const GSList *slaves) { const GSList *iter; /* Any enslaved slave is "ready" in the generic case as it's * at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2 * properties set up. */ for (iter = slaves; iter; iter = g_slist_next (iter)) { if (nm_device_get_enslaved (iter->data)) return TRUE; } return FALSE; } static gboolean ip4_requires_slaves (NMConnection *connection) { const char *method; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); return strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0; } static NMActStageReturn act_stage3_ip4_config_start (NMDevice *self, NMIP4Config **out_config, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE; const char *method; GSList *slaves; gboolean ready_slaves; g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE); connection = nm_device_get_connection (self); g_assert (connection); if ( connection_ip4_method_requires_carrier (connection, NULL) && priv->is_master && !priv->carrier) { _LOGI (LOGD_IP4 | LOGD_DEVICE, "IPv4 config waiting until carrier is on"); return NM_ACT_STAGE_RETURN_WAIT; } if (priv->is_master && ip4_requires_slaves (connection)) { /* If the master has no ready slaves, and depends on slaves for * a successful IPv4 attempt, then postpone IPv4 addressing. */ slaves = nm_device_master_get_slaves (self); ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves); g_slist_free (slaves); if (ready_slaves == FALSE) { _LOGI (LOGD_DEVICE | LOGD_IP4, "IPv4 config waiting until slaves are ready"); return NM_ACT_STAGE_RETURN_WAIT; } } method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); /* Start IPv4 addressing based on the method requested */ if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0) ret = dhcp4_start (self, connection, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) == 0) ret = aipd_start (self, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL) == 0) { /* Use only IPv4 config from the connection data */ *out_config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (*out_config); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) { *out_config = shared4_new_config (self, connection, reason); if (*out_config) { priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self)); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else ret = NM_ACT_STAGE_RETURN_FAILURE; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0) { /* Nothing to do... */ ret = NM_ACT_STAGE_RETURN_STOP; } else _LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method); return ret; } /*********************************************/ /* DHCPv6 stuff */ static void dhcp6_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE; g_clear_object (&priv->dhcp6_ip6_config); if (priv->dhcp6_client) { if (priv->dhcp6_state_sigid) { g_signal_handler_disconnect (priv->dhcp6_client, priv->dhcp6_state_sigid); priv->dhcp6_state_sigid = 0; } if (stop) nm_dhcp_client_stop (priv->dhcp6_client, release); g_clear_object (&priv->dhcp6_client); } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE); if (priv->dhcp6_config) { g_clear_object (&priv->dhcp6_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } } static gboolean ip6_config_merge_and_apply (NMDevice *self, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP6Config *composite; gboolean has_direct_route; const struct in6_addr *gateway; /* If no config was passed in, create a new one */ composite = nm_ip6_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); g_assert (composite); /* Merge all the IP configs into the composite config */ if (priv->ac_ip6_config) nm_ip6_config_merge (composite, priv->ac_ip6_config); if (priv->dhcp6_ip6_config) nm_ip6_config_merge (composite, priv->dhcp6_ip6_config); if (priv->vpn6_config) nm_ip6_config_merge (composite, priv->vpn6_config); if (priv->ext_ip6_config) nm_ip6_config_merge (composite, priv->ext_ip6_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip6_config) nm_ip6_config_merge (composite, priv->wwan_ip6_config); /* Merge user overrides into the composite config. For assumed connections, * con_ip6_config is empty. */ if (priv->con_ip6_config) nm_ip6_config_merge (composite, priv->con_ip6_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip6_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v6_has = FALSE; priv->default_route.v6_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v6_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip6_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip6_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip6_config_get_gateway (composite); if (!gateway) goto END_ADD_DEFAULT_ROUTE; has_direct_route = nm_ip6_config_get_direct_route_for_host (composite, gateway) != NULL; priv->default_route.v6_has = TRUE; memset (&priv->default_route.v6, 0, sizeof (priv->default_route.v6)); priv->default_route.v6.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v6.gateway = *gateway; priv->default_route.v6.metric = nm_device_get_ip6_route_metric (self); priv->default_route.v6.mss = nm_ip6_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP6Route r = priv->default_route.v6; /* add a direct route to the gateway */ r.network = *gateway; r.plen = 128; r.gateway = in6addr_any; nm_ip6_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v6_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v6_has = _device_get_default_route_from_platform (self, AF_INET6, (NMPlatformIPRoute *) &priv->default_route.v6); } nm_ip6_config_addresses_sort (composite, priv->rdisc ? priv->rdisc_use_tempaddr : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN); /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit (self, composite); } success = nm_device_set_ip6_config (self, composite, commit, out_reason); g_object_unref (composite); return success; } static void dhcp6_lease_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; if (priv->dhcp6_ip6_config == NULL) { _LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); return; } g_assert (priv->dhcp6_client); /* sanity check */ connection = nm_device_get_connection (self); g_assert (connection); /* Apply the updated config */ if (ip6_config_merge_and_apply (self, TRUE, &reason) == FALSE) { _LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCPv6 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE, connection, self, NULL, NULL, NULL); } } static void dhcp6_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp6_cleanup (self, TRUE, FALSE); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) { if (timeout || (priv->ip6_state == IP_CONF)) nm_device_activate_schedule_ip6_config_timeout (self); else if (priv->ip6_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } else { /* not a hard failure; just live with the RA info */ if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_timeout (NMDevice *self, NMDhcpClient *client) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) dhcp6_fail (self, TRUE); else { /* not a hard failure; just live with the RA info */ dhcp6_cleanup (self, TRUE, FALSE); if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_update_config (NMDevice *self, NMDhcp6Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP6 config object with new DHCP options */ nm_dhcp6_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp6_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } static void dhcp6_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP6Config *ip6_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == TRUE); g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config)); _LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: g_clear_object (&priv->dhcp6_ip6_config); if (ip6_config) { priv->dhcp6_ip6_config = g_object_ref (ip6_config); dhcp6_update_config (self, priv->dhcp6_config, options); } if (priv->ip6_state == IP_CONF) { if (priv->dhcp6_ip6_config == NULL) { /* FIXME: Initial DHCP failed; should we fail IPv6 entirely then? */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); break; } nm_device_activate_schedule_ip6_config_result (self); } else if (priv->ip6_state == IP_DONE) dhcp6_lease_change (self); break; case NM_DHCP_STATE_TIMEOUT: dhcp6_timeout (self, client); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip6_state != IP_CONF) dhcp6_fail (self, FALSE); break; case NM_DHCP_STATE_DONE: /* In IPv6 info-only mode, the client doesn't handle leases so it * may exit right after getting a response from the server. That's * normal. In that case we just ignore the exit. */ if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) break; /* Otherwise, fall through */ case NM_DHCP_STATE_FAIL: dhcp6_fail (self, FALSE); break; default: break; } } static gboolean dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip6; GByteArray *tmp = NULL; const guint8 *hw_addr; size_t hw_addr_len = 0; g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); g_assert (s_ip6); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } priv->dhcp6_client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip6_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip6), nm_setting_ip_config_get_dhcp_hostname (s_ip6), priv->dhcp_timeout, priv->dhcp_anycast_address, (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE, nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6))); if (tmp) g_byte_array_free (tmp, TRUE); if (priv->dhcp6_client) { priv->dhcp6_state_sigid = g_signal_connect (priv->dhcp6_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp6_state_changed), self); } return !!priv->dhcp6_client; } static gboolean dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMSettingIPConfig *s_ip6; g_clear_object (&priv->dhcp6_config); priv->dhcp6_config = nm_dhcp6_config_new (); g_warn_if_fail (priv->dhcp6_ip6_config == NULL); g_clear_object (&priv->dhcp6_ip6_config); connection = nm_device_get_connection (self); g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); if (!nm_setting_ip_config_get_may_fail (s_ip6) || !strcmp (nm_setting_ip_config_get_method (s_ip6), NM_SETTING_IP6_CONFIG_METHOD_DHCP)) nm_device_add_pending_action (self, PENDING_ACTION_DHCP6, TRUE); if (wait_for_ll) { NMActStageReturn ret; /* ensure link local is ready... */ ret = linklocal6_start (self); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { /* success; wait for the LL address to show up */ return TRUE; } /* success; already have the LL address; kick off DHCP */ g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (!dhcp6_start_with_link_ready (self, connection)) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return FALSE; } return TRUE; } gboolean nm_device_dhcp6_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_val_if_fail (priv->dhcp6_client != NULL, FALSE); _LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp6_cleanup (self, TRUE, release); /* Start DHCP again on the interface */ return dhcp6_start (self, FALSE, NULL); } /******************************************/ static gboolean have_ip6_address (const NMIP6Config *ip6_config, gboolean linklocal) { guint i; if (!ip6_config) return FALSE; linklocal = !!linklocal; for (i = 0; i < nm_ip6_config_get_num_addresses (ip6_config); i++) { const NMPlatformIP6Address *addr = nm_ip6_config_get_address (ip6_config, i); if ((IN6_IS_ADDR_LINKLOCAL (&addr->address) == linklocal) && !(addr->flags & IFA_F_TENTATIVE)) return TRUE; } return FALSE; } static void linklocal6_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->linklocal6_timeout_id) { g_source_remove (priv->linklocal6_timeout_id); priv->linklocal6_timeout_id = 0; } } static gboolean linklocal6_timeout_cb (gpointer user_data) { NMDevice *self = user_data; linklocal6_cleanup (self); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout"); nm_device_activate_schedule_ip6_config_timeout (self); return G_SOURCE_REMOVE; } static void linklocal6_complete (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; g_assert (priv->linklocal6_timeout_id); g_assert (have_ip6_address (priv->ip6_config, TRUE)); linklocal6_cleanup (self); connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method); if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) { if (!addrconf6_start_with_link_ready (self)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) { if (!dhcp6_start_with_link_ready (self, connection)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0) nm_device_activate_schedule_ip6_config_result (self); else g_return_if_fail (FALSE); } static void check_and_add_ipv6ll_addr (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMUtilsIPv6IfaceId iid; struct in6_addr lladdr; guint i, n; if (priv->nm_ipv6ll == FALSE) return; if (priv->ip6_config) { n = nm_ip6_config_get_num_addresses (priv->ip6_config); for (i = 0; i < n; i++) { const NMPlatformIP6Address *addr; addr = nm_ip6_config_get_address (priv->ip6_config, i); if (IN6_IS_ADDR_LINKLOCAL (&addr->address)) { /* Already have an LL address, nothing to do */ return; } } } if (!nm_device_get_ip_iface_identifier (self, &iid)) { _LOGW (LOGD_IP6, "failed to get interface identifier; IPv6 may be broken"); return; } memset (&lladdr, 0, sizeof (lladdr)); lladdr.s6_addr16[0] = htons (0xfe80); nm_utils_ipv6_addr_set_interface_identfier (&lladdr, iid); _LOGD (LOGD_IP6, "adding IPv6LL address %s", nm_utils_inet6_ntop (&lladdr, NULL)); if (!nm_platform_ip6_address_add (ip_ifindex, lladdr, in6addr_any, 64, NM_PLATFORM_LIFETIME_PERMANENT, NM_PLATFORM_LIFETIME_PERMANENT, 0)) { _LOGW (LOGD_IP6, "failed to add IPv6 link-local address %s", nm_utils_inet6_ntop (&lladdr, NULL)); } } static NMActStageReturn linklocal6_start (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; linklocal6_cleanup (self); if (have_ip6_address (priv->ip6_config, TRUE)) return NM_ACT_STAGE_RETURN_SUCCESS; connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.", method); check_and_add_ipv6ll_addr (self); priv->linklocal6_timeout_id = g_timeout_add_seconds (5, linklocal6_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /******************************************/ static void print_support_extended_ifa_flags (NMSettingIP6ConfigPrivacy use_tempaddr) { static gint8 warn = 0; static gint8 s_libnl = -1, s_kernel; if (warn >= 2) return; if (s_libnl == -1) { s_libnl = !!nm_platform_check_support_libnl_extended_ifa_flags (); s_kernel = !!nm_platform_check_support_kernel_extended_ifa_flags (); if (s_libnl && s_kernel) { nm_log_dbg (LOGD_IP6, "kernel and libnl support extended IFA_FLAGS (needed by NM for IPv6 private addresses)"); warn = 2; return; } } if ( use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR && use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR) { if (warn == 0) { nm_log_dbg (LOGD_IP6, "%s%s%s %s not support extended IFA_FLAGS (needed by NM for IPv6 private addresses)", !s_kernel ? "kernel" : "", !s_kernel && !s_libnl ? " and " : "", !s_libnl ? "libnl" : "", !s_kernel && !s_libnl ? "do" : "does"); warn = 1; } return; } if (!s_libnl && !s_kernel) { nm_log_warn (LOGD_IP6, "libnl and the kernel do not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_libnl) { nm_log_warn (LOGD_IP6, "libnl does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_kernel) { nm_log_warn (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { address.preferred = discovered_address->preferred; if (address.preferred > address.lifetime) address.preferred = address.lifetime; address.source = NM_IP_CONFIG_SOURCE_RDISC; address.flags = ifa_flags; nm_ip6_config_add_address (priv->ac_ip6_config, &address); } }
C
NetworkManager
1
null
null
null
https://github.com/chromium/chromium/commit/d1a59e4e845a01d7d7b80ef184b672752a9eae4d
d1a59e4e845a01d7d7b80ef184b672752a9eae4d
Fixing cross-process postMessage replies on more than two iterations. When two frames are replying to each other using event.source across processes, after the first two replies, things break down. The root cause is that in RenderViewImpl::GetFrameByMappedID, the lookup was incorrect. It is now properly searching for the remote frame id and returning the local one. BUG=153445 Review URL: https://chromiumcodereview.appspot.com/11040015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@159924 0039d316-1c4b-4281-b951-d872f2087c98
WebKit::WebPlugin* RenderViewImpl::GetWebPluginFromPluginDocument() { return webview()->mainFrame()->document().to<WebPluginDocument>().plugin(); }
WebKit::WebPlugin* RenderViewImpl::GetWebPluginFromPluginDocument() { return webview()->mainFrame()->document().to<WebPluginDocument>().plugin(); }
C
Chrome
0